repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
Jonatino/Java-Memory-Manipulation | src/main/java/com/github/jonatino/natives/unix/libc.java | 962 | /*
* Copyright 2016 Jonathan Beaudoin
*
* 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.github.jonatino.natives.unix;
import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
/**
* Created by root on 1/12/16.
*/
public final class libc {
static {
Native.register(NativeLibrary.getInstance("c"));
}
public static native int getuid();
public static native int getpid();
}
| apache-2.0 |
MRCHENDQ/JoinOurs | mblog-core/src/main/java/mblog/core/persist/service/UserService.java | 2120 | /*
+--------------------------------------------------------------------------
| Mblog [#RELEASE_VERSION#]
| ========================================
| Copyright (c) 2014, 2015 mtons. All Rights Reserved
| http://www.mtons.com
|
+---------------------------------------------------------------------------
*/
package mblog.core.persist.service;
import java.util.List;
import java.util.Map;
import java.util.Set;
import mblog.core.data.AccountProfile;
import mblog.core.data.AuthMenu;
import mblog.core.data.User;
import mtons.modules.pojos.Paging;
/**
* @author cdq
*
*/
public interface UserService {
/**
* 登录
* @param username
* @param password
* @return
*/
AccountProfile login(String username, String password);
/**
* 登录,用于记住登录时获取用户信息
* @param username
* @return
*/
AccountProfile getProfileByName(String username);
/**
* 注册
* @param user
*/
User register(User user);
/**
* 修改用户信息
* @param user
* @return
*/
AccountProfile update(User user);
/**
* 修改用户信息
* @param email
* @return
*/
AccountProfile updateEmail(long id, String email);
/**
* 查询单个用户
* @param id
* @return
*/
User get(long id);
User getByUsername(String username);
/**
* 修改头像
* @param id
* @param path
* @return
*/
AccountProfile updateAvatar(long id, String path);
/**
* 修改密码
* @param id
* @param newPassword
*/
void updatePassword(long id, String newPassword);
/**
* 修改密码
* @param id
* @param oldPassword
* @param newPassword
*/
void updatePassword(long id, String oldPassword, String newPassword);
/**
* 修改用户状态
* @param id
* @param status
*/
void updateStatus(long id, int status);
AccountProfile updateActiveEmail(long id, int activeEmail);
void updateRole(long id, Long[] roleIds);
/**
* 分页查询
* @param paging
*/
void paging(Paging paging, String key);
Map<Long, User> findMapByIds(Set<Long> ids);
List<AuthMenu> getMenuList(long id);
List<User> getHotUserByfans(int maxResults);
}
| apache-2.0 |
d-sauer/JCalcAPI | src/main/java/org/jdice/calc/extension/ArcTan.java | 1063 | /*
* Copyright 2014 Davor Sauer
*
* 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.jdice.calc.extension;
import org.jdice.calc.AbstractCalculator;
import org.jdice.calc.BindExtension;
/**
*
* @author Davor Sauer <davor.sauer@gmail.com>
*
* @param <CALC>
*/
@BindExtension(implementation = ArcTanFunction.class)
public interface ArcTan<CALC> {
public CALC atan(AbstractCalculator expression);
public CALC atan(Object value);
public CALC atan(String value, char decimalSeparator);
}
| apache-2.0 |
BridgeGeorge/secret | secret/src/com/graduate/secret/view/ProgressDialogCustom.java | 909 | package com.graduate.secret.view;
import android.app.Dialog;
import com.graduate.secret.R;
import android.content.Context;
import android.view.Gravity;
import android.widget.TextView;
/**
* 自定义进度条对话框
* @author George
*
*/
public class ProgressDialogCustom extends Dialog {
public ProgressDialogCustom(Context context, String strMessage) {
this(context, R.style.MyDialogStyle, strMessage);
}
public ProgressDialogCustom(Context context, int theme, String strMessage) {
super(context, theme);
this.setContentView(R.layout.progress_loading);
this.getWindow().getAttributes().gravity = Gravity.CENTER;
TextView tvMsg = (TextView) this.findViewById(R.id.progress_title);
if (tvMsg != null) {
tvMsg.setText(strMessage);
}
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
if (!hasFocus) {
dismiss();
}
}
}
| apache-2.0 |
akarnokd/RxJava2Extensions | src/main/java/hu/akarnokd/rxjava2/basetypes/SoloHide.java | 2134 | /*
* Copyright 2016-2019 David Karnok
*
* 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 hu.akarnokd.rxjava2.basetypes;
import org.reactivestreams.*;
import io.reactivex.internal.subscriptions.SubscriptionHelper;
/**
* Hides the identity of the upstream Solo and its Subscription.
*
* @param <T> the value type
*/
final class SoloHide<T> extends Solo<T> {
final Solo<T> source;
SoloHide(Solo<T> source) {
this.source = source;
}
@Override
protected void subscribeActual(Subscriber<? super T> s) {
source.subscribe(new HideSubscriber<T>(s));
}
static final class HideSubscriber<T> implements Subscriber<T>, Subscription {
final Subscriber<? super T> downstream;
Subscription upstream;
HideSubscriber(Subscriber<? super T> downstream) {
this.downstream = downstream;
}
@Override
public void onSubscribe(Subscription s) {
if (SubscriptionHelper.validate(this.upstream, s)) {
this.upstream = s;
downstream.onSubscribe(this);
}
}
@Override
public void onNext(T t) {
downstream.onNext(t);
}
@Override
public void onError(Throwable t) {
downstream.onError(t);
}
@Override
public void onComplete() {
downstream.onComplete();
}
@Override
public void request(long n) {
upstream.request(n);
}
@Override
public void cancel() {
upstream.cancel();
}
}
}
| apache-2.0 |
javierj/nikkylittlequest | test/org/iwt2/nikky/model/actors/TestFighterActor.java | 1718 | package org.iwt2.nikky.model.actors;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.hamcrest.CoreMatchers;
import org.iwt2.nikky.model.actors.FighterActor;
import org.junit.Before;
import org.junit.Test;
/**
* A fighter Actor is a LibGDX Actor that has hit points
* @author Javier
*
*/
public class TestFighterActor {
FighterActor fighter;
int hitPoints = 30;
@Before
public void setUp() throws Exception {
fighter = new FighterActor(hitPoints);
}
@Test
public void aFighterHasHitPoints() {
assertThat(fighter.getHP(), equalTo(30));
}
@Test
public void ifNoTextureIndicatedInConstructor_ActorHasNoDrawable() {
assertNull(fighter.getDrawable());
}
/**
* No pueod probar esto porque no puedo crear una textura.
@Test
public void ifTextureIndicatedInConstructor_ActorHasDrawable() {
fighter = new FighterActor(new SpriteDrawable(new Sprite()),hitPoints);
assertNotNull(fighter.getDrawable());
}*/
@Test
public void whenAFighterIsHitted_HisHPDecreaed() {
fighter.hitted(5);
assertThat(fighter.getHP(), equalTo(25));
}
@Test
public void whenAFicherActorHasMoreHPThanCero_IsNotDeath() {
assertFalse(fighter.isDeath());
}
@Test
public void whenAFicherActorHasEqualHPThanCero_IsDeath() {
fighter.hitted(this.hitPoints);
assertTrue(fighter.isDeath());
}
@Test
public void aNewFighterActorHasATable2DWithThreeColumns() {
assertThat(fighter.hpTable.columnLimit(),is(3));
}
@Test
public void aNewFighterActorHasAsManyHeartsAsHP_InTable() {
HeartImage heart = new HeartImage();
fighter.setHPImage(heart);
assertThat(fighter.hpTable.countElements(), is(hitPoints));
}
}
| apache-2.0 |
2629743986/SpringMVC | src/main/java/com/wangjie/spring/validate/MyValidator.java | 696 | package com.wangjie.spring.validate;
import com.wangjie.spring.model.User;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
/**
* Created by 26297 on 2016/12/29.
*/
public class MyValidator implements Validator {
public boolean supports(Class<?> aClass) {
return User.class.equals(aClass);
}
public void validate(Object obj, Errors errors) {
ValidationUtils.rejectIfEmpty(errors, "username", null, "Username is empty.");
User user = (User) obj;
if (null == user.getPassword() || "".equals(user.getPassword()))
errors.rejectValue("password", null, "Password is empty.");
}
}
| apache-2.0 |
iburmistrov/Cassandra | src/java/org/apache/cassandra/config/DatabaseDescriptor.java | 59444 | /*
* 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.cassandra.config;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableSet;
import com.google.common.primitives.Longs;
import org.apache.cassandra.thrift.ThriftServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.auth.AllowAllAuthenticator;
import org.apache.cassandra.auth.AllowAllAuthorizer;
import org.apache.cassandra.auth.AllowAllInternodeAuthenticator;
import org.apache.cassandra.auth.IAuthenticator;
import org.apache.cassandra.auth.IAuthorizer;
import org.apache.cassandra.auth.IInternodeAuthenticator;
import org.apache.cassandra.config.Config.RequestSchedulerId;
import org.apache.cassandra.config.EncryptionOptions.ClientEncryptionOptions;
import org.apache.cassandra.config.EncryptionOptions.ServerEncryptionOptions;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.db.DefsTables;
import org.apache.cassandra.db.SystemKeyspace;
import org.apache.cassandra.dht.IPartitioner;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.io.FSWriteError;
import org.apache.cassandra.io.util.FileUtils;
import org.apache.cassandra.io.util.IAllocator;
import org.apache.cassandra.locator.DynamicEndpointSnitch;
import org.apache.cassandra.locator.EndpointSnitchInfo;
import org.apache.cassandra.locator.IEndpointSnitch;
import org.apache.cassandra.locator.SeedProvider;
import org.apache.cassandra.net.MessagingService;
import org.apache.cassandra.scheduler.IRequestScheduler;
import org.apache.cassandra.scheduler.NoScheduler;
import org.apache.cassandra.service.CacheService;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.utils.JVMStabilityInspector;
import org.apache.cassandra.utils.memory.HeapPool;
import org.apache.cassandra.utils.memory.NativePool;
import org.apache.cassandra.utils.memory.MemtablePool;
import org.apache.cassandra.utils.memory.SlabPool;
public class DatabaseDescriptor
{
private static final Logger logger = LoggerFactory.getLogger(DatabaseDescriptor.class);
/**
* Tokens are serialized in a Gossip VersionedValue String. VV are restricted to 64KB
* when we send them over the wire, which works out to about 1700 tokens.
*/
private static final int MAX_NUM_TOKENS = 1536;
private static IEndpointSnitch snitch;
private static InetAddress listenAddress; // leave null so we can fall through to getLocalHost
private static InetAddress broadcastAddress;
private static InetAddress rpcAddress;
private static InetAddress broadcastRpcAddress;
private static SeedProvider seedProvider;
private static IInternodeAuthenticator internodeAuthenticator;
/* Hashing strategy Random or OPHF */
private static IPartitioner partitioner;
private static String paritionerName;
private static Config.DiskAccessMode indexAccessMode;
private static Config conf;
private static IAuthenticator authenticator = new AllowAllAuthenticator();
private static IAuthorizer authorizer = new AllowAllAuthorizer();
private static IRequestScheduler requestScheduler;
private static RequestSchedulerId requestSchedulerId;
private static RequestSchedulerOptions requestSchedulerOptions;
private static long keyCacheSizeInMB;
private static long counterCacheSizeInMB;
private static IAllocator memoryAllocator;
private static long indexSummaryCapacityInMB;
private static String localDC;
private static Comparator<InetAddress> localComparator;
static
{
// In client mode, we use a default configuration. Note that the fields of this class will be
// left unconfigured however (the partitioner or localDC will be null for instance) so this
// should be used with care.
try
{
if (Config.isClientMode())
{
conf = new Config();
// at least we have to set memoryAllocator to open SSTable in client mode
memoryAllocator = FBUtilities.newOffHeapAllocator(conf.memory_allocator);
}
else
{
applyConfig(loadConfig());
}
}
catch (ConfigurationException e)
{
logger.error("Fatal configuration error", e);
System.err.println(e.getMessage() + "\nFatal configuration error; unable to start. See log for stacktrace.");
System.exit(1);
}
catch (Exception e)
{
logger.error("Fatal error during configuration loading", e);
System.err.println(e.getMessage() + "\nFatal error during configuration loading; unable to start. See log for stacktrace.");
JVMStabilityInspector.inspectThrowable(e);
System.exit(1);
}
}
@VisibleForTesting
public static Config loadConfig() throws ConfigurationException
{
String loaderClass = System.getProperty("cassandra.config.loader");
ConfigurationLoader loader = loaderClass == null
? new YamlConfigurationLoader()
: FBUtilities.<ConfigurationLoader>construct(loaderClass, "configuration loading");
return loader.loadConfig();
}
private static InetAddress getNetworkInterfaceAddress(String intf, String configName, boolean preferIPv6) throws ConfigurationException
{
try
{
NetworkInterface ni = NetworkInterface.getByName(intf);
if (ni == null)
throw new ConfigurationException("Configured " + configName + " \"" + intf + "\" could not be found");
Enumeration<InetAddress> addrs = ni.getInetAddresses();
if (!addrs.hasMoreElements())
throw new ConfigurationException("Configured " + configName + " \"" + intf + "\" was found, but had no addresses");
/*
* Try to return the first address of the preferred type, otherwise return the first address
*/
InetAddress retval = null;
while (addrs.hasMoreElements())
{
InetAddress temp = addrs.nextElement();
if (preferIPv6 && temp.getClass() == Inet6Address.class) return temp;
if (!preferIPv6 && temp.getClass() == Inet4Address.class) return temp;
if (retval == null) retval = temp;
}
return retval;
}
catch (SocketException e)
{
throw new ConfigurationException("Configured " + configName + " \"" + intf + "\" caused an exception", e);
}
}
@VisibleForTesting
static void applyAddressConfig(Config config) throws ConfigurationException
{
listenAddress = null;
rpcAddress = null;
broadcastAddress = null;
broadcastRpcAddress = null;
/* Local IP, hostname or interface to bind services to */
if (config.listen_address != null && config.listen_interface != null)
{
throw new ConfigurationException("Set listen_address OR listen_interface, not both");
}
else if (config.listen_address != null)
{
try
{
listenAddress = InetAddress.getByName(config.listen_address);
}
catch (UnknownHostException e)
{
throw new ConfigurationException("Unknown listen_address '" + config.listen_address + "'");
}
if (listenAddress.isAnyLocalAddress())
throw new ConfigurationException("listen_address cannot be a wildcard address (" + config.listen_address + ")!");
}
else if (config.listen_interface != null)
{
listenAddress = getNetworkInterfaceAddress(config.listen_interface, "listen_interface", config.listen_interface_prefer_ipv6);
}
/* Gossip Address to broadcast */
if (config.broadcast_address != null)
{
try
{
broadcastAddress = InetAddress.getByName(config.broadcast_address);
}
catch (UnknownHostException e)
{
throw new ConfigurationException("Unknown broadcast_address '" + config.broadcast_address + "'");
}
if (broadcastAddress.isAnyLocalAddress())
throw new ConfigurationException("broadcast_address cannot be a wildcard address (" + config.broadcast_address + ")!");
}
/* Local IP, hostname or interface to bind RPC server to */
if (config.rpc_address != null && config.rpc_interface != null)
{
throw new ConfigurationException("Set rpc_address OR rpc_interface, not both");
}
else if (config.rpc_address != null)
{
try
{
rpcAddress = InetAddress.getByName(config.rpc_address);
}
catch (UnknownHostException e)
{
throw new ConfigurationException("Unknown host in rpc_address " + config.rpc_address);
}
}
else if (config.rpc_interface != null)
{
rpcAddress = getNetworkInterfaceAddress(config.rpc_interface, "rpc_interface", config.rpc_interface_prefer_ipv6);
}
else
{
rpcAddress = FBUtilities.getLocalAddress();
}
/* RPC address to broadcast */
if (config.broadcast_rpc_address != null)
{
try
{
broadcastRpcAddress = InetAddress.getByName(config.broadcast_rpc_address);
}
catch (UnknownHostException e)
{
throw new ConfigurationException("Unknown broadcast_rpc_address '" + config.broadcast_rpc_address + "'");
}
if (broadcastRpcAddress.isAnyLocalAddress())
throw new ConfigurationException("broadcast_rpc_address cannot be a wildcard address (" + config.broadcast_rpc_address + ")!");
}
else
{
if (rpcAddress.isAnyLocalAddress())
throw new ConfigurationException("If rpc_address is set to a wildcard address (" + config.rpc_address + "), then " +
"you must set broadcast_rpc_address to a value other than " + config.rpc_address);
broadcastRpcAddress = rpcAddress;
}
}
private static void applyConfig(Config config) throws ConfigurationException
{
conf = config;
if (conf.commitlog_sync == null)
{
throw new ConfigurationException("Missing required directive CommitLogSync");
}
if (conf.commitlog_sync == Config.CommitLogSync.batch)
{
if (conf.commitlog_sync_batch_window_in_ms == null)
{
throw new ConfigurationException("Missing value for commitlog_sync_batch_window_in_ms: Double expected.");
}
else if (conf.commitlog_sync_period_in_ms != null)
{
throw new ConfigurationException("Batch sync specified, but commitlog_sync_period_in_ms found. Only specify commitlog_sync_batch_window_in_ms when using batch sync");
}
logger.debug("Syncing log with a batch window of {}", conf.commitlog_sync_batch_window_in_ms);
}
else
{
if (conf.commitlog_sync_period_in_ms == null)
{
throw new ConfigurationException("Missing value for commitlog_sync_period_in_ms: Integer expected");
}
else if (conf.commitlog_sync_batch_window_in_ms != null)
{
throw new ConfigurationException("commitlog_sync_period_in_ms specified, but commitlog_sync_batch_window_in_ms found. Only specify commitlog_sync_period_in_ms when using periodic sync.");
}
logger.debug("Syncing log with a period of {}", conf.commitlog_sync_period_in_ms);
}
if (conf.commitlog_total_space_in_mb == null)
conf.commitlog_total_space_in_mb = hasLargeAddressSpace() ? 8192 : 32;
// Always force standard mode access on Windows - CASSANDRA-6993. Windows won't allow deletion of hard-links to files that
// are memory-mapped which causes trouble with snapshots.
if (FBUtilities.isWindows())
{
conf.disk_access_mode = Config.DiskAccessMode.standard;
indexAccessMode = conf.disk_access_mode;
logger.info("Windows environment detected. DiskAccessMode set to {}, indexAccessMode {}", conf.disk_access_mode, indexAccessMode);
}
else
{
/* evaluate the DiskAccessMode Config directive, which also affects indexAccessMode selection */
if (conf.disk_access_mode == Config.DiskAccessMode.auto)
{
conf.disk_access_mode = hasLargeAddressSpace() ? Config.DiskAccessMode.mmap : Config.DiskAccessMode.standard;
indexAccessMode = conf.disk_access_mode;
logger.info("DiskAccessMode 'auto' determined to be {}, indexAccessMode is {}", conf.disk_access_mode, indexAccessMode);
}
else if (conf.disk_access_mode == Config.DiskAccessMode.mmap_index_only)
{
conf.disk_access_mode = Config.DiskAccessMode.standard;
indexAccessMode = Config.DiskAccessMode.mmap;
logger.info("DiskAccessMode is {}, indexAccessMode is {}", conf.disk_access_mode, indexAccessMode);
}
else
{
indexAccessMode = conf.disk_access_mode;
logger.info("DiskAccessMode is {}, indexAccessMode is {}", conf.disk_access_mode, indexAccessMode);
}
}
/* Authentication and authorization backend, implementing IAuthenticator and IAuthorizer */
if (conf.authenticator != null)
authenticator = FBUtilities.newAuthenticator(conf.authenticator);
if (conf.authorizer != null)
authorizer = FBUtilities.newAuthorizer(conf.authorizer);
if (authenticator instanceof AllowAllAuthenticator && !(authorizer instanceof AllowAllAuthorizer))
throw new ConfigurationException("AllowAllAuthenticator can't be used with " + conf.authorizer);
if (conf.internode_authenticator != null)
internodeAuthenticator = FBUtilities.construct(conf.internode_authenticator, "internode_authenticator");
else
internodeAuthenticator = new AllowAllInternodeAuthenticator();
authenticator.validateConfiguration();
authorizer.validateConfiguration();
internodeAuthenticator.validateConfiguration();
/* Hashing strategy */
if (conf.partitioner == null)
{
throw new ConfigurationException("Missing directive: partitioner");
}
try
{
partitioner = FBUtilities.newPartitioner(System.getProperty("cassandra.partitioner", conf.partitioner));
}
catch (Exception e)
{
throw new ConfigurationException("Invalid partitioner class " + conf.partitioner);
}
paritionerName = partitioner.getClass().getCanonicalName();
if (conf.gc_warn_threshold_in_ms < 0)
{
throw new ConfigurationException("gc_warn_threshold_in_ms must be a positive integer");
}
if (conf.max_hint_window_in_ms == null)
{
throw new ConfigurationException("max_hint_window_in_ms cannot be set to null");
}
/* phi convict threshold for FailureDetector */
if (conf.phi_convict_threshold < 5 || conf.phi_convict_threshold > 16)
{
throw new ConfigurationException("phi_convict_threshold must be between 5 and 16");
}
/* Thread per pool */
if (conf.concurrent_reads != null && conf.concurrent_reads < 2)
{
throw new ConfigurationException("concurrent_reads must be at least 2");
}
if (conf.concurrent_writes != null && conf.concurrent_writes < 2)
{
throw new ConfigurationException("concurrent_writes must be at least 2");
}
if (conf.concurrent_counter_writes != null && conf.concurrent_counter_writes < 2)
throw new ConfigurationException("concurrent_counter_writes must be at least 2");
if (conf.concurrent_replicates != null)
logger.warn("concurrent_replicates has been deprecated and should be removed from cassandra.yaml");
if (conf.file_cache_size_in_mb == null)
conf.file_cache_size_in_mb = Math.min(512, (int) (Runtime.getRuntime().maxMemory() / (4 * 1048576)));
if (conf.memtable_offheap_space_in_mb == null)
conf.memtable_offheap_space_in_mb = (int) (Runtime.getRuntime().maxMemory() / (4 * 1048576));
if (conf.memtable_offheap_space_in_mb < 0)
throw new ConfigurationException("memtable_offheap_space_in_mb must be positive");
// for the moment, we default to twice as much on-heap space as off-heap, as heap overhead is very large
if (conf.memtable_heap_space_in_mb == null)
conf.memtable_heap_space_in_mb = (int) (Runtime.getRuntime().maxMemory() / (4 * 1048576));
if (conf.memtable_heap_space_in_mb <= 0)
throw new ConfigurationException("memtable_heap_space_in_mb must be positive");
logger.info("Global memtable on-heap threshold is enabled at {}MB", conf.memtable_heap_space_in_mb);
if (conf.memtable_offheap_space_in_mb == 0)
logger.info("Global memtable off-heap threshold is disabled, HeapAllocator will be used instead");
else
logger.info("Global memtable off-heap threshold is enabled at {}MB", conf.memtable_offheap_space_in_mb);
applyAddressConfig(config);
if (conf.thrift_framed_transport_size_in_mb <= 0)
throw new ConfigurationException("thrift_framed_transport_size_in_mb must be positive");
if (conf.native_transport_max_frame_size_in_mb <= 0)
throw new ConfigurationException("native_transport_max_frame_size_in_mb must be positive");
// fail early instead of OOMing (see CASSANDRA-8116)
if (ThriftServer.HSHA.equals(conf.rpc_server_type) && conf.rpc_max_threads == Integer.MAX_VALUE)
throw new ConfigurationException("The hsha rpc_server_type is not compatible with an rpc_max_threads " +
"setting of 'unlimited'. Please see the comments in cassandra.yaml " +
"for rpc_server_type and rpc_max_threads.");
if (ThriftServer.HSHA.equals(conf.rpc_server_type) && conf.rpc_max_threads > (FBUtilities.getAvailableProcessors() * 2 + 1024))
logger.warn("rpc_max_threads setting of {} may be too high for the hsha server and cause unnecessary thread contention, reducing performance", conf.rpc_max_threads);
/* end point snitch */
if (conf.endpoint_snitch == null)
{
throw new ConfigurationException("Missing endpoint_snitch directive");
}
snitch = createEndpointSnitch(conf.endpoint_snitch);
EndpointSnitchInfo.create();
localDC = snitch.getDatacenter(FBUtilities.getBroadcastAddress());
localComparator = new Comparator<InetAddress>()
{
public int compare(InetAddress endpoint1, InetAddress endpoint2)
{
boolean local1 = localDC.equals(snitch.getDatacenter(endpoint1));
boolean local2 = localDC.equals(snitch.getDatacenter(endpoint2));
if (local1 && !local2)
return -1;
if (local2 && !local1)
return 1;
return 0;
}
};
/* Request Scheduler setup */
requestSchedulerOptions = conf.request_scheduler_options;
if (conf.request_scheduler != null)
{
try
{
if (requestSchedulerOptions == null)
{
requestSchedulerOptions = new RequestSchedulerOptions();
}
Class<?> cls = Class.forName(conf.request_scheduler);
requestScheduler = (IRequestScheduler) cls.getConstructor(RequestSchedulerOptions.class).newInstance(requestSchedulerOptions);
}
catch (ClassNotFoundException e)
{
throw new ConfigurationException("Invalid Request Scheduler class " + conf.request_scheduler);
}
catch (Exception e)
{
throw new ConfigurationException("Unable to instantiate request scheduler", e);
}
}
else
{
requestScheduler = new NoScheduler();
}
if (conf.request_scheduler_id == RequestSchedulerId.keyspace)
{
requestSchedulerId = conf.request_scheduler_id;
}
else
{
// Default to Keyspace
requestSchedulerId = RequestSchedulerId.keyspace;
}
// if data dirs, commitlog dir, or saved caches dir are set in cassandra.yaml, use that. Otherwise,
// use -Dcassandra.storagedir (set in cassandra-env.sh) as the parent dir for data/, commitlog/, and saved_caches/
if (conf.commitlog_directory == null)
{
conf.commitlog_directory = System.getProperty("cassandra.storagedir", null);
if (conf.commitlog_directory == null)
throw new ConfigurationException("commitlog_directory is missing and -Dcassandra.storagedir is not set");
conf.commitlog_directory += File.separator + "commitlog";
}
if (conf.saved_caches_directory == null)
{
conf.saved_caches_directory = System.getProperty("cassandra.storagedir", null);
if (conf.saved_caches_directory == null)
throw new ConfigurationException("saved_caches_directory is missing and -Dcassandra.storagedir is not set");
conf.saved_caches_directory += File.separator + "saved_caches";
}
if (conf.data_file_directories == null)
{
String defaultDataDir = System.getProperty("cassandra.storagedir", null);
if (defaultDataDir == null)
throw new ConfigurationException("data_file_directories is not missing and -Dcassandra.storagedir is not set");
conf.data_file_directories = new String[]{ defaultDataDir + File.separator + "data" };
}
/* data file and commit log directories. they get created later, when they're needed. */
for (String datadir : conf.data_file_directories)
{
if (datadir.equals(conf.commitlog_directory))
throw new ConfigurationException("commitlog_directory must not be the same as any data_file_directories");
if (datadir.equals(conf.saved_caches_directory))
throw new ConfigurationException("saved_caches_directory must not be the same as any data_file_directories");
}
if (conf.commitlog_directory.equals(conf.saved_caches_directory))
throw new ConfigurationException("saved_caches_directory must not be the same as the commitlog_directory");
if (conf.memtable_flush_writers == null)
conf.memtable_flush_writers = Math.min(8, Math.max(2, Math.min(FBUtilities.getAvailableProcessors(), conf.data_file_directories.length)));
if (conf.memtable_flush_writers < 1)
throw new ConfigurationException("memtable_flush_writers must be at least 1");
if (conf.memtable_cleanup_threshold == null)
conf.memtable_cleanup_threshold = (float) (1.0 / (1 + conf.memtable_flush_writers));
if (conf.memtable_cleanup_threshold < 0.01f)
throw new ConfigurationException("memtable_cleanup_threshold must be >= 0.01");
if (conf.memtable_cleanup_threshold > 0.99f)
throw new ConfigurationException("memtable_cleanup_threshold must be <= 0.99");
if (conf.memtable_cleanup_threshold < 0.1f)
logger.warn("memtable_cleanup_threshold is set very low, which may cause performance degradation");
if (conf.concurrent_compactors == null)
conf.concurrent_compactors = Math.min(8, Math.max(2, Math.min(FBUtilities.getAvailableProcessors(), conf.data_file_directories.length)));
if (conf.concurrent_compactors <= 0)
throw new ConfigurationException("concurrent_compactors should be strictly greater than 0");
if (conf.initial_token != null)
for (String token : tokensFromString(conf.initial_token))
partitioner.getTokenFactory().validate(token);
if (conf.num_tokens == null)
conf.num_tokens = 1;
else if (conf.num_tokens > MAX_NUM_TOKENS)
throw new ConfigurationException(String.format("A maximum number of %d tokens per node is supported", MAX_NUM_TOKENS));
try
{
// if key_cache_size_in_mb option was set to "auto" then size of the cache should be "min(5% of Heap (in MB), 100MB)
keyCacheSizeInMB = (conf.key_cache_size_in_mb == null)
? Math.min(Math.max(1, (int) (Runtime.getRuntime().totalMemory() * 0.05 / 1024 / 1024)), 100)
: conf.key_cache_size_in_mb;
if (keyCacheSizeInMB < 0)
throw new NumberFormatException(); // to escape duplicating error message
}
catch (NumberFormatException e)
{
throw new ConfigurationException("key_cache_size_in_mb option was set incorrectly to '"
+ conf.key_cache_size_in_mb + "', supported values are <integer> >= 0.");
}
try
{
// if counter_cache_size_in_mb option was set to "auto" then size of the cache should be "min(2.5% of Heap (in MB), 50MB)
counterCacheSizeInMB = (conf.counter_cache_size_in_mb == null)
? Math.min(Math.max(1, (int) (Runtime.getRuntime().totalMemory() * 0.025 / 1024 / 1024)), 50)
: conf.counter_cache_size_in_mb;
if (counterCacheSizeInMB < 0)
throw new NumberFormatException(); // to escape duplicating error message
}
catch (NumberFormatException e)
{
throw new ConfigurationException("counter_cache_size_in_mb option was set incorrectly to '"
+ conf.counter_cache_size_in_mb + "', supported values are <integer> >= 0.");
}
// if set to empty/"auto" then use 5% of Heap size
indexSummaryCapacityInMB = (conf.index_summary_capacity_in_mb == null)
? Math.max(1, (int) (Runtime.getRuntime().totalMemory() * 0.05 / 1024 / 1024))
: conf.index_summary_capacity_in_mb;
if (indexSummaryCapacityInMB < 0)
throw new ConfigurationException("index_summary_capacity_in_mb option was set incorrectly to '"
+ conf.index_summary_capacity_in_mb + "', it should be a non-negative integer.");
memoryAllocator = FBUtilities.newOffHeapAllocator(conf.memory_allocator);
if(conf.encryption_options != null)
{
logger.warn("Please rename encryption_options as server_encryption_options in the yaml");
//operate under the assumption that server_encryption_options is not set in yaml rather than both
conf.server_encryption_options = conf.encryption_options;
}
// Hardcoded system keyspaces
List<KSMetaData> systemKeyspaces = Arrays.asList(KSMetaData.systemKeyspace());
assert systemKeyspaces.size() == Schema.systemKeyspaceNames.size();
for (KSMetaData ksmd : systemKeyspaces)
Schema.instance.load(ksmd);
/* Load the seeds for node contact points */
if (conf.seed_provider == null)
{
throw new ConfigurationException("seeds configuration is missing; a minimum of one seed is required.");
}
try
{
Class<?> seedProviderClass = Class.forName(conf.seed_provider.class_name);
seedProvider = (SeedProvider)seedProviderClass.getConstructor(Map.class).newInstance(conf.seed_provider.parameters);
}
// there are about 5 checked exceptions that could be thrown here.
catch (Exception e)
{
logger.error("Fatal configuration error", e);
System.err.println(e.getMessage() + "\nFatal configuration error; unable to start server. See log for stacktrace.");
System.exit(1);
}
if (seedProvider.getSeeds().size() == 0)
throw new ConfigurationException("The seed provider lists no seeds.");
}
private static IEndpointSnitch createEndpointSnitch(String snitchClassName) throws ConfigurationException
{
if (!snitchClassName.contains("."))
snitchClassName = "org.apache.cassandra.locator." + snitchClassName;
IEndpointSnitch snitch = FBUtilities.construct(snitchClassName, "snitch");
return conf.dynamic_snitch ? new DynamicEndpointSnitch(snitch) : snitch;
}
/**
* load keyspace (keyspace) definitions, but do not initialize the keyspace instances.
* Schema version may be updated as the result.
*/
public static void loadSchemas()
{
loadSchemas(true);
}
/**
* Load schema definitions.
*
* @param updateVersion true if schema version needs to be updated
*/
public static void loadSchemas(boolean updateVersion)
{
ColumnFamilyStore schemaCFS = SystemKeyspace.schemaCFS(SystemKeyspace.SCHEMA_KEYSPACES_CF);
// if keyspace with definitions is empty try loading the old way
if (schemaCFS.estimateKeys() == 0)
{
logger.info("Couldn't detect any schema definitions in local storage.");
// peek around the data directories to see if anything is there.
if (hasExistingNoSystemTables())
logger.info("Found keyspace data in data directories. Consider using cqlsh to define your schema.");
else
logger.info("To create keyspaces and column families, see 'help create' in cqlsh.");
}
else
{
Schema.instance.load(DefsTables.loadFromKeyspace());
}
if (updateVersion)
Schema.instance.updateVersion();
}
private static boolean hasExistingNoSystemTables()
{
for (String dataDir : getAllDataFileLocations())
{
File dataPath = new File(dataDir);
if (dataPath.exists() && dataPath.isDirectory())
{
// see if there are other directories present.
int dirCount = dataPath.listFiles(new FileFilter()
{
public boolean accept(File pathname)
{
return (pathname.isDirectory() && !Schema.systemKeyspaceNames.contains(pathname.getName()));
}
}).length;
if (dirCount > 0)
return true;
}
}
return false;
}
public static IAuthenticator getAuthenticator()
{
return authenticator;
}
public static IAuthorizer getAuthorizer()
{
return authorizer;
}
public static int getPermissionsValidity()
{
return conf.permissions_validity_in_ms;
}
public static void setPermissionsValidity(int timeout)
{
conf.permissions_validity_in_ms = timeout;
}
public static int getPermissionsCacheMaxEntries()
{
return conf.permissions_cache_max_entries;
}
public static int getPermissionsUpdateInterval()
{
return conf.permissions_update_interval_in_ms == -1
? conf.permissions_validity_in_ms
: conf.permissions_update_interval_in_ms;
}
public static void setPermissionsUpdateInterval(int updateInterval)
{
conf.permissions_update_interval_in_ms = updateInterval;
}
public static int getThriftFramedTransportSize()
{
return conf.thrift_framed_transport_size_in_mb * 1024 * 1024;
}
/**
* Creates all storage-related directories.
*/
public static void createAllDirectories()
{
try
{
if (conf.data_file_directories.length == 0)
throw new ConfigurationException("At least one DataFileDirectory must be specified");
for (String dataFileDirectory : conf.data_file_directories)
{
FileUtils.createDirectory(dataFileDirectory);
}
if (conf.commitlog_directory == null)
throw new ConfigurationException("commitlog_directory must be specified");
FileUtils.createDirectory(conf.commitlog_directory);
if (conf.saved_caches_directory == null)
throw new ConfigurationException("saved_caches_directory must be specified");
FileUtils.createDirectory(conf.saved_caches_directory);
}
catch (ConfigurationException e)
{
logger.error("Fatal error: {}", e.getMessage());
System.err.println("Bad configuration; unable to start server");
System.exit(1);
}
catch (FSWriteError e)
{
logger.error("Fatal error: {}", e.getMessage());
System.err.println(e.getCause().getMessage() + "; unable to start server");
System.exit(1);
}
}
public static IPartitioner getPartitioner()
{
return partitioner;
}
public static String getPartitionerName()
{
return paritionerName;
}
/* For tests ONLY, don't use otherwise or all hell will break loose */
public static void setPartitioner(IPartitioner newPartitioner)
{
partitioner = newPartitioner;
}
public static IEndpointSnitch getEndpointSnitch()
{
return snitch;
}
public static void setEndpointSnitch(IEndpointSnitch eps)
{
snitch = eps;
}
public static IRequestScheduler getRequestScheduler()
{
return requestScheduler;
}
public static RequestSchedulerOptions getRequestSchedulerOptions()
{
return requestSchedulerOptions;
}
public static RequestSchedulerId getRequestSchedulerId()
{
return requestSchedulerId;
}
public static int getColumnIndexSize()
{
return conf.column_index_size_in_kb * 1024;
}
public static int getBatchSizeWarnThreshold()
{
return conf.batch_size_warn_threshold_in_kb * 1024;
}
public static Collection<String> getInitialTokens()
{
return tokensFromString(System.getProperty("cassandra.initial_token", conf.initial_token));
}
public static Collection<String> tokensFromString(String tokenString)
{
List<String> tokens = new ArrayList<String>();
if (tokenString != null)
for (String token : tokenString.split(","))
tokens.add(token.replaceAll("^\\s+", "").replaceAll("\\s+$", ""));
return tokens;
}
public static Integer getNumTokens()
{
return conf.num_tokens;
}
public static InetAddress getReplaceAddress()
{
try
{
if (System.getProperty("cassandra.replace_address", null) != null)
return InetAddress.getByName(System.getProperty("cassandra.replace_address", null));
else if (System.getProperty("cassandra.replace_address_first_boot", null) != null)
return InetAddress.getByName(System.getProperty("cassandra.replace_address_first_boot", null));
return null;
}
catch (UnknownHostException e)
{
return null;
}
}
public static Collection<String> getReplaceTokens()
{
return tokensFromString(System.getProperty("cassandra.replace_token", null));
}
public static UUID getReplaceNode()
{
try
{
return UUID.fromString(System.getProperty("cassandra.replace_node", null));
} catch (NullPointerException e)
{
return null;
}
}
public static boolean isReplacing()
{
if (System.getProperty("cassandra.replace_address_first_boot", null) != null && SystemKeyspace.bootstrapComplete())
{
logger.info("Replace address on first boot requested; this node is already bootstrapped");
return false;
}
return getReplaceAddress() != null;
}
public static String getClusterName()
{
return conf.cluster_name;
}
public static int getMaxStreamingRetries()
{
return conf.max_streaming_retries;
}
public static int getStoragePort()
{
return Integer.parseInt(System.getProperty("cassandra.storage_port", conf.storage_port.toString()));
}
public static int getSSLStoragePort()
{
return Integer.parseInt(System.getProperty("cassandra.ssl_storage_port", conf.ssl_storage_port.toString()));
}
public static int getRpcPort()
{
return Integer.parseInt(System.getProperty("cassandra.rpc_port", conf.rpc_port.toString()));
}
public static int getRpcListenBacklog()
{
return conf.rpc_listen_backlog;
}
public static long getRpcTimeout()
{
return conf.request_timeout_in_ms;
}
public static void setRpcTimeout(Long timeOutInMillis)
{
conf.request_timeout_in_ms = timeOutInMillis;
}
public static long getReadRpcTimeout()
{
return conf.read_request_timeout_in_ms;
}
public static void setReadRpcTimeout(Long timeOutInMillis)
{
conf.read_request_timeout_in_ms = timeOutInMillis;
}
public static long getRangeRpcTimeout()
{
return conf.range_request_timeout_in_ms;
}
public static void setRangeRpcTimeout(Long timeOutInMillis)
{
conf.range_request_timeout_in_ms = timeOutInMillis;
}
public static long getWriteRpcTimeout()
{
return conf.write_request_timeout_in_ms;
}
public static void setWriteRpcTimeout(Long timeOutInMillis)
{
conf.write_request_timeout_in_ms = timeOutInMillis;
}
public static long getCounterWriteRpcTimeout()
{
return conf.counter_write_request_timeout_in_ms;
}
public static void setCounterWriteRpcTimeout(Long timeOutInMillis)
{
conf.counter_write_request_timeout_in_ms = timeOutInMillis;
}
public static long getCasContentionTimeout()
{
return conf.cas_contention_timeout_in_ms;
}
public static void setCasContentionTimeout(Long timeOutInMillis)
{
conf.cas_contention_timeout_in_ms = timeOutInMillis;
}
public static long getTruncateRpcTimeout()
{
return conf.truncate_request_timeout_in_ms;
}
public static void setTruncateRpcTimeout(Long timeOutInMillis)
{
conf.truncate_request_timeout_in_ms = timeOutInMillis;
}
public static boolean hasCrossNodeTimeout()
{
return conf.cross_node_timeout;
}
// not part of the Verb enum so we can change timeouts easily via JMX
public static long getTimeout(MessagingService.Verb verb)
{
switch (verb)
{
case READ:
return getReadRpcTimeout();
case RANGE_SLICE:
return getRangeRpcTimeout();
case TRUNCATE:
return getTruncateRpcTimeout();
case READ_REPAIR:
case MUTATION:
case PAXOS_COMMIT:
case PAXOS_PREPARE:
case PAXOS_PROPOSE:
return getWriteRpcTimeout();
case COUNTER_MUTATION:
return getCounterWriteRpcTimeout();
default:
return getRpcTimeout();
}
}
/**
* @return the minimum configured {read, write, range, truncate, misc} timeout
*/
public static long getMinRpcTimeout()
{
return Longs.min(getRpcTimeout(),
getReadRpcTimeout(),
getRangeRpcTimeout(),
getWriteRpcTimeout(),
getCounterWriteRpcTimeout(),
getTruncateRpcTimeout());
}
public static double getPhiConvictThreshold()
{
return conf.phi_convict_threshold;
}
public static void setPhiConvictThreshold(double phiConvictThreshold)
{
conf.phi_convict_threshold = phiConvictThreshold;
}
public static int getConcurrentReaders()
{
return conf.concurrent_reads;
}
public static int getConcurrentWriters()
{
return conf.concurrent_writes;
}
public static int getConcurrentCounterWriters()
{
return conf.concurrent_counter_writes;
}
public static int getFlushWriters()
{
return conf.memtable_flush_writers;
}
public static int getConcurrentCompactors()
{
return conf.concurrent_compactors;
}
public static int getCompactionThroughputMbPerSec()
{
return conf.compaction_throughput_mb_per_sec;
}
public static void setCompactionThroughputMbPerSec(int value)
{
conf.compaction_throughput_mb_per_sec = value;
}
public static int getCompactionLargePartitionWarningThreshold() { return conf.compaction_large_partition_warning_threshold_mb * 1024 * 1024; }
public static boolean getDisableSTCSInL0()
{
return Boolean.getBoolean("cassandra.disable_stcs_in_l0");
}
public static int getStreamThroughputOutboundMegabitsPerSec()
{
return conf.stream_throughput_outbound_megabits_per_sec;
}
public static void setStreamThroughputOutboundMegabitsPerSec(int value)
{
conf.stream_throughput_outbound_megabits_per_sec = value;
}
public static int getInterDCStreamThroughputOutboundMegabitsPerSec()
{
return conf.inter_dc_stream_throughput_outbound_megabits_per_sec;
}
public static void setInterDCStreamThroughputOutboundMegabitsPerSec(int value)
{
conf.inter_dc_stream_throughput_outbound_megabits_per_sec = value;
}
public static String[] getAllDataFileLocations()
{
return conf.data_file_directories;
}
public static String getCommitLogLocation()
{
return conf.commitlog_directory;
}
public static int getTombstoneWarnThreshold()
{
return conf.tombstone_warn_threshold;
}
public static void setTombstoneWarnThreshold(int threshold)
{
conf.tombstone_warn_threshold = threshold;
}
public static int getTombstoneFailureThreshold()
{
return conf.tombstone_failure_threshold;
}
public static void setTombstoneFailureThreshold(int threshold)
{
conf.tombstone_failure_threshold = threshold;
}
public static boolean getCommitLogSegmentRecyclingEnabled()
{
return conf.commitlog_segment_recycling;
}
/**
* size of commitlog segments to allocate
*/
public static int getCommitLogSegmentSize()
{
return conf.commitlog_segment_size_in_mb * 1024 * 1024;
}
public static String getSavedCachesLocation()
{
return conf.saved_caches_directory;
}
public static Set<InetAddress> getSeeds()
{
return ImmutableSet.<InetAddress>builder().addAll(seedProvider.getSeeds()).build();
}
public static InetAddress getListenAddress()
{
return listenAddress;
}
public static InetAddress getBroadcastAddress()
{
return broadcastAddress;
}
public static IInternodeAuthenticator getInternodeAuthenticator()
{
return internodeAuthenticator;
}
public static void setBroadcastAddress(InetAddress broadcastAdd)
{
broadcastAddress = broadcastAdd;
}
public static boolean startRpc()
{
return conf.start_rpc;
}
public static InetAddress getRpcAddress()
{
return rpcAddress;
}
public static void setBroadcastRpcAddress(InetAddress broadcastRPCAddr)
{
broadcastRpcAddress = broadcastRPCAddr;
}
public static InetAddress getBroadcastRpcAddress()
{
return broadcastRpcAddress;
}
public static String getRpcServerType()
{
return conf.rpc_server_type;
}
public static boolean getRpcKeepAlive()
{
return conf.rpc_keepalive;
}
public static Integer getRpcMinThreads()
{
return conf.rpc_min_threads;
}
public static Integer getRpcMaxThreads()
{
return conf.rpc_max_threads;
}
public static Integer getRpcSendBufferSize()
{
return conf.rpc_send_buff_size_in_bytes;
}
public static Integer getRpcRecvBufferSize()
{
return conf.rpc_recv_buff_size_in_bytes;
}
public static Integer getInternodeSendBufferSize()
{
return conf.internode_send_buff_size_in_bytes;
}
public static Integer getInternodeRecvBufferSize()
{
return conf.internode_recv_buff_size_in_bytes;
}
public static boolean startNativeTransport()
{
return conf.start_native_transport;
}
public static int getNativeTransportPort()
{
return Integer.parseInt(System.getProperty("cassandra.native_transport_port", conf.native_transport_port.toString()));
}
public static Integer getNativeTransportMaxThreads()
{
return conf.native_transport_max_threads;
}
public static int getNativeTransportMaxFrameSize()
{
return conf.native_transport_max_frame_size_in_mb * 1024 * 1024;
}
public static Long getNativeTransportMaxConcurrentConnections()
{
return conf.native_transport_max_concurrent_connections;
}
public static void setNativeTransportMaxConcurrentConnections(long nativeTransportMaxConcurrentConnections)
{
conf.native_transport_max_concurrent_connections = nativeTransportMaxConcurrentConnections;
}
public static Long getNativeTransportMaxConcurrentConnectionsPerIp() {
return conf.native_transport_max_concurrent_connections_per_ip;
}
public static void setNativeTransportMaxConcurrentConnectionsPerIp(long native_transport_max_concurrent_connections_per_ip)
{
conf.native_transport_max_concurrent_connections_per_ip = native_transport_max_concurrent_connections_per_ip;
}
public static double getCommitLogSyncBatchWindow()
{
return conf.commitlog_sync_batch_window_in_ms;
}
public static int getCommitLogSyncPeriod()
{
return conf.commitlog_sync_period_in_ms;
}
public static int getCommitLogPeriodicQueueSize()
{
return conf.commitlog_periodic_queue_size;
}
public static Config.CommitLogSync getCommitLogSync()
{
return conf.commitlog_sync;
}
public static Config.DiskAccessMode getDiskAccessMode()
{
return conf.disk_access_mode;
}
public static Config.DiskAccessMode getIndexAccessMode()
{
return indexAccessMode;
}
public static void setDiskFailurePolicy(Config.DiskFailurePolicy policy)
{
conf.disk_failure_policy = policy;
}
public static Config.DiskFailurePolicy getDiskFailurePolicy()
{
return conf.disk_failure_policy;
}
public static void setCommitFailurePolicy(Config.CommitFailurePolicy policy)
{
conf.commit_failure_policy = policy;
}
public static Config.CommitFailurePolicy getCommitFailurePolicy()
{
return conf.commit_failure_policy;
}
public static boolean isSnapshotBeforeCompaction()
{
return conf.snapshot_before_compaction;
}
public static boolean isAutoSnapshot() {
return conf.auto_snapshot;
}
@VisibleForTesting
public static void setAutoSnapshot(boolean autoSnapshot) {
conf.auto_snapshot = autoSnapshot;
}
public static boolean isAutoBootstrap()
{
return Boolean.parseBoolean(System.getProperty("cassandra.auto_bootstrap", conf.auto_bootstrap.toString()));
}
public static void setHintedHandoffEnabled(boolean hintedHandoffEnabled)
{
conf.hinted_handoff_enabled_global = hintedHandoffEnabled;
conf.hinted_handoff_enabled_by_dc.clear();
}
public static void setHintedHandoffEnabled(final String dcNames)
{
List<String> dcNameList;
try
{
dcNameList = Config.parseHintedHandoffEnabledDCs(dcNames);
}
catch (IOException e)
{
throw new IllegalArgumentException("Could not read csv of dcs for hinted handoff enable. " + dcNames, e);
}
if (dcNameList.isEmpty())
throw new IllegalArgumentException("Empty list of Dcs for hinted handoff enable");
conf.hinted_handoff_enabled_by_dc.clear();
conf.hinted_handoff_enabled_by_dc.addAll(dcNameList);
}
public static boolean hintedHandoffEnabled()
{
return conf.hinted_handoff_enabled_global;
}
public static Set<String> hintedHandoffEnabledByDC()
{
return Collections.unmodifiableSet(conf.hinted_handoff_enabled_by_dc);
}
public static boolean shouldHintByDC()
{
return !conf.hinted_handoff_enabled_by_dc.isEmpty();
}
public static boolean hintedHandoffEnabled(final String dcName)
{
return conf.hinted_handoff_enabled_by_dc.contains(dcName);
}
public static void setMaxHintWindow(int ms)
{
conf.max_hint_window_in_ms = ms;
}
public static int getMaxHintWindow()
{
return conf.max_hint_window_in_ms;
}
@Deprecated
public static Integer getIndexInterval()
{
return conf.index_interval;
}
public static File getSerializedCachePath(CacheService.CacheType cacheType, String version)
{
String name = cacheType.toString()
+ (version == null ? "" : "-" + version + ".db");
return new File(conf.saved_caches_directory, name);
}
public static int getDynamicUpdateInterval()
{
return conf.dynamic_snitch_update_interval_in_ms;
}
public static void setDynamicUpdateInterval(Integer dynamicUpdateInterval)
{
conf.dynamic_snitch_update_interval_in_ms = dynamicUpdateInterval;
}
public static int getDynamicResetInterval()
{
return conf.dynamic_snitch_reset_interval_in_ms;
}
public static void setDynamicResetInterval(Integer dynamicResetInterval)
{
conf.dynamic_snitch_reset_interval_in_ms = dynamicResetInterval;
}
public static double getDynamicBadnessThreshold()
{
return conf.dynamic_snitch_badness_threshold;
}
public static void setDynamicBadnessThreshold(Double dynamicBadnessThreshold)
{
conf.dynamic_snitch_badness_threshold = dynamicBadnessThreshold;
}
public static ServerEncryptionOptions getServerEncryptionOptions()
{
return conf.server_encryption_options;
}
public static ClientEncryptionOptions getClientEncryptionOptions()
{
return conf.client_encryption_options;
}
public static int getHintedHandoffThrottleInKB()
{
return conf.hinted_handoff_throttle_in_kb;
}
public static int getBatchlogReplayThrottleInKB()
{
return conf.batchlog_replay_throttle_in_kb;
}
public static void setHintedHandoffThrottleInKB(Integer throttleInKB)
{
conf.hinted_handoff_throttle_in_kb = throttleInKB;
}
public static int getMaxHintsThread()
{
return conf.max_hints_delivery_threads;
}
public static boolean isIncrementalBackupsEnabled()
{
return conf.incremental_backups;
}
public static void setIncrementalBackupsEnabled(boolean value)
{
conf.incremental_backups = value;
}
public static int getFileCacheSizeInMB()
{
return conf.file_cache_size_in_mb;
}
public static long getTotalCommitlogSpaceInMB()
{
return conf.commitlog_total_space_in_mb;
}
public static int getSSTablePreempiveOpenIntervalInMB()
{
return conf.sstable_preemptive_open_interval_in_mb;
}
public static boolean getTrickleFsync()
{
return conf.trickle_fsync;
}
public static int getTrickleFsyncIntervalInKb()
{
return conf.trickle_fsync_interval_in_kb;
}
public static long getKeyCacheSizeInMB()
{
return keyCacheSizeInMB;
}
public static long getIndexSummaryCapacityInMB()
{
return indexSummaryCapacityInMB;
}
public static int getKeyCacheSavePeriod()
{
return conf.key_cache_save_period;
}
public static void setKeyCacheSavePeriod(int keyCacheSavePeriod)
{
conf.key_cache_save_period = keyCacheSavePeriod;
}
public static int getKeyCacheKeysToSave()
{
return conf.key_cache_keys_to_save;
}
public static void setKeyCacheKeysToSave(int keyCacheKeysToSave)
{
conf.key_cache_keys_to_save = keyCacheKeysToSave;
}
public static long getRowCacheSizeInMB()
{
return conf.row_cache_size_in_mb;
}
@VisibleForTesting
public static void setRowCacheSizeInMB(long val)
{
conf.row_cache_size_in_mb = val;
}
public static int getRowCacheSavePeriod()
{
return conf.row_cache_save_period;
}
public static void setRowCacheSavePeriod(int rowCacheSavePeriod)
{
conf.row_cache_save_period = rowCacheSavePeriod;
}
public static int getRowCacheKeysToSave()
{
return conf.row_cache_keys_to_save;
}
public static long getCounterCacheSizeInMB()
{
return counterCacheSizeInMB;
}
public static int getCounterCacheSavePeriod()
{
return conf.counter_cache_save_period;
}
public static void setCounterCacheSavePeriod(int counterCacheSavePeriod)
{
conf.counter_cache_save_period = counterCacheSavePeriod;
}
public static int getCounterCacheKeysToSave()
{
return conf.counter_cache_keys_to_save;
}
public static void setCounterCacheKeysToSave(int counterCacheKeysToSave)
{
conf.counter_cache_keys_to_save = counterCacheKeysToSave;
}
public static IAllocator getoffHeapMemoryAllocator()
{
return memoryAllocator;
}
public static void setRowCacheKeysToSave(int rowCacheKeysToSave)
{
conf.row_cache_keys_to_save = rowCacheKeysToSave;
}
public static int getStreamingSocketTimeout()
{
return conf.streaming_socket_timeout_in_ms;
}
public static String getLocalDataCenter()
{
return localDC;
}
public static Comparator<InetAddress> getLocalComparator()
{
return localComparator;
}
public static Config.InternodeCompression internodeCompression()
{
return conf.internode_compression;
}
public static boolean getInterDCTcpNoDelay()
{
return conf.inter_dc_tcp_nodelay;
}
public static MemtablePool getMemtableAllocatorPool()
{
long heapLimit = ((long) conf.memtable_heap_space_in_mb) << 20;
long offHeapLimit = ((long) conf.memtable_offheap_space_in_mb) << 20;
switch (conf.memtable_allocation_type)
{
case unslabbed_heap_buffers:
return new HeapPool(heapLimit, conf.memtable_cleanup_threshold, new ColumnFamilyStore.FlushLargestColumnFamily());
case heap_buffers:
return new SlabPool(heapLimit, 0, conf.memtable_cleanup_threshold, new ColumnFamilyStore.FlushLargestColumnFamily());
case offheap_buffers:
if (!FileUtils.isCleanerAvailable())
{
logger.error("Could not free direct byte buffer: offheap_buffers is not a safe memtable_allocation_type without this ability, please adjust your config. This feature is only guaranteed to work on an Oracle JVM. Refusing to start.");
System.exit(-1);
}
return new SlabPool(heapLimit, offHeapLimit, conf.memtable_cleanup_threshold, new ColumnFamilyStore.FlushLargestColumnFamily());
case offheap_objects:
return new NativePool(heapLimit, offHeapLimit, conf.memtable_cleanup_threshold, new ColumnFamilyStore.FlushLargestColumnFamily());
default:
throw new AssertionError();
}
}
public static int getIndexSummaryResizeIntervalInMinutes()
{
return conf.index_summary_resize_interval_in_minutes;
}
public static boolean hasLargeAddressSpace()
{
// currently we just check if it's a 64bit arch, but any we only really care if the address space is large
String datamodel = System.getProperty("sun.arch.data.model");
if (datamodel != null)
{
switch (datamodel)
{
case "64": return true;
case "32": return false;
}
}
String arch = System.getProperty("os.arch");
return arch.contains("64") || arch.contains("sparcv9");
}
public static String getOtcCoalescingStrategy()
{
return conf.otc_coalescing_strategy;
}
public static int getOtcCoalescingWindow()
{
return conf.otc_coalescing_window_us;
}
public static long getGCWarnThreshold()
{
return conf.gc_warn_threshold_in_ms;
}
}
| apache-2.0 |
skyofthinking/AndRapid | sample/src/main/java/com/joyue/tech/sample/MainActivity.java | 3451 | package com.joyue.tech.sample;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG).setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
| apache-2.0 |
c0deb0y/windmill | src/com/prezerak/windmill/main/WindMill.java | 5059 |
package com.prezerak.windmill.main;
import java.awt.EventQueue;
import java.awt.Font;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Locale;
import java.util.Properties;
import java.util.TimeZone;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.RollingFileAppender;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import com.prezerak.windmill.derby.WindDB;
import com.prezerak.windmill.gui.MainFrame;
import com.prezerak.windmill.model.Anemometer;
import com.prezerak.windmill.util.MySimpleLayout;
import com.prezerak.windmill.util.Utilities;
public class WindMill {
final public static String FILE_SEPARATOR = System.getProperty("file.separator");
final public static String APPHOME = System.getProperty("user.home")+FILE_SEPARATOR+"WindMill_GH_Runnable"+System.getProperty("file.separator");
final public static String DBPATH = APPHOME+"WindDB";
final private static String LOGGERPATH = APPHOME+"logs"+FILE_SEPARATOR+"windmill.log";
final public static String INIPATH = APPHOME+FILE_SEPARATOR+"windmill.ini";
public static MainFrame mainFrame;
public static Anemometer anemometer = null;
final public static float KNOTS_TO_METERS_CONV_FACTOR = 0.51444f;
final public static float MILES_PER_HR_TO_METERS_CONV_FACTOR = 0.44704f;
public static final float KM_PER_HR_TO_METERS_CONV_FACTOR = 1000/3600.0f;
public static long appStartTime;
public static Properties propertyFile=null;
public static final String VERSION = "GitHub";
public static final Logger logger = Logger.getLogger(WindMill.class);
public static WindDB database = null;
/**
* Launch the application.
*/
public static void main(String[] args) {
//Set ENGLISH locale so that time/date uses this format
Locale.setDefault(Locale.ENGLISH);
//Always use GMT
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
//set the logger level programmatically
final MySimpleLayout msl = new MySimpleLayout();
try {
logger.addAppender(new RollingFileAppender(msl,LOGGERPATH, true));
} catch (IOException e) {
logger.addAppender(new ConsoleAppender());
}
logger.setLevel(Level.INFO);
logger.debug(APPHOME);
//First check if the app is already running
if (Utilities.anotherInstanceExists()) {
final JLabel lbl = new JLabel("Another instance of WindMill is already running...");
lbl.setFont(new Font("Tahoma", Font.BOLD, 11));
logger.warn(lbl.getText());
JOptionPane.showMessageDialog(null, lbl);
System.exit(0);
}
database = new WindDB();
//Then check if the database has been installed
if (Utilities.databaseMissing()) {
database.createDB();
}
//Load the properties file
//If not found then a message is shown but app continues with default values
BufferedReader bReader = null;
try {
propertyFile = new Properties();
//Load the properties
bReader = new BufferedReader(
new InputStreamReader(new FileInputStream(INIPATH)));
propertyFile.load(bReader);
bReader.close();
} catch (FileNotFoundException e) {
final JLabel lbl = new JLabel("Initialization file missing !!!");
lbl.setFont(new Font("Tahoma", Font.BOLD, 11));
logger.warn(lbl.getText());
JOptionPane.showMessageDialog(null, lbl);
initParams();
} catch (IOException e) {
final JLabel lbl = new JLabel("Problem with initialization !!!");
lbl.setFont(new Font("Tahoma", Font.BOLD, 11));
logger.warn(lbl.getText());
JOptionPane.showMessageDialog(null, lbl);
initParams();
}
//Log the start time
appStartTime = System.currentTimeMillis();
logger.info("Application started at:"+new Date(appStartTime).toString());
//Show the main window
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
mainFrame = new MainFrame();
}
});
}
/**
*
*/
private static void initParams() {
// TODO Auto-generated method stub
propertyFile.setProperty("SHIP", "Anonymous");
propertyFile.setProperty("MODE", "TIMER_MODE");
propertyFile.setProperty("PORT", "COM1");
propertyFile.setProperty("BAUD", "9600");
propertyFile.setProperty("DATABITS", "8");
propertyFile.setProperty("STOPBITS", "1");
propertyFile.setProperty("PARITY", "NONE");
propertyFile.setProperty("Gust.FLOOR", "1");
propertyFile.setProperty("Gust.CEILING", "12");
propertyFile.setProperty("Gust.DIFFERENCE", "3.5");
propertyFile.setProperty("Gust.TIMEWINDOW", "10");
propertyFile.setProperty("High.TIMEWINDOW", "10");
propertyFile.setProperty("High.FLOOR", "1");
propertyFile.setProperty("High.CEILING", "14.5");
propertyFile.setProperty("High.AVG", "10.0");
propertyFile.setProperty("Higher.TIMEWINDOW", "10");
propertyFile.setProperty("Higher.FLOOR", "14.5");
propertyFile.setProperty("Higher.CEILING", "25");
propertyFile.setProperty("Higher.AVG", "15");
}
}
| apache-2.0 |
MissionCriticalCloud/cosmic | cosmic-core/server/src/main/java/com/cloud/api/response/DedicateHostResponse.java | 2340 | package com.cloud.api.response;
import com.cloud.api.BaseResponse;
import com.cloud.serializer.Param;
import com.google.gson.annotations.SerializedName;
public class DedicateHostResponse extends BaseResponse {
@SerializedName("id")
@Param(description = "the ID of the dedicated resource")
private String id;
@SerializedName("hostid")
@Param(description = "the ID of the host")
private String hostId;
@SerializedName("hostname")
@Param(description = "the name of the host")
private String hostName;
@SerializedName("domainid")
@Param(description = "the domain ID of the host")
private String domainId;
@SerializedName("domainname")
@Param(description = "the domain name of the host")
private String domainName;
@SerializedName("accountid")
@Param(description = "the Account ID of the host")
private String accountId;
@SerializedName("accountname")
@Param(description = "the Account name of the host")
private String accountName;
@SerializedName("affinitygroupid")
@Param(description = "the Dedication Affinity Group ID of the host")
private String affinityGroupId;
public String getId() {
return id;
}
public void setId(final String id) {
this.id = id;
}
public String getHostId() {
return hostId;
}
public void setHostId(final String hostId) {
this.hostId = hostId;
}
public String getHostName() {
return hostName;
}
public void setHostName(final String hostName) {
this.hostName = hostName;
}
public String getDomainId() {
return domainId;
}
public void setDomainId(final String domainId) {
this.domainId = domainId;
}
public String getAccountId() {
return accountId;
}
public void setAccountId(final String accountId) {
this.accountId = accountId;
}
public String getAffinityGroupId() {
return affinityGroupId;
}
public void setAffinityGroupId(final String affinityGroupId) {
this.affinityGroupId = affinityGroupId;
}
public void setDomainName(final String domainName) {
this.domainName = domainName;
}
public void setAccountName(final String accountName) {
this.accountName = accountName;
}
}
| apache-2.0 |
web3j/web3j | abi/src/main/java/org/web3j/abi/datatypes/generated/StaticArray7.java | 845 | package org.web3j.abi.datatypes.generated;
import java.util.List;
import org.web3j.abi.datatypes.StaticArray;
import org.web3j.abi.datatypes.Type;
/**
* Auto generated code.
* <p><strong>Do not modifiy!</strong>
* <p>Please use org.web3j.codegen.AbiTypesGenerator in the
* <a href="https://github.com/web3j/web3j/tree/master/codegen">codegen module</a> to update.
*/
public class StaticArray7<T extends Type> extends StaticArray<T> {
@Deprecated
public StaticArray7(List<T> values) {
super(7, values);
}
@Deprecated
@SafeVarargs
public StaticArray7(T... values) {
super(7, values);
}
public StaticArray7(Class<T> type, List<T> values) {
super(type, 7, values);
}
@SafeVarargs
public StaticArray7(Class<T> type, T... values) {
super(type, 7, values);
}
}
| apache-2.0 |
xiangzhuyuan/spring-security-oauth | spring-security-oauth2/src/main/java/org/springframework/security/oauth2/common/exceptions/OAuth2ExceptionJackson1Serializer.java | 1745 | /*
* Copyright 2006-2011 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.security.oauth2.common.exceptions;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;
import java.io.IOException;
import java.util.Map.Entry;
/**
* @author Dave Syer
*/
public class OAuth2ExceptionJackson1Serializer extends JsonSerializer<OAuth2Exception> {
@Override
public void serialize(OAuth2Exception value, JsonGenerator jgen, SerializerProvider provider) throws IOException,
JsonProcessingException {
jgen.writeStartObject();
jgen.writeStringField("error", value.getOAuth2ErrorCode());
jgen.writeStringField("error_description", value.getMessage());
if (value.getAdditionalInformation() != null) {
for (Entry<String, String> entry : value.getAdditionalInformation().entrySet()) {
String key = entry.getKey();
String add = entry.getValue();
jgen.writeStringField(key, add);
}
}
jgen.writeEndObject();
}
}
| apache-2.0 |
reactor/reactor-core | reactor-core/src/main/java/reactor/util/concurrent/MpscLinkedQueue.java | 9455 | /*
* Copyright (c) 2018-2021 VMware Inc. or its affiliates, 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
*
* 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.
*/
package reactor.util.concurrent;
import java.util.AbstractQueue;
import java.util.Iterator;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.function.BiPredicate;
import reactor.util.annotation.Nullable;
/*
* The code was inspired by the similarly named JCTools class:
* https://github.com/JCTools/JCTools/blob/master/jctools-core/src/main/java/org/jctools/queues/atomic
*/
/**
* A multi-producer single consumer unbounded queue.
* @param <E> the contained value type
*/
final class MpscLinkedQueue<E> extends AbstractQueue<E> implements BiPredicate<E, E> {
private volatile LinkedQueueNode<E> producerNode;
private final static AtomicReferenceFieldUpdater<MpscLinkedQueue, LinkedQueueNode> PRODUCER_NODE_UPDATER
= AtomicReferenceFieldUpdater.newUpdater(MpscLinkedQueue.class, LinkedQueueNode.class, "producerNode");
private volatile LinkedQueueNode<E> consumerNode;
private final static AtomicReferenceFieldUpdater<MpscLinkedQueue, LinkedQueueNode> CONSUMER_NODE_UPDATER
= AtomicReferenceFieldUpdater.newUpdater(MpscLinkedQueue.class, LinkedQueueNode.class, "consumerNode");
public MpscLinkedQueue() {
LinkedQueueNode<E> node = new LinkedQueueNode<>();
CONSUMER_NODE_UPDATER.lazySet(this, node);
PRODUCER_NODE_UPDATER.getAndSet(this, node);// this ensures correct construction:
// StoreLoad
}
/**
* {@inheritDoc} <br>
* <p>
* IMPLEMENTATION NOTES:<br>
* Offer is allowed from multiple threads.<br>
* Offer allocates a new node and:
* <ol>
* <li>Swaps it atomically with current producer node (only one producer 'wins')
* <li>Sets the new node as the node following from the swapped producer node
* </ol>
* This works because each producer is guaranteed to 'plant' a new node and link the old node. No 2
* producers can get the same producer node as part of XCHG guarantee.
*
* @see java.util.Queue#offer(java.lang.Object)
*/
@Override
@SuppressWarnings("unchecked")
public final boolean offer(final E e) {
Objects.requireNonNull(e, "The offered value 'e' must be non-null");
final LinkedQueueNode<E> nextNode = new LinkedQueueNode<>(e);
final LinkedQueueNode<E> prevProducerNode = PRODUCER_NODE_UPDATER.getAndSet(this, nextNode);
// Should a producer thread get interrupted here the chain WILL be broken until that thread is resumed
// and completes the store in prev.next.
prevProducerNode.soNext(nextNode); // StoreStore
return true;
}
/**
* This is an additional {@link java.util.Queue} extension for
* {@link java.util.Queue#offer} which allows atomically offer two elements at once.
* <p>
* IMPLEMENTATION NOTES:<br>
* Offer over {@link #test} is allowed from multiple threads.<br>
* Offer over {@link #test} allocates a two new nodes and:
* <ol>
* <li>Swaps them atomically with current producer node (only one producer 'wins')
* <li>Sets the new nodes as the node following from the swapped producer node
* </ol>
* This works because each producer is guaranteed to 'plant' a new node and link the old node. No 2
* producers can get the same producer node as part of XCHG guarantee.
*
* @see java.util.Queue#offer(java.lang.Object)
*
* @param e1 first element to offer
* @param e2 second element to offer
*
* @return indicate whether elements has been successfully offered
*/
@Override
@SuppressWarnings("unchecked")
public boolean test(E e1, E e2) {
Objects.requireNonNull(e1, "The offered value 'e1' must be non-null");
Objects.requireNonNull(e2, "The offered value 'e2' must be non-null");
final LinkedQueueNode<E> nextNode = new LinkedQueueNode<>(e1);
final LinkedQueueNode<E> nextNextNode = new LinkedQueueNode<>(e2);
final LinkedQueueNode<E> prevProducerNode = PRODUCER_NODE_UPDATER.getAndSet(this, nextNextNode);
// Should a producer thread get interrupted here the chain WILL be broken until that thread is resumed
// and completes the store in prev.next.
nextNode.soNext(nextNextNode);
prevProducerNode.soNext(nextNode); // StoreStore
return true;
}
/**
* {@inheritDoc} <br>
* <p>
* IMPLEMENTATION NOTES:<br>
* Poll is allowed from a SINGLE thread.<br>
* Poll reads the next node from the consumerNode and:
* <ol>
* <li>If it is null, the queue is assumed empty (though it might not be).
* <li>If it is not null set it as the consumer node and return it's now evacuated value.
* </ol>
* This means the consumerNode.value is always null, which is also the starting point for the queue.
* Because null values are not allowed to be offered this is the only node with it's value set to null at
* any one time.
*
* @see java.util.Queue#poll()
*/
@Nullable
@Override
public E poll() {
LinkedQueueNode<E> currConsumerNode = consumerNode; // don't load twice, it's alright
LinkedQueueNode<E> nextNode = currConsumerNode.lvNext();
if (nextNode != null)
{
// we have to null out the value because we are going to hang on to the node
final E nextValue = nextNode.getAndNullValue();
// Fix up the next ref of currConsumerNode to prevent promoted nodes from keeping new ones alive.
// We use a reference to self instead of null because null is already a meaningful value (the next of
// producer node is null).
currConsumerNode.soNext(currConsumerNode);
CONSUMER_NODE_UPDATER.lazySet(this, nextNode);
// currConsumerNode is now no longer referenced and can be collected
return nextValue;
}
else if (currConsumerNode != producerNode)
{
while ((nextNode = currConsumerNode.lvNext()) == null) { }
// got the next node...
// we have to null out the value because we are going to hang on to the node
final E nextValue = nextNode.getAndNullValue();
// Fix up the next ref of currConsumerNode to prevent promoted nodes from keeping new ones alive.
// We use a reference to self instead of null because null is already a meaningful value (the next of
// producer node is null).
currConsumerNode.soNext(currConsumerNode);
CONSUMER_NODE_UPDATER.lazySet(this, nextNode);
// currConsumerNode is now no longer referenced and can be collected
return nextValue;
}
return null;
}
@Nullable
@Override
public E peek() {
LinkedQueueNode<E> currConsumerNode = consumerNode; // don't load twice, it's alright
LinkedQueueNode<E> nextNode = currConsumerNode.lvNext();
if (nextNode != null)
{
return nextNode.lpValue();
}
else if (currConsumerNode != producerNode)
{
while ((nextNode = currConsumerNode.lvNext()) == null) { }
// got the next node...
return nextNode.lpValue();
}
return null;
}
@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
while (poll() != null && !isEmpty()) { } // NOPMD
}
@Override
public int size() {
// Read consumer first, this is important because if the producer is node is 'older' than the consumer
// the consumer may overtake it (consume past it) invalidating the 'snapshot' notion of size.
LinkedQueueNode<E> chaserNode = consumerNode;
LinkedQueueNode<E> producerNode = this.producerNode;
int size = 0;
// must chase the nodes all the way to the producer node, but there's no need to count beyond expected head.
while (chaserNode != producerNode && // don't go passed producer node
chaserNode != null && // stop at last node
size < Integer.MAX_VALUE) // stop at max int
{
LinkedQueueNode<E> next;
next = chaserNode.lvNext();
// check if this node has been consumed, if so return what we have
if (next == chaserNode)
{
return size;
}
chaserNode = next;
size++;
}
return size;
}
@Override
public boolean isEmpty() {
return consumerNode == producerNode;
}
@Override
public Iterator<E> iterator() {
throw new UnsupportedOperationException();
}
static final class LinkedQueueNode<E>
{
private volatile LinkedQueueNode<E> next;
private final static AtomicReferenceFieldUpdater<LinkedQueueNode, LinkedQueueNode> NEXT_UPDATER
= AtomicReferenceFieldUpdater.newUpdater(LinkedQueueNode.class, LinkedQueueNode.class, "next");
private E value;
LinkedQueueNode()
{
this(null);
}
LinkedQueueNode(@Nullable E val)
{
spValue(val);
}
/**
* Gets the current value and nulls out the reference to it from this node.
*
* @return value
*/
@Nullable
public E getAndNullValue()
{
E temp = lpValue();
spValue(null);
return temp;
}
@Nullable
public E lpValue()
{
return value;
}
public void spValue(@Nullable E newValue)
{
value = newValue;
}
public void soNext(@Nullable LinkedQueueNode<E> n)
{
NEXT_UPDATER.lazySet(this, n);
}
@Nullable
public LinkedQueueNode<E> lvNext()
{
return next;
}
}
}
| apache-2.0 |
eclipsky/xtools | src/test/java/org/sky/x/ClassLoaderTest.java | 906 | package org.sky.x;
import java.io.IOException;
import java.io.InputStream;
public class ClassLoaderTest {
public static void main(String[] args) throws Exception{
ClassLoader myLoader = new ClassLoader(){
public Class<?> loadClass(String name) throws ClassNotFoundException{
try{
String fileName = name.substring(name.lastIndexOf(".") + 1) + ".class";
InputStream is = getClass().getResourceAsStream(fileName);
if(is == null){
return super.loadClass(name);
}
byte[] b = new byte[is.available()];
is.read(b);
return defineClass(name, b, 0, b.length);
}catch(IOException e){
throw new ClassNotFoundException(name);
}
}
};
Object obj = myLoader.loadClass("org.sky.x.ClassLoaderTest").newInstance();
System.out.println(obj.getClass());
System.out.println(obj instanceof org.sky.x.ClassLoaderTest);
// System.out.println("so what");
}
}
| apache-2.0 |
philliprower/cas | support/cas-server-support-shell/src/main/java/org/apereo/cas/shell/commands/services/GenerateYamlRegisteredServiceCommand.java | 2931 | package org.apereo.cas.shell.commands.services;
import org.apereo.cas.services.util.RegisteredServiceJsonSerializer;
import org.apereo.cas.services.util.RegisteredServiceYamlSerializer;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.springframework.shell.standard.ShellCommandGroup;
import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;
import org.springframework.shell.standard.ShellOption;
import java.io.File;
import java.io.StringWriter;
/**
* This is {@link GenerateYamlRegisteredServiceCommand}.
*
* @author Misagh Moayyed
* @since 5.2.0
*/
@ShellCommandGroup("Registered Services")
@ShellComponent
@Slf4j
public class GenerateYamlRegisteredServiceCommand {
private static final int SEP_LINE_LENGTH = 70;
/**
* Validate service.
*
* @param file the file
* @param destination the destination
*/
@ShellMethod(key = "generate-yaml", value = "Generate a YAML registered service definition")
public static void generateYaml(
@ShellOption(value = "file",
help = "Path to the JSON service definition file") final String file,
@ShellOption(value = "destination",
help = "Path to the destination YAML service definition file") final String destination) {
if (StringUtils.isBlank(file)) {
LOGGER.warn("File must be specified");
return;
}
val filePath = new File(file);
val result = StringUtils.isBlank(destination) ? null : new File(destination);
generate(filePath, result);
}
private static void generate(final File filePath, final File result) {
try {
val validator = new RegisteredServiceJsonSerializer();
if (filePath.isFile() && filePath.exists() && filePath.canRead() && filePath.length() > 0) {
val svc = validator.from(filePath);
LOGGER.info("Service [{}] is valid at [{}].", svc.getName(), filePath.getCanonicalPath());
val yaml = new RegisteredServiceYamlSerializer();
try (val writer = new StringWriter()) {
yaml.to(writer, svc);
LOGGER.info(writer.toString());
if (result != null) {
yaml.to(result, svc);
LOGGER.info("YAML service definition is saved at [{}].", result.getCanonicalPath());
}
}
} else {
LOGGER.warn("File [{}] is does not exist, is not readable or is empty", filePath.getCanonicalPath());
}
} catch (final Exception e) {
LOGGER.error("Could not understand and validate [{}]: [{}]", filePath.getPath(), e.getMessage());
} finally {
LOGGER.info("-".repeat(SEP_LINE_LENGTH));
}
}
}
| apache-2.0 |
GaneshRepo/Material-Drawer | library/src/main/java/com/mikepenz/materialdrawer/accountswitcher/AccountHeader.java | 42602 | package com.mikepenz.materialdrawer.accountswitcher;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.mikepenz.google_material_typeface_library.GoogleMaterial;
import com.mikepenz.iconics.IconicsDrawable;
import com.mikepenz.iconics.utils.Utils;
import com.mikepenz.materialdrawer.Drawer;
import com.mikepenz.materialdrawer.R;
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IProfile;
import com.mikepenz.materialdrawer.model.interfaces.Identifyable;
import com.mikepenz.materialdrawer.util.UIUtils;
import com.mikepenz.materialdrawer.view.CircularImageView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Stack;
/**
* Created by mikepenz on 27.02.15.
*/
public class AccountHeader {
private static final String BUNDLE_SELECTION_HEADER = "bundle_selection_header";
// global references to views we need later
protected View mAccountHeader;
protected ImageView mAccountHeaderBackground;
protected CircularImageView mCurrentProfileView;
protected View mAccountHeaderTextSection;
protected ImageView mAccountSwitcherArrow;
protected TextView mCurrentProfileName;
protected TextView mCurrentProfileEmail;
protected CircularImageView mProfileFirstView;
protected CircularImageView mProfileSecondView;
protected CircularImageView mProfileThirdView;
// global references to the profiles
protected IProfile mCurrentProfile;
protected IProfile mProfileFirst;
protected IProfile mProfileSecond;
protected IProfile mProfileThird;
// global stuff
protected boolean mSelectionListShown = false;
// the activity to use
protected Activity mActivity;
/**
* Pass the activity you use the drawer in ;)
*
* @param activity
* @return
*/
public AccountHeader withActivity(Activity activity) {
this.mActivity = activity;
return this;
}
// defines if we use the compactStyle
protected boolean mCompactStyle = false;
/**
* Defines if we should use the compact style for the header.
*
* @param compactStyle
* @return
*/
public AccountHeader withCompactStyle(boolean compactStyle) {
this.mCompactStyle = compactStyle;
return this;
}
// set the account header height
protected int mHeightPx = -1;
protected int mHeightDp = -1;
protected int mHeightRes = -1;
/**
* set the height for the header
*
* @param heightPx
* @return
*/
public AccountHeader withHeightPx(int heightPx) {
this.mHeightPx = heightPx;
return this;
}
/**
* set the height for the header
*
* @param heightDp
* @return
*/
public AccountHeader withHeightDp(int heightDp) {
this.mHeightDp = heightDp;
return this;
}
/**
* set the height for the header by resource
*
* @param heightRes
* @return
*/
public AccountHeader withHeightRes(int heightRes) {
this.mHeightRes = heightRes;
return this;
}
//the background color for the slider
protected int mTextColor = 0;
protected int mTextColorRes = -1;
/**
* set the background for the slider as color
*
* @param textColor
* @return
*/
public AccountHeader withTextColor(int textColor) {
this.mTextColor = textColor;
return this;
}
/**
* set the background for the slider as resource
*
* @param textColorRes
* @return
*/
public AccountHeader withTextColorRes(int textColorRes) {
this.mTextColorRes = textColorRes;
return this;
}
//set one of these to define the text in the first or second line withint the account selector
protected String mSelectionFirstLine;
protected String mSelectionSecondLine;
/**
* set this to define the first line in the selection area if there is no profile
* note this will block any values from profiles!
*
* @param selectionFirstLine
* @return
*/
public AccountHeader withSelectionFirstLine(String selectionFirstLine) {
this.mSelectionFirstLine = selectionFirstLine;
return this;
}
/**
* set this to define the second line in the selection area if there is no profile
* note this will block any values from profiles!
*
* @param selectionSecondLine
* @return
*/
public AccountHeader withSelectionSecondLine(String selectionSecondLine) {
this.mSelectionSecondLine = selectionSecondLine;
return this;
}
// set non translucent statusBar mode
protected boolean mTranslucentStatusBar = true;
/**
* Set or disable this if you use a translucent statusbar
*
* @param translucentStatusBar
* @return
*/
public AccountHeader withTranslucentStatusBar(boolean translucentStatusBar) {
this.mTranslucentStatusBar = translucentStatusBar;
return this;
}
//the background for the header
protected Drawable mHeaderBackground = null;
protected int mHeaderBackgroundRes = -1;
/**
* set the background for the slider as color
*
* @param headerBackground
* @return
*/
public AccountHeader withHeaderBackground(Drawable headerBackground) {
this.mHeaderBackground = headerBackground;
return this;
}
/**
* set the background for the header as resource
*
* @param headerBackgroundRes
* @return
*/
public AccountHeader withHeaderBackground(int headerBackgroundRes) {
this.mHeaderBackgroundRes = headerBackgroundRes;
return this;
}
//background scale type
protected ImageView.ScaleType mHeaderBackgroundScaleType = null;
/**
* define the ScaleType for the header background
*
* @param headerBackgroundScaleType
* @return
*/
public AccountHeader withHeaderBackgroundScaleType(ImageView.ScaleType headerBackgroundScaleType) {
this.mHeaderBackgroundScaleType = headerBackgroundScaleType;
return this;
}
//profile images in the header are shown or not
protected boolean mProfileImagesVisible = true;
/**
* define if the profile images in the header are shown or not
*
* @param profileImagesVisible
* @return
*/
public AccountHeader withProfileImagesVisible(boolean profileImagesVisible) {
this.mProfileImagesVisible = profileImagesVisible;
return this;
}
// set the profile images clickable or not
protected boolean mProfileImagesClickable = true;
/**
* enable or disable the profile images to be clickable
*
* @param profileImagesClickable
* @return
*/
public AccountHeader withProfileImagesClickable(boolean profileImagesClickable) {
this.mProfileImagesClickable = profileImagesClickable;
return this;
}
// set to use the alternative profile header switching
protected boolean mAlternativeProfileHeaderSwitching = false;
/**
* enable the alternative profile header switching
*
* @param alternativeProfileHeaderSwitching
* @return
*/
public AccountHeader withAlternativeProfileHeaderSwitching(boolean alternativeProfileHeaderSwitching) {
this.mAlternativeProfileHeaderSwitching = alternativeProfileHeaderSwitching;
return this;
}
// enable 3 small header previews
protected boolean mThreeSmallProfileImages = false;
/**
* enable the extended profile icon view with 3 small header images instead of two
*
* @param threeSmallProfileImages
* @return
*/
public AccountHeader withThreeSmallProfileImages(boolean threeSmallProfileImages) {
this.mThreeSmallProfileImages = threeSmallProfileImages;
return this;
}
// the onAccountHeaderSelectionListener to set
protected OnAccountHeaderSelectionViewClickListener mOnAccountHeaderSelectionViewClickListener;
/**
* set a onSelection listener for the selection box
*
* @param onAccountHeaderSelectionViewClickListener
* @return
*/
public AccountHeader withOnAccountHeaderSelectionViewClickListener(OnAccountHeaderSelectionViewClickListener onAccountHeaderSelectionViewClickListener) {
this.mOnAccountHeaderSelectionViewClickListener = onAccountHeaderSelectionViewClickListener;
return this;
}
//set the selection list enabled if there is only a single profile
protected boolean mSelectionListEnabledForSingleProfile = true;
/**
* enable or disable the selection list if there is only a single profile
*
* @param selectionListEnabledForSingleProfile
* @return
*/
public AccountHeader withSelectionListEnabledForSingleProfile(boolean selectionListEnabledForSingleProfile) {
this.mSelectionListEnabledForSingleProfile = selectionListEnabledForSingleProfile;
return this;
}
//set the selection enabled disabled
protected boolean mSelectionListEnabled = true;
/**
* enable or disable the selection list
*
* @param selectionListEnabled
* @return
*/
public AccountHeader withSelectionListEnabled(boolean selectionListEnabled) {
this.mSelectionListEnabled = selectionListEnabled;
return this;
}
// the drawerLayout to use
protected View mAccountHeaderContainer;
/**
* You can pass a custom view for the drawer lib. note this requires the same structure as the drawer.xml
*
* @param accountHeader
* @return
*/
public AccountHeader withAccountHeader(View accountHeader) {
this.mAccountHeaderContainer = accountHeader;
return this;
}
/**
* You can pass a custom layout for the drawer lib. see the drawer.xml in layouts of this lib on GitHub
*
* @param resLayout
* @return
*/
public AccountHeader withAccountHeader(int resLayout) {
if (mActivity == null) {
throw new RuntimeException("please pass an activity first to use this call");
}
if (resLayout != -1) {
this.mAccountHeaderContainer = mActivity.getLayoutInflater().inflate(resLayout, null, false);
} else {
if (mCompactStyle) {
this.mAccountHeaderContainer = mActivity.getLayoutInflater().inflate(R.layout.material_drawer_compact_header, null, false);
} else {
this.mAccountHeaderContainer = mActivity.getLayoutInflater().inflate(R.layout.material_drawer_header, null, false);
}
}
return this;
}
// the profiles to display
protected ArrayList<IProfile> mProfiles;
/**
* set the arrayList of DrawerItems for the drawer
*
* @param profiles
* @return
*/
public AccountHeader withProfiles(ArrayList<IProfile> profiles) {
this.mProfiles = profiles;
return this;
}
/**
* add single ore more DrawerItems to the Drawer
*
* @param profiles
* @return
*/
public AccountHeader addProfiles(IProfile... profiles) {
if (this.mProfiles == null) {
this.mProfiles = new ArrayList<>();
}
if (profiles != null) {
Collections.addAll(this.mProfiles, profiles);
}
return this;
}
// the click listener to be fired on profile or selection click
protected OnAccountHeaderListener mOnAccountHeaderListener;
/**
* add a listener for the accountHeader
*
* @param onAccountHeaderListener
* @return
*/
public AccountHeader withOnAccountHeaderListener(OnAccountHeaderListener onAccountHeaderListener) {
this.mOnAccountHeaderListener = onAccountHeaderListener;
return this;
}
// the drawer to set the AccountSwitcher for
protected Drawer.Result mDrawer;
/**
* @param drawer
* @return
*/
public AccountHeader withDrawer(Drawer.Result drawer) {
this.mDrawer = drawer;
return this;
}
// savedInstance to restore state
protected Bundle mSavedInstance;
/**
* create the drawer with the values of a savedInstance
*
* @param savedInstance
* @return
*/
public AccountHeader withSavedInstance(Bundle savedInstance) {
this.mSavedInstance = savedInstance;
return this;
}
/**
* helper method to set the height for the header!
*
* @param height
*/
private void setHeaderHeight(int height) {
if (mAccountHeaderContainer != null) {
ViewGroup.LayoutParams params = mAccountHeaderContainer.getLayoutParams();
if (params != null) {
params.height = height;
mAccountHeaderContainer.setLayoutParams(params);
}
View accountHeader = mAccountHeaderContainer.findViewById(R.id.account_header_drawer);
if (accountHeader != null) {
params = accountHeader.getLayoutParams();
params.height = height;
accountHeader.setLayoutParams(params);
}
View accountHeaderBackground = mAccountHeaderContainer.findViewById(R.id.account_header_drawer_background);
if (accountHeaderBackground != null) {
params = accountHeaderBackground.getLayoutParams();
params.height = height;
accountHeaderBackground.setLayoutParams(params);
}
}
}
/**
* method to build the header view
*
* @return
*/
public Result build() {
// if the user has not set a accountHeader use the default one :D
if (mAccountHeaderContainer == null) {
withAccountHeader(-1);
}
// get the header view within the container
mAccountHeader = mAccountHeaderContainer.findViewById(R.id.account_header_drawer);
// handle the height for the header
int height = -1;
if (mHeightPx != -1) {
height = mHeightPx;
} else if (mHeightDp != -1) {
height = Utils.convertDpToPx(mActivity, mHeightDp);
} else if (mHeightRes != -1) {
height = mActivity.getResources().getDimensionPixelSize(mHeightRes);
} else {
if (mCompactStyle) {
height = mActivity.getResources().getDimensionPixelSize(R.dimen.material_drawer_account_header_height_compact);
} else {
height = mActivity.getResources().getDimensionPixelSize(R.dimen.material_drawer_account_header_height);
}
}
// handle everything if we don't have a translucent status bar
if (mTranslucentStatusBar) {
mAccountHeader.setPadding(0, mActivity.getResources().getDimensionPixelSize(R.dimen.tool_bar_top_padding), 0, 0);
height = height + mActivity.getResources().getDimensionPixelSize(R.dimen.tool_bar_top_padding);
}
//set the height for the header
setHeaderHeight(height);
// get the background view
mAccountHeaderBackground = (ImageView) mAccountHeaderContainer.findViewById(R.id.account_header_drawer_background);
// set the background
if (mHeaderBackground != null) {
mAccountHeaderBackground.setImageDrawable(mHeaderBackground);
} else if (mHeaderBackgroundRes != -1) {
mAccountHeaderBackground.setImageResource(mHeaderBackgroundRes);
}
if (mHeaderBackgroundScaleType != null) {
mAccountHeaderBackground.setScaleType(mHeaderBackgroundScaleType);
}
// get the text color to use for the text section
int textColor = mTextColor;
if (textColor == 0 && mTextColorRes != -1) {
textColor = mActivity.getResources().getColor(mTextColorRes);
} else {
textColor = UIUtils.getThemeColorFromAttrOrRes(mActivity, R.attr.material_drawer_header_selection_text, R.color.material_drawer_header_selection_text);
}
mTextColor = textColor;
// set the background for the section
if (mCompactStyle) {
mAccountHeaderTextSection = mAccountHeader;
} else {
mAccountHeaderTextSection = mAccountHeaderContainer.findViewById(R.id.account_header_drawer_text_section);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// If we're running on Honeycomb or newer, then we can use the Theme's
// selectableItemBackground to ensure that the View has a pressed state
TypedValue outValue = new TypedValue();
mActivity.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);
mAccountHeaderTextSection.setBackgroundResource(outValue.resourceId);
} else {
TypedValue outValue = new TypedValue();
mActivity.getTheme().resolveAttribute(android.R.attr.itemBackground, outValue, true);
mAccountHeaderTextSection.setBackgroundResource(outValue.resourceId);
}
// set the arrow :D
mAccountSwitcherArrow = (ImageView) mAccountHeaderContainer.findViewById(R.id.account_header_drawer_text_switcher);
mAccountSwitcherArrow.setImageDrawable(new IconicsDrawable(mActivity, GoogleMaterial.Icon.gmd_arrow_drop_down).sizeDp(24).paddingDp(6).color(textColor));
//get the fields for the name
mCurrentProfileView = (CircularImageView) mAccountHeader.findViewById(R.id.account_header_drawer_current);
mCurrentProfileName = (TextView) mAccountHeader.findViewById(R.id.account_header_drawer_name);
mCurrentProfileEmail = (TextView) mAccountHeader.findViewById(R.id.account_header_drawer_email);
mCurrentProfileName.setTextColor(textColor);
mCurrentProfileEmail.setTextColor(textColor);
mProfileFirstView = (CircularImageView) mAccountHeader.findViewById(R.id.account_header_drawer_small_first);
mProfileSecondView = (CircularImageView) mAccountHeader.findViewById(R.id.account_header_drawer_small_second);
mProfileThirdView = (CircularImageView) mAccountHeader.findViewById(R.id.account_header_drawer_small_third);
//calculate the profiles to set
calculateProfiles();
//process and build the profiles
buildProfiles();
// try to restore all saved values again
if (mSavedInstance != null) {
int selection = mSavedInstance.getInt(BUNDLE_SELECTION_HEADER, -1);
if (selection != -1) {
//predefine selection (should be the first element
if (mProfiles != null && (selection) > -1 && selection < mProfiles.size()) {
switchProfiles(mProfiles.get(selection));
}
}
}
//everything created. now set the header
if (mDrawer != null) {
mDrawer.setHeader(mAccountHeaderContainer);
}
//forget the reference to the activity
mActivity = null;
return new Result(this);
}
/**
* helper method to calculate the order of the profiles
*/
protected void calculateProfiles() {
if (mProfiles != null) {
if (mCurrentProfile == null) {
int setCount = 0;
for (int i = 0; i < mProfiles.size(); i++) {
if (mProfiles.size() > i && mProfiles.get(i).isSelectable()) {
if (setCount == 0 && (mCurrentProfile == null)) {
mCurrentProfile = mProfiles.get(i);
} else if (setCount == 1 && (mProfileFirst == null)) {
mProfileFirst = mProfiles.get(i);
} else if (setCount == 2 && (mProfileSecond == null)) {
mProfileSecond = mProfiles.get(i);
} else if (setCount == 3 && (mProfileThird == null)) {
mProfileThird = mProfiles.get(i);
}
setCount++;
}
}
return;
}
IProfile[] previousActiveProfiles = new IProfile[]{
mCurrentProfile,
mProfileFirst,
mProfileSecond,
mProfileThird
};
IProfile[] newActiveProfiles = new IProfile[4];
Stack<IProfile> unusedProfiles = new Stack<>();
// try to keep existing active profiles in the same positions
for (int i = 0; i < mProfiles.size(); i++) {
IProfile p = mProfiles.get(i);
if (p.isSelectable()) {
boolean used = false;
for (int j = 0; j < 4; j++) {
if (previousActiveProfiles[j] == p) {
newActiveProfiles[j] = p;
used = true;
break;
}
}
if (!used) {
unusedProfiles.push(p);
}
}
}
Stack<IProfile> activeProfiles = new Stack<>();
// try to fill the gaps with new available profiles
for (int i = 0; i < 4; i++) {
if (newActiveProfiles[i] != null) {
activeProfiles.push(newActiveProfiles[i]);
} else if (!unusedProfiles.isEmpty()) {
activeProfiles.push(unusedProfiles.pop());
}
}
Stack<IProfile> reversedActiveProfiles = new Stack<IProfile>();
while (!activeProfiles.empty()) {
reversedActiveProfiles.push(activeProfiles.pop());
}
// reassign active profiles
if (reversedActiveProfiles.isEmpty()) {
mCurrentProfile = null;
} else {
mCurrentProfile = reversedActiveProfiles.pop();
}
if (reversedActiveProfiles.isEmpty()) {
mProfileFirst = null;
} else {
mProfileFirst = reversedActiveProfiles.pop();
}
if (reversedActiveProfiles.isEmpty()) {
mProfileSecond = null;
} else {
mProfileSecond = reversedActiveProfiles.pop();
}
if (reversedActiveProfiles.isEmpty()) {
mProfileThird = null;
} else {
mProfileThird = reversedActiveProfiles.pop();
}
}
}
/**
* helper method to switch the profiles
*
* @param newSelection
*/
protected void switchProfiles(IProfile newSelection) {
if (newSelection == null) {
return;
}
if (mCurrentProfile == newSelection) {
return;
}
if (mAlternativeProfileHeaderSwitching) {
int prevSelection = -1;
if (mProfileFirst == newSelection) {
prevSelection = 1;
} else if (mProfileSecond == newSelection) {
prevSelection = 2;
} else if (mProfileThird == newSelection) {
prevSelection = 3;
}
IProfile tmp = mCurrentProfile;
mCurrentProfile = newSelection;
if (prevSelection == 1) {
mProfileFirst = tmp;
} else if (prevSelection == 2) {
mProfileSecond = tmp;
} else if (prevSelection == 3) {
mProfileThird = tmp;
}
} else {
if (mProfiles != null) {
ArrayList<IProfile> previousActiveProfiles = new ArrayList<>(Arrays.asList(mCurrentProfile, mProfileFirst, mProfileSecond, mProfileThird));
if (previousActiveProfiles.contains(newSelection)) {
int position = -1;
for (int i = 0; i < 4; i++) {
if (previousActiveProfiles.get(i) == newSelection) {
position = i;
break;
}
}
if (position != -1) {
previousActiveProfiles.remove(position);
previousActiveProfiles.add(0, newSelection);
mCurrentProfile = previousActiveProfiles.get(0);
mProfileFirst = previousActiveProfiles.get(1);
mProfileSecond = previousActiveProfiles.get(2);
mProfileThird = previousActiveProfiles.get(3);
}
} else {
mProfileThird = mProfileSecond;
mProfileSecond = mProfileFirst;
mProfileFirst = mCurrentProfile;
mCurrentProfile = newSelection;
}
}
}
buildProfiles();
}
/**
* helper method to build the views for the ui
*/
protected void buildProfiles() {
mCurrentProfileView.setVisibility(View.INVISIBLE);
mAccountHeaderTextSection.setVisibility(View.INVISIBLE);
mAccountHeaderTextSection.setOnClickListener(onSelectionClickListener);
mAccountSwitcherArrow.setVisibility(View.INVISIBLE);
mProfileFirstView.setVisibility(View.INVISIBLE);
mProfileFirstView.setOnClickListener(null);
mProfileSecondView.setVisibility(View.INVISIBLE);
mProfileSecondView.setOnClickListener(null);
mProfileThirdView.setVisibility(View.INVISIBLE);
mProfileThirdView.setOnClickListener(null);
if (mCurrentProfile != null) {
if (mProfileImagesVisible) {
setImageOrPlaceholder(mCurrentProfileView, mCurrentProfile.getIcon());
mCurrentProfileView.setTag(mCurrentProfile);
if (mProfileImagesClickable) {
mCurrentProfileView.setOnClickListener(onProfileClickListener);
}
mCurrentProfileView.setVisibility(View.VISIBLE);
} else if (mCompactStyle) {
mCurrentProfileView.setVisibility(View.GONE);
}
mAccountHeaderTextSection.setTag(mCurrentProfile);
mAccountHeaderTextSection.setVisibility(View.VISIBLE);
mAccountSwitcherArrow.setVisibility(View.VISIBLE);
mCurrentProfileName.setText(mCurrentProfile.getName());
mCurrentProfileEmail.setText(mCurrentProfile.getEmail());
if (mProfileFirst != null && mProfileImagesVisible) {
setImageOrPlaceholder(mProfileFirstView, mProfileFirst.getIcon());
mProfileFirstView.setTag(mProfileFirst);
if (mProfileImagesClickable) {
mProfileFirstView.setOnClickListener(onProfileClickListener);
}
mProfileFirstView.setVisibility(View.VISIBLE);
}
if (mProfileSecond != null && mProfileImagesVisible) {
setImageOrPlaceholder(mProfileSecondView, mProfileSecond.getIcon());
mProfileSecondView.setTag(mProfileSecond);
if (mProfileImagesClickable) {
mProfileSecondView.setOnClickListener(onProfileClickListener);
}
mProfileSecondView.setVisibility(View.VISIBLE);
alignParentLayoutParam(mProfileFirstView, 0);
} else {
alignParentLayoutParam(mProfileFirstView, 1);
}
if (mProfileThird != null && mThreeSmallProfileImages && mProfileImagesVisible) {
setImageOrPlaceholder(mProfileThirdView, mProfileThird.getIcon());
mProfileThirdView.setTag(mProfileThird);
if (mProfileImagesClickable) {
mProfileThirdView.setOnClickListener(onProfileClickListener);
}
mProfileThirdView.setVisibility(View.VISIBLE);
alignParentLayoutParam(mProfileSecondView, 0);
} else {
alignParentLayoutParam(mProfileSecondView, 1);
}
} else if (mProfiles != null && mProfiles.size() > 0) {
IProfile profile = mProfiles.get(0);
mAccountHeaderTextSection.setTag(profile);
mAccountHeaderTextSection.setVisibility(View.VISIBLE);
mAccountSwitcherArrow.setVisibility(View.VISIBLE);
mCurrentProfileName.setText(profile.getName());
mCurrentProfileEmail.setText(profile.getEmail());
}
if (!TextUtils.isEmpty(mSelectionFirstLine)) {
mCurrentProfileName.setText(mSelectionFirstLine);
mAccountHeaderTextSection.setVisibility(View.VISIBLE);
}
if (!TextUtils.isEmpty(mSelectionSecondLine)) {
mCurrentProfileEmail.setText(mSelectionSecondLine);
mAccountHeaderTextSection.setVisibility(View.VISIBLE);
}
//if we disabled the list
if (!mSelectionListEnabled) {
mAccountSwitcherArrow.setVisibility(View.INVISIBLE);
}
if (!mSelectionListEnabledForSingleProfile && mProfileFirst == null) {
mAccountSwitcherArrow.setVisibility(View.INVISIBLE);
}
}
/**
* small helper method to change the align parent lp for the view
*
* @param view
* @param add
*/
private void alignParentLayoutParam(View view, int add) {
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) view.getLayoutParams();
lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, add);
if (Build.VERSION.SDK_INT >= 17) {
lp.addRule(RelativeLayout.ALIGN_PARENT_END, add);
}
view.setLayoutParams(lp);
}
/**
* small helper method to set an profile image or a placeholder
*
* @param iv
* @param d
*/
private void setImageOrPlaceholder(ImageView iv, Drawable d) {
if (d == null) {
iv.setImageDrawable(new IconicsDrawable(iv.getContext(), GoogleMaterial.Icon.gmd_person).color(mTextColor).backgroundColorRes(R.color.primary).iconOffsetYDp(2).paddingDp(2).sizeDp(56));
} else {
iv.setImageDrawable(d);
}
}
/**
* onProfileClickListener to notify onClick on a profile image
*/
private View.OnClickListener onProfileClickListener = new View.OnClickListener() {
@Override
public void onClick(final View v) {
final IProfile profile = (IProfile) v.getTag();
switchProfiles(profile);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (mOnAccountHeaderListener != null) {
mOnAccountHeaderListener.onProfileChanged(v, profile);
}
if (mDrawer != null) {
mDrawer.closeDrawer();
}
}
}, 200);
}
};
/**
* get the current selection
*
* @return
*/
private int getCurrentSelection() {
if (mCurrentProfile != null && mProfiles != null) {
int i = 0;
for (IProfile profile : mProfiles) {
if (profile == mCurrentProfile) {
return i;
}
i++;
}
}
return -1;
}
/**
* onSelectionClickListener to notify the onClick on the checkbox
*/
private View.OnClickListener onSelectionClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mOnAccountHeaderSelectionViewClickListener != null) {
mOnAccountHeaderSelectionViewClickListener.onClick(v, (IProfile) v.getTag());
}
if (mAccountSwitcherArrow.getVisibility() == View.VISIBLE) {
toggleSelectionList(v.getContext());
}
}
};
/**
* helper method to toggle the collection
*
* @param ctx
*/
protected void toggleSelectionList(Context ctx) {
if (mDrawer != null) {
//if we already show the list. reset everything instead
if (mDrawer.switchedDrawerContent()) {
resetDrawerContent(ctx);
mSelectionListShown = false;
} else {
//build and set the drawer selection list
buildDrawerSelectionList();
// update the arrow image within the drawer
mAccountSwitcherArrow.setImageDrawable(new IconicsDrawable(ctx, GoogleMaterial.Icon.gmd_arrow_drop_up).sizeDp(24).paddingDp(6).color(mTextColor));
mSelectionListShown = true;
}
}
}
/**
* helper method to build and set the drawer selection list
*/
protected void buildDrawerSelectionList() {
int selectedPosition = -1;
int position = 0;
ArrayList<IDrawerItem> profileDrawerItems = new ArrayList<>();
for (IProfile profile : mProfiles) {
if (profile == mCurrentProfile) {
selectedPosition = position;
}
if (profile instanceof IDrawerItem) {
profileDrawerItems.add((IDrawerItem) profile);
}
position = position + 1;
}
mDrawer.switchDrawerContent(onDrawerItemClickListener, profileDrawerItems, selectedPosition);
}
/**
* onDrawerItemClickListener to catch the selection for the new profile!
*/
private Drawer.OnDrawerItemClickListener onDrawerItemClickListener = new Drawer.OnDrawerItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id, final IDrawerItem drawerItem) {
if (drawerItem != null && drawerItem instanceof IProfile && ((IProfile) drawerItem).isSelectable()) {
switchProfiles((IProfile) drawerItem);
}
mDrawer.setOnDrawerItemClickListener(null);
//wrap the onSelection call and the reset stuff within a handler to prevent lag
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (drawerItem != null && drawerItem instanceof IProfile) {
if (mOnAccountHeaderListener != null) {
mOnAccountHeaderListener.onProfileChanged(view, (IProfile) drawerItem);
}
}
if (mDrawer != null) {
resetDrawerContent(view.getContext());
}
}
}, 350);
}
};
/**
* helper method to reset the drawer content
*/
private void resetDrawerContent(Context ctx) {
mDrawer.resetDrawerContent();
mAccountSwitcherArrow.setImageDrawable(new IconicsDrawable(ctx, GoogleMaterial.Icon.gmd_arrow_drop_down).sizeDp(24).paddingDp(6).color(mTextColor));
}
/**
* small helper class to update the header and the list
*/
protected void updateHeaderAndList() {
//recalculate the profiles
calculateProfiles();
//update the profiles in the header
buildProfiles();
//if we currently show the list add the new item directly to it
if (mSelectionListShown) {
buildDrawerSelectionList();
}
}
public static class Result {
private final AccountHeader mAccountHeader;
protected Result(AccountHeader accountHeader) {
this.mAccountHeader = accountHeader;
}
/**
* Get the Root view for the Header
*
* @return
*/
public View getView() {
return mAccountHeader.mAccountHeaderContainer;
}
/**
* Set the drawer for the AccountHeader so we can use it for the select
*
* @param drawer
*/
public void setDrawer(Drawer.Result drawer) {
mAccountHeader.mDrawer = drawer;
}
/**
* Returns the header background view so the dev can set everything on it
*
* @return
*/
public ImageView getHeaderBackgroundView() {
return mAccountHeader.mAccountHeaderBackground;
}
/**
* Set the background for the Header
*
* @param headerBackground
*/
public void setBackground(Drawable headerBackground) {
mAccountHeader.mAccountHeaderBackground.setImageDrawable(headerBackground);
}
/**
* Set the background for the Header as resource
*
* @param headerBackgroundRes
*/
public void setBackgroundRes(int headerBackgroundRes) {
mAccountHeader.mAccountHeaderBackground.setImageResource(headerBackgroundRes);
}
/**
* Toggle the selection list (show or hide it)
*
* @param ctx
*/
public void toggleSelectionList(Context ctx) {
mAccountHeader.toggleSelectionList(ctx);
}
/**
* returns if the selection list is currently shown
*
* @return
*/
public boolean isSelectionListShown() {
return mAccountHeader.mSelectionListShown;
}
/**
* returns the current list of profiles set for this header
*
* @return
*/
public ArrayList<IProfile> getProfiles() {
return mAccountHeader.mProfiles;
}
/**
* Set a new list of profiles for the header
*
* @param profiles
*/
public void setProfiles(ArrayList<IProfile> profiles) {
mAccountHeader.mProfiles = profiles;
mAccountHeader.updateHeaderAndList();
}
/**
* Selects the given profile and sets it to the new active profile
*
* @param profile
*/
public void setActiveProfile(IProfile profile) {
mAccountHeader.switchProfiles(profile);
}
/**
* Selects a profile by its identifier
*
* @param identifier
*/
public void setActiveProfile(int identifier) {
if (mAccountHeader.mProfiles != null) {
for (IProfile profile : mAccountHeader.mProfiles) {
if (profile instanceof Identifyable) {
if (profile.getIdentifier() == identifier) {
mAccountHeader.switchProfiles(profile);
return;
}
}
}
}
}
/**
* Helper method to update a profile using it's identifier
*
* @param newProfile
*/
public void updateProfileByIdentifier(IProfile newProfile) {
if (mAccountHeader.mProfiles != null) {
for (IProfile profile : mAccountHeader.mProfiles) {
if (profile instanceof Identifyable) {
if (profile.getIdentifier() == newProfile.getIdentifier()) {
profile = newProfile;
mAccountHeader.updateHeaderAndList();
return;
}
}
}
}
}
/**
* Add new profiles to the existing list of profiles
*
* @param profiles
*/
public void addProfiles(IProfile... profiles) {
if (mAccountHeader.mProfiles == null) {
mAccountHeader.mProfiles = new ArrayList<IProfile>();
}
if (profiles != null) {
Collections.addAll(mAccountHeader.mProfiles, profiles);
}
mAccountHeader.updateHeaderAndList();
}
/**
* Add a new profile at a specific position to the list
*
* @param profile
* @param position
*/
public void addProfile(IProfile profile, int position) {
if (mAccountHeader.mProfiles == null) {
mAccountHeader.mProfiles = new ArrayList<IProfile>();
}
mAccountHeader.mProfiles.add(position, profile);
mAccountHeader.updateHeaderAndList();
}
/**
* remove a profile from the given position
*
* @param position
*/
public void removeProfile(int position) {
if (mAccountHeader.mProfiles != null && mAccountHeader.mProfiles.size() > position) {
mAccountHeader.mProfiles.remove(position);
}
mAccountHeader.updateHeaderAndList();
}
/**
* try to remove the given profile
*
* @param profile
*/
public void removeProfile(IProfile profile) {
if (mAccountHeader.mProfiles != null) {
mAccountHeader.mProfiles.remove(profile);
}
mAccountHeader.updateHeaderAndList();
}
/**
* add the values to the bundle for saveInstanceState
*
* @param savedInstanceState
* @return
*/
public Bundle saveInstanceState(Bundle savedInstanceState) {
if (savedInstanceState != null) {
savedInstanceState.putInt(BUNDLE_SELECTION_HEADER, mAccountHeader.getCurrentSelection());
}
return savedInstanceState;
}
}
public interface OnAccountHeaderListener {
public void onProfileChanged(View view, IProfile profile);
}
public interface OnAccountHeaderSelectionViewClickListener {
public void onClick(View view, IProfile profile);
}
}
| apache-2.0 |
febo/myra | src/test/java/myra/SynchronizedArchiveTest.java | 1453 | /*
* SynchronizedArchiveTest.java
* (this file is part of MYRA)
*
* Copyright 2008-2015 Fernando Esteban Barril Otero
*
* 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 myra;
import junit.framework.TestCase;
import myra.Archive.SynchronizedArchive;
import myra.DefaultArchiveTest.WInteger;
/**
* <code>SynchronizedArchive</code> class test.
*
* @author Fernando Esteban Barril Otero
*/
public class SynchronizedArchiveTest extends TestCase {
/**
* Tests the addition of elements to the archive.
*/
public void testAdd() {
Archive<WInteger> archive = new Archive.DefaultArchive<>(5);
Archive<WInteger> pool = new SynchronizedArchive<>(archive);
for (int i = 0; i < 5; i++) {
pool.add(new WInteger(i));
}
assertEquals(5, archive.size());
assertEquals(0, archive.lowest().intValue());
assertEquals(4, archive.highest().intValue());
}
} | apache-2.0 |
dtag-dbu/task4java | com.task4java/src/com/task4java/http/client/RestClientGingerbread.java | 10518 | /*
* Copyright (c) 2014 Andree Hagelstein, Maik Schulze, Deutsche Telekom AG. All Rights Reserved.
*
* Filename: RestClientGingerbread.java
*/
package com.task4java.http.client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.cert.CertificateException;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.GZIPInputStream;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import com.task4java.KeyValuePair;
import com.task4java.Stopwatch;
import com.task4java.Tuple;
import com.task4java.http.HttpHeaders;
import com.task4java.http.HttpMimeTypes;
import com.task4java.http.HttpRequestMethods;
import com.task4java.http.HttpStatusCodes;
import com.task4java.net.URLBuilder;
import com.task4java.util.log.Logger;
public class RestClientGingerbread implements IRestClient {
private static final String DID_NOT_DEFINE_AN_ACTION = "You did not define an action! REST call canceled!";
private static final String TAG = RestClientGingerbread.class.getName();
private static AtomicInteger _operations = new AtomicInteger( 0 );
private static AtomicInteger _connects = new AtomicInteger(0);
private static boolean _activateContentLog = false;
private static Tuple<String, Integer> _proxySettings = null;
public int getOperations()
{
return _operations.get();
}
public void ignoreCertificateErrors()
{
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
} };
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
catch (Exception e) {
}
}
public void activateContentLog()
{
_activateContentLog = true;
}
public void setProxy(String hostname, Integer port)
{
if (hostname == null)
{
_proxySettings = null;
}
else
{
_proxySettings = new Tuple<String, Integer>(hostname, port);
}
}
public RestResponse get(URL action, List<KeyValuePair> requestHeaders, List<KeyValuePair> requestParams) throws IOException {
return execute(HttpRequestMethods.GET, action, requestHeaders, requestParams, null);
}
public RestResponse post(URL action, List<KeyValuePair> requestHeaders, List<KeyValuePair> requestParams, HttpContent requestBody) throws IOException {
return execute(HttpRequestMethods.POST, action, requestHeaders, requestParams, requestBody);
}
public RestResponse delete(URL action, List<KeyValuePair> requestHeaders, List<KeyValuePair> requestParams) throws IOException, URISyntaxException {
return execute(HttpRequestMethods.DELETE, action, requestHeaders, requestParams, null);
}
public RestResponse put(URL action, List<KeyValuePair> requestHeaders, List<KeyValuePair> requestParams, HttpContent requestBody) throws IOException, URISyntaxException {
return execute(HttpRequestMethods.PUT, action, requestHeaders, requestParams, requestBody);
}
private static RestResponse execute(HttpRequestMethods requestMethod, URL action, List<KeyValuePair> requestHeaders, List<KeyValuePair> requestParams, HttpContent requestEntity)
throws IOException {
HttpURLConnection connection = null;
InputStream inputStream = null;
OutputStream outputStream = null;
int responseLength = -1;
Stopwatch watch = new Stopwatch();
watch.start();
try {
if (action == null) {
Logger.instance.e(TAG, DID_NOT_DEFINE_AN_ACTION);
throw new IllegalArgumentException(DID_NOT_DEFINE_AN_ACTION);
}
int connects = _connects.incrementAndGet();
_operations.incrementAndGet();
if (_proxySettings == null)
{
connection = (HttpURLConnection) attachParameters(action, requestParams).openConnection();
}
else
{
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(_proxySettings.left, _proxySettings.right));
connection = (HttpURLConnection) attachParameters(action, requestParams).openConnection(proxy);
}
Logger.instance.d(TAG, "Enter execute, method: " + requestMethod.toString() + ", connects: " + connects + ", url: " + connection.getURL());
connection.setReadTimeout(60000);
connection.setConnectTimeout(60000);
switch (requestMethod) {
case CONNECT:
break;
case DELETE:
connection.setRequestMethod("DELETE");
attachHeaders(connection, requestHeaders);
connection.setRequestProperty(HttpHeaders.AcceptEncoding, HttpMimeTypes.Encoding_Gzip);
break;
case GET:
attachHeaders(connection, requestHeaders);
connection.setRequestProperty(HttpHeaders.AcceptEncoding, HttpMimeTypes.Encoding_Gzip);
connection.connect();
break;
case HEAD:
break;
case OPTIONS:
break;
case PATCH:
break;
case POST:
connection.setRequestMethod("POST");
connection.setDoOutput(true);
attachHeaders(connection, requestHeaders);
connection.setRequestProperty(HttpHeaders.AcceptEncoding, HttpMimeTypes.Encoding_Gzip);
connection.connect();
// get the output stream to force a content length header
outputStream = connection.getOutputStream();
if (requestEntity != null){
requestEntity.writeTo(outputStream);
}
break;
case PUT:
connection.setRequestMethod("PUT");
connection.setDoOutput(true);
attachHeaders(connection, requestHeaders);
connection.setRequestProperty(HttpHeaders.AcceptEncoding, HttpMimeTypes.Encoding_Gzip);
connection.connect();
// get the output stream to force a content length header
outputStream = connection.getOutputStream();
if (requestEntity != null){
requestEntity.writeTo(outputStream);
}
break;
case TRACE:
break;
case UNDEFINED:
break;
}
if (outputStream != null)
{
outputStream.close();
outputStream = null;
}
if (_activateContentLog)
{
for(Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
for(String value : header.getValue())
{
Logger.instance.d(TAG, header.getKey() + ":" + value);
}
}
}
RestResponse response = new RestResponse(connection.getResponseCode());
if (response.getStatusCode() < HttpStatusCodes.OK || response.getStatusCode() >= HttpStatusCodes.BadRequest)
{
inputStream = connection.getErrorStream();
}
else
{
inputStream = connection.getInputStream();
}
if (inputStream != null) {
BufferedReader rd = null;
String contentEncodingHeader = connection.getHeaderField(HttpHeaders.ContentEncoding);
if ((contentEncodingHeader != null) && (contentEncodingHeader.contains(HttpMimeTypes.Encoding_Gzip))) {
rd = new BufferedReader(new InputStreamReader(new GZIPInputStream(inputStream)));
} else {
rd = new BufferedReader(new InputStreamReader(inputStream));
}
StringWriter sw = new StringWriter();
char[] buffer = new char[1024 * 4];
int n = 0;
while (-1 != (n = rd.read(buffer))) {
sw.write(buffer, 0, n);
}
response.setResponseData(sw.toString());
responseLength = response.getResponseData().length();
}
if (_activateContentLog)
{
Logger.instance.d(TAG, "RestResponse: " + response.toString());
}
return response;
} finally {
int connects = _connects.decrementAndGet();
watch.stop();
if (connection != null)
{
Logger.instance.d(TAG, "Leave execute, connects: " + connects + ", time: " + watch.getElapsedMilliseconds() + ", length: " + responseLength + ", url: " + connection.getURL());
}
if (inputStream != null) {
inputStream.close();
inputStream = null;
}
if (connection != null) {
connection.disconnect();
connection = null;
}
}
}
private static void attachHeaders(HttpURLConnection connection, List<KeyValuePair> requestHeaders) {
if (requestHeaders != null) {
for (KeyValuePair header : requestHeaders) {
connection.setRequestProperty(header.getKey(), header.getValue());
}
}
}
private static URL attachParameters(URL action, List<KeyValuePair> requestParams) throws MalformedURLException, UnsupportedEncodingException {
URLBuilder urlBuilder = new URLBuilder(action);
urlBuilder.addQueryParts(requestParams);
return urlBuilder.getURL();
}
}
| apache-2.0 |
learnopengles/dsp-perf-test | AndroidPerformanceTest/src/com/example/performancetest/DspRenderscript.java | 1043 | /*******************************************************************************
* Copyright 2014 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.example.performancetest;
import android.renderscript.Allocation;
public class DspRenderscript {
public static void applyJustLowpass(Allocation in, Allocation out, int length, ScriptC_LowPassFilter filterScript) {
filterScript.invoke_apply_lowpass(in, out, length);
}
} | apache-2.0 |
AstromechZA/PLYMeshSplitterJava | src/org/uct/cs/simplify/Blueprintify.java | 3995 | package org.uct.cs.simplify;
import org.apache.commons.cli.*;
import org.uct.cs.simplify.blueprint.BluePrintGenerator;
import org.uct.cs.simplify.ply.reader.PLYReader;
import org.uct.cs.simplify.util.Timer;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class Blueprintify
{
private static final int DEFAULT_RESOLUTION = 1024;
private static final float DEFAULT_ALPHA_MOD = 0.1f;
private static final int DEFAULT_SKIP_SIZE = 1;
private static final String OUTPUT_FORMAT = "png";
public static void run(File inputFile, File outputDir, int resolution, float alphamod, int skipsize) throws IOException
{
PLYReader reader = new PLYReader(inputFile);
run(reader, outputDir, resolution, alphamod, skipsize);
}
public static void run(PLYReader reader, File outputDir, int resolution, float alphamod, int skipsize) throws IOException
{
File outputFile;
for (BluePrintGenerator.CoordinateSpace coordinateSpace : BluePrintGenerator.CoordinateSpace.values())
{
outputFile = new File(outputDir, reader.getFile().getName() + '.' + coordinateSpace.name() + '.' + OUTPUT_FORMAT);
BufferedImage bi = BluePrintGenerator.createImage(reader, resolution, alphamod, coordinateSpace, skipsize).output;
ImageIO.write(bi, OUTPUT_FORMAT, outputFile);
System.out.println("Saved blueprint to " + outputFile);
}
}
@SuppressWarnings("unused")
public static void main(String[] args)
{
CommandLine cmd = parseArgs(args);
try (Timer ignored = new Timer("Blueprintifying"))
{
int resolution = cmd.hasOption("resolution") ? Integer.parseInt(cmd.getOptionValue("resolution")) : DEFAULT_RESOLUTION;
float alphamod = cmd.hasOption("alphamod") ? Float.parseFloat(cmd.getOptionValue("alphamod")) : DEFAULT_ALPHA_MOD;
int skipsize = cmd.hasOption("skipsize") ? Integer.parseInt(cmd.getOptionValue("skipsize")) : DEFAULT_SKIP_SIZE;
String filename = cmd.getOptionValue("filename");
String outputDirectory = cmd.getOptionValue("output");
// process output dir
File outputDir = new File(new File(outputDirectory).getCanonicalPath());
if (!outputDir.exists() && !outputDir.mkdirs())
throw new IOException("Could not create output directory " + outputDir);
File inputFile = new File(filename);
run(inputFile, outputDir, resolution, alphamod, skipsize);
}
catch (IOException e)
{
e.printStackTrace();
}
}
private static CommandLine parseArgs(String[] args)
{
CommandLineParser clp = new BasicParser();
Options options = new Options();
Option o1 = new Option("f", "filename", true, "Path to PLY model to process");
o1.setRequired(true);
options.addOption(o1);
Option o2 = new Option("o", "output", true, "Destination directory of blueprints");
o2.setRequired(true);
options.addOption(o2);
Option o3 = new Option(
"r", "resolution", true,
String.format("Resolution of image to output (default %s)", DEFAULT_RESOLUTION)
);
options.addOption(o3);
Option o4 = new Option(
"a", "alphamod", true,
String.format("Translucency of applied pixels (default %.2f)", DEFAULT_ALPHA_MOD)
);
options.addOption(o4);
options.addOption(new Option("s", "skipsize", true, "Only draw every nth vertex"));
try
{
return clp.parse(options, args);
}
catch (ParseException e)
{
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("--filename <path> --output <path>", options);
System.exit(1);
return null;
}
}
}
| apache-2.0 |
shokoro3434/test2 | eitax-front-core/src/main/java/com/eitax/recall/front/dao/CustomerDAO.java | 278 | package com.eitax.recall.front.dao;
import java.util.List;
import com.eitax.recall.front.domain.Customer;
public interface CustomerDAO {
public abstract List<Customer> findAll();
public Customer findOne(Integer customerId);
public abstract void save(Customer customer);
}
| apache-2.0 |
chao-sun-kaazing/gateway | mina.core/core/src/main/java/org/apache/mina/core/buffer/IoBufferWrapper.java | 19793 | /**
* Copyright 2007-2015, Kaazing Corporation. 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.apache.mina.core.buffer;
import java.io.FilterOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.CharBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
import java.nio.ShortBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.EnumSet;
import java.util.Set;
/**
* A {@link IoBuffer} that wraps a buffer and proxies any operations to it.
* <p>
* You can think this class like a {@link FilterOutputStream}. All operations
* are proxied by default so that you can extend this class and override existing
* operations selectively. You can introduce new operations, too.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class IoBufferWrapper extends IoBuffer {
/**
* The buffer proxied by this proxy.
*/
private final IoBuffer buf;
/**
* Create a new instance.
* @param buf the buffer to be proxied
*/
protected IoBufferWrapper(IoBuffer buf) {
if (buf == null) {
throw new NullPointerException("buf");
}
this.buf = buf;
}
/**
* Returns the parent buffer that this buffer wrapped.
*/
public IoBuffer getParentBuffer() {
return buf;
}
@Override
public boolean isDirect() {
return buf.isDirect();
}
@Override
public ByteBuffer buf() {
return buf.buf();
}
@Override
public int capacity() {
return buf.capacity();
}
@Override
public int position() {
return buf.position();
}
@Override
public IoBuffer position(int newPosition) {
buf.position(newPosition);
return this;
}
@Override
public int limit() {
return buf.limit();
}
@Override
public IoBuffer limit(int newLimit) {
buf.limit(newLimit);
return this;
}
@Override
public IoBuffer mark() {
buf.mark();
return this;
}
@Override
public IoBuffer reset() {
buf.reset();
return this;
}
@Override
public IoBuffer clear() {
buf.clear();
return this;
}
@Override
public IoBuffer sweep() {
buf.sweep();
return this;
}
@Override
public IoBuffer sweep(byte value) {
buf.sweep(value);
return this;
}
@Override
public IoBuffer flip() {
buf.flip();
return this;
}
@Override
public IoBuffer rewind() {
buf.rewind();
return this;
}
@Override
public int remaining() {
return buf.remaining();
}
@Override
public boolean hasRemaining() {
return buf.hasRemaining();
}
@Override
public byte get() {
return buf.get();
}
@Override
public short getUnsigned() {
return buf.getUnsigned();
}
@Override
public IoBuffer put(byte b) {
buf.put(b);
return this;
}
@Override
public byte get(int index) {
return buf.get(index);
}
@Override
public short getUnsigned(int index) {
return buf.getUnsigned(index);
}
@Override
public IoBuffer put(int index, byte b) {
buf.put(index, b);
return this;
}
@Override
public IoBuffer get(byte[] dst, int offset, int length) {
buf.get(dst, offset, length);
return this;
}
@Override
public IoBuffer getSlice(int index, int length) {
return buf.getSlice(index, length);
}
@Override
public IoBuffer getSlice(int length) {
return buf.getSlice(length);
}
@Override
public IoBuffer get(byte[] dst) {
buf.get(dst);
return this;
}
@Override
public IoBuffer put(IoBuffer src) {
buf.put(src);
return this;
}
@Override
public IoBuffer put(ByteBuffer src) {
buf.put(src);
return this;
}
@Override
public IoBuffer put(byte[] src, int offset, int length) {
buf.put(src, offset, length);
return this;
}
@Override
public IoBuffer put(byte[] src) {
buf.put(src);
return this;
}
@Override
public IoBuffer compact() {
buf.compact();
return this;
}
@Override
public String toString() {
return buf.toString();
}
@Override
public int hashCode() {
return buf.hashCode();
}
@Override
public boolean equals(Object ob) {
return buf.equals(ob);
}
public int compareTo(IoBuffer that) {
return buf.compareTo(that);
}
@Override
public ByteOrder order() {
return buf.order();
}
@Override
public IoBuffer order(ByteOrder bo) {
buf.order(bo);
return this;
}
@Override
public char getChar() {
return buf.getChar();
}
@Override
public IoBuffer putChar(char value) {
buf.putChar(value);
return this;
}
@Override
public char getChar(int index) {
return buf.getChar(index);
}
@Override
public IoBuffer putChar(int index, char value) {
buf.putChar(index, value);
return this;
}
@Override
public CharBuffer asCharBuffer() {
return buf.asCharBuffer();
}
@Override
public short getShort() {
return buf.getShort();
}
@Override
public int getUnsignedShort() {
return buf.getUnsignedShort();
}
@Override
public IoBuffer putShort(short value) {
buf.putShort(value);
return this;
}
@Override
public short getShort(int index) {
return buf.getShort(index);
}
@Override
public int getUnsignedShort(int index) {
return buf.getUnsignedShort(index);
}
@Override
public IoBuffer putShort(int index, short value) {
buf.putShort(index, value);
return this;
}
@Override
public ShortBuffer asShortBuffer() {
return buf.asShortBuffer();
}
@Override
public int getInt() {
return buf.getInt();
}
@Override
public long getUnsignedInt() {
return buf.getUnsignedInt();
}
@Override
public IoBuffer putInt(int value) {
buf.putInt(value);
return this;
}
@Override
public int getInt(int index) {
return buf.getInt(index);
}
@Override
public long getUnsignedInt(int index) {
return buf.getUnsignedInt(index);
}
@Override
public IoBuffer putInt(int index, int value) {
buf.putInt(index, value);
return this;
}
@Override
public IntBuffer asIntBuffer() {
return buf.asIntBuffer();
}
@Override
public long getLong() {
return buf.getLong();
}
@Override
public IoBuffer putLong(long value) {
buf.putLong(value);
return this;
}
@Override
public long getLong(int index) {
return buf.getLong(index);
}
@Override
public IoBuffer putLong(int index, long value) {
buf.putLong(index, value);
return this;
}
@Override
public LongBuffer asLongBuffer() {
return buf.asLongBuffer();
}
@Override
public float getFloat() {
return buf.getFloat();
}
@Override
public IoBuffer putFloat(float value) {
buf.putFloat(value);
return this;
}
@Override
public float getFloat(int index) {
return buf.getFloat(index);
}
@Override
public IoBuffer putFloat(int index, float value) {
buf.putFloat(index, value);
return this;
}
@Override
public FloatBuffer asFloatBuffer() {
return buf.asFloatBuffer();
}
@Override
public double getDouble() {
return buf.getDouble();
}
@Override
public IoBuffer putDouble(double value) {
buf.putDouble(value);
return this;
}
@Override
public double getDouble(int index) {
return buf.getDouble(index);
}
@Override
public IoBuffer putDouble(int index, double value) {
buf.putDouble(index, value);
return this;
}
@Override
public DoubleBuffer asDoubleBuffer() {
return buf.asDoubleBuffer();
}
@Override
public String getHexDump() {
return buf.getHexDump();
}
@Override
public String getString(int fieldSize, CharsetDecoder decoder)
throws CharacterCodingException {
return buf.getString(fieldSize, decoder);
}
@Override
public String getString(CharsetDecoder decoder)
throws CharacterCodingException {
return buf.getString(decoder);
}
@Override
public String getPrefixedString(CharsetDecoder decoder)
throws CharacterCodingException {
return buf.getPrefixedString(decoder);
}
@Override
public String getPrefixedString(int prefixLength, CharsetDecoder decoder)
throws CharacterCodingException {
return buf.getPrefixedString(prefixLength, decoder);
}
@Override
public IoBuffer putString(CharSequence in, int fieldSize,
CharsetEncoder encoder) throws CharacterCodingException {
buf.putString(in, fieldSize, encoder);
return this;
}
@Override
public IoBuffer putString(CharSequence in, CharsetEncoder encoder)
throws CharacterCodingException {
buf.putString(in, encoder);
return this;
}
@Override
public IoBuffer putPrefixedString(CharSequence in, CharsetEncoder encoder)
throws CharacterCodingException {
buf.putPrefixedString(in, encoder);
return this;
}
@Override
public IoBuffer putPrefixedString(CharSequence in, int prefixLength,
CharsetEncoder encoder) throws CharacterCodingException {
buf.putPrefixedString(in, prefixLength, encoder);
return this;
}
@Override
public IoBuffer putPrefixedString(CharSequence in, int prefixLength,
int padding, CharsetEncoder encoder)
throws CharacterCodingException {
buf.putPrefixedString(in, prefixLength, padding, encoder);
return this;
}
@Override
public IoBuffer putPrefixedString(CharSequence in, int prefixLength,
int padding, byte padValue, CharsetEncoder encoder)
throws CharacterCodingException {
buf.putPrefixedString(in, prefixLength, padding, padValue, encoder);
return this;
}
@Override
public IoBuffer skip(int size) {
buf.skip(size);
return this;
}
@Override
public IoBuffer fill(byte value, int size) {
buf.fill(value, size);
return this;
}
@Override
public IoBuffer fillAndReset(byte value, int size) {
buf.fillAndReset(value, size);
return this;
}
@Override
public IoBuffer fill(int size) {
buf.fill(size);
return this;
}
@Override
public IoBuffer fillAndReset(int size) {
buf.fillAndReset(size);
return this;
}
@Override
public boolean isAutoExpand() {
return buf.isAutoExpand();
}
@Override
public IoBuffer setAutoExpand(boolean autoExpand) {
buf.setAutoExpand(autoExpand);
return this;
}
@Override
public IoBuffer expand(int pos, int expectedRemaining) {
buf.expand(pos, expectedRemaining);
return this;
}
@Override
public IoBuffer expand(int expectedRemaining) {
buf.expand(expectedRemaining);
return this;
}
@Override
public Object getObject() throws ClassNotFoundException {
return buf.getObject();
}
@Override
public Object getObject(ClassLoader classLoader)
throws ClassNotFoundException {
return buf.getObject(classLoader);
}
@Override
public IoBuffer putObject(Object o) {
buf.putObject(o);
return this;
}
@Override
public InputStream asInputStream() {
return buf.asInputStream();
}
@Override
public OutputStream asOutputStream() {
return buf.asOutputStream();
}
@Override
public IoBuffer duplicate() {
return buf.duplicate();
}
@Override
public IoBuffer slice() {
return buf.slice();
}
@Override
public IoBuffer asReadOnlyBuffer() {
return buf.asReadOnlyBuffer();
}
@Override
public byte[] array() {
return buf.array();
}
@Override
public int arrayOffset() {
return buf.arrayOffset();
}
@Override
public int minimumCapacity() {
return buf.minimumCapacity();
}
@Override
public IoBuffer minimumCapacity(int minimumCapacity) {
buf.minimumCapacity(minimumCapacity);
return this;
}
@Override
public IoBuffer capacity(int newCapacity) {
buf.capacity(newCapacity);
return this;
}
@Override
public boolean isReadOnly() {
return buf.isReadOnly();
}
@Override
public int markValue() {
return buf.markValue();
}
@Override
public boolean hasArray() {
return buf.hasArray();
}
@Override
public void free() {
buf.free();
}
@Override
public boolean isDerived() {
return buf.isDerived();
}
@Override
public boolean isAutoShrink() {
return buf.isAutoShrink();
}
@Override
public IoBuffer setAutoShrink(boolean autoShrink) {
buf.setAutoShrink(autoShrink);
return this;
}
@Override
public IoBuffer shrink() {
buf.shrink();
return this;
}
@Override
public int getMediumInt() {
return buf.getMediumInt();
}
@Override
public int getUnsignedMediumInt() {
return buf.getUnsignedMediumInt();
}
@Override
public int getMediumInt(int index) {
return buf.getMediumInt(index);
}
@Override
public int getUnsignedMediumInt(int index) {
return buf.getUnsignedMediumInt(index);
}
@Override
public IoBuffer putMediumInt(int value) {
buf.putMediumInt(value);
return this;
}
@Override
public IoBuffer putMediumInt(int index, int value) {
buf.putMediumInt(index, value);
return this;
}
@Override
public String getHexDump(int lengthLimit) {
return buf.getHexDump(lengthLimit);
}
@Override
public boolean prefixedDataAvailable(int prefixLength) {
return buf.prefixedDataAvailable(prefixLength);
}
@Override
public boolean prefixedDataAvailable(int prefixLength, int maxDataLength) {
return buf.prefixedDataAvailable(prefixLength, maxDataLength);
}
@Override
public int indexOf(byte b) {
return buf.indexOf(b);
}
@Override
public <E extends Enum<E>> E getEnum(Class<E> enumClass) {
return buf.getEnum(enumClass);
}
@Override
public <E extends Enum<E>> E getEnum(int index, Class<E> enumClass) {
return buf.getEnum(index, enumClass);
}
@Override
public <E extends Enum<E>> E getEnumShort(Class<E> enumClass) {
return buf.getEnumShort(enumClass);
}
@Override
public <E extends Enum<E>> E getEnumShort(int index, Class<E> enumClass) {
return buf.getEnumShort(index, enumClass);
}
@Override
public <E extends Enum<E>> E getEnumInt(Class<E> enumClass) {
return buf.getEnumInt(enumClass);
}
@Override
public <E extends Enum<E>> E getEnumInt(int index, Class<E> enumClass) {
return buf.getEnumInt(index, enumClass);
}
@Override
public IoBuffer putEnum(Enum<?> e) {
buf.putEnum(e);
return this;
}
@Override
public IoBuffer putEnum(int index, Enum<?> e) {
buf.putEnum(index, e);
return this;
}
@Override
public IoBuffer putEnumShort(Enum<?> e) {
buf.putEnumShort(e);
return this;
}
@Override
public IoBuffer putEnumShort(int index, Enum<?> e) {
buf.putEnumShort(index, e);
return this;
}
@Override
public IoBuffer putEnumInt(Enum<?> e) {
buf.putEnumInt(e);
return this;
}
@Override
public IoBuffer putEnumInt(int index, Enum<?> e) {
buf.putEnumInt(index, e);
return this;
}
@Override
public <E extends Enum<E>> EnumSet<E> getEnumSet(Class<E> enumClass) {
return buf.getEnumSet(enumClass);
}
@Override
public <E extends Enum<E>> EnumSet<E> getEnumSet(int index, Class<E> enumClass) {
return buf.getEnumSet(index, enumClass);
}
@Override
public <E extends Enum<E>> EnumSet<E> getEnumSetShort(Class<E> enumClass) {
return buf.getEnumSetShort(enumClass);
}
@Override
public <E extends Enum<E>> EnumSet<E> getEnumSetShort(int index, Class<E> enumClass) {
return buf.getEnumSetShort(index, enumClass);
}
@Override
public <E extends Enum<E>> EnumSet<E> getEnumSetInt(Class<E> enumClass) {
return buf.getEnumSetInt(enumClass);
}
@Override
public <E extends Enum<E>> EnumSet<E> getEnumSetInt(int index, Class<E> enumClass) {
return buf.getEnumSetInt(index, enumClass);
}
@Override
public <E extends Enum<E>> EnumSet<E> getEnumSetLong(Class<E> enumClass) {
return buf.getEnumSetLong(enumClass);
}
@Override
public <E extends Enum<E>> EnumSet<E> getEnumSetLong(int index, Class<E> enumClass) {
return buf.getEnumSetLong(index, enumClass);
}
@Override
public <E extends Enum<E>> IoBuffer putEnumSet(Set<E> set) {
buf.putEnumSet(set);
return this;
}
@Override
public <E extends Enum<E>> IoBuffer putEnumSet(int index, Set<E> set) {
buf.putEnumSet(index, set);
return this;
}
@Override
public <E extends Enum<E>> IoBuffer putEnumSetShort(Set<E> set) {
buf.putEnumSetShort(set);
return this;
}
@Override
public <E extends Enum<E>> IoBuffer putEnumSetShort(int index, Set<E> set) {
buf.putEnumSetShort(index, set);
return this;
}
@Override
public <E extends Enum<E>> IoBuffer putEnumSetInt(Set<E> set) {
buf.putEnumSetInt(set);
return this;
}
@Override
public <E extends Enum<E>> IoBuffer putEnumSetInt(int index, Set<E> set) {
buf.putEnumSetInt(index, set);
return this;
}
@Override
public <E extends Enum<E>> IoBuffer putEnumSetLong(Set<E> set) {
buf.putEnumSetLong(set);
return this;
}
@Override
public <E extends Enum<E>> IoBuffer putEnumSetLong(int index, Set<E> set) {
buf.putEnumSetLong(index, set);
return this;
}
}
| apache-2.0 |
jbeecham/ovirt-engine | backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/AddDiskCommand.java | 22369 | package org.ovirt.engine.core.bll;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.ovirt.engine.core.bll.command.utils.StorageDomainSpaceChecker;
import org.ovirt.engine.core.bll.job.ExecutionHandler;
import org.ovirt.engine.core.bll.quota.Quotable;
import org.ovirt.engine.core.bll.quota.StorageQuotaValidationParameter;
import org.ovirt.engine.core.bll.snapshots.SnapshotsValidator;
import org.ovirt.engine.core.bll.storage.StorageDomainCommandBase;
import org.ovirt.engine.core.bll.utils.PermissionSubject;
import org.ovirt.engine.core.bll.utils.VmDeviceUtils;
import org.ovirt.engine.core.bll.utils.WipeAfterDeleteUtils;
import org.ovirt.engine.core.bll.validator.StorageDomainValidator;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.VdcObjectType;
import org.ovirt.engine.core.common.action.AddDiskParameters;
import org.ovirt.engine.core.common.action.AddImageFromScratchParameters;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.action.VdcReturnValueBase;
import org.ovirt.engine.core.common.businessentities.ActionGroup;
import org.ovirt.engine.core.common.businessentities.Disk;
import org.ovirt.engine.core.common.businessentities.Disk.DiskStorageType;
import org.ovirt.engine.core.common.businessentities.DiskImage;
import org.ovirt.engine.core.common.businessentities.DiskLunMap;
import org.ovirt.engine.core.common.businessentities.LUNs;
import org.ovirt.engine.core.common.businessentities.LunDisk;
import org.ovirt.engine.core.common.businessentities.QuotaEnforcementTypeEnum;
import org.ovirt.engine.core.common.businessentities.Snapshot.SnapshotType;
import org.ovirt.engine.core.common.businessentities.StoragePoolIsoMapId;
import org.ovirt.engine.core.common.businessentities.StorageType;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VMStatus;
import org.ovirt.engine.core.common.businessentities.VmDeviceId;
import org.ovirt.engine.core.common.businessentities.VolumeType;
import org.ovirt.engine.core.common.businessentities.permissions;
import org.ovirt.engine.core.common.businessentities.storage_domains;
import org.ovirt.engine.core.common.businessentities.storage_server_connections;
import org.ovirt.engine.core.common.config.Config;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.locks.LockingGroup;
import org.ovirt.engine.core.common.utils.VmDeviceType;
import org.ovirt.engine.core.common.validation.group.UpdateEntity;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.NGuid;
import org.ovirt.engine.core.dal.VdcBllMessages;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.dao.BaseDiskDao;
import org.ovirt.engine.core.dao.DiskLunMapDao;
import org.ovirt.engine.core.dao.SnapshotDao;
import org.ovirt.engine.core.dao.StorageDomainStaticDAO;
import org.ovirt.engine.core.utils.transaction.TransactionMethod;
import org.ovirt.engine.core.utils.transaction.TransactionSupport;
@DisableInPrepareMode
@NonTransactiveCommandAttribute(forceCompensation = true)
public class AddDiskCommand<T extends AddDiskParameters> extends AbstractDiskVmCommand<T>
implements Quotable {
private static final long serialVersionUID = 4499428315430159917L;
/**
* Constructor for command creation when compensation is applied on startup
*
* @param commandId
*/
protected AddDiskCommand(Guid commandId) {
super(commandId);
}
public AddDiskCommand(T parameters) {
super(parameters);
parameters.getDiskInfo().setId(Guid.NewGuid());
parameters.setEntityId(parameters.getDiskInfo().getId());
}
@Override
protected boolean canDoAction() {
boolean returnValue = isVmExist() && acquireLockInternal();
VM vm = getVm();
// if user sent drive check that its not in use
returnValue = returnValue && (vm == null || isDiskCanBeAddedToVm(getParameters().getDiskInfo()));
if (returnValue && DiskStorageType.IMAGE == getParameters().getDiskInfo().getDiskStorageType()) {
returnValue = checkIfImageDiskCanBeAdded(vm);
}
if (returnValue && DiskStorageType.LUN == getParameters().getDiskInfo().getDiskStorageType()) {
returnValue = checkIfLunDiskCanBeAdded();
}
return returnValue;
}
protected boolean checkIfLunDiskCanBeAdded() {
LUNs lun = ((LunDisk) getParameters().getDiskInfo()).getLun();
switch (lun.getLunType()) {
case UNKNOWN:
return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_HAS_NO_VALID_TYPE);
case ISCSI:
if (lun.getLunConnections() == null || lun.getLunConnections().isEmpty()) {
return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_ISCSI_MISSING_CONNECTION_PARAMS);
}
for (storage_server_connections conn : lun.getLunConnections()) {
if (StringUtils.isEmpty(conn.getiqn()) || StringUtils.isEmpty(conn.getconnection())
|| StringUtils.isEmpty(conn.getport())) {
return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_ISCSI_MISSING_CONNECTION_PARAMS);
}
}
break;
}
if (getDiskLunMapDao().getDiskIdByLunId(lun.getLUN_id()) != null) {
return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_IS_ALREADY_IN_USE);
}
return true;
}
private boolean checkIfImageDiskCanBeAdded(VM vm) {
boolean returnValue;
StorageDomainValidator validator = new StorageDomainValidator(getStorageDomain());
returnValue = validator.isDomainExistAndActive(getReturnValue().getCanDoActionMessages());
if (returnValue && vm != null && getStoragePoolIsoMapDao().get(new StoragePoolIsoMapId(
getStorageDomainId().getValue(), vm.getstorage_pool_id())) == null) {
returnValue = false;
addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_POOL_OF_VM_NOT_MATCH);
}
returnValue = returnValue
&& checkImageConfiguration()
&& (vm == null || isDiskPassPciAndIdeLimit(getParameters().getDiskInfo()));
returnValue = returnValue && (vm == null || performImagesChecks(vm));
if (returnValue && !hasFreeSpace(getStorageDomain())) {
returnValue = false;
addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_DISK_SPACE_LOW);
}
if (returnValue && isExceedMaxBlockDiskSize()) {
addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_DISK_MAX_SIZE_EXCEEDED);
getReturnValue().getCanDoActionMessages().add(
String.format("$max_disk_size %1$s", Config.<Integer> GetValue(ConfigValues.MaxBlockDiskSize)));
returnValue = false;
}
if (returnValue && getParameters().getDiskInfo().isShareable()) {
if (!Config.<Boolean> GetValue(ConfigValues.ShareableDiskEnabled,
getStoragePool().getcompatibility_version().getValue())) {
returnValue = false;
addCanDoActionMessage(VdcBllMessages.ACTION_NOT_SUPPORTED_FOR_CLUSTER_POOL_LEVEL);
}
else if (!isVolumeFormatSupportedForShareable(
((DiskImage) getParameters().getDiskInfo()).getvolume_format())) {
returnValue = false;
addCanDoActionMessage(VdcBllMessages.SHAREABLE_DISK_IS_NOT_SUPPORTED_BY_VOLUME_FORMAT);
}
}
return returnValue && (vm == null || validate(getSnapshotValidator().vmNotDuringSnapshot(vm.getId())));
}
protected SnapshotsValidator getSnapshotValidator() {
return new SnapshotsValidator();
}
/** Checks if the iamge's configuration is legal */
protected boolean checkImageConfiguration() {
return ImagesHandler.CheckImageConfiguration(
getStorageDomain().getStorageStaticData(),
getDiskImageInfo(),
getReturnValue().getCanDoActionMessages());
}
protected boolean performImagesChecks(VM vm) {
return ImagesHandler.PerformImagesChecks(vm,
getReturnValue().getCanDoActionMessages(),
vm.getstorage_pool_id(),
getStorageDomainId().getValue(),
false,
true,
false,
false,
true,
false,
false,
true,
null);
}
private long getRequestDiskSpace() {
if (getParameters().getDiskInfo().getDiskStorageType() == DiskStorageType.IMAGE) {
return getDiskImageInfo().getSizeInGigabytes();
}
return 0;
}
@Override
protected boolean isVmExist() {
return getParameters().getVmId() == null || Guid.Empty.equals(getParameters().getVmId()) || super.isVmExist();
}
private boolean hasFreeSpace(storage_domains storageDomain) {
if (getDiskImageInfo().getvolume_type() == VolumeType.Preallocated) {
return doesStorageDomainhaveSpaceForRequest(storageDomain);
}
return isStorageDomainBelowThresholds(storageDomain);
}
protected boolean doesStorageDomainhaveSpaceForRequest(storage_domains storageDomain) {
return StorageDomainSpaceChecker.hasSpaceForRequest(storageDomain, getDiskImageInfo().getSizeInGigabytes());
}
protected boolean isStorageDomainBelowThresholds(storage_domains storageDomain) {
return StorageDomainSpaceChecker.isBelowThresholds(storageDomain);
}
/** @return The disk from the parameters, cast to a {@link DiskImage} */
private DiskImage getDiskImageInfo() {
return (DiskImage) getParameters().getDiskInfo();
}
private boolean isExceedMaxBlockDiskSize() {
StorageType storageType = getStorageDomain().getstorage_type();
boolean isBlockStorageDomain = storageType == StorageType.ISCSI || storageType == StorageType.FCP;
boolean isRequestedLargerThanMaxSize = getRequestDiskSpace() > Config.<Integer> GetValue(ConfigValues.MaxBlockDiskSize);
return isBlockStorageDomain && isRequestedLargerThanMaxSize;
}
/**
* @return The StorageDomainStaticDAO
*/
protected StorageDomainStaticDAO getStorageDomainStaticDao() {
return DbFacade.getInstance().getStorageDomainStaticDao();
}
@Override
protected SnapshotDao getSnapshotDao() {
return DbFacade.getInstance().getSnapshotDao();
}
protected BaseDiskDao getBaseDiskDao() {
return DbFacade.getInstance().getBaseDiskDao();
}
protected DiskLunMapDao getDiskLunMapDao() {
return DbFacade.getInstance().getDiskLunMapDao();
}
/**
* @return The ID of the storage domain where the VM's disks reside.
*/
private Guid getDisksStorageDomainId() {
return ((DiskImage) getVm().getDiskMap().values().iterator().next()).getstorage_ids().get(0);
}
@Override
public NGuid getStorageDomainId() {
Guid storageDomainId = getParameters().getStorageDomainId();
if (Guid.Empty.equals(storageDomainId) &&
getVm() != null &&
getVm().getDiskMap() != null &&
!getVm().getDiskMap().isEmpty()) {
return getDisksStorageDomainId();
}
return storageDomainId == null ? Guid.Empty : storageDomainId;
}
@Override
public List<PermissionSubject> getPermissionCheckSubjects() {
List<PermissionSubject> listPermissionSubjects;
if (getParameters().getVmId() == null || Guid.Empty.equals(getParameters().getVmId())) {
listPermissionSubjects = new ArrayList<PermissionSubject>();
} else {
listPermissionSubjects = super.getPermissionCheckSubjects();
}
// If the storage domain ID is empty/null, it means we are going to create an external disk
// In order to do that we need CREATE_DISK permissions on System level
if (getParameters().getStorageDomainId() == null || Guid.Empty.equals(getParameters().getStorageDomainId())) {
listPermissionSubjects.add(new PermissionSubject(Guid.SYSTEM,
VdcObjectType.System,
ActionGroup.CREATE_DISK));
} else {
listPermissionSubjects.add(new PermissionSubject(getParameters().getStorageDomainId(),
VdcObjectType.Storage,
ActionGroup.CREATE_DISK));
}
return listPermissionSubjects;
}
@Override
protected void setActionMessageParameters() {
addCanDoActionMessage(VdcBllMessages.VAR__ACTION__ADD);
addCanDoActionMessage(VdcBllMessages.VAR__TYPE__VM_DISK);
}
@Override
protected void executeVmCommand() {
ImagesHandler.setDiskAlias(getParameters().getDiskInfo(), getVm());
if (!getParameters().getDiskInfo().isWipeAfterDeleteSet()) {
StorageType storageType = getStorageDomain().getstorage_type();
getParameters().getDiskInfo()
.setWipeAfterDelete(WipeAfterDeleteUtils.getDefaultWipeAfterDeleteFlag(storageType));
}
if (DiskStorageType.IMAGE == getParameters().getDiskInfo().getDiskStorageType()) {
createDiskBasedOnImage();
} else {
createDiskBasedOnLun();
}
}
private void createDiskBasedOnLun() {
final LUNs lun = ((LunDisk) getParameters().getDiskInfo()).getLun();
TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() {
@Override
public Void runInTransaction() {
StorageDomainCommandBase.proceedLUNInDb(lun, lun.getLunType());
getBaseDiskDao().save(getParameters().getDiskInfo());
getDiskLunMapDao().save(new DiskLunMap(getParameters().getDiskInfo().getId(), lun.getLUN_id()));
if (getVm() != null) {
VmDeviceUtils.addManagedDevice(new VmDeviceId(getParameters().getDiskInfo().getId(), getVmId()),
VmDeviceType.DISK,
VmDeviceType.DISK,
null,
getVm().getstatus() == VMStatus.Down,
false);
}
return null;
}
});
getReturnValue().setActionReturnValue(getParameters().getDiskInfo().getId());
setSucceeded(true);
}
private void createDiskBasedOnImage() {
// create from blank template, create new vm snapshot id
AddImageFromScratchParameters parameters =
new AddImageFromScratchParameters(Guid.Empty,
getParameters().getVmId(),
getDiskImageInfo());
parameters.setQuotaId(getQuotaId());
parameters.setDiskAlias(getDiskAlias());
parameters.setStorageDomainId(getStorageDomainId().getValue());
parameters.setParentCommand(VdcActionType.AddDisk);
parameters.setEntityId(getParameters().getEntityId());
parameters.setStoragePoolId(getStorageDomain().getstorage_pool_id().getValue());
getParameters().getImagesParameters().add(parameters);
parameters.setParentParameters(getParameters());
if (getVm() != null) {
setVmSnapshotIdForDisk(parameters);
getCompensationContext().snapshotNewEntity(VmDeviceUtils.addManagedDevice(new VmDeviceId(getParameters().getDiskInfo()
.getId(),
getVmId()),
VmDeviceType.DISK,
VmDeviceType.DISK,
null,
getVm().getstatus() == VMStatus.Down,
false));
getCompensationContext().stateChanged();
}
VdcReturnValueBase tmpRetValue =
Backend.getInstance().runInternalAction(VdcActionType.AddImageFromScratch,
parameters,
ExecutionHandler.createDefaultContexForTasks(getExecutionContext(), getLock()));
// Setting lock to null because the lock is released in the child command
setLock(null);
getReturnValue().getTaskIdList().addAll(tmpRetValue.getInternalTaskIdList());
if (tmpRetValue.getActionReturnValue() != null) {
DiskImage diskImage = (DiskImage) tmpRetValue.getActionReturnValue();
addDiskPermissions(diskImage);
getReturnValue().setActionReturnValue(diskImage.getId());
}
getReturnValue().setFault(tmpRetValue.getFault());
setSucceeded(tmpRetValue.getSucceeded());
}
/**
* If disk is not allow to have snapshot no VM snapshot Id should be updated.
* @param parameters
*/
private void setVmSnapshotIdForDisk(AddImageFromScratchParameters parameters) {
if (getParameters().getDiskInfo().isAllowSnapshot()) {
parameters.setVmSnapshotId(getSnapshotDao().getId(getVmId(), SnapshotType.ACTIVE));
}
}
private void addDiskPermissions(Disk disk) {
permissions perms =
new permissions(getCurrentUser().getUserId(),
PredefinedRoles.DISK_OPERATOR.getId(),
disk.getId(),
VdcObjectType.Disk);
MultiLevelAdministrationHandler.addPermission(perms);
}
@Override
public AuditLogType getAuditLogTypeValue() {
switch (getActionState()) {
case EXECUTE:
return getExecuteAuditLogTypeValue(getSucceeded());
case END_SUCCESS:
return getEndSuccessAuditLogTypeValue(getSucceeded());
default:
return AuditLogType.USER_ADD_DISK_FINISHED_FAILURE;
}
}
private AuditLogType getExecuteAuditLogTypeValue(boolean successful) {
boolean isVmNameExist = StringUtils.isNotEmpty(getVmName());
if (successful) {
if (isVmNameExist) {
return AuditLogType.USER_ADD_DISK_TO_VM;
} else {
return AuditLogType.USER_ADD_DISK;
}
} else {
if (isVmNameExist) {
return AuditLogType.USER_FAILED_ADD_DISK_TO_VM;
} else {
return AuditLogType.USER_FAILED_ADD_DISK;
}
}
}
private AuditLogType getEndSuccessAuditLogTypeValue(boolean successful) {
boolean isVmNameExist = StringUtils.isNotEmpty(getVmName());
if (successful) {
if (isVmNameExist) {
return AuditLogType.USER_ADD_DISK_TO_VM_FINISHED_SUCCESS;
} else {
return AuditLogType.USER_ADD_DISK_FINISHED_SUCCESS;
}
} else {
if (isVmNameExist) {
return AuditLogType.USER_ADD_DISK_TO_VM_FINISHED_FAILURE;
} else {
return AuditLogType.USER_ADD_DISK_FINISHED_FAILURE;
}
}
}
@Override
protected VdcActionType getChildActionType() {
return VdcActionType.AddImageFromScratch;
}
@Override
protected List<Class<?>> getValidationGroups() {
addValidationGroup(UpdateEntity.class);
return super.getValidationGroups();
}
@Override
protected Map<String, String> getExclusiveLocks() {
if (getParameters().getDiskInfo().isBoot() && getParameters().getVmId() != null
&& !Guid.Empty.equals(getParameters().getVmId())) {
return Collections.singletonMap(getParameters().getVmId().toString(), LockingGroup.VM_DISK_BOOT.name());
}
return null;
}
@Override
protected Map<String, String> getSharedLocks() {
if (getParameters().getVmId() != null && !Guid.Empty.equals(getParameters().getVmId())) {
return Collections.singletonMap(getParameters().getVmId().toString(), LockingGroup.VM.name());
}
return null;
}
@Override
public boolean validateAndSetQuota() {
if (getParameters().getDiskInfo().getDiskStorageType() == DiskStorageType.IMAGE) {
if (getStoragePool() == null) {
setStoragePoolId(getStorageDomain().getstorage_pool_id().getValue());
}
return getQuotaManager().validateAndSetStorageQuota(getStoragePool(),
getStorageQuotaListParameters(),
getReturnValue().getCanDoActionMessages());
}
return true;
}
@Override
public void rollbackQuota() {
if (getParameters().getDiskInfo().getDiskStorageType() == DiskStorageType.IMAGE) {
getQuotaManager().rollbackQuota(getStoragePool(),
getQuotaManager().getQuotaListFromParameters(getStorageQuotaListParameters()));
}
}
@Override
public Guid getQuotaId() {
if (getParameters().getDiskInfo() != null
&& DiskStorageType.IMAGE == getParameters().getDiskInfo().getDiskStorageType()) {
return ((DiskImage) getParameters().getDiskInfo()).getQuotaId();
}
return null;
}
private List<StorageQuotaValidationParameter> getStorageQuotaListParameters() {
List<StorageQuotaValidationParameter> list = new ArrayList<StorageQuotaValidationParameter>();
list.add(new StorageQuotaValidationParameter(getQuotaId(),
getStorageDomainId().getValue(),
getRequestDiskSpace()));
return list;
}
@Override
public void addQuotaPermissionSubject(List<PermissionSubject> quotaPermissionList) {
if (getStoragePool() != null &&
getQuotaId() != null &&
!getStoragePool().getQuotaEnforcementType().equals(QuotaEnforcementTypeEnum.DISABLED)) {
quotaPermissionList.add(new PermissionSubject(getQuotaId(), VdcObjectType.Quota, ActionGroup.CONSUME_QUOTA));
}
}
@Override
protected void endWithFailure() {
super.endWithFailure();
rollbackQuota();
}
}
| apache-2.0 |
scalecube/scalecube | services-api/src/main/java/io/scalecube/services/auth/PrincipalMapper.java | 269 | package io.scalecube.services.auth;
@FunctionalInterface
public interface PrincipalMapper<A, P> {
/**
* Turns {@code authData} to concrete principal object.
*
* @param authData auth data
* @return converted principle object
*/
P map(A authData);
}
| apache-2.0 |
vam-google/google-cloud-java | google-api-grpc/proto-google-cloud-dlp-v2/src/main/java/com/google/privacy/dlp/v2/ListJobTriggersResponseOrBuilder.java | 2230 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/privacy/dlp/v2/dlp.proto
package com.google.privacy.dlp.v2;
public interface ListJobTriggersResponseOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.privacy.dlp.v2.ListJobTriggersResponse)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* List of triggeredJobs, up to page_size in ListJobTriggersRequest.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.JobTrigger job_triggers = 1;</code>
*/
java.util.List<com.google.privacy.dlp.v2.JobTrigger> getJobTriggersList();
/**
*
*
* <pre>
* List of triggeredJobs, up to page_size in ListJobTriggersRequest.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.JobTrigger job_triggers = 1;</code>
*/
com.google.privacy.dlp.v2.JobTrigger getJobTriggers(int index);
/**
*
*
* <pre>
* List of triggeredJobs, up to page_size in ListJobTriggersRequest.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.JobTrigger job_triggers = 1;</code>
*/
int getJobTriggersCount();
/**
*
*
* <pre>
* List of triggeredJobs, up to page_size in ListJobTriggersRequest.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.JobTrigger job_triggers = 1;</code>
*/
java.util.List<? extends com.google.privacy.dlp.v2.JobTriggerOrBuilder>
getJobTriggersOrBuilderList();
/**
*
*
* <pre>
* List of triggeredJobs, up to page_size in ListJobTriggersRequest.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.JobTrigger job_triggers = 1;</code>
*/
com.google.privacy.dlp.v2.JobTriggerOrBuilder getJobTriggersOrBuilder(int index);
/**
*
*
* <pre>
* If the next page is available then the next page token to be used
* in following ListJobTriggers request.
* </pre>
*
* <code>string next_page_token = 2;</code>
*/
java.lang.String getNextPageToken();
/**
*
*
* <pre>
* If the next page is available then the next page token to be used
* in following ListJobTriggers request.
* </pre>
*
* <code>string next_page_token = 2;</code>
*/
com.google.protobuf.ByteString getNextPageTokenBytes();
}
| apache-2.0 |
gchq/gaffer-doc | src/main/java/uk/gov/gchq/gaffer/doc/function/ExtractWalkEdgesExample.java | 3556 | /*
* Copyright 2017-2020 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 uk.gov.gchq.gaffer.doc.function;
import uk.gov.gchq.gaffer.data.element.Edge;
import uk.gov.gchq.gaffer.data.element.Entity;
import uk.gov.gchq.gaffer.data.graph.Walk;
import uk.gov.gchq.gaffer.data.graph.function.walk.ExtractWalkEdges;
public class ExtractWalkEdgesExample extends FunctionExample {
public static void main(final String[] args) {
new ExtractWalkEdgesExample().runAndPrint();
}
public ExtractWalkEdgesExample() {
super(ExtractWalkEdges.class, "An ExtractWalkEdges will extract a List of ALL Sets of Edges, from a given Walk.");
}
@Override
protected void runExamples() {
extractEdgesFromWalk();
}
public void extractEdgesFromWalk() {
// ---------------------------------------------------------
final ExtractWalkEdges function = new ExtractWalkEdges();
// ---------------------------------------------------------
runExample(function,
null,
new Walk.Builder()
.entity(new Entity.Builder()
.group("BasicEntity")
.vertex("A")
.build())
.edge(new Edge.Builder()
.group("BasicEdge")
.source("A")
.dest("B")
.directed(true)
.build())
.entity(new Entity.Builder()
.group("BasicEntity")
.vertex("B")
.build())
.edges(new Edge.Builder()
.group("BasicEdge")
.source("B")
.dest("C")
.directed(true)
.build(),
new Edge.Builder()
.group("EnhancedEdge")
.source("B")
.dest("C")
.directed(true)
.build())
.entity(new Entity.Builder()
.group("BasicEntity")
.vertex("C")
.build())
.edge(new Edge.Builder()
.group("BasicEdge")
.source("C")
.dest("A")
.directed(true)
.build())
.entity(new Entity.Builder()
.group("BasicEntity")
.vertex("A")
.build())
.build());
}
}
| apache-2.0 |
CognizantQAHub/Cognizant-Intelligent-Test-Scripter | IDE/src/main/java/com/cognizant/cognizantits/ide/util/browser/PlatformBrowser.java | 792 | /*
* Copyright 2014 - 2017 Cognizant Technology Solutions
*
* 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.cognizant.cognizantits.ide.util.browser;
public class PlatformBrowser {
public static Browser getBrowser() {
return new JavaFXBrowser();
}
}
| apache-2.0 |
haryadi87/Coffeestore | src/com/coffeestore/MenuActivity.java | 3542 | /**
* @author Haryadi,Matthew,Nouras
*/
package com.coffeestore;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import com.coffeestore.communication.Communication;
import com.coffeestore.control.Mediator;
import com.coffeestore.utils.OrderMenu;
import com.coffeestore.view.ListMenuFragment;
import com.coffeestore.view.OrderMenuFragment;
public class MenuActivity extends Activity {
private String[] tabledata;
private Button button;
private static Mediator mediator;
private static ListMenuFragment listMenuFragment ;
private static OrderMenuFragment orderMenuFragment;
private static OrderMenu orderMenu;
private static Communication communication;
/**
* When class is created, all components is initialised
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
// Show the Up button in the action bar.
setupActionBar();
addButtonListener();
Intent intent = getIntent();
String buffer = intent.getStringExtra(CameraActivity.EXTRA_MESSAGE);
tabledata = buffer.split(",");
communication = communication.create(mediator, tabledata[0], Integer.parseInt(tabledata[1]));
communication.connect();
TextView textView = (TextView) findViewById(R.id.textview);
textView.setTextSize(40);
textView.setText("Order table no " +tabledata[2]);
}
/**
* Listener for a button
*/
public void addButtonListener() {
button = (Button) findViewById(R.id.send);
button.setOnClickListener(new ButtonHandler());
}
/**
*
* Send data to the server
*
*/
public class ButtonHandler implements OnClickListener {
@Override
public void onClick(View arg0) {
mediator.sendData(tabledata[2]);
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
/**
* Set up the {@link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
mediator = Mediator.create();
orderMenu = OrderMenu.create(mediator);
listMenuFragment = (ListMenuFragment) getFragmentManager().findFragmentById(R.id.listmenu);
listMenuFragment.setMediator(mediator);
orderMenuFragment = (OrderMenuFragment) getFragmentManager().findFragmentById(R.id.ordermenu);
orderMenuFragment.setMediator(mediator);
Log.d("Food", "Components initialised");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
| apache-2.0 |
mikheladun/mvn-ejb3-jpa | persistence/src/main/java/co/adun/mvnejb3jpa/persistence/eao/impl/DisposCloseSystemCodeEaoImpl.java | 990 | package co.adun.mvnejb3jpa.persistence.eao.impl;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import co.adun.mvnejb3jpa.persistence.eao.DisposCloseSystemCodeEao;
import co.adun.mvnejb3jpa.persistence.entity.DisposCloseSystemCode;
/**
* A entity access object class to provide persistent storage functions and CRUD operations for Member entity. Strongly-typed interface created since
* it could be used by @Autowired
*
* @author Mikhel Adun
*
*/
@Component
@Stateless
@Transactional
public class DisposCloseSystemCodeEaoImpl extends BaseEaoImpl<DisposCloseSystemCode> implements DisposCloseSystemCodeEao
{
@SuppressWarnings("unused")
private static final Logger logger = Logger.getLogger(DisposCloseSystemCodeEaoImpl.class.getName());
@Override
public Class<DisposCloseSystemCode> getEntityClass()
{
return DisposCloseSystemCode.class;
}
} | apache-2.0 |
davidcarboni/listpoint-ws | src/main/java/uk/co/listpoint/context/ContextFindDraftsResponse.java | 1857 |
package uk.co.listpoint.context;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{http://www.listpoint.co.uk/messages/Context}ContextFindDraftsResponse" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"contextFindDraftsResponse"
})
@XmlRootElement(name = "ContextFindDraftsResponse")
public class ContextFindDraftsResponse {
@XmlElement(name = "ContextFindDraftsResponse", namespace = "http://www.listpoint.co.uk/messages/Context")
protected ContextFindDraftsResponse6Type contextFindDraftsResponse;
/**
* Gets the value of the contextFindDraftsResponse property.
*
* @return
* possible object is
* {@link ContextFindDraftsResponse6Type }
*
*/
public ContextFindDraftsResponse6Type getContextFindDraftsResponse() {
return contextFindDraftsResponse;
}
/**
* Sets the value of the contextFindDraftsResponse property.
*
* @param value
* allowed object is
* {@link ContextFindDraftsResponse6Type }
*
*/
public void setContextFindDraftsResponse(ContextFindDraftsResponse6Type value) {
this.contextFindDraftsResponse = value;
}
}
| apache-2.0 |
palava/palava-grapher | src/test/java/de/cosmocode/palava/grapher/GrapherServiceTest.java | 1510 | /**
* Copyright 2010 CosmoCode GmbH
*
* 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 de.cosmocode.palava.grapher;
import java.io.File;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
import de.cosmocode.palava.core.Framework;
import de.cosmocode.palava.core.Palava;
/**
* Tests {@link DefaultGrapherService}.
*
* @author Willi Schoenborn
*/
public final class GrapherServiceTest {
/**
* Tests {@link DefaultGrapherService#execute()}.
*
* @throws IOException should not happen
*/
@Test
public void execute() throws IOException {
final File file = new File("graph.dot");
file.delete();
Assert.assertFalse(file.exists());
final Framework framework = Palava.newFramework();
framework.start();
framework.getInstance(GrapherService.class).execute();
framework.stop();
Assert.assertTrue(file.exists());
Assert.assertTrue(file.length() > 0);
}
}
| apache-2.0 |
wzx54321/XinFramework | app/src/main/java/com/xin/framework/xinframwork/ui/widget/titlebar/utils/TitleViewUtils.java | 3018 | package com.xin.framework.xinframwork.ui.widget.titlebar.utils;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.os.Build;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
/**
*/
@SuppressWarnings("SuspiciousNameCombination")
public class TitleViewUtils {
static private float density = -1;
static private int screenWidth = -1;
static private int screenHeight = -1;
public static void init(Context context) {
if (density == -1) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
density = metrics.density;
if (metrics.widthPixels < metrics.heightPixels) {
screenWidth = metrics.widthPixels;
screenHeight = metrics.heightPixels;
} else { // 部分机器使用application的context宽高反转
screenHeight = metrics.widthPixels;
screenWidth = metrics.heightPixels;
}
}
}
public static int getStatusBarHeight(Context context) {
int result = 0;
Resources resources = context.getResources();
int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = resources.getDimensionPixelSize(resourceId);
}
if (result <= 0) {
result = dpToPx(25);
}
return result;
}
public static float getDensity() {
return density;
}
public static int getScreenWidth() {
return screenWidth;
}
public static int getScreenHeight() {
return screenHeight;
}
public static int dpToPx(float dp) {
return Math.round(dp * getDensity());
}
public static int PxToDp(float px) {
return Math.round(px / getDensity());
}
/**
* 在xml里设置android:alpha对api11以前的系统不起作用,所以在代码里获取并设置透明度
*/
public static void setAlpha(View view, float alphaValue) {
if (view == null) {
return;
}
view.setAlpha(alphaValue);
}
@SuppressLint("InlinedApi")
public static void full(Activity activity, boolean isImmersive) {
if(activity==null){
return;
}
activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
if (isImmersive) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); //透明状态栏
}
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); //透明导航栏
} else {
activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
}
} | apache-2.0 |
ua-eas/ksd-kc5.2.1-rice2.3.6-ua | rice-middleware/krms/impl/src/test/java/org/kuali/rice/krms/impl/repository/NaturalLanguageTemplateBoServiceImplGenTest.java | 7851 | /**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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.kuali.rice.krms.impl.repository;
import org.junit.Before;
import org.junit.Test;
import org.kuali.rice.krad.service.BusinessObjectService;
import org.kuali.rice.krms.api.repository.NaturalLanguageTemplateGenTest;
import org.kuali.rice.krms.api.repository.language.NaturalLanguageTemplate;
import org.kuali.rice.krms.api.repository.language.NaturalLanguageUsage;
import org.kuali.rice.krms.api.repository.type.KrmsAttributeDefinition;
import org.kuali.rice.krms.api.repository.type.KrmsTypeDefinition;
import org.kuali.rice.krms.api.repository.type.KrmsTypeRepositoryService;
import java.util.Map;
import static org.mockito.Mockito.mock;
/**
* @author Kuali Rice Team (rice.collab@kuali.org)
*
*/
public final class NaturalLanguageTemplateBoServiceImplGenTest {
NaturalLanguageTemplateBoServiceImpl naturalLanguageTemplateBoServiceImpl;
NaturalLanguageTemplate naturalLanguageTemplate;
KrmsAttributeDefinitionService krmsAttributeDefinitionService;
NaturalLanguageTemplate getNaturalLanguageTemplate() {
return naturalLanguageTemplate;
}
public void setNaturalLanguageTemplateBoServiceImpl(NaturalLanguageTemplateBoServiceImpl impl) {
this.naturalLanguageTemplateBoServiceImpl = impl;
}
public void setKrmsAttributeDefinitionService(KrmsAttributeDefinitionService impl) {
krmsAttributeDefinitionService = impl;
}
public static org.kuali.rice.krms.impl.repository.NaturalLanguageTemplateBoServiceImplGenTest create(
NaturalLanguageTemplateBoServiceImpl nlTemplateBoService,
KrmsAttributeDefinitionService attributeDefService) {
org.kuali.rice.krms.impl.repository.NaturalLanguageTemplateBoServiceImplGenTest test =
new org.kuali.rice.krms.impl.repository.NaturalLanguageTemplateBoServiceImplGenTest();
test.setKrmsAttributeDefinitionService(attributeDefService);
test.setNaturalLanguageTemplateBoServiceImpl(nlTemplateBoService);
return test;
}
@Before
public void setUp() {
naturalLanguageTemplateBoServiceImpl = new NaturalLanguageTemplateBoServiceImpl();
KrmsAttributeDefinitionService mockAttributeService = mock(KrmsAttributeDefinitionService.class);
NaturalLanguageTemplateBo.setAttributeDefinitionService(mockAttributeService);
KrmsTypeRepositoryService mockTypeRepositoryService = mock(KrmsTypeRepositoryService.class);
NaturalLanguageTemplateBo.setTypeRepositoryService(mockTypeRepositoryService);
naturalLanguageTemplateBoServiceImpl.setAttributeDefinitionService(mockAttributeService);
naturalLanguageTemplateBoServiceImpl.setBusinessObjectService(mock(BusinessObjectService.class));
}
@Test(expected = java.lang.IllegalArgumentException.class)
public void test_getNaturalLanguageTemplatesByAttributes_null_fail() {
naturalLanguageTemplateBoServiceImpl.findNaturalLanguageTemplatesByAttributes(null);
}
@Test(expected = java.lang.IllegalArgumentException.class)
public void test_getNaturalLanguageTemplatesByLanguageCode_null_fail() {
naturalLanguageTemplateBoServiceImpl.findNaturalLanguageTemplatesByLanguageCode(null);
}
@Test(expected = java.lang.IllegalArgumentException.class)
public void test_getNaturalLanguageTemplatesByNaturalLanguageUsage_null_fail() {
naturalLanguageTemplateBoServiceImpl.findNaturalLanguageTemplatesByNaturalLanguageUsage(null);
}
@Test(expected = java.lang.IllegalArgumentException.class)
public void test_getNaturalLanguageTemplatesByType_null_fail() {
naturalLanguageTemplateBoServiceImpl.findNaturalLanguageTemplatesByType(null);
}
@Test(expected = java.lang.IllegalArgumentException.class)
public void test_getNaturalLanguageTemplatesByTemplate_null_fail() {
naturalLanguageTemplateBoServiceImpl.findNaturalLanguageTemplatesByTemplate(null);
}
@Test
public void test_from_null_yields_null() {
assert(naturalLanguageTemplateBoServiceImpl.from(null) == null);
}
@Test
public void test_from() {
NaturalLanguageTemplate def = NaturalLanguageTemplateGenTest.buildFullNaturalLanguageTemplate();
NaturalLanguageTemplateBo naturalLanguageTemplateBo = naturalLanguageTemplateBoServiceImpl.from(def);
assert(naturalLanguageTemplateBo.getLanguageCode().equals(def.getLanguageCode()));
assert(naturalLanguageTemplateBo.getNaturalLanguageUsageId().equals(def.getNaturalLanguageUsageId()));
assert(naturalLanguageTemplateBo.getTypeId().equals(def.getTypeId()));
assert(naturalLanguageTemplateBo.getTemplate().equals(def.getTemplate()));
assert(naturalLanguageTemplateBo.getId().equals(def.getId()));
}
@Test
public void test_to() {
NaturalLanguageTemplate def = NaturalLanguageTemplateGenTest.buildFullNaturalLanguageTemplate();
NaturalLanguageTemplateBo naturalLanguageTemplateBo = naturalLanguageTemplateBoServiceImpl.from(def);
NaturalLanguageTemplate def2 = NaturalLanguageTemplateBo.to(naturalLanguageTemplateBo);
assert(def.equals(def2));
}
@Test
public void test_createNaturalLanguageTemplate() {
NaturalLanguageTemplate def = NaturalLanguageTemplateGenTest.buildFullNaturalLanguageTemplate();
naturalLanguageTemplate = naturalLanguageTemplateBoServiceImpl.createNaturalLanguageTemplate(def);
}
@Test(expected = java.lang.IllegalArgumentException.class)
public void test_createNaturalLanguageTemplate_null_fail() {
naturalLanguageTemplateBoServiceImpl.createNaturalLanguageTemplate(null);
}
@Test(expected = java.lang.IllegalArgumentException.class)
public void test_updateNaturalLanguageTemplate_null_fail() {
naturalLanguageTemplateBoServiceImpl.updateNaturalLanguageTemplate(null);
}
@Test(expected = java.lang.IllegalArgumentException.class)
public void test_deleteNaturalLanguageTemplate_null_fail() {
naturalLanguageTemplateBoServiceImpl.deleteNaturalLanguageTemplate(null);
}
void createNaturalLanguageTemplate(NaturalLanguageUsage naturalLanguageUsage, KrmsTypeDefinition type) {
NaturalLanguageTemplate def = NaturalLanguageTemplateGenTest.buildFullNaturalLanguageTemplate(naturalLanguageUsage, type);
for (Map.Entry<String, String> attributeEntry : def.getAttributes().entrySet()) {
// check for template attribute definition, create if not there
KrmsAttributeDefinition attrDef = krmsAttributeDefinitionService.getAttributeDefinitionByNameAndNamespace(
attributeEntry.getKey(), type.getNamespace());
// rebuild attributes in all cases until Constraint Error found and corrected
// if (null == attrDef) {
KrmsAttributeDefinition.Builder attrDefBuilder =
KrmsAttributeDefinition.Builder.create(null, attributeEntry.getKey(), type.getNamespace());
krmsAttributeDefinitionService.createAttributeDefinition(attrDefBuilder.build());
// }
}
naturalLanguageTemplate = naturalLanguageTemplateBoServiceImpl.createNaturalLanguageTemplate(def);
}
}
| apache-2.0 |
AbleOne/link-rest | agrest/src/main/java/io/agrest/runtime/cayenne/processor/select/CayenneFetchDataStage.java | 1850 | package io.agrest.runtime.cayenne.processor.select;
import io.agrest.AgException;
import io.agrest.meta.AgEntity;
import io.agrest.processor.Processor;
import io.agrest.processor.ProcessorOutcome;
import io.agrest.runtime.cayenne.ICayennePersister;
import io.agrest.runtime.processor.select.SelectContext;
import org.apache.cayenne.di.Inject;
import org.apache.cayenne.query.SelectQuery;
import javax.ws.rs.core.Response;
import java.util.List;
/**
* @since 2.7
*/
public class CayenneFetchDataStage implements Processor<SelectContext<?>> {
private ICayennePersister persister;
public CayenneFetchDataStage(@Inject ICayennePersister persister) {
// Store persister, don't extract ObjectContext from it right away.
// Such deferred initialization may help building POJO pipelines.
this.persister = persister;
}
@Override
public ProcessorOutcome execute(SelectContext<?> context) {
doExecute(context);
return ProcessorOutcome.CONTINUE;
}
protected <T> void doExecute(SelectContext<T> context) {
SelectQuery<T> select = context.getSelect();
List<T> objects = persister.sharedContext().select(select);
if (context.isAtMostOneObject() && objects.size() != 1) {
AgEntity<?> entity = context.getEntity().getAgEntity();
if (objects.isEmpty()) {
throw new AgException(Response.Status.NOT_FOUND,
String.format("No object for ID '%s' and entity '%s'", context.getId(), entity.getName()));
} else {
throw new AgException(Response.Status.INTERNAL_SERVER_ERROR, String.format(
"Found more than one object for ID '%s' and entity '%s'", context.getId(), entity.getName()));
}
}
context.setObjects(objects);
}
}
| apache-2.0 |
nkurihar/pulsar | pulsar-client-tools/src/main/java/org/apache/pulsar/admin/cli/CmdBase.java | 3069 | /**
* 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.pulsar.admin.cli;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import org.apache.pulsar.client.admin.PulsarAdmin;
import org.apache.pulsar.client.admin.PulsarAdminException;
import org.apache.pulsar.client.admin.PulsarAdminException.ConnectException;
public abstract class CmdBase {
protected final JCommander jcommander;
protected final PulsarAdmin admin;
@Parameter(names = { "-h", "--help" }, help = true, hidden = true)
private boolean help;
public CmdBase(String cmdName, PulsarAdmin admin) {
this.admin = admin;
jcommander = new JCommander();
jcommander.setProgramName("pulsar-admin " + cmdName);
}
public boolean run(String[] args) {
try {
jcommander.parse(args);
} catch (Exception e) {
System.err.println(e.getMessage());
System.err.println();
String chosenCommand = jcommander.getParsedCommand();
jcommander.usage(chosenCommand);
return false;
}
String cmd = jcommander.getParsedCommand();
if (cmd == null) {
jcommander.usage();
return false;
} else {
JCommander obj = jcommander.getCommands().get(cmd);
CliCommand cmdObj = (CliCommand) obj.getObjects().get(0);
try {
cmdObj.run();
return true;
} catch (ParameterException e) {
System.err.println(e.getMessage());
System.err.println();
return false;
} catch (ConnectException e) {
System.err.println(e.getMessage());
System.err.println();
System.err.println("Error connecting to: " + admin.getServiceUrl());
return false;
} catch (PulsarAdminException e) {
System.err.println(e.getHttpError());
System.err.println();
System.err.println("Reason: " + e.getMessage());
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
}
| apache-2.0 |
sbrossie/killbill | util/src/main/java/org/killbill/billing/util/glue/KillBillShiroModule.java | 6281 | /*
* Copyright 2010-2013 Ning, Inc.
* Copyright 2014-2019 Groupon, Inc
* Copyright 2014-2019 The Billing Project, LLC
*
* The Billing Project licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.billing.util.glue;
import java.util.Collection;
import java.util.Set;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.guice.ShiroModule;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.mgt.SubjectDAO;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.session.mgt.DefaultSessionManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.killbill.billing.platform.api.KillbillConfigSource;
import org.killbill.billing.util.config.definition.RbacConfig;
import org.killbill.billing.util.config.definition.RedisCacheConfig;
import org.killbill.billing.util.config.definition.SecurityConfig;
import org.killbill.billing.util.security.shiro.realm.KillBillJdbcRealm;
import org.killbill.billing.util.security.shiro.realm.KillBillJndiLdapRealm;
import org.killbill.billing.util.security.shiro.realm.KillBillOktaRealm;
import org.skife.config.ConfigSource;
import org.skife.config.ConfigurationObjectFactory;
import com.google.common.collect.ImmutableSet;
import com.google.inject.TypeLiteral;
import com.google.inject.binder.AnnotatedBindingBuilder;
import com.google.inject.name.Names;
// For Kill Bill library only.
// See org.killbill.billing.server.modules.KillBillShiroWebModule for Kill Bill server.
public class KillBillShiroModule extends ShiroModule {
public static final String KILLBILL_LDAP_PROPERTY = "killbill.server.ldap";
public static final String KILLBILL_OKTA_PROPERTY = "killbill.server.okta";
public static final String KILLBILL_RBAC_PROPERTY = "killbill.server.rbac";
public static boolean isLDAPEnabled() {
return Boolean.parseBoolean(System.getProperty(KILLBILL_LDAP_PROPERTY, "false"));
}
public static boolean isOktaEnabled() {
return Boolean.parseBoolean(System.getProperty(KILLBILL_OKTA_PROPERTY, "false"));
}
public static boolean isRBACEnabled() {
return Boolean.parseBoolean(System.getProperty(KILLBILL_RBAC_PROPERTY, "true"));
}
private final KillbillConfigSource configSource;
private final ConfigSource skifeConfigSource;
private final DefaultSecurityManager defaultSecurityManager;
public KillBillShiroModule(final KillbillConfigSource configSource) {
this.configSource = configSource;
this.skifeConfigSource = new ConfigSource() {
@Override
public String getString(final String propertyName) {
return configSource.getString(propertyName);
}
};
this.defaultSecurityManager = RealmsFromShiroIniProvider.get(skifeConfigSource);
}
protected void configureShiro() {
final RbacConfig config = new ConfigurationObjectFactory(new ConfigSource() {
@Override
public String getString(final String propertyName) {
return configSource.getString(propertyName);
}
}).build(RbacConfig.class);
bind(RbacConfig.class).toInstance(config);
bind(RbacConfig.class).toInstance(config);
final SecurityConfig securityConfig = new ConfigurationObjectFactory(skifeConfigSource).build(SecurityConfig.class);
final Collection<Realm> realms = defaultSecurityManager.getRealms() != null ? defaultSecurityManager.getRealms() :
ImmutableSet.<Realm>of(new IniRealm(securityConfig.getShiroResourcePath())); // Mainly for testing
for (final Realm realm : realms) {
bindRealm().toInstance(realm);
}
configureJDBCRealm();
configureLDAPRealm();
configureOktaRealm();
expose(new TypeLiteral<Set<Realm>>() {});
}
protected void configureJDBCRealm() {
bindRealm().to(KillBillJdbcRealm.class).asEagerSingleton();
}
protected void configureLDAPRealm() {
if (isLDAPEnabled()) {
bindRealm().to(KillBillJndiLdapRealm.class).asEagerSingleton();
}
}
protected void configureOktaRealm() {
if (isOktaEnabled()) {
bindRealm().to(KillBillOktaRealm.class).asEagerSingleton();
}
}
@Override
protected void bindSecurityManager(final AnnotatedBindingBuilder<? super SecurityManager> bind) {
//super.bindSecurityManager(bind);
bind.toInstance(defaultSecurityManager);
final RedisCacheConfig redisCacheConfig = new ConfigurationObjectFactory(new ConfigSource() {
@Override
public String getString(final String propertyName) {
return configSource.getString(propertyName);
}
}).build(RedisCacheConfig.class);
// Magic provider to configure the cache manager
if (redisCacheConfig.isRedisCachingEnabled()) {
bind(CacheManager.class).toProvider(RedisShiroManagerProvider.class).asEagerSingleton();
} else {
bind(CacheManager.class).toProvider(EhcacheShiroManagerProvider.class).asEagerSingleton();
}
}
@Override
protected void bindSessionManager(final AnnotatedBindingBuilder<SessionManager> bind) {
bind.to(DefaultSessionManager.class).asEagerSingleton();
bind(SubjectDAO.class).toProvider(KillBillSubjectDAOProvider.class).asEagerSingleton();
// Magic provider to configure the session DAO
bind(SessionDAO.class).toProvider(SessionDAOProvider.class).asEagerSingleton();
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-clouddirectory/src/main/java/com/amazonaws/services/clouddirectory/model/transform/CreateTypedLinkFacetRequestMarshaller.java | 2404 | /*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.clouddirectory.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.clouddirectory.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* CreateTypedLinkFacetRequestMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class CreateTypedLinkFacetRequestMarshaller {
private static final MarshallingInfo<String> SCHEMAARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.HEADER)
.marshallLocationName("x-amz-data-partition").build();
private static final MarshallingInfo<StructuredPojo> FACET_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Facet").build();
private static final CreateTypedLinkFacetRequestMarshaller instance = new CreateTypedLinkFacetRequestMarshaller();
public static CreateTypedLinkFacetRequestMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(CreateTypedLinkFacetRequest createTypedLinkFacetRequest, ProtocolMarshaller protocolMarshaller) {
if (createTypedLinkFacetRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createTypedLinkFacetRequest.getSchemaArn(), SCHEMAARN_BINDING);
protocolMarshaller.marshall(createTypedLinkFacetRequest.getFacet(), FACET_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
joewalnes/idea-community | java/java-impl/src/com/intellij/codeInsight/completion/PreferDefaultTypeWeigher.java | 3870 | /*
* Copyright 2000-2009 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.codeInsight.completion;
import com.intellij.codeInsight.ExpectedTypeInfo;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.openapi.util.NullableLazyKey;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiType;
import com.intellij.psi.PsiTypeParameter;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.util.NullableFunction;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* @author peter
*/
public class PreferDefaultTypeWeigher extends CompletionWeigher {
private static final NullableLazyKey<PsiTypeParameter, CompletionLocation> TYPE_PARAMETER = NullableLazyKey.create("expectedTypes", new NullableFunction<CompletionLocation, PsiTypeParameter>() {
@Nullable
public PsiTypeParameter fun(final CompletionLocation location) {
final Pair<PsiClass,Integer> pair =
JavaSmartCompletionContributor.getTypeParameterInfo(location.getCompletionParameters().getPosition());
if (pair == null) return null;
return pair.first.getTypeParameters()[pair.second.intValue()];
}
});
private enum MyResult {
normal,
exactlyExpected,
ofDefaultType,
exactlyDefault,
expectedNoSelect
}
public MyResult weigh(@NotNull final LookupElement item, @NotNull final CompletionLocation location) {
if (location == null) {
return null;
}
final Object object = item.getObject();
if (location.getCompletionType() != CompletionType.SMART) return MyResult.normal;
if (object instanceof PsiClass) {
final PsiTypeParameter parameter = TYPE_PARAMETER.getValue(location);
if (parameter != null && object.equals(PsiUtil.resolveClassInType(TypeConversionUtil.typeParameterErasure(parameter)))) {
return MyResult.exactlyExpected;
}
}
ExpectedTypeInfo[] expectedInfos = JavaCompletionUtil.EXPECTED_TYPES.getValue(location);
if (expectedInfos == null) return MyResult.normal;
PsiType itemType = JavaCompletionUtil.getLookupElementType(item);
if (itemType == null || !itemType.isValid()) return MyResult.normal;
if (object instanceof PsiClass) {
for (final ExpectedTypeInfo info : expectedInfos) {
if (TypeConversionUtil.erasure(info.getType().getDeepComponentType()).equals(TypeConversionUtil.erasure(itemType))) {
return AbstractExpectedTypeSkipper.skips(item, location) ? MyResult.expectedNoSelect : MyResult.exactlyExpected;
}
}
}
for (final ExpectedTypeInfo expectedInfo : expectedInfos) {
final PsiType defaultType = expectedInfo.getDefaultType();
final PsiType expectedType = expectedInfo.getType();
if (!expectedType.isValid()) {
return MyResult.normal;
}
if (defaultType != expectedType) {
if (defaultType.equals(itemType)) {
return MyResult.exactlyDefault;
}
if (defaultType.isAssignableFrom(itemType)) {
return MyResult.ofDefaultType;
}
}
if (PsiType.VOID.equals(itemType) && PsiType.VOID.equals(expectedType)) {
return MyResult.exactlyExpected;
}
}
return MyResult.normal;
}
} | apache-2.0 |
unlimitedggames/gdxjam-ugg | core/src/com/ugg/gdxjam/model/configs/EnemyFacePursueConfig.java | 992 | package com.ugg.gdxjam.model.configs;
import com.badlogic.gdx.ai.steer.Steerable;
import com.badlogic.gdx.ai.steer.behaviors.Pursue;
import com.ugg.gdxjam.model.components.SteeringBehaviorComponent;
/**
* Created by Jose Cuellar on 14/01/2016.
*/
public class EnemyFacePursueConfig implements BaseConfig<SteeringBehaviorComponent> {
static final float MAX_LINEAR_SPEED = 0f;
static final float MAX_LINEAR_ACCELERATION = 1500;
static final float MAX_ANGULAR_SPEED = 1000;
static final float MAX_ANGULAR_ACCELERATION = 1500;
@Override
public void applyConfigs(SteeringBehaviorComponent steeringBC) {
Pursue pursue = (Pursue)steeringBC.behavior;
Steerable steerable = pursue.getOwner();
steerable.setMaxLinearSpeed(MAX_LINEAR_SPEED);
steerable.setMaxLinearAcceleration(MAX_LINEAR_ACCELERATION);
steerable.setMaxAngularSpeed(MAX_ANGULAR_SPEED);
steerable.setMaxAngularAcceleration(MAX_ANGULAR_ACCELERATION);
}
}
| apache-2.0 |
confile/dagger-proguard-helper | dagger-proguard-helper-processor/src/main/java/com/idamobile/dagger/helper/TypeParams.java | 2180 | package com.idamobile.dagger.helper;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeMirror;
import java.util.ArrayList;
import java.util.List;
public class TypeParams {
private String typeName;
private List<TypeParams> genericTypes = new ArrayList<TypeParams>();
public TypeParams(TypeMirror type) {
typeName = type.toString();
if (typeName.contains("<")) {
typeName = typeName.substring(0, typeName.indexOf("<"));
}
if (type instanceof DeclaredType) {
DeclaredType declaredType = (DeclaredType) type;
if (!declaredType.getTypeArguments().isEmpty()) {
for (TypeMirror genericMirrorType : declaredType.getTypeArguments()) {
genericTypes.add(new TypeParams(genericMirrorType));
}
}
}
}
public String getName() {
return typeName;
}
public List<TypeParams> getGenerics(){
return genericTypes;
}
public boolean isPrimitiveType() {
return !typeName.contains(".");
}
public boolean isList() {
return typeName.startsWith("java.util.List");
}
public boolean isByteArray() {
return typeName.equals("byte[]");
}
public boolean isKeepRequaried() {
return !isPrimitiveType() && !isSimpleTypeWrapper() && !typeName.equals("java.lang.String");
}
private boolean isSimpleTypeWrapper() {
if (typeName.equals("java.lang.Byte")) {
return true;
}
if (typeName.equals("java.lang.Short")) {
return true;
}
if (typeName.equals("java.lang.Integer")) {
return true;
}
if (typeName.equals("java.lang.Long")) {
return true;
}
if (typeName.equals("java.lang.Float")) {
return true;
}
if (typeName.equals("java.lang.Double")) {
return true;
}
if (typeName.equals("java.lang.Char")) {
return true;
}
if (typeName.equals("java.lang.Boolean")) {
return true;
}
return false;
}
}
| apache-2.0 |
asvishen/jsonrpc-java-lite | src/edu/asu/ser/jsonrpc/parameters/PositionalParams.java | 4261 | package edu.asu.ser.jsonrpc.parameters;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import edu.asu.ser.jsonrpc.exception.JsonRpcException;
import edu.asu.ser.jsonrpc.exception.RPCError;
/**
* Copyright 2016 Avijit Singh Vishen
*
* 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.
*
* Positional Parameters representation and methods
* @version 1.0.0
* @author: Avijit Vishen avijit.vishen@asu.edu
* Software Engineering, CIDSE, Arizona State University,Polytechnic Campus
*/
public class PositionalParams implements Serializable {
private static final long serialVersionUID = 1L;
protected JSONArray params;
public static final Set<Class<?>> PRIMITIVE_TYPES = new HashSet<Class<?>>();
static
{
PRIMITIVE_TYPES.add(Boolean.class);
PRIMITIVE_TYPES.add(Integer.class);
PRIMITIVE_TYPES.add(Character.class);
PRIMITIVE_TYPES.add(Byte.class);
PRIMITIVE_TYPES.add(Short.class);
PRIMITIVE_TYPES.add(Long.class);
PRIMITIVE_TYPES.add(Float.class);
PRIMITIVE_TYPES.add(Double.class);
PRIMITIVE_TYPES.add(Void.class);
PRIMITIVE_TYPES.add(String.class);
}
/**
* Constructor to set Params from JSON array
* @param id: id to be set for request
*/
public PositionalParams(JSONArray params)
{
this.params = params;
}
/**
* Sets the value for JSON request parameters by converting Java objects to JSONArray
* @param objects : Parameters objects of RPC method
* @throws JsonRpcException
*/
public void setParamsFromObjects(Object[] objects) throws JsonRpcException
{
JSONArray arr = new JSONArray();
for(Object object: objects)
{
if(PRIMITIVE_TYPES.contains(object.getClass()) || object.getClass().isPrimitive())
{
arr.put(object);
} else
try {
arr.put(object.getClass().getMethod("toJson", null).invoke(object, null));
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException | NoSuchMethodException
| SecurityException e) {
throw new JsonRpcException(RPCError.INTERNAL_ERROR);
}
}
this.params = arr;
}
/**
* Getter for params array
* @return params: json array of paramters
*/
public JSONArray getParamsJSONArray()
{
return params;
}
/**
* Converts JSONObjects from Request to Java Types
* @param method : method for which parameters are to be converted
* @return Object[]: Objects converted from JSON to Java Objects
* @exception IllegalArgumentException when request params cannot be casted to method parameters
* @throws JsonRpcException
*/
public Object[] getObjectsFromJSONArray(Method m) throws JsonRpcException
{
Object[] objects = new Object[params.length()];
Class<?>[] paramClasses = m.getParameterTypes();
//System.out.println(paramClasses[0].toString() + paramClasses[1].toString());
for(int i=0;i<params.length();i++)
{
try{
if(paramClasses[i].isPrimitive())
{
objects[i] = params.get(i);
}
else if (PRIMITIVE_TYPES.contains(paramClasses[i]))
{
objects[i] = paramClasses[i].cast(params.get(i));
}
else{
JSONObject jsonObj = new JSONObject(params.get(i));
objects[i] = paramClasses[i].getConstructor(JSONObject.class).newInstance(jsonObj);
}
}catch (ClassCastException | JSONException | NoSuchMethodException | IllegalArgumentException | InstantiationException | IllegalAccessException | InvocationTargetException | SecurityException ex)
{
ex.printStackTrace();
throw new JsonRpcException(RPCError.INVALID_PARAMS_ERROR);
}
}
return objects;
}
}
| apache-2.0 |
xdtianyu/Moments | app/src/main/java/org/xdty/moments/model/Sender.java | 1094 | package org.xdty.moments.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
* Created by ty on 15-10-5.
*/
public class Sender {
@SerializedName("username")
@Expose
private String username;
@SerializedName("nick")
@Expose
private String nick;
@SerializedName("avatar")
@Expose
private String avatar;
/**
* @return The username
*/
public String getUsername() {
return username;
}
/**
* @param username The username
*/
public void setUsername(String username) {
this.username = username;
}
/**
* @return The nick
*/
public String getNick() {
return nick;
}
/**
* @param nick The nick
*/
public void setNick(String nick) {
this.nick = nick;
}
/**
* @return The avatar
*/
public String getAvatar() {
return avatar;
}
/**
* @param avatar The avatar
*/
public void setAvatar(String avatar) {
this.avatar = avatar;
}
}
| apache-2.0 |
rhtconsulting/fuse-quickstarts | karaf/infinispan/remote-client/src/main/java/com/redhat/consulting/fusequickstarts/karaf/infinispan/RemoteClientRoute.java | 500 | package com.redhat.consulting.fusequickstarts.karaf.infinispan;
import org.apache.camel.builder.RouteBuilder;
public class RemoteClientRoute extends RouteBuilder {
@Override
public void configure() throws Exception {
from("timer://remoteClient?fixedRate=true&period=5000")
.to("bean:remoteClient?method=process('PUT', ${property.CamelTimerCounter}, ${property.CamelTimerFiredTime})")
.to("log:remoteClient?showAll=true");
}
}
| apache-2.0 |
laobie/StatusBarUtil | sample/src/main/java/com/jaeger/statusbarutil/ColorStatusBarActivity.java | 2623 | package com.jaeger.statusbarutil;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import com.jaeger.library.StatusBarUtil;
import com.jaeger.statusbardemo.R;
import java.util.Random;
/**
* Created by Jaeger on 16/2/14.
*
* Email: chjie.jaeger@gmail.com
* GitHub: https://github.com/laobie
*/
public class ColorStatusBarActivity extends BaseActivity {
private Toolbar mToolbar;
private Button mBtnChangeColor;
private SeekBar mSbChangeAlpha;
private TextView mTvStatusAlpha;
private int mColor;
private int mAlpha;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_color_status_bar);
mToolbar = findViewById(R.id.toolbar);
mBtnChangeColor = findViewById(R.id.btn_change_color);
mTvStatusAlpha = findViewById(R.id.tv_status_alpha);
mSbChangeAlpha = findViewById(R.id.sb_change_alpha);
// 设置toolbar
setSupportActionBar(mToolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
// 改变颜色
mBtnChangeColor.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Random random = new Random();
mColor = 0xff000000 | random.nextInt(0xffffff);
mToolbar.setBackgroundColor(mColor);
StatusBarUtil.setColor(ColorStatusBarActivity.this, mColor, mAlpha);
}
});
mSbChangeAlpha.setMax(255);
mSbChangeAlpha.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
mAlpha = progress;
StatusBarUtil.setColor(ColorStatusBarActivity.this, mColor, mAlpha);
mTvStatusAlpha.setText(String.valueOf(mAlpha));
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
mSbChangeAlpha.setProgress(StatusBarUtil.DEFAULT_STATUS_BAR_ALPHA);
}
@Override
protected void setStatusBar() {
mColor = getResources().getColor(R.color.colorPrimary);
StatusBarUtil.setColor(this, mColor);
}
}
| apache-2.0 |
vito-c/Smack | smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/OfferConfirmation.java | 3838 | /**
*
* Copyright 2003-2007 Jive Software.
*
* 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.jivesoftware.smackx.workgroup.agent;
import java.io.IOException;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.SimpleIQ;
import org.jivesoftware.smack.provider.IQProvider;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
public class OfferConfirmation extends SimpleIQ {
private String userJID;
private long sessionID;
public OfferConfirmation() {
super("offer-confirmation", "http://jabber.org/protocol/workgroup");
}
public String getUserJID() {
return userJID;
}
public void setUserJID(String userJID) {
this.userJID = userJID;
}
public long getSessionID() {
return sessionID;
}
public void setSessionID(long sessionID) {
this.sessionID = sessionID;
}
public void notifyService(XMPPConnection con, String workgroup, String createdRoomName) throws NotConnectedException {
NotifyServicePacket packet = new NotifyServicePacket(workgroup, createdRoomName);
con.sendPacket(packet);
}
public static class Provider extends IQProvider<OfferConfirmation> {
@Override
public OfferConfirmation parse(XmlPullParser parser, int initialDepth)
throws XmlPullParserException, IOException {
final OfferConfirmation confirmation = new OfferConfirmation();
boolean done = false;
while (!done) {
parser.next();
String elementName = parser.getName();
if (parser.getEventType() == XmlPullParser.START_TAG && "user-jid".equals(elementName)) {
try {
confirmation.setUserJID(parser.nextText());
}
catch (NumberFormatException nfe) {
}
}
else if (parser.getEventType() == XmlPullParser.START_TAG && "session-id".equals(elementName)) {
try {
confirmation.setSessionID(Long.valueOf(parser.nextText()));
}
catch (NumberFormatException nfe) {
}
}
else if (parser.getEventType() == XmlPullParser.END_TAG && "offer-confirmation".equals(elementName)) {
done = true;
}
}
return confirmation;
}
}
/**
* Packet for notifying server of RoomName
*/
private class NotifyServicePacket extends IQ {
String roomName;
NotifyServicePacket(String workgroup, String roomName) {
super("offer-confirmation", "http://jabber.org/protocol/workgroup");
this.setTo(workgroup);
this.setType(IQ.Type.result);
this.roomName = roomName;
}
@Override
protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder xml) {
xml.attribute("roomname", roomName);
xml.setEmptyElement();
return xml;
}
}
}
| apache-2.0 |
openaire/iis | iis-wf/iis-wf-transformers/src/test/java/eu/dnetlib/iis/wf/transformers/metadatamerger/WorkflowTest.java | 414 | package eu.dnetlib.iis.wf.transformers.metadatamerger;
import eu.dnetlib.iis.common.AbstractOozieWorkflowTestCase;
import org.junit.jupiter.api.Test;
/**
*
* @author Dominika Tkaczyk
*
*/
public class WorkflowTest extends AbstractOozieWorkflowTestCase {
@Test
public void testJoin() throws Exception {
testWorkflow("eu/dnetlib/iis/wf/transformers/metadatamerger/sampledataproducer");
}
}
| apache-2.0 |
liberostrategies/Udacity-Sunshine2 | app/src/androidTest/java/com/example/android/sunshine/app/data/TestUriMatcher.java | 2604 | /*
* Copyright (c) 2016. Libero Strategies, LLC - All Rights Reserved
* Unauthorized copying of this file, via any medium is strictly prohibited
* Proprietary and Confidential
*/
package com.example.android.sunshine.app.data;
import android.content.UriMatcher;
import android.net.Uri;
import android.test.AndroidTestCase;
/*
Uncomment this class when you are ready to test your UriMatcher. Note that this class utilizes
constants that are declared with package protection inside of the UriMatcher, which is why
the test must be in the same data package as the Android app code. Doing the test this way is
a nice compromise between data hiding and testability.
*/
public class TestUriMatcher extends AndroidTestCase {
private static final String LOCATION_QUERY = "London, UK";
private static final long TEST_DATE = 1419033600L; // December 20th, 2014
private static final long TEST_LOCATION_ID = 10L;
// content://com.example.android.sunshine.app/weather"
private static final Uri TEST_WEATHER_DIR = WeatherContract.WeatherEntry.CONTENT_URI;
private static final Uri TEST_WEATHER_WITH_LOCATION_DIR = WeatherContract.WeatherEntry.buildWeatherLocation(LOCATION_QUERY);
private static final Uri TEST_WEATHER_WITH_LOCATION_AND_DATE_DIR = WeatherContract.WeatherEntry.buildWeatherLocationWithDate(LOCATION_QUERY, TEST_DATE);
// content://com.example.android.sunshine.app/location"
private static final Uri TEST_LOCATION_DIR = WeatherContract.LocationEntry.CONTENT_URI;
/*
Students: This function tests that your UriMatcher returns the correct integer value
for each of the Uri types that our ContentProvider can handle. Uncomment this when you are
ready to test your UriMatcher.
*/
public void testUriMatcher() {
UriMatcher testMatcher = WeatherProvider.buildUriMatcher();
assertEquals("Error: The WEATHER URI was matched incorrectly.",
testMatcher.match(TEST_WEATHER_DIR), WeatherProvider.WEATHER);
assertEquals("Error: The WEATHER WITH LOCATION URI was matched incorrectly.",
testMatcher.match(TEST_WEATHER_WITH_LOCATION_DIR), WeatherProvider.WEATHER_WITH_LOCATION);
assertEquals("Error: The WEATHER WITH LOCATION AND DATE URI was matched incorrectly.",
testMatcher.match(TEST_WEATHER_WITH_LOCATION_AND_DATE_DIR), WeatherProvider.WEATHER_WITH_LOCATION_AND_DATE);
assertEquals("Error: The LOCATION URI was matched incorrectly.",
testMatcher.match(TEST_LOCATION_DIR), WeatherProvider.LOCATION);
}
}
| apache-2.0 |
The-Lizard-Project/android-basics | Code/app/src/main/java/basic/android/fp/pl/androidbasic/model/ExchangeRate.java | 573 | package basic.android.fp.pl.androidbasic.model;
import java.io.Serializable;
public class ExchangeRate implements Serializable {
private final String currency;
private final String country;
private Float rate;
public ExchangeRate(String currency, String country, Float rate) {
this.currency = currency;
this.country = country;
this.rate = rate;
}
public String getCurrency() {
return currency;
}
public String getCountry() {
return country;
}
public Float getRate() {
return rate;
}
public void setRate(Float rate) {
this.rate = rate;
}
} | apache-2.0 |
dbeaver/dbeaver | plugins/org.jkiss.dbeaver.ui.editors.base/src/org/jkiss/dbeaver/ui/editors/text/handlers/AbstractCommentHandler.java | 2982 | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2022 DBeaver Corp and 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 org.jkiss.dbeaver.ui.editors.text.handlers;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.ui.handlers.HandlerUtil;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.ui.ICommentsSupport;
import org.jkiss.dbeaver.ui.editors.text.BaseTextEditor;
/**
* This class contains all of the shared functionality for comment handlers
*/
public abstract class AbstractCommentHandler extends AbstractTextHandler {
static protected final Log log = Log.getLog(AbstractCommentHandler.class);
public final Object execute(ExecutionEvent event) throws ExecutionException {
BaseTextEditor textEditor = BaseTextEditor.getTextEditor(HandlerUtil.getActiveEditor(event));
if (textEditor != null) {
ICommentsSupport commentsSupport = textEditor.getCommentsSupport();
IDocument document = textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput());
if (document != null && commentsSupport != null) {
// get current text selection
ISelectionProvider provider = textEditor.getSelectionProvider();
if (provider != null) {
ISelection selection = provider.getSelection();
if (selection instanceof ITextSelection) {
ITextSelection textSelection = (ITextSelection) selection;
if (!textSelection.isEmpty()) {
try {
processAction(textEditor.getSelectionProvider(), commentsSupport, document, textSelection);
} catch (BadLocationException e) {
log.warn(e);
}
}
}
}
}
}
return null;
}
protected abstract void processAction(ISelectionProvider selectionProvider, ICommentsSupport commentsSupport, IDocument document, ITextSelection textSelection) throws BadLocationException;
}
| apache-2.0 |
boundary/dropwizard | dropwizard-logging/src/test/java/io/dropwizard/logging/SyslogAppenderFactoryTest.java | 2184 | package io.dropwizard.logging;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.net.SyslogAppender;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.AsyncAppenderBase;
import io.dropwizard.jackson.DiscoverableSubtypeResolver;
import org.junit.Test;
import java.lang.reflect.Field;
import static org.fest.assertions.api.Assertions.assertThat;
public class SyslogAppenderFactoryTest {
@Test
public void isDiscoverable() throws Exception {
assertThat(new DiscoverableSubtypeResolver().getDiscoveredSubtypes())
.contains(SyslogAppenderFactory.class);
}
@Test
public void defaultIncludesAppName() throws Exception {
assertThat(new SyslogAppenderFactory().getLogFormat())
.contains("%app");
}
@Test
public void defaultIncludesPid() throws Exception {
assertThat(new SyslogAppenderFactory().getLogFormat())
.contains("%pid");
}
@Test
public void patternIncludesAppNameAndPid() throws Exception {
Appender<ILoggingEvent> wrapper = new SyslogAppenderFactory()
.build(new LoggerContext(), "MyApplication", null);
// hack to get at the SyslogAppender beneath the AsyncAppender
// todo: find a nicer way to do all this
Field delegate = AsyncAppender.class.getDeclaredField("delegate");
delegate.setAccessible(true);
SyslogAppender appender = (SyslogAppender) delegate.get(wrapper);
assertThat(appender.getSuffixPattern())
.matches("^MyApplication\\[\\d+\\].+");
}
@Test
public void stackTracePatternCanBeSet() throws Exception {
SyslogAppenderFactory syslogAppenderFactory = new SyslogAppenderFactory();
syslogAppenderFactory.setStackTracePrefix("--->");
AsyncAppender wrapper = (AsyncAppender) syslogAppenderFactory.build(
new LoggerContext(), "MyApplication", null);
SyslogAppender delegate = (SyslogAppender) wrapper.getDelegate();
assertThat(delegate.getStackTracePattern())
.isEqualTo("--->");
}
}
| apache-2.0 |
ajoshow/JustPass | src/main/java/com/ajoshow/justpass/pass/domain/Generic.java | 545 | package com.ajoshow.justpass.pass.domain;
import static com.ajoshow.justpass.pass.domain.PassKeyType.Style;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import com.ajoshow.justpass.annoation.pass.TopLevelKey;
@Entity
@DiscriminatorValue("generic")
public class Generic extends Pass {
private static final long serialVersionUID = 2715788353427365741L;
/**
* Information specific to a generic pass.
*/
@Embedded
@TopLevelKey(Style)
private Structure generic;
}
| apache-2.0 |
cfung/Android_App_ud851-Exercises | Lesson09b-ToDo-List-AAC/T09b.02-Exercise-SaveTaskInDatabaseFromAddTaskActivity/app/src/main/java/com/example/android/todolist/AddTaskActivity.java | 6382 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.todolist;
import android.arch.persistence.room.Room;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.example.android.todolist.database.AppDatabase;
import com.example.android.todolist.database.TaskEntry;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class AddTaskActivity extends AppCompatActivity {
// Extra for the task ID to be received in the intent
public static final String EXTRA_TASK_ID = "extraTaskId";
// Extra for the task ID to be received after rotation
public static final String INSTANCE_TASK_ID = "instanceTaskId";
// Constants for priority
public static final int PRIORITY_HIGH = 1;
public static final int PRIORITY_MEDIUM = 2;
public static final int PRIORITY_LOW = 3;
// Constant for default task id to be used when not in update mode
private static final int DEFAULT_TASK_ID = -1;
// Constant for logging
private static final String TAG = AddTaskActivity.class.getSimpleName();
// Fields for views
EditText mEditText;
RadioGroup mRadioGroup;
Button mButton;
private int mTaskId = DEFAULT_TASK_ID;
// completed (3) Create AppDatabase member variable for the Database
AppDatabase appDatabase;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_task);
initViews();
// completed (4) Initialize member variable for the data base
//appDatabase = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, ).build();
appDatabase = AppDatabase.getInstance(getApplicationContext());
if (savedInstanceState != null && savedInstanceState.containsKey(INSTANCE_TASK_ID)) {
mTaskId = savedInstanceState.getInt(INSTANCE_TASK_ID, DEFAULT_TASK_ID);
}
Intent intent = getIntent();
if (intent != null && intent.hasExtra(EXTRA_TASK_ID)) {
mButton.setText(R.string.update_button);
if (mTaskId == DEFAULT_TASK_ID) {
// populate the UI
}
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt(INSTANCE_TASK_ID, mTaskId);
super.onSaveInstanceState(outState);
}
/**
* initViews is called from onCreate to init the member variable views
*/
private void initViews() {
mEditText = findViewById(R.id.editTextTaskDescription);
mRadioGroup = findViewById(R.id.radioGroup);
mButton = findViewById(R.id.saveButton);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onSaveButtonClicked();
}
});
}
/**
* populateUI would be called to populate the UI when in update mode
*
* @param task the taskEntry to populate the UI
*/
private void populateUI(TaskEntry task) {
}
/**
* onSaveButtonClicked is called when the "save" button is clicked.
* It retrieves user input and inserts that new task data into the underlying database.
*/
public void onSaveButtonClicked() {
// completed (5) Create a description variable and assign to it the value in the edit text
String description = mEditText.getText().toString();
// completed (6) Create a priority variable and assign the value returned by getPriorityFromViews()
int priority = getPriorityFromViews();
// compelted (7) Create a date variable and assign to it the current Date
Calendar calendar = Calendar.getInstance().getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date date = Calendar.getInstance().getTime();
// completed (8) Create taskEntry variable using the variables defined above
TaskEntry taskEntry = new TaskEntry(description, priority, date);
// completed (9) Use the taskDao in the AppDatabase variable to insert the taskEntry
appDatabase.taskDao().insertTask(taskEntry);
// completed (10) call finish() to come back to MainActivity
finish();
//public TaskEntry(String description, int priority, Date updatedAt)
}
/**
* getPriority is called whenever the selected priority needs to be retrieved
*/
public int getPriorityFromViews() {
int priority = 1;
int checkedId = ((RadioGroup) findViewById(R.id.radioGroup)).getCheckedRadioButtonId();
switch (checkedId) {
case R.id.radButton1:
priority = PRIORITY_HIGH;
break;
case R.id.radButton2:
priority = PRIORITY_MEDIUM;
break;
case R.id.radButton3:
priority = PRIORITY_LOW;
}
return priority;
}
/**
* setPriority is called when we receive a task from MainActivity
*
* @param priority the priority value
*/
public void setPriorityInViews(int priority) {
switch (priority) {
case PRIORITY_HIGH:
((RadioGroup) findViewById(R.id.radioGroup)).check(R.id.radButton1);
break;
case PRIORITY_MEDIUM:
((RadioGroup) findViewById(R.id.radioGroup)).check(R.id.radButton2);
break;
case PRIORITY_LOW:
((RadioGroup) findViewById(R.id.radioGroup)).check(R.id.radButton3);
}
}
}
| apache-2.0 |
ieugen/trainings | dependency-injection/spring-configuration/src/main/java/di/spring/config/java/Baz.java | 230 | package di.spring.config.java;
public class Baz {
private String aString;
public String getaString() {
return aString;
}
public void setaString(String aString) {
this.aString = aString;
}
}
| apache-2.0 |
griffon/griffon-jcr-plugin | src/main/griffon/plugins/jcr/JcrProvider.java | 1010 | /*
* Copyright 2012-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package griffon.plugins.jcr;
import griffon.util.CallableWithArgs;
import groovy.lang.Closure;
/**
* @author Andres Almiray
*/
public interface JcrProvider {
<R> R withJcr(Closure<R> closure);
<R> R withJcr(String repositoryName, Closure<R> closure);
<R> R withJcr(CallableWithArgs<R> callable);
<R> R withJcr(String repositoryName, CallableWithArgs<R> callable);
} | apache-2.0 |
codeine-cd/codeine | src/common/codeine/api/NodeWithPeerInfo.java | 1534 | package codeine.api;
import codeine.jsons.peer_status.PeerStatusJsonV2;
import codeine.jsons.peer_status.PeerStatusString;
public class NodeWithPeerInfo extends NodeInfo{
private transient PeerStatusJsonV2 peer;
private String peer_address;
private String peer_host_port;
private String peer_key;
private PeerStatusString peer_status;
public NodeWithPeerInfo(String name, String alias, PeerStatusJsonV2 peer) {
super(name, alias);
this.peer = peer;
if (null != peer) {
peer_host_port = peer.canonical_host_port();
peer_address = peer.address_port();
peer_key = peer.key();
peer_status = peer.status();
}
}
public NodeWithPeerInfo(NodeWithPeerInfo nodeWithPeerInfo) {
this(nodeWithPeerInfo.name(), nodeWithPeerInfo.alias(), nodeWithPeerInfo.peer());
}
public PeerStatusJsonV2 peer() {
return peer;
}
public void peer(PeerStatusJsonV2 peer) {
this.peer = peer;
peer_host_port = peer.canonical_host_port();
peer_address = peer.address_port();
peer_key = peer.key();
peer_status = peer.status();
}
public String peer_address() {
return peer_address;
}
public String peer_key() {
return peer_key;
}
public PeerStatusString peer_status() {
return peer_status;
}
public void peer_address(String peer_address) {
this.peer_address = peer_address;
}
@Override
public String toString() {
return "NodeWithPeerInfo [peer_address=" + peer_address + ", peer_host_port=" + peer_host_port + ", peer_key="
+ peer_key + ", peer_status=" + peer_status + "]";
}
}
| apache-2.0 |
idea4bsd/idea4bsd | platform/structuralsearch/testSource/com/intellij/structuralsearch/StructuralReplaceTest.java | 96396 | /*
* Copyright 2000-2016 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.structuralsearch;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.psi.CommonClassNames;
import com.intellij.testFramework.PlatformTestUtil;
import com.intellij.util.ThrowableRunnable;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
/**
* @by Maxim.Mossienko
*/
@SuppressWarnings({"ALL"})
public class StructuralReplaceTest extends StructuralReplaceTestCase {
@Override
protected void setUp() throws Exception {
super.setUp();
final MatchOptions matchOptions = this.options.getMatchOptions();
matchOptions.setFileType(StdFileTypes.JAVA);
matchOptions.setLooseMatching(true);
}
public void testReplaceInLiterals() {
String s1 = "String ID_SPEED = \"Speed\";";
String s2 = "String 'name = \"'_string\";";
String s2_2 = "String 'name = \"'_string:[regex( .* )]\";";
String s3 = "VSegAttribute $name$ = new VSegAttribute(\"$string$\");";
String expectedResult = "VSegAttribute ID_SPEED = new VSegAttribute(\"Speed\");";
assertEquals(
"Matching/replacing literals",
expectedResult,
replacer.testReplace(s1,s2,s3,options)
);
assertEquals(
"Matching/replacing literals",
expectedResult,
replacer.testReplace(s1,s2_2,s3,options)
);
String s4 = "params.put(\"BACKGROUND\", \"#7B528D\");";
String s5 = "params.put(\"$FieldName$\", \"#$exp$\");";
String s6 = "String $FieldName$ = \"$FieldName$\";\n" +
"params.put($FieldName$, \"$exp$\");";
String expectedResult2 = "String BACKGROUND = \"BACKGROUND\";\n" +
"params.put(BACKGROUND, \"7B528D\");";
assertEquals(
"string literal replacement 2",
expectedResult2,
replacer.testReplace(s4,s5,s6,options)
);
String s7 = "IconLoader.getIcon(\"/ant/property.png\");\n" +
"IconLoader.getIcon(\"/ant/another/property.png\");\n";
String s8 = "IconLoader.getIcon(\"/'_module/'_name:[regex( \\w+ )].png\");";
String s9 = "Icons.$module$.$name$;";
String expectedResult3 = "Icons.ant.property;\n" +
"IconLoader.getIcon(\"/ant/another/property.png\");\n";
assertEquals(
"string literal replacement 3",
expectedResult3,
replacer.testReplace(s7,s8,s9,options)
);
String s10 = "configureByFile(path + \"1.html\");\n" +
" checkResultByFile(path + \"1_after.html\");\n" +
" checkResultByFile(path + \"1_after2.html\");\n" +
" checkResultByFile(path + \"1_after3.html\");";
String s11 = "\"'a.html\"";
String s12 = "\"$a$.\"+ext";
String expectedResult4 = "configureByFile(path + \"1.\"+ext);\n" +
" checkResultByFile(path + \"1_after.\"+ext);\n" +
" checkResultByFile(path + \"1_after2.\"+ext);\n" +
" checkResultByFile(path + \"1_after3.\"+ext);";
assertEquals(
"string literal replacement 4",
expectedResult4,
replacer.testReplace(s10,s11,s12,options)
);
}
public void testReplace2() {
String s1 = "package com.www.xxx.yyy;\n" +
"\n" +
"import javax.swing.*;\n" +
"\n" +
"public class Test {\n" +
" public static void main(String[] args) {\n" +
" if (1==1)\n" +
" JOptionPane.showMessageDialog(null, \"MESSAGE\");\n" +
" }\n" +
"}";
String s2 = "JOptionPane.'showDialog(null, '_msg);";
String s3 = "//FIXME provide a parent frame\n" +
"JOptionPane.$showDialog$(null, $msg$);";
String expectedResult = "package com.www.xxx.yyy;\n" +
"\n" +
"import javax.swing.*;\n" +
"\n" +
"public class Test {\n" +
" public static void main(String[] args) {\n" +
" if (1==1)\n" +
" //FIXME provide a parent frame\n" +
"JOptionPane.showMessageDialog(null, \"MESSAGE\");\n" +
" }\n" +
"}";
assertEquals(
"adding comment to statement inside the if body",
expectedResult,
replacer.testReplace(s1,s2,s3,options)
);
String s4 = "myButton.setText(\"Ok\");";
String s5 = "'_Instance.'_MethodCall:[regex( setText )]('_Parameter*:[regex( \"Ok\" )]);";
String s6 = "$Instance$.$MethodCall$(\"OK\");";
String expectedResult2 = "myButton.setText(\"OK\");";
assertEquals(
"adding comment to statement inside the if body",
expectedResult2,
replacer.testReplace(s4,s5,s6,options)
);
}
public void testReplace() {
String str = "// searching for several constructions\n" +
" lastTest = \"several constructions match\";\n" +
" matches = testMatcher.findMatches(s5,s4, options);\n" +
" if (matches==null || matches.size()!=3) return false;\n" +
"\n" +
" // searching for several constructions\n" +
" lastTest = \"several constructions 2\";\n" +
" matches = testMatcher.findMatches(s5,s6, options);\n" +
" if (matches.size()!=0) return false;\n" +
"\n" +
" //options.setLooseMatching(true);\n" +
" // searching for several constructions\n" +
" lastTest = \"several constructions 3\";\n" +
" matches = testMatcher.findMatches(s7,s8, options);\n" +
" if (matches.size()!=2) return false;";
String str2=" lastTest = '_Descr;\n" +
" matches = testMatcher.findMatches('_In,'_Pattern, options);\n" +
" if (matches.size()!='_Number) return false;";
String str3 = "assertEquals($Descr$,testMatcher.findMatches($In$,$Pattern$, options).size(),$Number$);";
String expectedResult1 = "// searching for several constructions\n" +
" lastTest = \"several constructions match\";\n" +
" matches = testMatcher.findMatches(s5, s4, options);\n" +
" if (matches == null || matches.size() != 3) return false;\n" +
"\n" +
" // searching for several constructions\n" +
" assertEquals(\"several constructions 2\", testMatcher.findMatches(s5, s6, options).size(), 0);\n" +
"\n" +
" //options.setLooseMatching(true);\n" +
" // searching for several constructions\n" +
" assertEquals(\"several constructions 3\", testMatcher.findMatches(s7, s8, options).size(), 2);";
String str4 = "";
options.setToReformatAccordingToStyle(true);
assertEquals("Basic replacement with formatter", expectedResult1, replacer.testReplace(str,str2,str3,options));
options.setToReformatAccordingToStyle(false);
String expectedResult2 = "// searching for several constructions\n" +
" lastTest = \"several constructions match\";\n" +
" matches = testMatcher.findMatches(s5,s4, options);\n" +
" if (matches==null || matches.size()!=3) return false;\n" +
"\n" +
" // searching for several constructions\n" +
"\n" +
" //options.setLooseMatching(true);\n" +
" // searching for several constructions";
assertEquals("Empty replacement", expectedResult2, replacer.testReplace(str,str2,str4,options));
String str5 = "testMatcher.findMatches('_In,'_Pattern, options).size()";
String str6 = "findMatchesCount($In$,$Pattern$)";
String expectedResult3="// searching for several constructions\n" +
" lastTest = \"several constructions match\";\n" +
" matches = testMatcher.findMatches(s5, s4, options);\n" +
" if (matches == null || matches.size() != 3) return false;\n" +
"\n" +
" // searching for several constructions\n" +
" assertEquals(\"several constructions 2\", findMatchesCount(s5,s6), 0);\n" +
"\n" +
" //options.setLooseMatching(true);\n" +
" // searching for several constructions\n" +
" assertEquals(\"several constructions 3\", findMatchesCount(s7,s8), 2);";
assertEquals("Expression replacement", expectedResult3, replacer.testReplace(expectedResult1,str5,str6,options));
String str7 = "try { a.doSomething(); b.doSomething(); } catch(IOException ex) { ex.printStackTrace(); throw new RuntimeException(ex); }";
String str8 = "try { 'Statements+; } catch('_ '_) { 'HandlerStatements+; }";
String str9 = "$Statements$;";
String expectedResult4 = "a.doSomething(); b.doSomething();";
assertEquals("Multi line match in replacement", expectedResult4, replacer.testReplace(str7,str8,str9,options));
String str10 = " parentNode.insert(compositeNode, i);\n" +
" if (asyncMode) {\n" +
" myTreeModel.nodesWereInserted(parentNode,new int[] {i} );\n" +
" }";
String str11 = " '_parentNode.insert('_newNode, '_i);\n" +
" if (asyncMode) {\n" +
" myTreeModel.nodesWereInserted('_parentNode,new int[] {'_i} );\n" +
" }";
String str12 = "addChild($parentNode$,$newNode$, $i$);";
String expectedResult5 = " addChild(parentNode,compositeNode, i);";
assertEquals("Array initializer replacement", expectedResult5, replacer.testReplace(str10,str11,str12,options));
String str13 = " aaa(5,6,3,4,1,2);";
String str14 = "aaa('_t{2,2},3,4,'_q{2,2});";
String str15 = "aaa($q$,3,4,$t$);";
String expectedResult6 = " aaa(1,2,3,4,5,6);";
assertEquals("Parameter multiple match", expectedResult6, replacer.testReplace(str13,str14,str15,options));
String str16 = " int c = a();";
String str17 = "'_t:a ('_q*,'_p*)";
String str18 = "$t$($q$,1,$p$)";
String expectedResult7 = " int c = a(1);";
assertEquals("Replacement of init in definition + empty substitution", expectedResult7, replacer.testReplace(str16,str17,str18,options));
String str19 = " aaa(bbb);";
String str20 = "'t('_);";
String str21 = "$t$(ccc);";
String expectedResult8 = " aaa(ccc);";
assertEquals("One substition replacement", expectedResult8, replacer.testReplace(str19,str20,str21,options));
String str22 = " instance.setAAA(anotherInstance.getBBB());";
String str23 = " '_i.'_m:set(.+) ('_a.'_m2:get(.+) ());";
String str24 = " $a$.set$m2_1$( $i$.get$m_1$() );";
String expectedResult9 = " anotherInstance.setBBB( instance.getAAA() );";
assertEquals("Reg exp substitution replacement", expectedResult9, replacer.testReplace(str22,str23,str24,options));
String str25 = " LaterInvocator.invokeLater(new Runnable() {\n" +
" public void run() {\n" +
" LOG.info(\"refreshFilesAsync, modalityState=\" + ModalityState.current());\n" +
" myHandler.getFiles().refreshFilesAsync(new Runnable() {\n" +
" public void run() {\n" +
" semaphore.up();\n" +
" }\n" +
" });\n" +
" }\n" +
" });";
String str26 = " LaterInvocator.invokeLater('Params{1,10});";
String str27 = " com.intellij.openapi.application.ApplicationManager.getApplication().invokeLater($Params$);";
String expectedResult10 = " com.intellij.openapi.application.ApplicationManager.getApplication().invokeLater(new Runnable() {\n" +
" public void run() {\n" +
" LOG.info(\"refreshFilesAsync, modalityState=\" + ModalityState.current());\n" +
" myHandler.getFiles().refreshFilesAsync(new Runnable() {\n" +
" public void run() {\n" +
" semaphore.up();\n" +
" }\n" +
" });\n" +
" }\n" +
" });";
assertEquals("Anonymous in parameter", expectedResult10, replacer.testReplace(str25,str26,str27,options));
String str28 = "UTElementNode elementNode = new UTElementNode(myProject, processedElement, psiFile,\n" +
" processedElement.getTextOffset(), true,\n" +
" !myUsageViewDescriptor.toMarkInvalidOrReadonlyUsages(), null);";
String str29 = "new UTElementNode('_param, '_directory, '_null, '_0, '_true, !'_descr.toMarkInvalidOrReadonlyUsages(),\n" +
" 'referencesWord)";
String str30 = "new UTElementNode($param$, $directory$, $null$, $0$, $true$, true,\n" +
" $referencesWord$)";
String expectedResult11 = "UTElementNode elementNode = new UTElementNode(myProject, processedElement, psiFile, processedElement.getTextOffset(), true, true,\n" +
" null);";
assertEquals("Replace in def initializer", expectedResult11, replacer.testReplace(str28,str29,str30,options));
String s31 = "a = b; b = c; a=a; c=c;";
String s32 = "'a = 'a;";
String s33 = "1 = 1;";
String expectedResult12 = "a = b; b = c; 1 = 1; 1 = 1;";
assertEquals("replace silly assignments", expectedResult12, replacer.testReplace(s31,s32,s33,options));
String s34 = "ParamChecker.isTrue(1==1, \"!!!\");";
String s35 = "ParamChecker.isTrue('_expr, '_msg)";
String s36 = "assert $expr$ : $msg$";
String expectedResult13 = "assert 1==1 : \"!!!\";";
assertEquals("replace with assert", expectedResult13, replacer.testReplace(s34,s35,s36,options));
String s37 = "try { \n" +
" ParamChecker.isTrue(1==1, \"!!!\");\n \n" +
" // comment we want to leave\n \n" +
" ParamChecker.isTrue(2==2, \"!!!\");\n" +
"} catch(Exception ex) {}";
String s38 = "try {\n" +
" 'Statement{0,100};\n" +
"} catch(Exception ex) {}";
String s39 = "$Statement$;";
String expectedResult14 = "ParamChecker.isTrue(1==1, \"!!!\");\n \n" +
" // comment we want to leave\n \n" +
" ParamChecker.isTrue(2==2, \"!!!\");";
assertEquals("remove try with comments inside", expectedResult14, replacer.testReplace(s37,s38,s39,options));
String s40 = "ParamChecker.instanceOf(queryKey, GroupBySqlTypePolicy.GroupKey.class);";
String s41 = "ParamChecker.instanceOf('_obj, '_class.class);";
String s42 = "assert $obj$ instanceof $class$ : \"$obj$ is an instance of \" + $obj$.getClass() + \"; expected \" + $class$.class;";
String expectedResult15 = "assert queryKey instanceof GroupBySqlTypePolicy.GroupKey : \"queryKey is an instance of \" + queryKey.getClass() + \"; expected \" + GroupBySqlTypePolicy.GroupKey.class;";
assertEquals("Matching/replacing .class literals", expectedResult15, replacer.testReplace(s40,s41,s42,options));
String s43 = "class Wpd {\n" +
" static final String TAG_BEAN_VALUE = \"\";\n" +
"}\n" +
"XmlTag beanTag = rootTag.findSubTag(Wpd.TAG_BEAN_VALUE);";
String s44 = "'_Instance?.findSubTag( '_Parameter:[exprtype( *String ) ])";
String s45 = "jetbrains.fabrique.util.XmlApiUtil.findSubTag($Instance$, $Parameter$)";
String expectedResult16 = "class Wpd {\n" +
" static final String TAG_BEAN_VALUE = \"\";\n" +
"}\n" +
"XmlTag beanTag = jetbrains.fabrique.util.XmlApiUtil.findSubTag(rootTag, Wpd.TAG_BEAN_VALUE);";
assertEquals("Matching/replacing static fields", expectedResult16, replacer.testReplace(s43,s44,s45,options));
String s46 = "Rectangle2D rec = new Rectangle2D.Double(\n" +
" drec.getX(),\n" +
" drec.getY(),\n" +
" drec.getWidth(),\n" +
" drec.getWidth());";
String s47 = "$Instance$.$MethodCall$()";
String s48 = "OtherClass.round($Instance$.$MethodCall$(),5)";
String expectedResult17 = "Rectangle2D rec = new Rectangle2D.Double(\n" +
" OtherClass.round(drec.getX(),5),\n" +
" OtherClass.round(drec.getY(),5),\n" +
" OtherClass.round(drec.getWidth(),5),\n" +
" OtherClass.round(drec.getWidth(),5));";
assertEquals("Replace in constructor", expectedResult17, replacer.testReplace(s46,s47,s48,options));
String s49 = "class A {}\n" +
"class B extends A {}\n" +
"A a = new B();";
String s50 = "A '_b = new '_B:*A ();";
String s51 = "A $b$ = new $B$(\"$b$\");";
String expectedResult18 = "class A {}\n" +
"class B extends A {}\n" +
"A a = new B(\"a\");";
assertEquals("Class navigation", expectedResult18, replacer.testReplace(s49,s50,s51,options));
String s52 = "try {\n" +
" aaa();\n" +
"} finally {\n" +
" System.out.println();" +
"}\n" +
"try {\n" +
" aaa2();\n" +
"} catch(Exception ex) {\n" +
" aaa3();\n" +
"}\n" +
"finally {\n" +
" System.out.println();\n" +
"}\n" +
"try {\n" +
" aaa4();\n" +
"} catch(Exception ex) {\n" +
" aaa5();\n" +
"}\n";
String s53 = "try { '_a; } finally {\n" +
" '_b;" +
"}";
String s54 = "$a$;";
String expectedResult19 = "aaa();\n" +
"try {\n" +
" aaa2();\n" +
"} catch(Exception ex) {\n" +
" aaa3();\n" +
"}\n" +
"finally {\n" +
" System.out.println();\n" +
"}\n" +
"try {\n" +
" aaa4();\n" +
"} catch(Exception ex) {\n" +
" aaa5();\n" +
"}\n";
options.getMatchOptions().setLooseMatching(false);
try {
assertEquals("Try/finally unwrapped with strict matching", expectedResult19, replacer.testReplace(s52, s53, s54, options));
} finally {
options.getMatchOptions().setLooseMatching(true);
}
String expectedResult19Loose = "aaa();\n" +
"aaa2();\n" +
"try {\n" +
" aaa4();\n" +
"} catch(Exception ex) {\n" +
" aaa5();\n" +
"}\n";
assertEquals("Try/finally unwrapped with loose matching", expectedResult19Loose, replacer.testReplace(s52, s53, s54, options));
String s55 = "for(Iterator<String> iterator = stringlist.iterator(); iterator.hasNext();) {\n" +
" String str = iterator.next();\n" +
" System.out.println( str );\n" +
"}";
String s56 = "for (Iterator<$Type$> $variable$ = $container$.iterator(); $variable$.hasNext();) {\n" +
" $Type$ $var$ = $variable$.next();\n" +
" $Statements$;\n" +
"}";
String s57 = "for($Type$ $var$:$container$) {\n" +
" $Statements$;\n" +
"}";
String expectedResult20 = "for(String str:stringlist) {\n" +
" System.out.println( str );\n" +
"}";
assertEquals("for with foreach", expectedResult20, replacer.testReplace(s55,s56,s57,options));
String s58 = "class A {\n" +
" static Set<String> b_MAP = new HashSet<String>();\n" +
" int c;\n" +
"}";
String s59 = "'a:[ regex( (.*)_MAP ) ]";
String s60 = "$a_1$_SET";
String expectedResult21 = "class A {\n" +
" static Set<String> b_SET = new HashSet<String>();\n" +
" int c;\n" +
"}";
assertEquals("replace symbol in definition", expectedResult21, replacer.testReplace(s58,s59,s60,options));
String s64 = "int x = 42;\n" +
"int y = 42; // Stuff";
String s65 = "'_Type '_Variable = '_Value; // '_Comment";
String s66 = "/**\n" +
" *$Comment$\n" +
" */\n" +
"$Type$ $Variable$ = $Value$;";
String expectedResult23 = "int x = 42;\n" +
"/**\n" +
" * Stuff\n" +
" */\n" +
"int y = 42;";
assertEquals("Replacement of the comment with javadoc", expectedResult23, replacer.testReplace(s64,s65,s66,options));
String s61 = "try { 1=1; } catch(Exception e) { 1=1; } catch(Throwable t) { 2=2; }";
String s62 = "try { '_a; } catch(Exception e) { '_b; }";
String s63 = "try { $a$; } catch(Exception1 e) { $b$; } catch(Exception2 e) { $b$; }";
String expectedResult22 = "try { 1=1; } catch(Exception1 e) { 1=1; } catch(Exception2 e) { 1=1; } catch(Throwable t) { 2=2; }";
assertEquals("try replacement by another try will leave the unmatched catch",
expectedResult22,
replacer.testReplace(s61,s62,s63,options));
}
public void testReplaceExpr() {
String s1 = "new SimpleDateFormat(\"yyyyMMddHHmmss\")";
String s2 = "'expr";
String s3 = "new AtomicReference<DateFormat>($expr$)";
String expectedResult = "new AtomicReference<DateFormat>(new SimpleDateFormat(\"yyyyMMddHHmmss\"))";
assertEquals("Replacement of top-level expression only", expectedResult, replacer.testReplace(s1, s2, s3, options));
String s4 = "get(\"smth\")";
String s5 = "'expr";
String s6 = "new Integer($expr$)";
String expectedResult1 = "new Integer(get(\"smth\"))";
assertEquals("Replacement of top-level expression only", expectedResult1, replacer.testReplace(s4, s5, s6, options));
}
public void testReplaceParameter() {
String s1 = "class A { void b(int c, int d, int e) {} }";
String s2 = "int d;";
String s3 = "int d2;";
String expectedResult = "class A { void b(int c, int d2, int e) {} }";
assertEquals("replace method parameter", expectedResult, replacer.testReplace(s1,s2,s3,options));
}
public void testReplaceWithComments() {
String s1 = "map.put(key, value); // line 1";
String s2 = "map.put(key, value); // line 1";
String s3 = "map.put(key, value); // line 1";
String expectedResult = "map.put(key, value); // line 1";
assertEquals("replace self with comment after", expectedResult, replacer.testReplace(s1,s2,s3,options));
String s4 = "if (true) System.out.println(\"1111\"); else System.out.println(\"2222\");\n" +
"while(true) System.out.println(\"1111\");";
String s5 = "System.out.println('Test);";
String s6 = "/* System.out.println($Test$); */";
String expectedResult2 = "if (true) /* System.out.println(\"1111\"); */; else /* System.out.println(\"2222\"); */;\n" +
"while(true) /* System.out.println(\"1111\"); */;";
assertEquals("replace with comment", expectedResult2, replacer.testReplace(s4,s5,s6,options));
}
public void testSeveralStatements() {
String s1 = "{\n" +
" System.out.println(1);\n" +
" System.out.println(2);\n" +
" System.out.println(3);\n" +
" }\n" +
"{\n" +
" System.out.println(1);\n" +
" System.out.println(2);\n" +
" System.out.println(3);\n" +
" }\n" +
"{\n" +
" System.out.println(1);\n" +
" System.out.println(2);\n" +
" System.out.println(3);\n" +
" }";
String s2 =
" System.out.println(1);\n" +
" System.out.println(2);\n" +
" System.out.println(3);\n";
String s3 = " System.out.println(3);\n" +
" System.out.println(2);\n" +
" System.out.println(1);\n";
String expectedResult1 = " {\n" +
" System.out.println(3);\n" +
" System.out.println(2);\n" +
" System.out.println(1);\n" +
" }\n" +
" {\n" +
" System.out.println(3);\n" +
" System.out.println(2);\n" +
" System.out.println(1);\n" +
" }\n" +
" {\n" +
" System.out.println(3);\n" +
" System.out.println(2);\n" +
" System.out.println(1);\n" +
" }";
options.setToReformatAccordingToStyle(true);
assertEquals("three statements replacement", expectedResult1, replacer.testReplace(s1,s2,s3,options));
options.setToReformatAccordingToStyle(false);
String s4 = "ProgressManager.getInstance().startNonCancelableAction();\n" +
" try {\n" +
" read(id, READ_PARENT);\n" +
" return myViewport.parent;\n" +
" }\n" +
" finally {\n" +
" ProgressManager.getInstance().finishNonCancelableAction();\n" +
" }";
String s5 = "ProgressManager.getInstance().startNonCancelableAction();\n" +
" try {\n" +
" '_statement{2,2};\n" +
" }\n" +
" finally {\n" +
" ProgressManager.getInstance().finishNonCancelableAction();\n" +
" }";
String s6 = "$statement$;";
String expectedResult2 = "read(id, READ_PARENT);\n" +
" return myViewport.parent;";
assertEquals("extra ;", expectedResult2, replacer.testReplace(s4,s5,s6,options));
String s7 = "public class A {\n" +
" void f() {\n" +
" new Runnable() {\n" +
" public void run() {\n" +
" l();\n" +
" }\n" +
"\n" +
" private void l() {\n" +
" int i = 9;\n" +
" int j = 9;\n" +
" }\n" +
" };\n" +
" new Runnable() {\n" +
" public void run() {\n" +
" l();\n" +
" }\n" +
"\n" +
" private void l() {\n" +
" l();\n" +
" l();\n" +
" }\n" +
" };\n" +
" }\n" +
"\n" +
"}";
String s8 = "new Runnable() {\n" +
" public void run() {\n" +
" '_l ();\n" +
" }\n" +
" private void '_l () {\n" +
" '_st{2,2};\n" +
" }\n" +
"};";
String s9 = "new My() {\n" +
" public void f() {\n" +
" $st$;\n" +
" }\n" +
"};";
String expectedResult3 = "public class A {\n" +
" void f() {\n" +
" new My() {\n" +
" public void f() {\n" +
" int i = 9;\n" +
" int j = 9;\n" +
" }\n" +
" };\n" +
" new My() {\n" +
" public void f() {\n" +
" l();\n" +
" l();\n" +
" }\n" +
" };\n" +
" }\n" +
"\n" +
"}";
boolean formatAccordingToStyle = options.isToReformatAccordingToStyle();
options.setToReformatAccordingToStyle(true);
assertEquals("extra ; 2", expectedResult3, replacer.testReplace(s7,s8,s9,options));
String s10 = "public class A {\n" +
" void f() {\n" +
" new Runnable() {\n" +
" public void run() {\n" +
" l();\n" +
" l();\n" +
" }\n" +
" public void run2() {\n" +
" l();\n" +
" l();\n" +
" }\n" +
"\n" +
" };\n" +
" new Runnable() {\n" +
" public void run() {\n" +
" l();\n" +
" l();\n" +
" }\n" +
" public void run2() {\n" +
" l();\n" +
" l();\n" +
" }\n" +
"\n" +
" };\n" +
"new Runnable() {\n" +
" public void run() {\n" +
" l();\n" +
" l();\n" +
" }\n" +
" public void run2() {\n" +
" l2();\n" +
" l2();\n" +
" }\n" +
"\n" +
" };\n" +
" }\n" +
"\n" +
" private void l() {\n" +
" int i = 9;\n" +
" int j = 9;\n" +
" }\n" +
"}\n" +
"\n" +
"abstract class My {\n" +
" abstract void f();\n" +
"}";
String s11 = "new Runnable() {\n" +
" public void run() {\n" +
" 'l{2,2};\n" +
" }\n" +
" public void run2() {\n" +
" 'l;\n" +
" }\n" +
"\n" +
" };";
String s12 = "new My() {\n" +
" public void f() {\n" +
" $l$;\n" +
" }\n" +
" };";
String expectedResult4 = "public class A {\n" +
" void f() {\n" +
" new My() {\n" +
" public void f() {\n" +
" l();\n" +
" l();\n" +
" }\n" +
" };\n" +
" new My() {\n" +
" public void f() {\n" +
" l();\n" +
" l();\n" +
" }\n" +
" };\n" +
" new Runnable() {\n" +
" public void run() {\n" +
" l();\n" +
" l();\n" +
" }\n" +
"\n" +
" public void run2() {\n" +
" l2();\n" +
" l2();\n" +
" }\n" +
"\n" +
" };\n" +
" }\n" +
"\n" +
" private void l() {\n" +
" int i = 9;\n" +
" int j = 9;\n" +
" }\n" +
"}\n" +
"\n" +
"abstract class My {\n" +
" abstract void f();\n" +
"}";
assertEquals("same multiple occurences 2 times", expectedResult4, replacer.testReplace(s10,s11,s12,options));
options.setToReformatAccordingToStyle(formatAccordingToStyle);
String s13 = " PsiLock.LOCK.acquire();\n" +
" try {\n" +
" return value;\n" +
" }\n" +
" finally {\n" +
" PsiLock.LOCK.release();\n" +
" }";
String s13_2 = " PsiLock.LOCK.acquire();\n" +
" try {\n" +
" if (true) { return value; }\n" +
" }\n" +
" finally {\n" +
" PsiLock.LOCK.release();\n" +
" }";
String s13_3 = " PsiLock.LOCK.acquire();\n" +
" try {\n" +
" if (true) { return value; }\n\n" +
" if (true) { return value; }\n" +
" }\n" +
" finally {\n" +
" PsiLock.LOCK.release();\n" +
" }";
String s14 = " PsiLock.LOCK.acquire();\n" +
" try {\n" +
" 'T{1,1000};\n" +
" }\n" +
" finally {\n" +
" PsiLock.LOCK.release();\n" +
" }";
String s15 = "synchronized(PsiLock.LOCK) {\n" +
" $T$;\n" +
"}";
String expectedResult5 = " synchronized (PsiLock.LOCK) {\n" +
" return value;\n" +
" }";
options.setToReformatAccordingToStyle(true);
assertEquals("extra ; over return", expectedResult5, replacer.testReplace(s13,s14,s15,options));
options.setToReformatAccordingToStyle(false);
String expectedResult6 = " synchronized (PsiLock.LOCK) {\n" +
" if (true) {\n" +
" return value;\n" +
" }\n" +
" }";
options.setToReformatAccordingToStyle(true);
assertEquals("extra ; over if", expectedResult6, replacer.testReplace(s13_2,s14,s15,options));
options.setToReformatAccordingToStyle(false);
String expectedResult7 = " synchronized (PsiLock.LOCK) {\n" +
" if (true) {\n" +
" return value;\n" +
" }\n" +
"\n" +
" if (true) {\n" +
" return value;\n" +
" }\n" +
" }";
options.setToReformatAccordingToStyle(true);
assertEquals("newlines in matches of several lines", expectedResult7, replacer.testReplace(s13_3,s14,s15,options));
options.setToReformatAccordingToStyle(false);
String s16 = "public class SSTest {\n" +
" Object lock;\n" +
" public Object getProducts (String[] productNames) {\n" +
" synchronized (lock) {\n" +
" Object o = new Object ();\n" +
" assert o != null;\n" +
" return o;\n" +
" }\n" +
" }\n" +
"}";
String s16_2 = "public class SSTest {\n" +
" Object lock;\n" +
" public void getProducts (String[] productNames) {\n" +
" synchronized (lock) {\n" +
" boolean[] v = {true};\n" +
" }\n" +
" }\n" +
"}";
String s17 = "synchronized(lock) {\n" +
" 'Statement*;\n" +
"}";
String s18 = "$Statement$;";
String expectedResult8 = "public class SSTest {\n" +
" Object lock;\n" +
" public Object getProducts (String[] productNames) {\n" +
" Object o = new Object ();\n" +
" assert o != null;\n" +
" return o;\n" +
" }\n" +
"}";
String expectedResult8_2 = "public class SSTest {\n" +
" Object lock;\n" +
" public void getProducts (String[] productNames) {\n" +
" boolean[] v = {true};\n" +
" }\n" +
"}";
assertEquals("extra ;", expectedResult8, replacer.testReplace(s16,s17,s18,options));
assertEquals("missed ;", expectedResult8_2, replacer.testReplace(s16_2,s17,s18,options));
}
public void testClassReplacement() {
boolean formatAccordingToStyle = options.isToReformatAccordingToStyle();
options.setToReformatAccordingToStyle(true);
String s1 = "class A { public void b() {} }";
String s2 = "class 'a { '_Other* }";
String s3 = "class $a$New { Logger LOG; $Other$ }";
String expectedResult = " class ANew {\n" +
" Logger LOG;\n\n" +
" public void b() {\n" +
" }\n" +
" }";
assertEquals(
"Basic class replacement",
expectedResult,
replacer.testReplace(s1,s2,s3,options)
);
String s4 = "class A { class C {} public void b() {} int f; }";
String s5 = "class 'a { '_Other* }";
String s6 = "class $a$ { Logger LOG; $Other$ }";
String expectedResult2 = " class A {\n" +
" Logger LOG;\n\n" +
" class C {\n" +
" }\n\n" +
" public void b() {\n" +
" }\n\n" +
" int f;\n" +
" }";
assertEquals("Order of members in class replacement", expectedResult2, replacer.testReplace(s4,s5,s6,options));
String s7 = "class A extends B { int c; void b() {} { a = 1; } }";
String s8 = "class 'A extends B { '_Other* }";
String s9 = "class $A$ extends B2 { $Other$ }";
String expectedResult3 = " class A extends B2 {\n" +
" int c;\n\n" +
" void b() {\n" +
" }\n\n" +
" {\n" +
" a = 1;\n" +
" }\n" +
" }";
assertEquals("Unsupported pattern exception", expectedResult3, replacer.testReplace(s7, s8, s9, options));
options.setToReformatAccordingToStyle(formatAccordingToStyle);
String s10 = "/** @example */\n" +
"class A {\n" +
" class C {}\n" +
" public void b() {}\n" +
" int f;\n" +
"}";
String s11 = "class 'a { '_Other* }";
String s12 = "public class $a$ {\n" +
" $Other$\n" +
"}";
String expectedResult4 = "/** @example */\n" +
" public class A {\n" +
" class C {\n" +
" }\n\n" +
" public void b() {\n" +
" }\n\n" +
" int f;\n" +
" }";
options.setToReformatAccordingToStyle(true);
assertEquals("Make class public", expectedResult4, replacer.testReplace(s10, s11, s12, options));
options.setToReformatAccordingToStyle(false);
String s13 = "class CustomThread extends Thread {\n" +
"public CustomThread(InputStream in, OutputStream out, boolean closeOutOnExit) {\n" +
" super(CustomThreadGroup.getThreadGroup(), \"CustomThread\");\n" +
" setDaemon(true);\n" +
" if (in instanceof BufferedInputStream) {\n" +
" bis = (BufferedInputStream)in;\n" +
" } else {\n" +
" bis = new BufferedInputStream(in);\n" +
" }\n" +
" this.out = out;\n" +
" this.closeOutOnExit = closeOutOnExit;\n" +
"}\n" +
"}";
String s14 = "class 'Class extends Thread {\n" +
" 'Class('_ParameterType* '_ParameterName*) {\n" +
"\t super (CustomThreadGroup.getThreadGroup(), '_superarg* );\n" +
" '_Statement*;\n" +
" }\n" +
"}";
String s15 = "class $Class$ extends CustomThread {\n" +
" $Class$($ParameterType$ $ParameterName$) {\n" +
"\t super($superarg$);\n" +
" $Statement$;\n" +
" }\n" +
"}";
String expectedResult5 = " class CustomThread extends CustomThread {\n" +
" CustomThread(InputStream in, OutputStream out, boolean closeOutOnExit) {\n" +
" super(\"CustomThread\");\n" +
" setDaemon(true);\n" +
" if (in instanceof BufferedInputStream) {\n" +
" bis = (BufferedInputStream) in;\n" +
" } else {\n" +
" bis = new BufferedInputStream(in);\n" +
" }\n" +
" this.out = out;\n" +
" this.closeOutOnExit = closeOutOnExit;\n" +
" }\n" +
" }";
options.setToReformatAccordingToStyle(true);
assertEquals("Constructor replacement", expectedResult5, replacer.testReplace(s13, s14, s15, options));
options.setToReformatAccordingToStyle(false);
String s16 = "public class A {}\n" +
"final class B {}";
String s17 = "class 'A { '_Other* }";
String s17_2 = "class 'A { private Log log = LogFactory.createLog(); '_Other* }";
String s18 = "class $A$ { private Log log = LogFactory.createLog(); $Other$ }";
String s18_2 = "class $A$ { $Other$ }";
String expectedResult6 = "public class A { private Log log = LogFactory.createLog(); }\n" +
"final class B { private Log log = LogFactory.createLog(); }";
assertEquals("Modifier list for class", expectedResult6, replacer.testReplace(s16, s17, s18, options));
String expectedResult7 = "public class A { }\n" +
"final class B { }";
assertEquals("Removing field", expectedResult7, replacer.testReplace(expectedResult6, s17_2, s18_2, options));
String s19 = "public class A extends Object implements Cloneable {}\n";
String s20 = "class 'A { '_Other* }";
String s21 = "class $A$ { private Log log = LogFactory.createLog(); $Other$ }";
String expectedResult8 = "public class A extends Object implements Cloneable { private Log log = LogFactory.createLog(); }\n";
assertEquals("Extends / implements list for class", expectedResult8, replacer.testReplace(s19, s20, s21, options));
String s22 = "public class A<T> { int Afield; }\n";
String s23 = "class 'A { '_Other* }";
String s24 = "class $A$ { private Log log = LogFactory.createLog(); $Other$ }";
String expectedResult9 = "public class A<T> { private Log log = LogFactory.createLog(); int Afield; }\n";
assertEquals("Type parameters for the class", expectedResult9, replacer.testReplace(s22, s23, s24, options));
String s25 = "class A {\n" +
" // comment before\n" +
" protected short a; // comment after\n" +
"}";
String s26 = "short a;";
String s27 = "Object a;";
String expectedResult10 = "class A {\n" +
" // comment before\n" +
" protected Object a; // comment after\n" +
"}";
assertEquals(
"Replacing dcl with saving access modifiers",
expectedResult10,
replacer.testReplace(s25,s26,s27,options)
);
String s28 = "aaa";
String s29 = "class 'Class {\n" +
" 'Class('_ParameterType '_ParameterName) {\n" +
" 'Class('_ParameterName);\n" +
" }\n" +
"}";
String s30 = "class $Class$ {\n" +
" $Class$($ParameterType$ $ParameterName$) {\n" +
" this($ParameterName$);\n" +
" }\n" +
"}";
String expectedResult11 = "aaa";
assertEquals(
"Complex class replacement",
expectedResult11,
replacer.testReplace(s28,s29,s30,options)
);
String s31 = "class A {\n" +
" int a; // comment\n" +
" char b;\n" +
" int c; // comment2\n" +
"}";
String s32 = "'_Type 'Variable = '_Value?; //'_Comment";
String s33 = "/**$Comment$*/\n" +
"$Type$ $Variable$ = $Value$;";
String expectedResult12 = " class A {\n" +
" /**\n" +
" * comment\n" +
" */\n" +
" int a;\n" +
" char b;\n" +
" /**\n" +
" * comment2\n" +
" */\n" +
" int c;\n" +
" }";
options.setToReformatAccordingToStyle(true);
assertEquals(
"Replacing comments with javadoc for fields",
expectedResult12,
replacer.testReplace(s31,s32,s33,options)
);
options.setToReformatAccordingToStyle(false);
String s34 = "/**\n" +
" * This interface stores XXX\n" +
" * <p/>\n" +
" */\n" +
"public interface X {\n" +
" public static final String HEADER = Headers.HEADER;\n" +
"\n" +
"}";
String s35 = "public interface 'MessageInterface {\n" +
" public static final String '_X = '_VALUE;\n" +
" 'blah*" +
"}";
String s36 = "public interface $MessageInterface$ {\n" +
" public static final String HEADER = $VALUE$;\n" +
" $blah$\n" +
"}";
String expectedResult13 = "/**\n" +
" * This interface stores XXX\n" +
" * <p/>\n" +
" */\n" +
"public interface X {\n" +
" public static final String HEADER = Headers.HEADER;\n" +
" \n" +
"}";
assertEquals(
"Replacing interface with interface, saving comments properly",
expectedResult13,
replacer.testReplace(s34,s35,s36,options, true)
);
}
public void testClassReplacement3() {
if (true) return;
String s37 = "class A { int a = 1; void B() {} int C(char ch) { int z = 1; } int b = 2; }";
String s38 = "class 'A { 'T* 'M*('PT* 'PN*) { 'S*; } 'O* }";
String s39 = "class $A$ { $T$ $M$($PT$ $PN$) { System.out.println(\"$M$\"); $S$; } $O$ }";
String expectedResult14 = "class A { int a = 1; void B( ) { System.out.println(\"B\"); } int C(char ch) { System.out.println(\"C\"); int z = 1; } int b = 2;}";
String expectedResult14_2 = "class A { int a = 1; void B( ) { System.out.println(\"B\"); } int C(char ch) { System.out.println(\"C\"); int z = 1; } int b = 2;}";
assertEquals(
"Multiple methods replacement",
expectedResult14,
replacer.testReplace(s37,s38,s39,options, true)
);
}
public void testClassReplacement4() {
String s1 = "class A {\n" +
" int a = 1;\n" +
" int b;\n" +
" private int c = 2;\n" +
"}";
String s2 = "@Modifier(\"packageLocal\") '_Type '_Instance = '_Init?;";
String s3 = "public $Type$ $Instance$ = $Init$;";
String expectedResult = "class A {\n" +
" public int a = 1;\n" +
" public int b ;\n" +
" private int c = 2;\n" +
"}";
assertEquals(
"Multiple fields replacement",
expectedResult,
replacer.testReplace(s1,s2,s3,options, true)
);
}
public void testClassReplacement5() {
String s1 = "public class X {\n" +
" /**\n" +
" * zzz\n" +
" */\n" +
" void f() {\n" +
"\n" +
" }\n" +
"}";
String s2 = "class 'c {\n" +
" /**\n" +
" * zzz\n" +
" */\n" +
" void f(){}\n" +
"}";
String s3 = "class $c$ {\n" +
" /**\n" +
" * ppp\n" +
" */\n" +
" void f(){}\n" +
"}";
String expectedResult = "public class X {\n" +
" /**\n" +
" * ppp\n" +
" */\n" +
" void f(){}\n" +
"}";
assertEquals(
"Not preserving comment if it is present",
expectedResult,
replacer.testReplace(s1,s2,s3,options, true)
);
}
public void testClassReplacement6() {
String s1 = "public class X {\n" +
" /**\n" +
" * zzz\n" +
" */\n" +
" private void f(int i) {\n" +
" //s\n" +
" }\n" +
"}";
String s1_2 = "public class X {\n" +
" /**\n" +
" * zzz\n" +
" */\n" +
" private void f(int i) {\n" +
" int a = 1;\n" +
" //s\n" +
" }\n" +
"}";
String s2 = "class 'c {\n" +
" /**\n" +
" * zzz\n" +
" */\n" +
" void f('_t '_p){'_s+;}\n" +
"}";
String s3 = "class $c$ {\n" +
" /**\n" +
" * ppp\n" +
" */\n" +
" void f($t$ $p$){$s$;}\n" +
"}";
String expectedResult = "public class X {\n" +
" /**\n" +
" * ppp\n" +
" */\n" +
" private void f(int i ){//s\n" +
"}\n" +
"}";
assertEquals(
"Correct class replacement",
expectedResult,
replacer.testReplace(s1,s2,s3,options)
);
String expectedResult2 = "public class X {\n" +
" /**\n" +
" * ppp\n" +
" */\n" +
" private void f(int i ){int a = 1;\n" +
" //s\n" +
"}\n" +
"}";
assertEquals(
"Correct class replacement, 2",
expectedResult2,
replacer.testReplace(s1_2,s2,s3,options)
);
}
public void testClassReplacement7() {
String s1 = "/**\n" +
"* Created by IntelliJ IDEA.\n" +
"* User: cdr\n" +
"* Date: Nov 15, 2005\n" +
"* Time: 4:23:29 PM\n" +
"* To change this template use File | Settings | File Templates.\n" +
"*/\n" +
"public class CC {\n" +
" /** My Comment */ int a = 3; // aaa\n" +
" // bbb\n" +
" long c = 2;\n" +
" void f() {\n" +
" }\n" +
"}";
String s2 = "/**\n" +
"* Created by IntelliJ IDEA.\n" +
"* User: '_USER\n" +
"* Date: '_DATE\n" +
"* Time: '_TIME\n" +
"* To change this template use File | Settings | File Templates.\n" +
"*/\n" +
"class 'c {\n" +
" '_other*\n" +
"}";
String s3 = "/**\n" +
"* by: $USER$\n" +
"*/\n" +
"class $c$ {\n" +
" $other$\n" +
"}";
String expectedResult = "/**\n" +
"* by: cdr\n" +
"*/\n" +
"public class CC {\n" +
" /** My Comment */ int a = 3; // aaa\n" +
"// bbb\n" +
" long c = 2;\n" +
"void f() {\n" +
" }\n" +
"}";
assertEquals("Class with comment replacement", expectedResult, replacer.testReplace(s1,s2,s3,options,true));
}
public void testClassReplacement8() {
String s1 = "public class CC {\n" +
" /** AAA*/ int b = 1; // comment\n" +
"}";
String s2 = "int b = 1;";
String s3 = "long c = 2;";
String expectedResult = "public class CC {\n" +
" /** AAA*/ long c = 2; // comment\n" +
"}";
assertEquals("Class field replacement with simple pattern",
expectedResult, replacer.testReplace(s1,s2,s3,options,true));
}
@NotNull
@Override
protected String getTestDataPath() {
return PlatformTestUtil.getCommunityPath() + "/platform/structuralsearch/testData/";
}
public void testClassReplacement9() throws IOException {
String s1 = loadFile("before1.java");
String s2 = "class 'A extends '_TestCaseCass:[regex( .*TestCase ) ] {\n" +
" '_OtherStatement*;\n" +
" public void '_testMethod*:[regex( test.* )] () {\n" +
" }\n" +
" '_OtherStatement2*;\n" +
"}";
String s3 = "class $A$ extends $TestCaseCass$ {\n" +
" $OtherStatement$;\n" +
" $OtherStatement2$;\n" +
"}";
String expectedResult = loadFile("after1.java");
options.setToReformatAccordingToStyle(true);
assertEquals("Class replacement 9", expectedResult, replacer.testReplace(s1,s2,s3,options,true));
}
public void testReplaceReturnWithArrayInitializer() {
String searchIn = "return ( new String[]{CoreVars.CMUAudioPort + \"\"} );";
String searchFor = "return ( 'A );";
String replaceBy = "return $A$;";
String expectedResult = "return new String[]{CoreVars.CMUAudioPort + \"\"};";
assertEquals("ReplaceReturnWithArrayInitializer", expectedResult, replacer.testReplace(searchIn,searchFor,replaceBy,options));
}
public void _testClassReplacement10() throws IOException {
String s1 = loadFile("before2.java");
String s2 = "class '_Class {\n" +
" '_ReturnType+ '_MethodName+('_ParameterType* '_Parameter*){\n" +
" '_content*;\n" +
" }\n" +
" '_remainingclass*" +
"}";
String s3 = "class $Class$ {\n" +
" $remainingclass$\n" +
" @Override $ReturnType$ $MethodName$($ParameterType$ $Parameter$){\n" +
" $content$;\n" +
" }\n" +
"}";
String expectedResult = loadFile("after2.java");
options.setToReformatAccordingToStyle(true);
assertEquals("Class replacement 10", expectedResult, replacer.testReplace(s1,s2,s3,options,true));
}
public void testCatchReplacement() throws Exception {
String s1 = "try {\n" +
" aaa();\n" +
"} catch(Exception ex) {\n" +
" LOG.assertTrue(false);\n" +
"}";
String s2 = "{ LOG.assertTrue(false); }";
String s3 = "{ if (false) LOG.assertTrue(false); }";
String expectedResult = "try {\n" +
" aaa();\n" +
"} catch (Exception ex) {\n" +
" if (false) LOG.assertTrue(false);\n" +
"}";
options.setToReformatAccordingToStyle(true);
assertEquals("Catch replacement by block", expectedResult, replacer.testReplace(s1,s2,s3,options));
options.setToReformatAccordingToStyle(false);
}
public void testSavingAccessModifiersDuringClassReplacement() {
String s43 = "public @Deprecated class Foo implements Comparable<Foo> {\n int x;\n void m(){}\n }";
String s44 = "class 'Class implements '_Interface { '_Content* }";
String s45 = "@MyAnnotation\n" +
"class $Class$ implements $Interface$ {$Content$}";
String expectedResult16 = "@MyAnnotation public @Deprecated\n" +
"class Foo implements Comparable<Foo> {int x;\n" +
"void m(){}}";
assertEquals(
"Preserving var modifiers and generic information in type during replacement",
expectedResult16,
replacer.testReplace(s43, s44, s45, options, true)
);
String in1 = "public class A {" +
" public class B {}" +
"}";
String what1 = "class '_A {" +
" class '_B {}" +
"}";
String by1 = "class $A$ {" +
" private class $B$ {}" +
"}";
String expected1 = "public class A { private class B {}}";
assertEquals("No illegal modifier combinations during replacement", expected1, replacer.testReplace(in1, what1, by1, options));
}
public void testDontRequireSpecialVarsForUnmatchedContent() {
String s43 = "public @Deprecated class Foo implements Comparable<Foo> {\n" +
" int x;\n" +
" void m(){}\n" +
" }";
String s44 = "class 'Class implements '_Interface {}";
String s45 = "@MyAnnotation\n" +
"class $Class$ implements $Interface$ {}";
String expectedResult16 = "@MyAnnotation public @Deprecated\n" +
"class Foo implements Comparable<Foo> {\n" +
" int x;\n" +
" void m(){}\n" +
" }";
assertEquals(
"Preserving class modifiers and generic information in type during replacement",
expectedResult16,
replacer.testReplace(s43, s44, s45, options, true)
);
String in = "public class A {\n" +
" int i,j, k;\n" +
" void m1() {}\n" +
"\n" +
" public void m2() {}\n" +
" void m3() {}\n" +
"}";
String what = "class '_A {\n" +
" public void '_m();\n" +
"}";
String by = "class $A$ {\n" +
"\tprivate void $m$() {}\n" +
"}";
assertEquals("Should keep member order when replacing",
"public class A {\n" +
" int i ,j , k;\n" +
" void m1() {}\n" +
"\n" +
" private void m2() {}\n" +
" void m3() {}\n" +
"}",
replacer.testReplace(in, what, by, options));
}
public void testClassReplacement2() {
String s40 = "class A {\n" +
" /* special comment*/\n" +
" private List<String> a = new ArrayList();\n" +
" static {\n" +
" int a = 1;" +
" }\n" +
"}";
String s41 = "class '_Class {\n" +
" '_Stuff2*\n" +
" '_FieldType '_FieldName = '_Init?;\n" +
" static {\n" +
" '_Stmt*;\n" +
" }\n" +
" '_Stuff*\n" +
"}";
String s42 = "class $Class$ {\n" +
" $Stuff2$\n" +
" $FieldType$ $FieldName$ = build$FieldName$Map();\n" +
" private static $FieldType$ build$FieldName$Map() {\n" +
" $FieldType$ $FieldName$ = $Init$;\n" +
" $Stmt$;\n" +
" return $FieldName$;\n" +
" }\n" +
" $Stuff$\n" +
"}";
String expectedResult15 = "class A {\n" +
" \n" +
" /* special comment*/\n" +
" private List<String> a = buildaMap();\n" +
" private static List<String> buildaMap() {\n" +
" List<String> a = new ArrayList();\n" +
" int a = 1;\n" +
" return a;\n" +
" }\n" +
" \n" +
"}";
assertEquals("Preserving var modifiers and generic information in type during replacement",
expectedResult15, replacer.testReplace(s40,s41,s42,options, true));
String s46 = "class Foo { int xxx; void foo() { assert false; } void yyy() {}}";
String s47 = "class '_Class { void '_foo:[regex( foo )](); }";
String s48 = "class $Class$ { void $foo$(int a); }";
String expectedResult17 = "class Foo { int xxx; void foo(int a) { assert false; } void yyy() {}}";
assertEquals(
"Preserving method bodies",
expectedResult17,
replacer.testReplace(s46,s47,s48,options, true)
);
}
public void testReplaceExceptions() {
String s1 = "a=a;";
String s2 = "'a";
String s3 = "$b$";
try {
replacer.testReplace(s1,s2,s3,options);
assertTrue("Undefined replace variable is not checked",false);
} catch(UnsupportedPatternException ex) {
}
String s4 = "a=a;";
String s5 = "a=a;";
String s6 = "a=a";
try {
replacer.testReplace(s4,s5,s6,options);
assertTrue("Undefined no ; in replace",false);
} catch(UnsupportedPatternException ex) {
}
try {
replacer.testReplace(s4,s6,s5,options);
assertTrue("Undefined no ; in search",false);
} catch(UnsupportedPatternException ex) {
}
}
public void testActualParameterReplacementInConstructorInvokation() {
String s1 = "filterActions[0] = new Action(TEXT,\n" +
" LifeUtil.getIcon(\"search\")) {\n" +
" void test() {\n" +
" int a = 1;\n" +
" }\n" +
"};";
String s2 = "LifeUtil.getIcon(\"search\")";
String s3 = "StdIcons.SEARCH_LIFE";
String expectedResult = "filterActions[0] = new Action(TEXT,\n" +
" StdIcons.SEARCH_LIFE) {\n" +
" void test() {\n" +
" int a = 1;\n" +
" }\n" +
"};";
options.setToReformatAccordingToStyle(true);
options.setToShortenFQN(true);
assertEquals("Replace in anonymous class parameter", expectedResult, replacer.testReplace(s1, s2, s3, options));
options.setToShortenFQN(false);
options.setToReformatAccordingToStyle(false);
}
public void testRemove() {
String s1 = "class A {\n" +
" /* */\n" +
" void a() {\n" +
" }\n" +
" /*\n" +
" */\n" +
" int b = 1;\n" +
" /*\n" +
" *\n" +
" */\n" +
" class C {}\n" +
" {\n" +
" /* aaa */\n" +
" int a;\n" +
" /* */\n" +
" a = 1;\n" +
" }\n" +
"}";
String s2 = "/* 'a:[regex( .* )] */";
String s2_2 = "/* */";
String s3 = "";
String expectedResult = "class A {\n" +
" void a() {\n" +
" }\n" +
"\n" +
" int b = 1;\n" +
"\n" +
" class C {\n" +
" }\n" +
"\n" +
" {\n" +
" int a;\n" +
" a = 1;\n" +
" }\n" +
"}";
options.setToReformatAccordingToStyle(true);
assertEquals("Removing comments", expectedResult, replacer.testReplace(s1,s2,s3,options));
options.setToReformatAccordingToStyle(false);
String expectedResult2 = "class A {\n" +
" void a() {\n" +
" }\n" +
" /*\n" +
" */\n" +
" int b = 1;\n" +
" /*\n" +
" *\n" +
" */\n" +
" class C {}\n" +
" {\n" +
" /* aaa */\n" +
" int a;\n" +
" a = 1;\n" +
" }\n" +
"}";
assertEquals("Removing comments", expectedResult2, replacer.testReplace(s1,s2_2,s3,options));
}
public void testTryCatchInLoop() throws Exception {
String code = "for (int i = 0; i < MIMEHelper.MIME_MAP.length; i++)\n" +
"{\n" +
" String s = aFileNameWithOutExtention + MIMEHelper.MIME_MAP[i][0][0];\n" +
" try\n" +
" {\n" +
" if (ENABLE_Z107_READING)\n" +
" { in = aFileNameWithOutExtention.getClass().getResourceAsStream(s); }\n" +
" else\n" +
" { data = ResourceHelper.readResource(s); }\n" +
" mime = MIMEHelper.MIME_MAP[i][1][0];\n" +
" break;\n" +
" }\n" +
" catch (final Exception e)\n" +
" { continue; }\n" +
"}";
String toFind = "try { '_TryStatement*; } catch(Exception '_ExceptionDcl) { '_CatchStatement*; }";
String replacement = "try { $TryStatement$; }\n" + "catch(Throwable $ExceptionDcl$) { $CatchStatement$; }";
String expectedResult = "for (int i = 0; i < MIMEHelper.MIME_MAP.length; i++)\n" +
"{\n" +
" String s = aFileNameWithOutExtention + MIMEHelper.MIME_MAP[i][0][0];\n" +
" try { if (ENABLE_Z107_READING)\n" +
" { in = aFileNameWithOutExtention.getClass().getResourceAsStream(s); }\n" +
" else\n" +
" { data = ResourceHelper.readResource(s); }\n" +
" mime = MIMEHelper.MIME_MAP[i][1][0];\n" +
" break; }\n" +
"catch(final Throwable e) { continue; }\n" +
"}";
assertEquals("Replacing try/catch in loop", expectedResult, replacer.testReplace(code,toFind,replacement,options));
}
public void testUseStaticImport() {
final String in = "class X {{ Math.abs(-1); }}";
final String what = "Math.abs('a)";
final String by = "Math.abs($a$)";
final boolean save = options.isToUseStaticImport();
options.setToUseStaticImport(true);
try {
final String expected = "import static java.lang.Math.abs;class X {{ abs(-1); }}";
assertEquals("Replacing with static import", expected, replacer.testReplace(in, what, by, options, true));
final String in2 = "class X { void m(java.util.Random r) { Math.abs(r.nextInt()); }}";
final String expected2 = "import static java.lang.Math.abs;class X { void m(java.util.Random r) { abs(r.nextInt()); }}";
assertEquals("don't add broken static imports", expected2, replacer.testReplace(in2, what, by, options, true));
final String by2 = "new java.util.Map.Entry() {}";
final String expected3 = "import static java.util.Map.Entry;class X {{ new Entry() {}; }}";
assertEquals("", expected3, replacer.testReplace(in, what, by2, options, true));
final String in3 = "import java.util.Collections;" +
"class X {" +
" void m() {" +
" System.out.println(Collections.<String>emptyList());" +
" }" +
"}";
final String what3 = "'_q.'_method:[regex( println )]('a)";
final String by3 = "$q$.$method$($a$)";
final String expected4 = "import java.util.Collections;" +
"import static java.lang.System.out;" +
"class X {" +
" void m() {" +
" out.println(Collections.<String>emptyList());" +
" }" +
"}";
assertEquals("don't break references with type parameters", expected4, replacer.testReplace(in3, what3, by3, options, true));
final String in4 = "import java.util.Collections;\n" +
"public class X {\n" +
" void some() {\n" +
" System.out.println(1);\n" +
" boolean b = Collections.eq(null, null);\n" +
" }\n" +
"}";
final String what4 = "System.out.println(1);";
final String by4 = "System.out.println(2);";
final String expected5 = "import java.util.Collections;import static java.lang.System.out;\n" +
"public class X {\n" +
" void some() {\n" +
" out.println(2);\n" +
" boolean b = Collections.eq(null, null);\n" +
" }\n" +
"}";
assertEquals("don't add static import to inaccessible members", expected5, replacer.testReplace(in4, what4, by4, options, true));
} finally {
options.setToUseStaticImport(save);
}
}
public void testUseStaticStarImport() {
final String in = "class ImportTest {{\n" +
" Math.abs(-0.5);\n" +
" Math.sin(0.5);\n" +
" Math.max(1, 2);\n" +
"}}";
final String what = "Math.'m('_a*)";
final String by = "Math.$m$($a$)";
final boolean save = options.isToUseStaticImport();
options.setToUseStaticImport(true);
try {
// depends on default setting being equal to 3 for names count to use import on demand
final String expected = "import static java.lang.Math.*;class ImportTest {{\n" +
" abs(-0.5);\n" +
" sin(0.5);\n" +
" max(1,2);\n" +
"}}";
assertEquals("Replacing with static star import", expected, replacer.testReplace(in, what, by, options, true));
} finally {
options.setToUseStaticImport(save);
}
}
public void testReformatAndShortenClassRefPerformance() throws IOException {
final String testName = getTestName(false);
final String ext = "java";
final String message = "Reformat And Shorten Class Ref Performance";
options.setToReformatAccordingToStyle(true);
options.setToShortenFQN(true);
try {
PlatformTestUtil.startPerformanceTest("SSR should work fast", 3500, new ThrowableRunnable() {
public void run() {
doTest(testName, ext, message);
}
}
).cpuBound().useLegacyScaling().assertTiming();
} finally {
options.setToReformatAccordingToStyle(false);
options.setToShortenFQN(false);
}
}
private void doTest(final String testName, final String ext, final String message) {
try {
String source = loadFile(testName + "_source." + ext);
String pattern = loadFile(testName + "_pattern." + ext);
String replacement = loadFile(testName + "_replacement." + ext);
String expected = loadFile(testName + "_result." + ext);
assertEquals(message, expected, replacer.testReplace(source,pattern,replacement,options));
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
public void testLeastSurprise() {
String s1 = "@Nullable (a=String.class) @String class Test {\n" +
" void aaa(String t) {\n" +
" String a = String.valueOf(' ');" +
" String2 a2 = String2.valueOf(' ');" +
" }\n" +
"}";
String s2 = "'String:String";
String s2_2 = "String";
String s2_3 = "'String:java\\.lang\\.String";
String s2_4 = "java.lang.String";
String replacement = CommonClassNames.JAVA_UTIL_LIST;
String expected = "@Nullable (a=java.util.List.class) @java.util.List class Test {\n" +
" void aaa(java.util.List t) {\n" +
" java.util.List a = java.util.List.valueOf(' ');" +
" String2 a2 = String2.valueOf(' ');" +
" }\n" +
"}";
assertEquals(expected, replacer.testReplace(s1,s2,replacement,options));
assertEquals(expected, replacer.testReplace(s1,s2_2,replacement,options));
assertEquals(expected, replacer.testReplace(s1,s2_3,replacement,options));
assertEquals(expected, replacer.testReplace(s1,s2_4,replacement,options));
}
public void testLeastSurprise2() {
String s1 = "class B { int s(int a) { a = 1; a = 2; c(a); } }";
String s2 = "a";
String replacement = "a2";
String expected = "class B { int s(int a2) { a2 = 1; a2 = 2; c(a2); } }";
assertEquals(expected, replacer.testReplace(s1,s2,replacement,options));
}
public void testReplaceTry() {
String s1 = "try {\n" +
" em.persist(p);\n" +
" } catch (PersistenceException e) {\n" +
" // good\n" +
" }";
String s2 = "try { '_TryStatement; } catch('_ExceptionType '_ExceptionDcl) { /* '_CommentContent */ }";
String replacement = "try { $TryStatement$; } catch($ExceptionType$ $ExceptionDcl$) { _logger.warning(\"$CommentContent$\", $ExceptionDcl$); }";
String expected = "try { em.persist(p); } catch(PersistenceException e) { _logger.warning(\" good\", e); }";
assertEquals(expected, replacer.testReplace(s1,s2,replacement,options));
final String in1 = "try {\n" +
" System.out.println(1);\n" +
"} catch (RuntimeException e) {\n" +
" System.out.println(2);\n" +
"} finally {\n" +
" System.out.println(3);\n" +
"}\n";
final String what1 = "try {\n" +
" '_Statement1;\n" +
"} finally {\n" +
" '_Statement2;\n" +
"}";
final String by1 = "try {\n" +
" // comment1\n" +
" $Statement1$;\n" +
"} finally {\n" +
" // comment2\n" +
" $Statement2$;\n" +
"}";
final String expected1 = "try {\n" +
" // comment1\n" +
" System.out.println(1);\n" +
"} catch (RuntimeException e) {\n" +
" System.out.println(2);\n" +
"} finally {\n" +
" // comment2\n" +
" System.out.println(3);\n" +
"}\n";
assertEquals("Replacing try/finally should leave unmatched catch sections alone",
expected1, replacer.testReplace(in1, what1, by1, options));
final String in2 = "try (AutoCloseable a = null) {" +
" System.out.println(1);" +
"} catch (Exception e) {" +
" System.out.println(2);" +
"} finally {" +
" System.out.println(3);" +
"}";
final String what2 = "try {" +
" '_Statement*;" +
"}";
final String by2 = "try {" +
" /* comment */" +
" $Statement$;" +
"}";
final String expected2 = "try (AutoCloseable a = null) {" +
" /* comment */ System.out.println(1);" +
"} catch (Exception e) {" +
" System.out.println(2);" +
"} finally {" +
" System.out.println(3);" +
"}";
assertEquals("Replacing try/finally should also keep unmatched resource lists and finally blocks",
expected2,
replacer.testReplace(in2, what2, by2, options));
}
public void testReplaceExtraSemicolon() {
String s1 = "try {\n" +
" String[] a = {\"a\"};\n" +
" System.out.println(\"blah\");\n" +
"} finally {\n" +
"}\n";
String s2 = "try {\n" + " 'statement*;\n" + "} finally {\n" + " \n" + "}";
String replacement = "$statement$;";
String expected = "String[] a = {\"a\"};\n" +
" System.out.println(\"blah\");\n";
assertEquals(expected, replacer.testReplace(s1,s2,replacement,options));
String s1_2 = "try {\n" +
" if (args == null) return ;\n" +
" while(true) return ;\n" +
" System.out.println(\"blah2\");\n" +
"} finally {\n" +
"}";
String expected_2 = "if (args == null) return ;\n" +
" while(true) return ;\n" +
" System.out.println(\"blah2\");";
assertEquals(expected_2, replacer.testReplace(s1_2,s2,replacement,options));
String s1_3 = "{\n" +
" try {\n" +
" System.out.println(\"blah1\");\n" +
"\n" +
" System.out.println(\"blah2\");\n" +
" } finally {\n" +
" }\n" +
"}";
String expected_3 = "{\n" +
" System.out.println(\"blah1\");\n" +
"\n" +
" System.out.println(\"blah2\");\n" +
"}";
assertEquals(expected_3, replacer.testReplace(s1_3,s2,replacement,options));
String s1_4 = "{\n" +
" try {\n" +
" System.out.println(\"blah1\");\n" +
" // indented comment\n" +
" System.out.println(\"blah2\");\n" +
" } finally {\n" +
" }\n" +
"}";
String expected_4 = "{\n" +
" System.out.println(\"blah1\");\n" +
" // indented comment\n" +
" System.out.println(\"blah2\");\n" +
"}";
assertEquals(expected_4, replacer.testReplace(s1_4,s2,replacement,options));
}
public void testReplaceFinalModifier() throws Exception {
String s1 = "class Foo {\n" +
" void foo(final int i,final int i2, final int i3) {\n" +
" final int x = 5;\n" +
" }\n" +
"}";
String s2 = "final '_type 'var = '_init?;";
String s3 = "$type$ $var$ = $init$;";
String expected = "class Foo {\n" +
" void foo(int i, int i2, int i3) {\n" +
" int x = 5;\n" +
" }\n" +
"}";
assertEquals(expected, replacer.testReplace(s1,s2,s3,options));
}
public void testRemovingRedundancy() throws Exception {
String s1 = "int a = 1;\n" +
"a = 2;\n" +
"int b = a;\n" +
"b2 = 3;";
String s2 = "int '_a = '_i;\n" +
"'_st*;\n" +
"'_a = '_c;";
String s3 = "$st$;\n" +
"$c$ = $i$;";
String expected = "2 = 1;\nint b = a;\nb2 = 3;";
assertEquals(expected, replacer.testReplace(s1,s2,s3,options));
String s2_2 = "int '_a = '_i;\n" +
"'_st*;\n" +
"int '_c = '_a;";
String s3_2 = "$st$;\n" +
"int $c$ = $i$;";
String expected_2 = "a = 2;\nint b = 1;\nb2 = 3;";
assertEquals(expected_2, replacer.testReplace(s1,s2_2,s3_2,options));
}
public void testReplaceWithEmptyString() {
String source = "public class Peepers {\n public long serialVersionUID = 1L; \n}";
String search = "long serialVersionUID = $value$;";
String replace = "";
String expectedResult = "public class Peepers { \n}";
assertEquals(expectedResult, replacer.testReplace(source, search, replace, options, true));
}
public void testReplaceMultipleFieldsInSingleDeclaration() {
String source = "abstract class MyClass implements java.util.List {\n private String a, b;\n}";
String search = "class 'Name implements java.util.List {\n '_ClassContent*\n}";
String replace = "class $Name$ {\n $ClassContent$\n}";
String expectedResult = "abstract class MyClass {\n private String a,b;\n}";
assertEquals(expectedResult, replacer.testReplace(source, search, replace, options, true));
}
public void testReplaceInImplementsList() {
String source = "import java.io.Externalizable;\n" +
"import java.io.Serializable;\n" +
"abstract class MyClass implements Serializable, java.util.List, Externalizable {}";
String search = "class 'TestCase implements java.util.List, '_others* {\n '_MyClassContent\n}";
String replace = "class $TestCase$ implements $others$ {\n $MyClassContent$\n}";
String expectedResult = "import java.io.Externalizable;\n" +
"import java.io.Serializable;\n" +
"abstract class MyClass implements Externalizable,Serializable {\n \n}";
assertEquals(expectedResult, replacer.testReplace(source, search, replace, options, true));
}
public void testReplaceFieldWithEndOfLineComment() {
String source = "class MyClass {\n" +
" private String b;// comment\n" +
" public void foo() {\n" +
" }\n" +
"}";
String search = "class 'Class {\n '_Content*\n}";
String replace = "class $Class$ {\n" +
" void x() {}\n" +
" $Content$\n" +
" void bar() {}\n" +
"}";
String expectedResult = "class MyClass {\n" +
" void x() {}\n" +
" private String b;// comment\n" +
"public void foo() {\n" +
" }\n" +
" void bar() {}\n" +
"}";
assertEquals(expectedResult, replacer.testReplace(source, search, replace, options, true));
}
public void testReplaceAnnotation() {
String in = "@SuppressWarnings(\"ALL\")\n" +
"public class A {}";
String what = "@SuppressWarnings(\"ALL\")";
final String by1 = "";
assertEquals("public class A {}", replacer.testReplace(in, what, by1, options, false));
final String by2 = "@SuppressWarnings(\"NONE\") @Deprecated";
assertEquals("@SuppressWarnings(\"NONE\") @Deprecated\n" +
"public class A {}", replacer.testReplace(in, what, by2, options, false));
}
public void testReplacePolyadicExpression() {
final String in1 = "class A {" +
" int i = 1 + 2 + 3;" +
"}";
final String what1 = "1 + '_a+";
final String by1 = "4";
assertEquals("class A { int i = 4;}", replacer.testReplace(in1, what1, by1, options, false));
final String by2 = "$a$";
assertEquals("class A { int i = 2+3;}", replacer.testReplace(in1, what1, by2, options, false));
final String by3 = "$a$+4";
assertEquals("class A { int i = 2+3+4;}", replacer.testReplace(in1, what1, by3, options, false));
final String what2 = "1 + 2 + 3 + '_a*";
final String by4 = "1 + 3 + $a$";
assertEquals("class A { int i = 1 + 3;}", replacer.testReplace(in1, what2, by4, options, false));
final String by5 = "$a$ + 1 + 3";
assertEquals("class A { int i = 1 + 3;}", replacer.testReplace(in1, what2, by5, options, false));
final String by6 = "1 + $a$ + 3";
assertEquals("class A { int i = 1 + 3;}", replacer.testReplace(in1, what2, by6, options, false));
final String in2 = "class A {" +
" boolean b = true && true;" +
"}";
final String what3 = "true && true && '_a*";
final String by7 = "true && true && $a$";
assertEquals("class A { boolean b = true && true;}", replacer.testReplace(in2, what3, by7, options, false));
final String by8 = "$a$ && true && true";
assertEquals("class A { boolean b = true && true;}", replacer.testReplace(in2, what3, by8, options, false));
}
public void testReplaceAssert() {
final String in = "class A {" +
" void m(int i) {" +
" assert 10 > i;" +
" }" +
"}";
final String what = "assert '_a > '_b : '_c?;";
final String by = "assert $b$ < $a$ : $c$;";
assertEquals("class A { void m(int i) { assert i < 10 ; }}", replacer.testReplace(in, what, by, options, false));
}
public void testReplaceMultipleVariablesInOneDeclaration() {
final String in = "class A {" +
" private int i, j, k;" +
" void m() {" +
" int i,j,k;" +
" }" +
"}";
final String what1 = "int '_i+;";
final String by1 = "float $i$;";
assertEquals("class A { private float i,j,k; void m() { float i,j,k; }}", replacer.testReplace(in, what1, by1, options));
final String what2 = "int '_a, '_b, '_c = '_d?;";
final String by2 = "float $a$, $b$, $c$ = $d$;";
assertEquals("class A { private float i, j, k ; void m() { float i, j, k ; }}", replacer.testReplace(in, what2, by2, options));
}
public void testReplaceWithScriptedVariable() {
final String in = "class A {\n" +
" void method(Object... os) {}\n" +
" void f(Object a, Object b, Object c) {\n" +
" method(a, b, c, \"one\" + \"two\");\n" +
" method(a);\n" +
" }\n" +
"}";
final String what = "method('_arg+)";
final String by = "method($newarg$)";
final ReplacementVariableDefinition variable = new ReplacementVariableDefinition();
variable.setName("newarg");
variable.setScriptCodeConstraint("arg.collect { \"(String)\" + it.getText() }.join(',')");
options.addVariableDefinition(variable);
final String expected = "class A {\n" +
" void method(Object... os) {}\n" +
" void f(Object a, Object b, Object c) {\n" +
" method((String)a,(String)b,(String)c,(String)\"one\" + \"two\");\n" +
" method((String)a);\n" +
" }\n" +
"}";
assertEquals(expected, replacer.testReplace(in, what, by, options));
options.clearVariableDefinitions();
}
public void testMethodContentReplacement() {
final String in = "class A extends TestCase {\n" +
" void testOne() {\n" +
" System.out.println();\n" +
" }\n" +
"}\n";
final String what = "class '_A { void '_b:[regex( test.* )](); }";
final String by = "class $A$ {\n @java.lang.Override void $b$();\n}";
assertEquals("class A extends TestCase {\n" +
" @Override void testOne() {\n" +
" System.out.println();\n" +
" }\n" +
"}\n", replacer.testReplace(in, what, by, options));
final String what2 = "void '_a:[regex( test.* )]();";
final String by2 = "@org.junit.Test void $a$();";
assertEquals("class A extends TestCase {\n" +
" @org.junit.Test void testOne() {\n" +
" System.out.println();\n" +
" }\n" +
"}\n",
replacer.testReplace(in, what2, by2, options));
}
public void testReplaceMethodWithoutBody() {
final String in = "abstract class A {\n" +
" abstract void a();\n" +
"}";
final String what = "void '_a();";
final String by = "void $a$(int i);";
assertEquals("abstract class A {\n" +
" abstract void a(int i);\n" +
"}",
replacer.testReplace(in, what, by, options));
}
public void testReplaceParameterWithComment() {
final String in = "class A {\n" +
" void a(int b) {}\n" +
"}";
final String what = "int '_a = '_b{0,1};";
final String by = "final long /*!*/ $a$ = $b$;";
assertEquals("class A {\n" +
" void a(final long /*!*/ b) {}\n" +
"}",
replacer.testReplace(in, what, by, options));
}
public void testReplaceInnerClass() {
String in = "public class A {\n" +
" public class B<T> extends A implements java.io.Serializable {}\n" +
"}";
String what = "class '_A {" +
" class '_B {}" +
"}";
String by = "class $A$ {\n" +
" private class $B$ {\n" +
" }\n" +
"}";
assertEquals("public class A {\n" +
" private class B<T> extends A implements java.io.Serializable {\n" +
" }\n" +
"}",
replacer.testReplace(in, what, by, options));
String in2 = "public class A {\n" +
" void m1() {}\n" +
" public void m2() {}\n" +
" public class B<T> extends A implements java.io.Serializable {\n" +
" int zero() {\n" +
" return 0;\n" +
" }\n" +
" }\n" +
" void m3() {}\n" +
"}";
assertEquals("should replace unmatched class content correctly",
"public class A {\n" +
" void m1() {}\n" +
" public void m2() {}\n" +
" private class B<T> extends A implements java.io.Serializable {\n" +
" int zero() {\n" +
" return 0;\n" +
" }\n" +
" }\n" +
" void m3() {}\n" +
"}",
replacer.testReplace(in2, what, by, options));
}
} | apache-2.0 |
fabriziocucci/CodeEval | moderate/lost-in-translation/java/src/main/java/Main.java | 3444 | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class Main {
private static final String ENCODED_PHRASE_1 = "rbc vjnmkf kd yxyqci na rbc zjkfoscdd ew rbc ujllmcp";
private static final String ENCODED_PHRASE_2 = "tc rbkso rbyr ejp mysljylc kd kxveddknmc re jsicpdrysi";
private static final String ENCODED_PHRASE_3 = "de kr kd eoya kw aej icfkici re zjkr";
private static final String DECODED_PHRASE_1 = "the public is amazed by the quickness of the juggler";
private static final String DECODED_PHRASE_2 = "we think that our language is impossible to understand";
private static final String DECODED_PHRASE_3 = "so it is okay if you decided to quit";
private static final Map<String, String> EXAMPLES = new HashMap<String, String>();
static {
EXAMPLES.put(ENCODED_PHRASE_1, DECODED_PHRASE_1);
EXAMPLES.put(ENCODED_PHRASE_2, DECODED_PHRASE_2);
EXAMPLES.put(ENCODED_PHRASE_3, DECODED_PHRASE_3);
}
private static final char[] CODEL_MAPPING = new char['z' - 'a' + 1];
static {
CODEL_MAPPING['n' - 'a'] = 'b';
CODEL_MAPPING['u' - 'a'] = 'j';
CODEL_MAPPING['g' - 'a'] = 'v';
populateCodelMapping();
ensureCodelMappingCompleteness();
}
public static void main(String[] args) throws IOException {
try(BufferedReader bufferedReader = new BufferedReader(new FileReader(args[0]))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(decodePhrase(line));
}
}
}
private static void populateCodelMapping() {
for (Map.Entry<String, String> entry : EXAMPLES.entrySet()) {
String encodedString = entry.getKey().replaceAll("\\s", "");
String decodedString = entry.getValue().replaceAll("\\s", "");
for (int i = 0; i < encodedString.length(); i++) {
CODEL_MAPPING[encodedString.charAt(i) - 'a'] = decodedString.charAt(i);
}
}
}
private static void ensureCodelMappingCompleteness() {
int missingMappingIndex = verifyCodelMapping();
if (missingMappingIndex != -1) {
fixMissingMapping(missingMappingIndex);
}
}
private static int verifyCodelMapping() {
int missingMappingIndex = -1;
for (int i = 0; i < CODEL_MAPPING.length; i++) {
if (CODEL_MAPPING[i] == '\u0000') {
if (missingMappingIndex == -1) {
missingMappingIndex = i;
} else {
throw new IllegalStateException("There are more than one missing mappings!");
}
}
}
return missingMappingIndex;
}
private static void fixMissingMapping(int missingMappingIndex) {
char[] allCharacters = new char['z' - 'a' + 1];
for (int i = 0; i < allCharacters.length; i++) {
allCharacters[i] = (char) ('a' + i);
}
for (int i = 0; i < CODEL_MAPPING.length; i++) {
if (i != missingMappingIndex) {
allCharacters[CODEL_MAPPING[i] - 'a'] = '\u0000';
}
}
for (int i = 0; i < allCharacters.length; i++) {
if (allCharacters[i] != '\u0000') {
CODEL_MAPPING[missingMappingIndex] = allCharacters[i];
break;
}
}
}
private static String decodePhrase(String encodedPhrase) {
StringBuilder decodedPhrase = new StringBuilder();
for (int i = 0; i < encodedPhrase.length(); i++) {
if (encodedPhrase.charAt(i) != ' ') {
decodedPhrase.append(CODEL_MAPPING[encodedPhrase.charAt(i) - 'a']);
} else {
decodedPhrase.append(encodedPhrase.charAt(i));
}
}
return decodedPhrase.toString();
}
}
| apache-2.0 |
OpenVnmrJ/OpenVnmrJ | src/vnmrj/src/vnmr/util/ButtonIF.java | 1935 | /*
* Copyright (C) 2015 University of Oregon
*
* You may distribute under the terms of either the GNU General Public
* License or the Apache License, as specified in the LICENSE file.
*
* For more information, see the LICENSE file.
*/
package vnmr.util;
import java.io.*;
import java.awt.event.*;
import vnmr.bo.*;
/**
* An ButtonIF provides the interface for button callback.
*
*/
public interface ButtonIF {
public void buttonActiveCall(int num);
public void tearOffOpen(boolean b);
public void childMouseProc(MouseEvent ev, boolean release, boolean drag);
public void sendToVnmr(String cmd);
public void sendVnmrCmd(VObjIF obj, String cmd);
public void sendVnmrCmd(VObjIF obj, String cmd, int nKey);
public void setBusy(boolean b);
public ParamIF syncQueryParam(String s);
public ParamIF syncQueryPStatus(String s);
public ParamIF syncQueryMinMax(String s);
public ParamIF syncQueryExpr(String s);
public ParamIF syncQueryVnmr(int type, String s);
public void asyncQueryParam(VObjIF o, String s);
public void asyncQueryParam(VObjIF o, String s, String s2);
public void asyncQueryShow(VObjIF o, String s);
public void asyncQueryParamNamed(String name, VObjIF o, String s);
public void asyncQueryParamNamed(String name, VObjIF o, String s, String u);
public void asyncQueryShowNamed(String name, VObjIF o, String s);
public void asyncQueryMinMax(VObjIF o, String s);
public void requestActive();
public void setInputFocus();
public void asyncQueryARRAY(VObjIF o, int cmdType, String s);
public void queryPanelInfo(String name);
public void queryPanelInfo();
public void setBusyTimer(boolean b);
public VContainer getLcPanel();
public void setPanelGeometry(VContainer comp, int size, char pos);
public void processMousePressed(MouseEvent e);
public void processMouseReleased(MouseEvent e);
} // ButtonIF
| apache-2.0 |
allure-framework/allure-java | allure-testng/src/test/java/io/qameta/allure/testng/samples/BaseTestA.java | 781 | /*
* Copyright 2019 Qameta Software 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 io.qameta.allure.testng.samples;
/**
* @author charlie (Dmitry Baev).
*/
public class BaseTestA extends BaseTest {
@Override
void check() {
}
}
| apache-2.0 |
PRIDE-Archive/archive-px-xml-generator | src/test/java/uk/ac/ebi/pride/archive/px/UpdateMessageOnePointFourTest.java | 1091 | package uk.ac.ebi.pride.archive.px;
import org.junit.Before;
import org.junit.Test;
import uk.ac.ebi.pride.data.exception.SubmissionFileException;
import java.io.File;
import java.io.IOException;
/**
* @author Suresh Hewapathirana
*/
public class UpdateMessageOnePointFourTest {
File submissionSummaryFile;
File outputDirectory;
final String pxAccession = "PXT000001";
final String datasetPathFragment = "2013/07/PXT000001";
final String pxSchemaVersion = "1.4.0";
@Before
public void setUp() throws Exception {
submissionSummaryFile = new File("src/test/resources/submission.px");
outputDirectory = new File("src/test/resources/pxxml");
}
@Test
public void updateMetadataPxXmlTest() throws Exception {
try {
UpdateMessage.updateMetadataPxXml( submissionSummaryFile, outputDirectory, pxAccession, datasetPathFragment, true, pxSchemaVersion);
} catch (SubmissionFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
} | apache-2.0 |
moosbusch/xbLIDO | src/net/opengis/gml/FeatureDocument.java | 8438 | /*
* Copyright 2013 Gunnar Kappei.
*
* 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.opengis.gml;
/**
* A document containing one _Feature(@http://www.opengis.net/gml) element.
*
* This is a complex type.
*/
public interface FeatureDocument extends net.opengis.gml.GMLDocument
{
public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType)
org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(FeatureDocument.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.s6E28D279B6C224D74769DB8B98AF1665").resolveHandle("feature3ab4doctype");
/**
* Gets the "_Feature" element
*/
net.opengis.gml.AbstractFeatureType getFeature();
/**
* Sets the "_Feature" element
*/
void setFeature(net.opengis.gml.AbstractFeatureType feature);
/**
* Appends and returns a new empty "_Feature" element
*/
net.opengis.gml.AbstractFeatureType addNewFeature();
/**
* A factory class with static methods for creating instances
* of this type.
*/
public static final class Factory
{
public static net.opengis.gml.FeatureDocument newInstance() {
return (net.opengis.gml.FeatureDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, null ); }
public static net.opengis.gml.FeatureDocument newInstance(org.apache.xmlbeans.XmlOptions options) {
return (net.opengis.gml.FeatureDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, options ); }
/** @param xmlAsString the string value to parse */
public static net.opengis.gml.FeatureDocument parse(java.lang.String xmlAsString) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.FeatureDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, null ); }
public static net.opengis.gml.FeatureDocument parse(java.lang.String xmlAsString, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.FeatureDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, options ); }
/** @param file the file from which to load an xml document */
public static net.opengis.gml.FeatureDocument parse(java.io.File file) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.FeatureDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, null ); }
public static net.opengis.gml.FeatureDocument parse(java.io.File file, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.FeatureDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, options ); }
public static net.opengis.gml.FeatureDocument parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.FeatureDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, null ); }
public static net.opengis.gml.FeatureDocument parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.FeatureDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, options ); }
public static net.opengis.gml.FeatureDocument parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.FeatureDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, null ); }
public static net.opengis.gml.FeatureDocument parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.FeatureDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, options ); }
public static net.opengis.gml.FeatureDocument parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.FeatureDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, null ); }
public static net.opengis.gml.FeatureDocument parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (net.opengis.gml.FeatureDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, options ); }
public static net.opengis.gml.FeatureDocument parse(javax.xml.stream.XMLStreamReader sr) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.FeatureDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, null ); }
public static net.opengis.gml.FeatureDocument parse(javax.xml.stream.XMLStreamReader sr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.FeatureDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, options ); }
public static net.opengis.gml.FeatureDocument parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.FeatureDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, null ); }
public static net.opengis.gml.FeatureDocument parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (net.opengis.gml.FeatureDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, options ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
@Deprecated
public static net.opengis.gml.FeatureDocument parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return (net.opengis.gml.FeatureDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, null ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
@Deprecated
public static net.opengis.gml.FeatureDocument parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return (net.opengis.gml.FeatureDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, options ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
@Deprecated
public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
@Deprecated
public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); }
private Factory() { } // No instance of this class allowed
}
}
| apache-2.0 |
krishnan-mani/idea-cloudformation | src/test/java/com/intellij/aws/cloudformation/tests/CompletionTests.java | 4269 | package com.intellij.aws.cloudformation.tests;
import com.intellij.codeInsight.completion.CompletionType;
import com.intellij.openapi.application.ApplicationInfo;
import com.intellij.openapi.util.BuildNumber;
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase;
import java.util.Arrays;
import java.util.List;
public class CompletionTests extends LightCodeInsightFixtureTestCase {
public void testResourceType1() throws Exception {
myFixture.configureByFiles("ResourceType1.template");
myFixture.complete(CompletionType.BASIC, 1);
List<String> strings = myFixture.getLookupElementStrings();
assertContainsElements(strings, "AWS::IAM::AccessKey");
}
public void testResourceType2() throws Exception {
myFixture.configureByFiles("ResourceType2.template");
myFixture.complete(CompletionType.BASIC, 1);
List<String> strings = myFixture.getLookupElementStrings();
assertDoesntContain(strings, "AWS::IAM::AccessKey");
}
public void testResourceProperty1() throws Exception {
checkBasicCompletion("ResourceProperty1.template", "ApplicationName", "ApplicationVersions");
}
public void testDependsOn1() throws Exception {
checkBasicCompletion("DependsOn1.template", "WebServerUser1");
}
public void testDependsOn2() throws Exception {
checkBasicCompletion("DependsOn2.template", "WebServerUser1", "WebServerUser2");
}
public void testGetAtt1() throws Exception {
checkBasicCompletion("GetAtt1.template", "Arn");
}
public void testGetAtt2() throws Exception {
checkBasicCompletion("GetAtt2.template", "ConfigurationEndpoint.Address", "ConfigurationEndpoint.Port");
}
public void testResourceTopLevelProperty1() throws Exception {
checkBasicCompletion("ResourceTopLevelProperty1.template", "Condition", "CreationPolicy", "DeletionPolicy", "Metadata", "Properties", "UpdatePolicy", "Version");
}
public void testPrefix1() throws Exception {
if (!checkIdeaHasWeb11859Fixed()) {
return;
}
myFixture.testCompletion("Prefix1.template", "Prefix1_after.template");
}
public void testPrefix2() throws Exception {
myFixture.testCompletion("Prefix2.template", "Prefix2_after.template");
}
public void testPrefix3() throws Exception {
if (!checkIdeaHasWeb11859Fixed()) {
return;
}
checkBasicCompletion("Prefix3.template", "AWS::ElasticBeanstalk::Application", "AWS::ElasticBeanstalk::ApplicationVersion");
}
public void testPredefinedParameters() throws Exception {
checkBasicCompletion("PredefinedParameters.template",
"AWS::AccountId",
"AWS::NoValue",
"AWS::NotificationARNs",
"AWS::Region",
"AWS::StackId",
"AWS::StackName");
}
public void testMappingTopLevelKey1() throws Exception {
// checkBasicCompletion("MappingTopLevelKey1.template", "cc1.4xlarge", "cc2.8xlarge");
}
public void _testMappingTopLevelKey2() throws Exception {
checkBasicCompletion("MappingTopLevelKey2.template", "m1.small", "t1.micro", "m2.small");
}
public void testMappingSecondLevelKey1() throws Exception {
checkBasicCompletion("MappingSecondLevelKey1.template", "Arch", "Arch2");
}
public void _testMappingSecondLevelKey2() throws Exception {
checkBasicCompletion("MappingSecondLevelKey2.template", "Arch", "Arch2", "Arch3");
}
public void _testMappingSecondLevelKey3() throws Exception {
checkBasicCompletion("MappingSecondLevelKey3.template", "Arch", "Arch2", "Arch3", "A56", "A4");
}
private void checkBasicCompletion(String fileName, String... expectedElements) {
myFixture.configureByFiles(fileName);
myFixture.complete(CompletionType.BASIC, 1);
List<String> strings = myFixture.getLookupElementStrings();
assertSameElements(strings, Arrays.asList(expectedElements));
}
private static boolean checkIdeaHasWeb11859Fixed() {
BuildNumber build = ApplicationInfo.getInstance().getBuild();
if (build.compareTo(new BuildNumber("IU", 135, 670)) < 0) {
System.out.println("fixed only by http://youtrack.jetbrains.com/issue/WEB-11859");
return false;
}
return true;
}
@Override
protected String getTestDataPath() {
return TestUtil.getTestDataPath("completion");
}
}
| apache-2.0 |
lburgazzoli/lb-axon | axon-hazelcast/src/main/java/org/axonframework/ext/hazelcast/distributed/commandbus/queue/HzCommandBusNode.java | 2520 | /*
* Copyright (c) 2010-2013. Axon Framework
*
* 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.axonframework.ext.hazelcast.distributed.commandbus.queue;
import com.google.common.base.MoreObjects;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.DataSerializable;
import java.io.IOException;
import java.util.Date;
/**
*
*/
public class HzCommandBusNode implements DataSerializable {
private String m_name;
private String m_queueName;
private Long m_lastHeartBeat;
/**
* c-tor
*/
public HzCommandBusNode() {
m_name = null;
m_queueName = null;
m_lastHeartBeat = null;
}
/**
* c-tor
*
* @param name the node name
* @param queueName the queue name
*/
public HzCommandBusNode(String name, String queueName) {
m_name = name;
m_queueName = queueName;
m_lastHeartBeat = System.currentTimeMillis();
}
/**
*
* @return the node name
*/
public String getName() {
return m_name;
}
/**
*
* @return the queue name
*/
public String getQueueName() {
return m_queueName;
}
@Override
public void writeData(ObjectDataOutput dataOutput) throws IOException {
dataOutput.writeUTF(m_name);
dataOutput.writeUTF(m_queueName);
dataOutput.writeLong(m_lastHeartBeat);
}
@Override
public void readData(ObjectDataInput dataInput) throws IOException {
m_name = dataInput.readUTF();
m_queueName = dataInput.readUTF();
m_lastHeartBeat = dataInput.readLong();
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("name" , m_name)
.add("inbox" , m_queueName)
.add("lastHeartBeat", new Date(m_lastHeartBeat))
.toString();
}
}
| apache-2.0 |
RcExtract/Minecord | src/main/java/com/rcextract/minecord/CommandExpansion.java | 72 | package com.rcextract.minecord;
public interface CommandExpansion {
}
| apache-2.0 |
acompagno/Android-Examples | AndroidExample/app/src/main/java/com/acompagno/example/fragments/Example2Fragment.java | 5000 | package com.acompagno.example.fragments;
import java.util.HashMap;
import java.util.Map;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar.LayoutParams;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
public class Example2Fragment extends Fragment {
private Map<String, String> strings;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Initializes a hashmap where the string from the text fields will be stored
strings = new HashMap<String, String>();
//Create a new scrollview this is the main view were gonna use.
ScrollView scroll = new ScrollView(getActivity());
//Create new linear layout to add the views
//Views cant be added directly to a scroll view
LinearLayout ll = new LinearLayout(getActivity());
//Set orientation of the linear layout
ll.setOrientation(LinearLayout.VERTICAL);
//add the linearlayout to the scrollview
scroll.addView(ll);
//Create a new text view. The final allows us to call to it inside the "setOnClickListener" later on
final TextView text = new TextView(getActivity());
//Set the text of the textview
text.setText("Type in the text fields and press the button");
//Set the size of the textview
text.setTextSize(30);
//Center the text
text.setGravity(Gravity.CENTER);
//Add the textview to the linear layout
ll.addView(text);
for (int i = 0; i < 5; i++) {
final int temp = i;
//Create a linear layout, these will be horizontal so we can have the text field and the button on the same line
LinearLayout linearHorizontal = new LinearLayout(getActivity());
//set the orientation of the linear layout to horizontal
linearHorizontal.setOrientation(LinearLayout.HORIZONTAL);
linearHorizontal.setGravity(Gravity.CENTER);
//initialize a spot in the hashmap for getActivity() specific field
strings.put("field" + i, "");
//create the text field
//createEditText is a method that handles creating the edit text. this helps make the code less cluttered
EditText field = createEditText(i);
//Create a new button
Button btn = new Button(getActivity());
//Set the text of the button.
btn.setText("Change Text");
// defines what the button does when it is clicked.
//Just add whatever you want it to do in the "onClick" method
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
//Change the text of the text we created in the beginning of the code
text.setText(strings.get("field" + temp));
}
});
//Add the views we just created to the horizontal linear layout
linearHorizontal.addView(field);
linearHorizontal.addView(btn);
//now add the horizontal linear layout to the main vertical one
ll.addView(linearHorizontal);
}
//since scroll is the main view that contains all other views, we return it
return scroll;
}
//Method creates, sets up, and returns an edit text
private EditText createEditText(final int i) {
//Set the define sizing for a view. we're going to use this sizing for the edit text
LayoutParams lparams = new LayoutParams(400, LayoutParams.WRAP_CONTENT); // Width , height
//create the edittext
EditText edittext = new EditText(getActivity());
//set the its sizing to the parameters we just created
edittext.setLayoutParams(lparams);
//Sets the max lines of the field
edittext.setSingleLine();
//Set what happens when you type
edittext.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//Store what is written in the field in the hashmap
//s contains whats in the text field.
strings.put("field" + i, s.toString());
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
//Return the exittext we just created
return edittext;
}
} | apache-2.0 |
youdian/springbase | src/main/java/org/youdian/springbase/service/LocationService.java | 559 | package org.youdian.springbase.service;
import java.util.List;
import org.youdian.springbase.model.GeoLocation;
/**
* 位置服务操作
* @author zhouzhou
*
*/
public interface LocationService {
//搜索范围限定到附近500英里内
static final double distance = 500;
/**
* 插入一条位置记录
* @param location
*/
public void insertLocation(GeoLocation location);
/**
* 查看位置附近一定距离内的所有记录
* @param location
* @return
*/
public List<GeoLocation> findNearbyLocations(GeoLocation location);
}
| apache-2.0 |
jinahya/openfire-bind | src/main/java/com/github/jinahya/openfire/ibatis/mapper/OfConversationMapper.java | 2095 | /*
* Copyright 2017 Jin Kwon <onacit at 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.github.jinahya.openfire.ibatis.mapper;
import com.github.jinahya.openfire.persistence.OfConversation;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.RowBounds;
/**
* A mapper interface for {@link OfConversation}.
*
* @author Jin Kwon <onacit at gmail.com>
*/
@Mapper
public interface OfConversationMapper extends OfMappedMapper<OfConversation> {
/**
* Parameter value for {@value OfConversation#COLUMN_NAME_CONVERSATION_ID}
* column.
*/
String PARAM_CONVERSATION_ID = "conversationId";
/**
* Parameter value for {@value OfConversation#COLUMN_NAME_ROOM} column.
*/
String PARAM_ROOM = "room";
// -------------------------------------------------------------------------
OfConversation selectOne01(
@Param(PARAM_CATALOG) String catalog,
@Param(PARAM_SCHEMA) String schema,
@Param(PARAM_CONVERSATION_ID) long conversaionId);
List<OfConversation> selectList01(@Param(PARAM_CATALOG) String catalog,
@Param(PARAM_SCHEMA) String schema,
@Param(PARAM_ROOM) String room,
@Param(PARAM_NATURAL) boolean natural,
@Param(PARAM_ASCENDING) boolean ascending,
RowBounds rowBounds);
}
| apache-2.0 |
abhijeetshm/gunners | CalenderApp/src/com/examples/SentItems.java | 1489 | package com.examples;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.OnItemClickListener;
public class SentItems extends Activity {
ListView lv;
CmsgAdapter adapter;
String num , message , time , date ;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.sentitems);
lv = (ListView)findViewById(R.id.sentitemslistView1);
}
public void onStart()
{
super.onStart();
adapter=MyApplication.getcAdapter();
adapter.open(CmsgAdapter.readMode);
Cursor cmsg = adapter.getAllSendCmsg();
SimpleCursorAdapter listAdapter=new SimpleCursorAdapter(this,R.layout.sentitemslayout,cmsg,new String[]{
"number","message","time" , "date"},new int[]{R.id.sentitemslayouttextView1,R.id.sentitemslayouttextView2,R.id.sentitemslayouttextView3,R.id.sentitemslayouttextView4});
Log.i("dbtest","list adapter created...");
lv.setAdapter(listAdapter);
Log.i("dbtest","list adapter provided to the list view...");
}
public void onStop()
{
super.onStop();
adapter.close();
}
}
| apache-2.0 |
openmhealth/shimmer | shim-server/src/main/java/org/openmhealth/shim/OptionalStreamSupport.java | 1046 | /*
* Copyright 2017 Open mHealth
*
* 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.openmhealth.shim;
import java.util.Optional;
import java.util.stream.Stream;
/**
* A set of utility methods to help with {@link Optional} {@link Stream} objects.
*
* @author Emerson Farrugia
*/
public class OptionalStreamSupport {
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public static <O> Stream<O> asStream(Optional<O> optional) {
return optional.map(Stream::of).orElseGet(Stream::empty);
}
}
| apache-2.0 |
simon-eastwood/DependencyCheckCM | dependency-check-core/src/main/java/org/owasp/dependencycheck/jaxb/pom/generated/Prerequisites.java | 2387 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.11.09 at 12:33:57 PM EST
//
package org.owasp.dependencycheck.jaxb.pom.generated;
import javax.annotation.Generated;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* Describes the prerequisites a project can have.
*
* <p>Java class for Prerequisites complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="Prerequisites">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <all>
* <element name="maven" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </all>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Prerequisites", propOrder = {
})
@Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2012-11-09T12:33:57-05:00", comments = "JAXB RI vJAXB 2.1.10 in JDK 6")
public class Prerequisites {
@XmlElement(defaultValue = "2.0")
@Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2012-11-09T12:33:57-05:00", comments = "JAXB RI vJAXB 2.1.10 in JDK 6")
protected String maven;
/**
* Gets the value of the maven property.
*
* @return
* possible object is
* {@link String }
*
*/
@Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2012-11-09T12:33:57-05:00", comments = "JAXB RI vJAXB 2.1.10 in JDK 6")
public String getMaven() {
return maven;
}
/**
* Sets the value of the maven property.
*
* @param value
* allowed object is
* {@link String }
*
*/
@Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2012-11-09T12:33:57-05:00", comments = "JAXB RI vJAXB 2.1.10 in JDK 6")
public void setMaven(String value) {
this.maven = value;
}
}
| apache-2.0 |
xavierlepretre/hacker-news-browser | hackernewsdto/src/test/java/com/ycombinator/news/service/ItemDeserialiserTest.java | 752 | package com.ycombinator.news.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ycombinator.news.dto.CommentDTO;
import com.ycombinator.news.dto.ItemDTO;
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
import static org.fest.assertions.api.Assertions.assertThat;
public class ItemDeserialiserTest
{
private ObjectMapper mapper;
@Before public void setUp()
{
this.mapper = HackerNewsMapper.createHackerNewsMapper();
}
@Test public void testMapperRobust() throws IOException
{
ItemDTO itemDTO = mapper.readValue(getClass().getResourceAsStream("comment_dto_1_too_much.json"), ItemDTO.class);
assertThat(itemDTO).isInstanceOf(CommentDTO.class);
}
}
| apache-2.0 |
vivosys/orientdb | core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateIndex.java | 9613 | /*
* Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.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.orientechnologies.orient.core.sql;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import com.orientechnologies.orient.core.command.OCommandRequestText;
import com.orientechnologies.orient.core.db.record.ODatabaseRecord;
import com.orientechnologies.orient.core.exception.OCommandExecutionException;
import com.orientechnologies.orient.core.index.OIndex;
import com.orientechnologies.orient.core.index.OPropertyMapIndexDefinition;
import com.orientechnologies.orient.core.index.ORuntimeKeyIndexDefinition;
import com.orientechnologies.orient.core.index.OSimpleKeyIndexDefinition;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OProperty;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.metadata.security.ODatabaseSecurityResources;
import com.orientechnologies.orient.core.metadata.security.ORole;
/**
* SQL CREATE INDEX command: Create a new index against a property.
* <p/>
* <p>
* Supports following grammar: <br/>
* "CREATE" "INDEX" <indexName> ["ON" <className> "(" <propName> ("," <propName>)* ")"] <indexType>
* [<keyType> ("," <keyType>)*]
* </p>
*
* @author Luca Garulli (l.garulli--at--orientechnologies.com)
*/
@SuppressWarnings("unchecked")
public class OCommandExecutorSQLCreateIndex extends OCommandExecutorSQLAbstract {
public static final String KEYWORD_CREATE = "CREATE";
public static final String KEYWORD_INDEX = "INDEX";
public static final String KEYWORD_ON = "ON";
private String indexName;
private OClass oClass;
private String[] fields;
private OClass.INDEX_TYPE indexType;
private OType[] keyTypes;
private byte serializerKeyId;
public OCommandExecutorSQLCreateIndex parse(final OCommandRequestText iRequest) {
getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ);
init(iRequest.getText());
final StringBuilder word = new StringBuilder();
int oldPos = 0;
int pos = OSQLHelper.nextWord(text, textUpperCase, oldPos, word, true);
if (pos == -1 || !word.toString().equals(KEYWORD_CREATE))
throw new OCommandSQLParsingException("Keyword " + KEYWORD_CREATE + " not found. Use " + getSyntax(), text, oldPos);
oldPos = pos;
pos = OSQLHelper.nextWord(text, textUpperCase, oldPos, word, true);
if (pos == -1 || !word.toString().equals(KEYWORD_INDEX))
throw new OCommandSQLParsingException("Keyword " + KEYWORD_INDEX + " not found. Use " + getSyntax(), text, oldPos);
oldPos = pos;
pos = OSQLHelper.nextWord(text, textUpperCase, oldPos, word, false);
if (pos == -1)
throw new OCommandSQLParsingException("Expected index name. Use " + getSyntax(), text, oldPos);
indexName = word.toString();
final int namePos = oldPos;
oldPos = pos;
pos = OSQLHelper.nextWord(text, textUpperCase, oldPos, word, true);
if (pos == -1)
throw new OCommandSQLParsingException("Index type requested. Use " + getSyntax(), text, oldPos + 1);
if (word.toString().equals(KEYWORD_ON)) {
if (indexName.contains(".")) {
throw new OCommandSQLParsingException("Index name cannot contain '.' character. Use " + getSyntax(), text, namePos);
}
oldPos = pos;
pos = OSQLHelper.nextWord(text, textUpperCase, oldPos, word, true);
if (pos == -1)
throw new OCommandSQLParsingException("Expected class name. Use " + getSyntax(), text, oldPos);
oldPos = pos;
oClass = findClass(word.toString());
if (oClass == null)
throw new OCommandExecutionException("Class " + word + " not found");
pos = textUpperCase.indexOf(")");
if (pos == -1) {
throw new OCommandSQLParsingException("No right bracket found. Use " + getSyntax(), text, oldPos);
}
final String props = textUpperCase.substring(oldPos, pos).trim().substring(1);
List<String> propList = new ArrayList<String>();
final List<OType> typeList = new ArrayList<OType>();
for (String propToIndex : props.trim().split("\\s*,\\s*")) {
checkMapIndexSpecifier(propToIndex, text, oldPos);
final String propName = propToIndex.split("\\s+")[0];
final OProperty property = oClass.getProperty(propName);
if (property == null)
throw new IllegalArgumentException("Property '" + propToIndex + "' was not found in class '" + oClass.getName() + "'");
propList.add(propToIndex);
typeList.add(property.getType());
}
fields = new String[propList.size()];
propList.toArray(fields);
oldPos = pos + 1;
pos = OSQLHelper.nextWord(text, textUpperCase, oldPos, word, true);
if (pos == -1)
throw new OCommandSQLParsingException("Index type requested. Use " + getSyntax(), text, oldPos + 1);
keyTypes = new OType[propList.size()];
typeList.toArray(keyTypes);
} else {
if (indexName.indexOf('.') > 0) {
final String[] parts = indexName.split("\\.");
oClass = findClass(parts[0]);
if (oClass == null)
throw new OCommandExecutionException("Class " + parts[0] + " not found");
final OProperty prop = oClass.getProperty(parts[1]);
if (prop == null)
throw new IllegalArgumentException("Property '" + parts[1] + "' was not found in class '" + oClass.getName() + "'");
fields = new String[] { prop.getName() };
keyTypes = new OType[] { prop.getType() };
}
}
indexType = OClass.INDEX_TYPE.valueOf(word.toString());
if (indexType == null)
throw new OCommandSQLParsingException("Index type is null", text, oldPos);
oldPos = pos;
pos = OSQLHelper.nextWord(text, textUpperCase, oldPos, word, true);
if (pos != -1 && !word.toString().equalsIgnoreCase("NULL")) {
final String typesString = textUpperCase.substring(oldPos).trim();
if (word.toString().equalsIgnoreCase("RUNTIME")) {
oldPos = pos;
pos = OSQLHelper.nextWord(text, textUpperCase, oldPos, word, true);
serializerKeyId = Byte.parseByte(word.toString());
} else {
ArrayList<OType> keyTypeList = new ArrayList<OType>();
for (String typeName : typesString.split("\\s*,\\s*")) {
keyTypeList.add(OType.valueOf(typeName));
}
OType[] parsedKeyTypes = new OType[keyTypeList.size()];
keyTypeList.toArray(parsedKeyTypes);
if (keyTypes == null) {
keyTypes = parsedKeyTypes;
} else {
if (!Arrays.deepEquals(keyTypes, parsedKeyTypes)) {
throw new OCommandSQLParsingException("Property type list not match with real property types", text, oldPos);
}
}
}
}
return this;
}
private OClass findClass(String part) {
return getDatabase().getMetadata().getSchema().getClass(part);
}
/**
* Execute the CREATE INDEX.
*/
public Object execute(final Map<Object, Object> iArgs) {
if (indexName == null)
throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet");
final ODatabaseRecord database = getDatabase();
final OIndex<?> idx;
if (fields == null || fields.length == 0) {
if (keyTypes != null)
idx = database.getMetadata().getIndexManager()
.createIndex(indexName, indexType.toString(), new OSimpleKeyIndexDefinition(keyTypes), null, null);
else if (serializerKeyId != 0) {
idx = database.getMetadata().getIndexManager()
.createIndex(indexName, indexType.toString(), new ORuntimeKeyIndexDefinition(serializerKeyId), null, null);
} else
idx = database.getMetadata().getIndexManager().createIndex(indexName, indexType.toString(), null, null, null);
} else {
idx = oClass.createIndex(indexName, indexType, fields);
}
if (idx != null)
return idx.getSize();
return null;
}
private void checkMapIndexSpecifier(final String fieldName, final String text, final int pos) {
String[] fieldNameParts = fieldName.split("\\s+");
if (fieldNameParts.length == 1)
return;
if (fieldNameParts.length == 3) {
if ("by".equals(fieldNameParts[1].toLowerCase())) {
try {
OPropertyMapIndexDefinition.INDEX_BY.valueOf(fieldNameParts[2].toUpperCase());
} catch (IllegalArgumentException iae) {
throw new OCommandSQLParsingException("Illegal field name format, should be '<property> [by key|value]' but was '"
+ fieldName + "'", text, pos);
}
return;
}
throw new OCommandSQLParsingException("Illegal field name format, should be '<property> [by key|value]' but was '"
+ fieldName + "'", text, pos);
}
throw new OCommandSQLParsingException("Illegal field name format, should be '<property> [by key|value]' but was '" + fieldName
+ "'", text, pos);
}
@Override
public String getSyntax() {
return "CREATE INDEX <name> [ON <class-name> (prop-names)] <type> [<key-type>]";
}
}
| apache-2.0 |
octaviospain/TimecodeString | src/com/transgressoft/timecode/TimecodeInputType.java | 1825 | /*
* Copyright 2016, 2017 Octavio Calleya
*
* 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.transgressoft.timecode;
import static com.transgressoft.timecode.TimecodeException.ErrorCase.INVALID_INPUT_FORMAT;
/**
* Enumeration of different type of input formats of the value of a timecode.
*
* @author Octavio Calleya
* @version 1.0
*/
public enum TimecodeInputType {
/**
* Timecode value as hours:minutes:seconds:frames
*/
UNITS_INPUT_TYPE,
/**
* Timecode value as total number of frames
*/
FRAME_COUNT_INPUT_TYPE;
/**
* Parses the given <tt>String</tt> to a <tt>TimecodeInputType</tt> that
* matches the string format of the timecode value
*
* @param string The value of a timecode with uncertain format
*
* @return The TimecodeInputType enum
*
* @throws TimecodeException if the given <tt>String</tt> has not a valid format
*/
public static TimecodeInputType fromString(String string) throws TimecodeException {
TimecodeInputType timecodeInputType = null;
if (string.matches("\\d{2}:\\d{2}:\\d{2}[;:]\\d{2}"))
timecodeInputType = UNITS_INPUT_TYPE;
else if (string.matches("\\d+"))
timecodeInputType = FRAME_COUNT_INPUT_TYPE;
if (timecodeInputType == null)
throw new TimecodeException(INVALID_INPUT_FORMAT);
return timecodeInputType;
}
}
| apache-2.0 |
viniciusboson/buendia | third_party/openmrs-module-sync/api/src/main/java/org/openmrs/module/sync/server/RemoteServer.java | 9853 | /**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.module.sync.server;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import org.openmrs.module.sync.SyncRecord;
import org.openmrs.module.sync.SyncServerClass;
import org.openmrs.module.sync.SyncTransmissionState;
import org.openmrs.util.OpenmrsUtil;
/**
* Represents another server that we are going to sync to/from.
*/
public class RemoteServer {
private Integer serverId;
private String nickname;
private String address;
private RemoteServerType serverType;
private String username;
private String password;
private Date lastSync;
private SyncTransmissionState lastSyncState;
private Set<SyncServerClass> serverClasses;
private Set<SyncServerRecord> serverRecords;
private String uuid;
private Boolean disabled = false;
private String childUsername = null;
private static Map<Integer, Date> syncServersInProgress = new LinkedHashMap<Integer, Date>();
public Boolean getDisabled() {
return disabled;
}
public void setDisabled(Boolean disabled) {
this.disabled = disabled;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public Set<SyncServerClass> getServerClasses() {
return serverClasses;
}
public void setServerClasses(Set<SyncServerClass> serverClasses) {
this.serverClasses = serverClasses;
}
public Date getLastSync() {
return lastSync;
}
public void setLastSync(Date lastSync) {
this.lastSync = lastSync;
}
public SyncTransmissionState getLastSyncState() {
return lastSyncState;
}
public void setLastSyncState(SyncTransmissionState value) {
this.lastSyncState = value;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Boolean getIsSSL() {
return this.address.startsWith("https");
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getServerId() {
return serverId;
}
public void setServerId(Integer serverId) {
this.serverId = serverId;
}
public RemoteServerType getServerType() {
return serverType;
}
public void setServerType(RemoteServerType serverType) {
this.serverType = serverType;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Set<String> getClassesNotSent() {
Set<String> ret = new HashSet<String>();
if (this.serverClasses != null) {
for (SyncServerClass serverClass : this.serverClasses) {
if (serverClass.getSendTo() == false)
ret.add(serverClass.getSyncClass().getName());
}
}
return ret;
}
public Set<String> getClassesNotReceived() {
Set<String> ret = new HashSet<String>();
if (this.serverClasses != null) {
for (SyncServerClass serverClass : this.serverClasses) {
if (serverClass.getReceiveFrom() == false)
ret.add(serverClass.getSyncClass().getName());
}
}
return ret;
}
/**
* Find out if a given sync record should be processed (i.e. ingested) by the provided server
* based on the contained types. Note, method can be called both on parent and child; i.e on
* child it is called while deciding what to send to the parent server (in this case object
* instance of the RemoteServer is 'parent').
*
* Remarks: The naming of methods shouldReceive() and shouldSend() is from the standpoint of
* the server.
*
* @return
*/
public Boolean shouldBeSentSyncRecord(SyncRecord record) {
Boolean ret = true; //assume it is good less we find match
if (record == null)
return false;
StringBuffer recordTypesStrings = new StringBuffer();
Set<String> recordTypes = record.getContainedClassSet();
if (recordTypes == null)
return ret;
if (this.serverClasses == null)
return ret;
//build up the search string of types
for (String type : recordTypes) {
recordTypesStrings.append("<");
recordTypesStrings.append(type);
recordTypesStrings.append(">");
}
//now do the comparison, note these can have wild cards
for (SyncServerClass serverClass : this.serverClasses) {
if (serverClass.getSendTo() == false) {
String typeToTest = serverClass.getSyncClass().getName();
if (Pattern.matches(".*<" + typeToTest + ".*>*", recordTypesStrings)) {
ret = false;
break;
}
}
}
return ret;
}
/**
* Find out if given sync record should be processed (i.e. ingested) by this server based on the
* contained types.
*
* Remarks: See shouldBeSentSyncRecord() for more background on how this works.
*
* @return
*/
public Boolean shouldReceiveSyncRecordFrom(SyncRecord record) {
Boolean ret = true; //assume it is good less we find match
if (record == null)
return false;
StringBuffer recordTypesStrings = new StringBuffer();
Set<String> recordTypes = record.getContainedClassSet();
if (recordTypes == null)
return ret;
if (this.serverClasses == null)
return ret;
//build up the search string of types
for (String type : recordTypes) {
recordTypesStrings.append("<");
recordTypesStrings.append(type);
recordTypesStrings.append(">");
}
//now do the comparison, note these can be package names too thus do the .* Pattern
for (SyncServerClass serverClass : this.serverClasses) {
if (serverClass.getReceiveFrom() == false) {
String typeToExclude = serverClass.getSyncClass().getName();
if (Pattern.matches(".*<" + typeToExclude + ".*>*", recordTypesStrings)) {
ret = false;
break;
}
}
}
return ret;
}
@Override
public int hashCode() {
final int PRIME = 31;
int result = 1;
result = PRIME * result + ((address == null) ? 0 : address.hashCode());
result = PRIME * result + ((uuid == null) ? 0 : uuid.hashCode());
result = PRIME * result + ((lastSync == null) ? 0 : lastSync.hashCode());
result = PRIME * result + ((nickname == null) ? 0 : nickname.hashCode());
result = PRIME * result + ((password == null) ? 0 : password.hashCode());
result = PRIME * result + ((serverClasses == null) ? 0 : serverClasses.hashCode());
result = PRIME * result + ((serverId == null) ? 0 : serverId.hashCode());
result = PRIME * result + ((serverType == null) ? 0 : serverType.hashCode());
result = PRIME * result + ((username == null) ? 0 : username.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof RemoteServer))
return false;
final RemoteServer other = (RemoteServer) obj;
if (OpenmrsUtil.nullSafeEquals(uuid, other.uuid))
return true;
if (OpenmrsUtil.nullSafeEquals(serverId, other.serverId))
return true;
// both the uuid and id are not equal, return false
return false;
}
public String getChildUsername() {
return childUsername;
}
public void setChildUsername(String childUsername) {
this.childUsername = childUsername;
}
public Set<SyncServerRecord> getServerRecords() {
return serverRecords;
}
public void setServerRecords(Set<SyncServerRecord> serverRecords) {
this.serverRecords = serverRecords;
}
public Boolean getSyncInProgress() {
synchronized (syncServersInProgress) {
if (getServerId() == null)
return false;
else
return syncServersInProgress.get(getServerId()) != null;
}
}
/**
* If given true, marks this current server as 'in progress' (static variable not to be saved in the database)
*
* @param syncInProgress
*/
public synchronized void setSyncInProgress(Boolean syncInProgress) {
synchronized (syncServersInProgress) {
if (syncInProgress) {
syncServersInProgress.put(getServerId(), new Date());
}
else {
syncServersInProgress.remove(getServerId());
}
}
}
private static DecimalFormat df = new DecimalFormat("0.00");
/**
* @return the number of minutes since the sync was started. If this is new server or sync is
* not in progress the empty string is returned
*/
public String getSyncInProgressMinutes() {
synchronized (syncServersInProgress) {
if (getServerId() == null || syncServersInProgress.get(getServerId()) == null)
return "";
Long difference = System.currentTimeMillis() - syncServersInProgress.get(getServerId()).getTime();
return df.format((float)(difference) / 1000 / 60);
}
}
@Override
public String toString() {
return "RemoteServer(" + getServerId() + "): " + getNickname();
}
}
| apache-2.0 |
supunucsc/java-sdk | tradeoff-analytics/src/main/java/com/ibm/watson/developer_cloud/tradeoff_analytics/v1/TradeoffAnalytics.java | 6634 | /**
* Copyright 2017 IBM Corp. 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.ibm.watson.developer_cloud.tradeoff_analytics.v1;
import java.util.ArrayList;
import java.util.List;
import com.ibm.watson.developer_cloud.http.HttpMediaType;
import com.ibm.watson.developer_cloud.http.RequestBuilder;
import com.ibm.watson.developer_cloud.http.ServiceCall;
import com.ibm.watson.developer_cloud.service.WatsonService;
import com.ibm.watson.developer_cloud.tradeoff_analytics.v1.model.Dilemma;
import com.ibm.watson.developer_cloud.tradeoff_analytics.v1.model.Problem;
import com.ibm.watson.developer_cloud.tradeoff_analytics.v1.model.Resolution;
import com.ibm.watson.developer_cloud.util.GsonSingleton;
import com.ibm.watson.developer_cloud.util.ResponseConverterUtils;
import com.ibm.watson.developer_cloud.util.Validator;
/**
* The IBM Watson Tradeoff Analytics service applies decision analytics technology, enabling users to avoid choice
* overload when making complex decisions involving multiple, conflicting goals.
*
* @version v1
* @see <a href= "http://www.ibm.com/watson/developercloud/tradeoff-analytics.html"> Tradeoff Analytics</a>
*/
public class TradeoffAnalytics extends WatsonService {
private static final String GENERATE_VISUALIZATION = "generate_visualization";
private static final String FIND_PREFERABLE_OPTIONS = "find_preferable_options";
private static final String PATH_DILEMMAS = "/v1/dilemmas";
private static final String SERVICE_NAME = "tradeoff_analytics";
private static final String URL = "https://gateway.watsonplatform.net/tradeoff-analytics/api";
/**
* Instantiates a new tradeoff analytics.
*/
public TradeoffAnalytics() {
super(SERVICE_NAME);
if ((getEndPoint() == null) || getEndPoint().isEmpty()) {
setEndPoint(URL);
}
}
/**
* Instantiates a new tradeoff analytics service by username and password.
*
* @param username the username
* @param password the password
*/
public TradeoffAnalytics(String username, String password) {
this();
setUsernameAndPassword(username, password);
}
/**
* Returns a dilemma that contains the {@link Problem} and a {@link Resolution}. The {@link Problem} contains a set of
* options and objectives. The {@link Resolution} contains a set of optimal options, their analytical characteristics,
* and by default their representation on a 2D space. <br>
* <br>
* Here is an example of how to call the Tradeoff Analytics service with a Problem:
*
* <pre>
* TradeoffAnalytics service = new TradeoffAnalytics();
* service.setUsernameAndPassword("USERNAME", "PASSWORD");
* Problem problem = new Problem(); // create the options and objectives here
* Dilemma dilemma = service.dilemmas(problem, false);
* </pre>
*
* @param problem the decision problem
* @return the dilemma
*/
public ServiceCall<Dilemma> dilemmas(final Problem problem) {
return dilemmas(problem, null, null);
}
/**
* Returns a dilemma that contains the {@link Problem} and a {@link Resolution}. The {@link Problem} contains a set of
* options and objectives. The {@link Resolution} contains a set of optimal options, their analytical characteristics,
* and by default their representation on a 2D space. <br>
* <br>
* Here is an example of how to call the Tradeoff Analytics service with a Problem:
*
* <pre>
* TradeoffAnalytics service = new TradeoffAnalytics();
* service.setUsernameAndPassword("USERNAME", "PASSWORD");
* Problem problem = new Problem(); // create the options and objectives here
* Dilemma dilemma = service.dilemmas(problem, false);
* </pre>
*
* @param problem the decision problem
* @param generateVisualization if true the Dilemma contains information to generate visualization
* @return the decision problem
*/
public ServiceCall<Dilemma> dilemmas(final Problem problem, final Boolean generateVisualization) {
return dilemmas(problem, generateVisualization, null);
}
/**
* Returns a dilemma that contains the {@link Problem} and a {@link Resolution}. The {@link Problem} contains a set of
* options and objectives. The {@link Resolution} contains a set of optimal options, their analytical characteristics,
* and by default their representation on a 2D space. <br>
* <br>
* Here is an example of how to call the Tradeoff Analytics service with a Problem:
*
* <pre>
* TradeoffAnalytics service = new TradeoffAnalytics();
* service.setUsernameAndPassword("USERNAME", "PASSWORD");
* Problem problem = new Problem(); // create the options and objectives here
* Dilemma dilemma = service.dilemmas(problem, false, true);
* </pre>
*
* @param problem the decision problem
* @param generateVisualization if true the Dilemma contains information to generate visualization
* @param findPreferableOptions if true the Dilemma includes a refined subset of best candidate options
* that will most likely satisfy the greatest number of users.
* @return the decision problem
*/
public ServiceCall<Dilemma> dilemmas(
final Problem problem,
final Boolean generateVisualization,
final Boolean findPreferableOptions) {
Validator.notNull(problem, "problem was not specified");
final String contentJson = GsonSingleton.getGsonWithoutPrettyPrinting().toJson(problem);
final RequestBuilder requestBuilder =
RequestBuilder.post(PATH_DILEMMAS).bodyContent(contentJson, HttpMediaType.APPLICATION_JSON);
List<String> queryParams = new ArrayList<String>();
if (generateVisualization != null) {
queryParams.add(GENERATE_VISUALIZATION);
queryParams.add(generateVisualization.toString());
}
if (findPreferableOptions != null) {
queryParams.add(FIND_PREFERABLE_OPTIONS);
queryParams.add(findPreferableOptions.toString());
}
requestBuilder.query(queryParams.toArray());
return createServiceCall(requestBuilder.build(), ResponseConverterUtils.getObject(Dilemma.class));
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-config/src/main/java/com/amazonaws/services/config/model/transform/DescribeDeliveryChannelsRequestMarshaller.java | 2161 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.config.model.transform;
import java.util.List;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.config.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* DescribeDeliveryChannelsRequestMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DescribeDeliveryChannelsRequestMarshaller {
private static final MarshallingInfo<List> DELIVERYCHANNELNAMES_BINDING = MarshallingInfo.builder(MarshallingType.LIST)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("DeliveryChannelNames").build();
private static final DescribeDeliveryChannelsRequestMarshaller instance = new DescribeDeliveryChannelsRequestMarshaller();
public static DescribeDeliveryChannelsRequestMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(DescribeDeliveryChannelsRequest describeDeliveryChannelsRequest, ProtocolMarshaller protocolMarshaller) {
if (describeDeliveryChannelsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(describeDeliveryChannelsRequest.getDeliveryChannelNames(), DELIVERYCHANNELNAMES_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-cognitosync/src/test/java/com/amazonaws/services/cognitosync/smoketests/AmazonCognitoSyncModuleInjector.java | 1680 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.cognitosync.smoketests;
import javax.annotation.Generated;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Stage;
import cucumber.api.guice.CucumberModules;
import cucumber.runtime.java.guice.InjectorSource;
import com.amazonaws.AmazonWebServiceClient;
import com.amazonaws.services.cognitosync.AmazonCognitoSyncClient;
/**
* Injector that binds the AmazonWebServiceClient interface to the
* com.amazonaws.services.cognitosync.AmazonCognitoSyncClient
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AmazonCognitoSyncModuleInjector implements InjectorSource {
@Override
public Injector getInjector() {
return Guice.createInjector(Stage.PRODUCTION, CucumberModules.SCENARIO, new AmazonCognitoSyncModule());
}
static class AmazonCognitoSyncModule extends AbstractModule {
@Override
protected void configure() {
bind(AmazonWebServiceClient.class).to(AmazonCognitoSyncClient.class);
}
}
}
| apache-2.0 |
brave-warrior/WearTimer | wear/src/main/java/com/cologne/hackaton/wearstopwatch/event/RequestStatusEvent.java | 128 | package com.cologne.hackaton.wearstopwatch.event;
/**
* Created by admin on 3/5/2015.
*/
public class RequestStatusEvent {
}
| apache-2.0 |
wmedvede/drools | drools-compiler/src/test/java/org/drools/compiler/xpath/Child.java | 573 | package org.drools.compiler.xpath;
import org.drools.core.phreak.ReactiveList;
import java.util.List;
public class Child extends Person {
private String mother;
private final List<Toy> toys = new ReactiveList<Toy>();
public Child(String name, int age) {
super(name, age);
}
public List<Toy> getToys() {
return toys;
}
public void addToy(Toy toy) {
toys.add(toy);
}
public String getMother() {
return mother;
}
public void setMother(String mother) {
this.mother = mother;
}
}
| apache-2.0 |
2BAB/WeatherX | app/src/main/java/net/bingyan/weatherx/network/base/ThreadManager.java | 2553 | package net.bingyan.weatherx.network.base;
import android.os.Handler;
import android.util.Log;
import net.bingyan.weatherx.database.WeatherDao;
import net.bingyan.weatherx.module.main.MainActivity;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Created by 2bab on 15/2/15.
*
* 网络线程池管理
*/
public class ThreadManager {
private static ThreadManager threadManager = new ThreadManager();
private MyThreadPool pool;
private ThreadManager() {
final int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();
final int KEEP_ALIVE_TIME = 1;
final TimeUnit KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS;
BlockingQueue<Runnable> queue = new PriorityBlockingQueue<>();
WeatherDao dao = new WeatherDao();
//在不超过两倍核心数的情况下,按照(当前城市数量*每个城市的任务数量)开线程
//否则遵循 “CPU负载大的操作开 N + 1 数量的线程”,“IO密集操作开 2N 数量的线程”
int poolSize = Math.min(dao.loadCitys().size() * 2, NUMBER_OF_CORES * 2);
pool = new MyThreadPool(
poolSize, //初始化线程池大小
poolSize, //线程池最大数量
KEEP_ALIVE_TIME, //空闲等待时间
KEEP_ALIVE_TIME_UNIT, //时间单位
queue); //队列实现
}
public static ThreadManager getInstance() {
return threadManager;
}
public void add(Runnable runnable) {
pool.execute(runnable);
}
/**
* 线程池的自定义,添加结束所有任务后的消息通知
*/
class MyThreadPool extends ThreadPoolExecutor {
public MyThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
if (getActiveCount() == 1) {
Handler handler = MainActivity.getHandler();
Log.e("afterExecute", "on");
handler.sendEmptyMessage(MainActivity.TASK_COMPLETE);
}
Log.e("ThreadPool Task Count", getActiveCount() + "");
}
}
}
| 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-backend-common/src/main/java/org/kie/workbench/common/stunner/core/backend/definition/adapter/ReflectionAdapterUtils.java | 7912 | /*
* 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.backend.definition.adapter;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.kie.workbench.common.stunner.core.definition.adapter.binding.BindableAdapterUtils;
public class ReflectionAdapterUtils {
@SuppressWarnings("unchecked")
public static <T, A extends Annotation, V> V getAnnotatedFieldValue(final T object,
final Class<A> annotationType) throws IllegalAccessException {
Class<?> c = object.getClass();
while (!c.getName().equals(Object.class.getName())) {
V result = getAnnotatedFieldValue(object,
c,
annotationType);
if (null != result) {
return result;
}
c = c.getSuperclass();
}
return null;
}
public static <T, V> Set<V> getFieldValues(final T object,
final Set<String> fieldNames) throws IllegalAccessException {
Set<V> result = new LinkedHashSet<V>();
if (null != fieldNames) {
for (String fieldName : fieldNames) {
Class<?> c = object.getClass();
while (!c.getName().equals(Object.class.getName())) {
V result1 = getFieldValue(object,
c,
fieldName);
if (null != result1) {
result.add(result1);
}
c = c.getSuperclass();
}
}
}
return result;
}
public static <T, V> V getFieldValue(final T object,
final String fieldName) throws IllegalAccessException {
Class<?> c = object.getClass();
while (!c.getName().equals(Object.class.getName())) {
V result = getFieldValue(object,
c,
fieldName);
if (null != result) {
return result;
}
c = c.getSuperclass();
}
return null;
}
@SuppressWarnings("unchecked")
public static <T, A extends Annotation, V> V getAnnotatedFieldValue(final T object,
final Class<?> sourceType,
final Class<A> annotationType) throws IllegalAccessException {
V result = null;
Field[] fields = sourceType.getDeclaredFields();
if (null != fields) {
for (Field field : fields) {
A annotation = field.getAnnotation(annotationType);
if (null != annotation) {
field.setAccessible(true);
result = (V) field.get(object);
break;
}
}
}
return result;
}
@SuppressWarnings("unchecked")
public static <T, V> V getFieldValue(final T object,
final Class<?> sourceType,
final String fieldName) throws IllegalAccessException {
V result = null;
Field[] fields = sourceType.getDeclaredFields();
if (null != fields) {
for (Field field : fields) {
if (field.getName().equals(fieldName)) {
field.setAccessible(true);
result = (V) field.get(object);
break;
}
}
}
return result;
}
public static <T> Field getField(final T object,
final String fieldName) throws SecurityException {
Class<?> c = object.getClass();
while (!c.getName().equals(Object.class.getName())) {
Field result = getField(c,
fieldName);
if (null != result) {
return result;
}
c = c.getSuperclass();
}
return null;
}
public static Field getField(final Class<?> sourceType,
final String fieldName) throws SecurityException {
Field[] fields = sourceType.getDeclaredFields();
if (null != fields) {
for (Field field : fields) {
if (field.getName().equals(fieldName)) {
return field;
}
}
}
return null;
}
public static List<Field> getFields(final Class<?> sourceType) throws SecurityException {
return Stream.of(sourceType.getDeclaredFields()).collect(Collectors.toList());
}
public static <T extends Annotation> T getClassAnnotation(final Class<?> type,
final Class<T> annotationType) {
Class<?> c = type;
while (!c.getName().equals(Object.class.getName())) {
T result = c.getAnnotation(annotationType);
if (null != result) {
return result;
}
c = c.getSuperclass();
}
return null;
}
public static <T extends Annotation> Collection<Field> getFieldAnnotations(final Class<?> type,
final Class<T> annotationType) {
if (null != type && null != annotationType) {
Collection<Field> result = new LinkedList<>();
Class<?> c = type;
while (!c.getName().equals(Object.class.getName())) {
Collection<Field> fields = _getFieldAnnotations(c,
annotationType);
if (null != fields && !fields.isEmpty()) {
result.addAll(fields);
}
c = c.getSuperclass();
}
return result;
}
return null;
}
private static <T extends Annotation> Collection<Field> _getFieldAnnotations(final Class<?> type,
final Class<T> annotationType) {
Field[] fields = type.getDeclaredFields();
if (null != fields) {
Collection<Field> result = new LinkedList<>();
for (Field field : fields) {
T annotation = field.getAnnotation(annotationType);
if (null != annotation) {
result.add(field);
}
}
return result;
}
return null;
}
public static String getDefinitionId(final Class<?> type) {
return BindableAdapterUtils.getDefinitionId(type);
}
public static String getPropertyId(final Object pojo) {
return BindableAdapterUtils.getPropertyId(pojo.getClass());
}
}
| apache-2.0 |
blernermhc/Bridge4Blind | src/model/GameState.java | 90 | package model;
public enum GameState {
DEALING, FIRSTCARD, SCANNING_DUMMY, PLAYING
} | apache-2.0 |
raavr/extradowcipy | app/src/main/java/pl/rr/extradowcipy/ui/categories/CategoriesRecyclerViewHolder.java | 819 | package pl.rr.extradowcipy.ui.categories;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import com.devspark.robototextview.widget.RobotoTextView;
import com.etsy.android.grid.util.DynamicHeightImageView;
import butterknife.ButterKnife;
import butterknife.InjectView;
import pl.rr.extradowcipy.R;
/**
* Created by Rafal on 2015-04-21.
*/
public class CategoriesRecyclerViewHolder extends RecyclerView.ViewHolder {
@InjectView(R.id.category_title)
RobotoTextView category_title;
@InjectView(R.id.imgView)
DynamicHeightImageView imageView;
@InjectView(R.id.expand_arrow)
ImageView expandImgView;
public CategoriesRecyclerViewHolder(View itemView) {
super(itemView);
ButterKnife.inject(this, itemView);
}
}
| apache-2.0 |
masonmei/apm-agent | profiler/src/main/java/com/baidu/oped/apm/profiler/modifier/db/oracle/parser/KeyValue.java | 2768 | /*
* Copyright 2014 NAVER Corp.
*
* 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.baidu.oped.apm.profiler.modifier.db.oracle.parser;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author emeroad
*/
public class KeyValue {
public String key;
public String value;
public List<KeyValue> keyValueList;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public List<KeyValue> getKeyValueList() {
if (keyValueList == null) {
return Collections.emptyList();
}
return keyValueList;
}
public void addKeyValueList(KeyValue keyValue) {
if (keyValueList == null) {
keyValueList = new ArrayList<KeyValue>();
}
this.keyValueList.add(keyValue);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("{key='").append(key).append('\'');
if (value != null) {
sb.append(", value='").append(value).append('\'');
}
if (keyValueList != null) {
sb.append(", keyValueList=").append(keyValueList);
}
sb.append('}');
return sb.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
KeyValue keyValue = (KeyValue) o;
if (key != null ? !key.equals(keyValue.key) : keyValue.key != null) return false;
if (keyValueList != null ? !keyValueList.equals(keyValue.keyValueList) : keyValue.keyValueList != null) return false;
if (value != null ? !value.equals(keyValue.value) : keyValue.value != null) return false;
return true;
}
@Override
public int hashCode() {
int result = key != null ? key.hashCode() : 0;
result = 31 * result + (value != null ? value.hashCode() : 0);
result = 31 * result + (keyValueList != null ? keyValueList.hashCode() : 0);
return result;
}
}
| apache-2.0 |
planoAccess/clonedONOS | protocols/bgp/ctl/src/main/java/org/onosproject/bgp/controller/impl/BgpConfig.java | 10352 | /*
* Copyright 2015 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.bgp.controller.impl;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import org.onlab.packet.Ip4Address;
import org.onlab.packet.IpAddress;
import org.onosproject.bgp.controller.BgpCfg;
import org.onosproject.bgp.controller.BgpConnectPeer;
import org.onosproject.bgp.controller.BgpController;
import org.onosproject.bgp.controller.BgpId;
import org.onosproject.bgp.controller.BgpPeer;
import org.onosproject.bgp.controller.BgpPeerCfg;
import org.onosproject.bgp.controller.impl.BgpControllerImpl.BgpPeerManagerImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Provides BGP configuration of this BGP speaker.
*/
public class BgpConfig implements BgpCfg {
protected static final Logger log = LoggerFactory.getLogger(BgpConfig.class);
private static final short DEFAULT_HOLD_TIMER = 120;
private static final short DEFAULT_CONN_RETRY_TIME = 120;
private static final short DEFAULT_CONN_RETRY_COUNT = 5;
private State state = State.INIT;
private int localAs;
private int maxSession;
private boolean lsCapability;
private short holdTime;
private boolean largeAs = false;
private int maxConnRetryTime;
private int maxConnRetryCount;
private Ip4Address routerId = null;
private TreeMap<String, BgpPeerCfg> bgpPeerTree = new TreeMap<>();
private BgpConnectPeer connectPeer;
private BgpPeerManagerImpl peerManager;
private BgpController bgpController;
/*
* Constructor to initialize the values.
*/
public BgpConfig(BgpController bgpController) {
this.bgpController = bgpController;
this.peerManager = (BgpPeerManagerImpl) bgpController.peerManager();
this.holdTime = DEFAULT_HOLD_TIMER;
this.maxConnRetryTime = DEFAULT_CONN_RETRY_TIME;
this.maxConnRetryCount = DEFAULT_CONN_RETRY_COUNT;
this.lsCapability = true;
}
@Override
public State getState() {
return state;
}
@Override
public void setState(State state) {
this.state = state;
}
@Override
public int getAsNumber() {
return this.localAs;
}
@Override
public void setAsNumber(int localAs) {
State localState = getState();
this.localAs = localAs;
/* Set configuration state */
if (localState == State.IP_CONFIGURED) {
setState(State.IP_AS_CONFIGURED);
} else {
setState(State.AS_CONFIGURED);
}
}
@Override
public int getMaxSession() {
return this.maxSession;
}
@Override
public void setMaxSession(int maxSession) {
this.maxSession = maxSession;
}
@Override
public boolean getLsCapability() {
return this.lsCapability;
}
@Override
public void setLsCapability(boolean lsCapability) {
this.lsCapability = lsCapability;
}
@Override
public String getRouterId() {
if (this.routerId != null) {
return this.routerId.toString();
} else {
return null;
}
}
@Override
public void setRouterId(String routerId) {
State localState = getState();
this.routerId = Ip4Address.valueOf(routerId);
/* Set configuration state */
if (localState == State.AS_CONFIGURED) {
setState(State.IP_AS_CONFIGURED);
} else {
setState(State.IP_CONFIGURED);
}
}
@Override
public boolean addPeer(String routerid, int remoteAs) {
return addPeer(routerid, remoteAs, DEFAULT_HOLD_TIMER);
}
@Override
public boolean addPeer(String routerid, short holdTime) {
return addPeer(routerid, this.getAsNumber(), holdTime);
}
@Override
public boolean addPeer(String routerid, int remoteAs, short holdTime) {
BgpPeerConfig lspeer = new BgpPeerConfig();
if (this.bgpPeerTree.get(routerid) == null) {
lspeer.setPeerRouterId(routerid);
lspeer.setAsNumber(remoteAs);
lspeer.setHoldtime(holdTime);
lspeer.setState(BgpPeerCfg.State.IDLE);
lspeer.setSelfInnitConnection(false);
if (this.getAsNumber() == remoteAs) {
lspeer.setIsIBgp(true);
} else {
lspeer.setIsIBgp(false);
}
this.bgpPeerTree.put(routerid, lspeer);
log.debug("added successfully");
return true;
} else {
log.debug("already exists");
return false;
}
}
@Override
public boolean connectPeer(String routerid) {
BgpPeerCfg lspeer = this.bgpPeerTree.get(routerid);
if (lspeer != null) {
lspeer.setSelfInnitConnection(true);
if (lspeer.connectPeer() == null) {
connectPeer = new BgpConnectPeerImpl(bgpController, routerid, Controller.getBgpPortNum());
lspeer.setConnectPeer(connectPeer);
connectPeer.connectPeer();
}
return true;
}
return false;
}
@Override
public boolean removePeer(String routerid) {
BgpPeerCfg lspeer = this.bgpPeerTree.get(routerid);
if (lspeer != null) {
disconnectPeer(routerid);
lspeer.setSelfInnitConnection(false);
lspeer = this.bgpPeerTree.remove(routerid);
log.debug("Deleted : " + routerid + " successfully");
return true;
} else {
log.debug("Did not find : " + routerid);
return false;
}
}
@Override
public boolean disconnectPeer(String routerid) {
BgpPeerCfg lspeer = this.bgpPeerTree.get(routerid);
if (lspeer != null) {
BgpPeer disconnPeer = peerManager.getPeer(BgpId.bgpId(IpAddress.valueOf(routerid)));
if (disconnPeer != null) {
// TODO: send notification peer deconfigured
disconnPeer.disconnectPeer();
}
lspeer.connectPeer().disconnectPeer();
lspeer.setState(BgpPeerCfg.State.IDLE);
lspeer.setSelfInnitConnection(false);
log.debug("Disconnected : " + routerid + " successfully");
return true;
} else {
log.debug("Did not find : " + routerid);
return false;
}
}
@Override
public void setPeerConnState(String routerid, BgpPeerCfg.State state) {
BgpPeerCfg lspeer = this.bgpPeerTree.get(routerid);
if (lspeer != null) {
lspeer.setState(state);
log.debug("Peer : " + routerid + " is not available");
return;
} else {
log.debug("Did not find : " + routerid);
return;
}
}
@Override
public BgpPeerCfg.State getPeerConnState(String routerid) {
BgpPeerCfg lspeer = this.bgpPeerTree.get(routerid);
if (lspeer != null) {
return lspeer.getState();
} else {
return BgpPeerCfg.State.INVALID; //No instance
}
}
@Override
public boolean isPeerConnectable(String routerid) {
BgpPeerCfg lspeer = this.bgpPeerTree.get(routerid);
if ((lspeer != null) && lspeer.getState().equals(BgpPeerCfg.State.IDLE)) {
return true;
}
return false;
}
@Override
public TreeMap<String, BgpPeerCfg> getPeerTree() {
return this.bgpPeerTree;
}
@Override
public TreeMap<String, BgpPeerCfg> displayPeers() {
if (this.bgpPeerTree.isEmpty()) {
log.debug("There are no BGP peers");
} else {
Set<Entry<String, BgpPeerCfg>> set = this.bgpPeerTree.entrySet();
Iterator<Entry<String, BgpPeerCfg>> list = set.iterator();
BgpPeerCfg lspeer;
while (list.hasNext()) {
Entry<String, BgpPeerCfg> me = list.next();
lspeer = me.getValue();
log.debug("Peer neighbor IP :" + me.getKey());
log.debug(", AS Number : " + lspeer.getAsNumber());
log.debug(", Hold Timer : " + lspeer.getHoldtime());
log.debug(", Is iBGP : " + lspeer.getIsIBgp());
}
}
return null;
}
@Override
public BgpPeerCfg displayPeers(String routerid) {
if (this.bgpPeerTree.isEmpty()) {
log.debug("There are no Bgp peers");
} else {
return this.bgpPeerTree.get(routerid);
}
return null;
}
@Override
public void setHoldTime(short holdTime) {
this.holdTime = holdTime;
}
@Override
public short getHoldTime() {
return this.holdTime;
}
@Override
public boolean getLargeASCapability() {
return this.largeAs;
}
@Override
public void setLargeASCapability(boolean largeAs) {
this.largeAs = largeAs;
}
@Override
public boolean isPeerConfigured(String routerid) {
BgpPeerCfg lspeer = this.bgpPeerTree.get(routerid);
return (lspeer != null) ? true : false;
}
@Override
public boolean isPeerConnected(String routerid) {
// TODO: is peer connected
return true;
}
@Override
public int getMaxConnRetryCount() {
return this.maxConnRetryCount;
}
@Override
public void setMaxConnRetryCout(int retryCount) {
this.maxConnRetryCount = retryCount;
}
@Override
public int getMaxConnRetryTime() {
return this.maxConnRetryTime;
}
@Override
public void setMaxConnRetryTime(int retryTime) {
this.maxConnRetryTime = retryTime;
}
}
| apache-2.0 |
christianvalver/elena | src/main/java/ec/com/vipsoft/sri/factura/_v1_1_0/SignatureMethodType.java | 3550 | //
// Este archivo ha sido generado por la arquitectura JavaTM para la implantación de la referencia de enlace (JAXB) XML v2.2.8-b130911.1802
// Visite <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Todas las modificaciones realizadas en este archivo se perderán si se vuelve a compilar el esquema de origen.
// Generado el: 2015.02.17 a las 07:13:10 PM ECT
//
package ec.com.vipsoft.sri.factura._v1_1_0;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlMixed;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Clase Java para SignatureMethodType complex type.
*
* <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase.
*
* <pre>
* <complexType name="SignatureMethodType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="HMACOutputLength" type="{http://www.w3.org/2000/09/xmldsig#}HMACOutputLengthType" minOccurs="0"/>
* <any namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* <attribute name="Algorithm" use="required" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SignatureMethodType", propOrder = {
"content"
})
public class SignatureMethodType {
@XmlElementRef(name = "HMACOutputLength", namespace = "http://www.w3.org/2000/09/xmldsig#", type = JAXBElement.class, required = false)
@XmlMixed
@XmlAnyElement(lax = true)
protected List<Object> content;
@XmlAttribute(name = "Algorithm", required = true)
@XmlSchemaType(name = "anyURI")
protected String algorithm;
/**
* Gets the value of the content property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the content property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getContent().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
* {@link JAXBElement }{@code <}{@link BigInteger }{@code >}
* {@link Object }
*
*
*/
public List<Object> getContent() {
if (content == null) {
content = new ArrayList<Object>();
}
return this.content;
}
/**
* Obtiene el valor de la propiedad algorithm.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAlgorithm() {
return algorithm;
}
/**
* Define el valor de la propiedad algorithm.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAlgorithm(String value) {
this.algorithm = value;
}
}
| apache-2.0 |
UniversityOfWuerzburg-ChairCompSciVI/ueps | src/main/java/de/uniwue/info6/database/map/Scenario.java | 6944 | package de.uniwue.info6.database.map;
/*
* #%L
* ************************************************************************
* ORGANIZATION : Institute of Computer Science, University of Wuerzburg
* PROJECT : UEPS - Uebungs-Programm fuer SQL
* FILENAME : Scenario.java
* ************************************************************************
* %%
* Copyright (C) 2014 - 2015 Institute of Computer Science, University of Wuerzburg
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
// Generated Oct 30, 2013 2:01:27 PM by Hibernate Tools 4.0.0
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import de.uniwue.info6.misc.StringTools;
/**
* Scenario generated by hbm2java
*/
@XmlRootElement
public class Scenario implements java.io.Serializable {
// ******************************************************************
// custom (not generated methods)
// ******************************************************************
@Override
public int hashCode() {
return new HashCodeBuilder(17, 31).append(id).toHashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Scenario)) {
return false;
}
Scenario other = (Scenario) obj;
return new EqualsBuilder().append(id, other.getId()).isEquals();
}
// ******************************************************************
// generated methods of hibernate
// ******************************************************************
private Integer id;
private Scenario scenario;
private String name;
private Date lastModified;
private Date startTime;
private Date endTime;
private String description;
private String createScriptPath;
private String imagePath;
private String dbHost;
private String dbUser;
private String dbPass;
private String dbPort;
private String dbName;
private Set userRights = new HashSet(0);
private Set exerciseGroups = new HashSet(0);
private Set scenarios = new HashSet(0);
public Scenario() {
}
public Scenario(String name, Date lastModified, Date startTime, Date endTime, String description,
String createScriptPath, String imagePath, String dbHost, String dbUser, String dbPass, String dbPort,
String dbName) {
this.name = name;
this.lastModified = lastModified;
this.startTime = startTime;
this.endTime = endTime;
this.description = description;
this.createScriptPath = createScriptPath;
this.imagePath = imagePath;
this.dbHost = dbHost;
this.dbUser = dbUser;
this.dbPass = dbPass;
this.dbPort = dbPort;
this.dbName = dbName;
}
public Scenario(Scenario scenario, String name, Date lastModified, Date startTime, Date endTime,
String description, String createScriptPath, String imagePath, String dbHost, String dbUser, String dbPass,
String dbPort, String dbName, Set userRights, Set exerciseGroups, Set scenarios) {
this.scenario = scenario;
this.name = name;
this.lastModified = lastModified;
this.startTime = startTime;
this.endTime = endTime;
this.description = description;
this.createScriptPath = createScriptPath;
this.imagePath = imagePath;
this.dbHost = dbHost;
this.dbUser = dbUser;
this.dbPass = dbPass;
this.dbPort = dbPort;
this.dbName = dbName;
this.userRights = userRights;
this.exerciseGroups = exerciseGroups;
this.scenarios = scenarios;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public Scenario getScenario() {
return this.scenario;
}
@XmlTransient
public void setScenario(Scenario scenario) {
this.scenario = scenario;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Date getLastModified() {
return this.lastModified;
}
public void setLastModified(Date lastModified) {
this.lastModified = lastModified;
}
public Date getStartTime() {
return this.startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return this.endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = StringTools.stripHtmlTagsForScenario(description);
}
public String getCreateScriptPath() {
return this.createScriptPath;
}
public void setCreateScriptPath(String createScriptPath) {
this.createScriptPath = createScriptPath;
}
public String getImagePath() {
return this.imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public String getDbHost() {
return this.dbHost;
}
public void setDbHost(String dbHost) {
this.dbHost = dbHost;
}
public String getDbUser() {
return this.dbUser;
}
public void setDbUser(String dbUser) {
this.dbUser = dbUser;
}
public String getDbPass() {
return this.dbPass;
}
public void setDbPass(String dbPass) {
this.dbPass = dbPass;
}
public String getDbPort() {
return this.dbPort;
}
public void setDbPort(String dbPort) {
this.dbPort = dbPort;
}
public String getDbName() {
return this.dbName;
}
public void setDbName(String dbName) {
this.dbName = dbName;
}
public Set getUserRights() {
return this.userRights;
}
@XmlTransient
public void setUserRights(Set userRights) {
this.userRights = userRights;
}
public Set getExerciseGroups() {
return this.exerciseGroups;
}
@XmlElement(name = "exerciseGroup", type = ExerciseGroup.class)
public void setExerciseGroups(Set exerciseGroups) {
this.exerciseGroups = exerciseGroups;
}
public Set getScenarios() {
return this.scenarios;
}
@XmlTransient
public void setScenarios(Set scenarios) {
this.scenarios = scenarios;
}
}
| apache-2.0 |
j3kstrum/CodeCarnage | src/test/java/common/MainTest.java | 748 | package common;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Tests the Main class and the main method.
*
* NOTE - We cannot spawn multiple JavaFX launch threads.
* Therefore, we call this test once to ensure that calling main doesn't break everything.
* To test all possible string argument lists, we'll have to do that manually
* (or, adopt a different testing framework).
*
* @author jacob.ekstrum
*/
public class MainTest {
/**
* Test main with some default arguments that should definitely not break anything (but may or may not be valid).
*/
@Test
public void mainTestSomeArgs() throws Exception {
common.Main.main(new String[] {"These", "Should", "Be", "Valid", "Args!"});
}
} | apache-2.0 |
Netflix/conductor | core/src/main/java/com/netflix/conductor/core/utils/QueueUtils.java | 4117 | /*
* Copyright 2022 Netflix, Inc.
* <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.netflix.conductor.core.utils;
import org.apache.commons.lang3.StringUtils;
import com.netflix.conductor.common.metadata.tasks.Task;
import com.netflix.conductor.model.TaskModel;
public class QueueUtils {
public static final String DOMAIN_SEPARATOR = ":";
private static final String ISOLATION_SEPARATOR = "-";
private static final String EXECUTION_NAME_SPACE_SEPARATOR = "@";
public static String getQueueName(TaskModel taskModel) {
return getQueueName(
taskModel.getTaskType(),
taskModel.getDomain(),
taskModel.getIsolationGroupId(),
taskModel.getExecutionNameSpace());
}
public static String getQueueName(Task task) {
return getQueueName(
task.getTaskType(),
task.getDomain(),
task.getIsolationGroupId(),
task.getExecutionNameSpace());
}
/**
* @param taskType
* @param domain
* @param isolationGroup
* @param executionNameSpace
* @return //domain:taskType@eexecutionNameSpace-isolationGroup
*/
public static String getQueueName(
String taskType, String domain, String isolationGroup, String executionNameSpace) {
String queueName;
if (domain == null) {
queueName = taskType;
} else {
queueName = domain + DOMAIN_SEPARATOR + taskType;
}
if (executionNameSpace != null) {
queueName = queueName + EXECUTION_NAME_SPACE_SEPARATOR + executionNameSpace;
}
if (isolationGroup != null) {
queueName = queueName + ISOLATION_SEPARATOR + isolationGroup;
}
return queueName;
}
public static String getQueueNameWithoutDomain(String queueName) {
return queueName.substring(queueName.indexOf(DOMAIN_SEPARATOR) + 1);
}
public static String getExecutionNameSpace(String queueName) {
if (StringUtils.contains(queueName, ISOLATION_SEPARATOR)
&& StringUtils.contains(queueName, EXECUTION_NAME_SPACE_SEPARATOR)) {
return StringUtils.substringBetween(
queueName, EXECUTION_NAME_SPACE_SEPARATOR, ISOLATION_SEPARATOR);
} else if (StringUtils.contains(queueName, EXECUTION_NAME_SPACE_SEPARATOR)) {
return StringUtils.substringAfter(queueName, EXECUTION_NAME_SPACE_SEPARATOR);
} else {
return StringUtils.EMPTY;
}
}
public static boolean isIsolatedQueue(String queue) {
return StringUtils.isNotBlank(getIsolationGroup(queue));
}
private static String getIsolationGroup(String queue) {
return StringUtils.substringAfter(queue, QueueUtils.ISOLATION_SEPARATOR);
}
public static String getTaskType(String queue) {
if (StringUtils.isBlank(queue)) {
return StringUtils.EMPTY;
}
int domainSeperatorIndex = StringUtils.indexOf(queue, DOMAIN_SEPARATOR);
int startIndex;
if (domainSeperatorIndex == -1) {
startIndex = 0;
} else {
startIndex = domainSeperatorIndex + 1;
}
int endIndex = StringUtils.indexOf(queue, EXECUTION_NAME_SPACE_SEPARATOR);
if (endIndex == -1) {
endIndex = StringUtils.lastIndexOf(queue, ISOLATION_SEPARATOR);
}
if (endIndex == -1) {
endIndex = queue.length();
}
return StringUtils.substring(queue, startIndex, endIndex);
}
}
| apache-2.0 |
moghaddam/cas | cas-server-support-wsfederation/src/main/java/org/jasig/cas/support/wsfederation/authentication/principal/WsFederationCredential.java | 5272 | package org.jasig.cas.support.wsfederation.authentication.principal;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.jasig.cas.authentication.Credential;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
/**
* This class represents the basic elements of the WsFederation token.
*
* @author John Gasper
* @since 4.2.0
*/
public final class WsFederationCredential implements Credential {
private final Logger logger = LoggerFactory.getLogger(WsFederationCredential.class);
private String audience;
private String authenticationMethod;
private String id;
private String issuer;
private DateTime issuedOn;
private DateTime notBefore;
private DateTime notOnOrAfter;
private DateTime retrievedOn;
private Map<String, Object> attributes;
public String getAuthenticationMethod() {
return this.authenticationMethod;
}
public void setAuthenticationMethod(final String authenticationMethod) {
this.authenticationMethod = authenticationMethod;
}
public String getAudience() {
return this.audience;
}
public void setAudience(final String audience) {
this.audience = audience;
}
public Map<String, Object> getAttributes() {
return this.attributes;
}
public void setAttributes(final Map<String, Object> attributes) {
this.attributes = attributes;
}
@Override
public String getId() {
return this.id;
}
public void setId(final String id) {
this.id = id;
}
public DateTime getIssuedOn() {
return this.issuedOn;
}
public void setIssuedOn(final DateTime issuedOn) {
this.issuedOn = issuedOn;
}
public String getIssuer() {
return this.issuer;
}
public void setIssuer(final String issuer) {
this.issuer = issuer;
}
public DateTime getNotBefore() {
return this.notBefore;
}
public void setNotBefore(final DateTime notBefore) {
this.notBefore = notBefore;
}
public DateTime getNotOnOrAfter() {
return this.notOnOrAfter;
}
public void setNotOnOrAfter(final DateTime notOnOrAfter) {
this.notOnOrAfter = notOnOrAfter;
}
public DateTime getRetrievedOn() {
return this.retrievedOn;
}
public void setRetrievedOn(final DateTime retrievedOn) {
this.retrievedOn = retrievedOn;
}
/**
* toString produces a human readable representation of the WsFederationCredential.
*
* @return a human readable representation of the WsFederationCredential
*/
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.NO_CLASS_NAME_STYLE)
.append("ID", this.id)
.append("Issuer", this.issuer)
.append("Audience", this.audience)
.append("Authentication Method", this.authenticationMethod)
.append("Issued On", this.issuedOn)
.append("Valid After", this.notBefore)
.append("Valid Before", this.notOnOrAfter)
.append("Attributes", this.attributes)
.build();
}
/**
* isValid validates the credential.
*
* @param expectedAudience the audience that the token was issued to (CAS Server)
* @param expectedIssuer the issuer of the token (the IdP)
* @param timeDrift the amount of acceptable time drift
* @return true if the credentials are valid, otherwise false
*/
public boolean isValid(final String expectedAudience, final String expectedIssuer, final int timeDrift) {
if (!this.getAudience().equalsIgnoreCase(expectedAudience)) {
logger.warn("Audience is invalid: {}", this.getAudience());
return false;
}
if (!this.getIssuer().equalsIgnoreCase(expectedIssuer)) {
logger.warn("Issuer is invalid: {}", this.getIssuer());
return false;
}
final DateTime retrievedOnTimeDrift = this.getRetrievedOn().minusMillis(timeDrift);
if (this.getIssuedOn().isBefore(retrievedOnTimeDrift)) {
logger.warn("Ticket is issued before the allowed drift. Issued on {} while allowed drift is {}",
this.getIssuedOn(), retrievedOnTimeDrift);
return false;
}
final DateTime retrievedOnTimeAfterDrift = this.getRetrievedOn().plusMillis(timeDrift);
if (this.getIssuedOn().isAfter(retrievedOnTimeAfterDrift)) {
logger.warn("Ticket is issued after the allowed drift. Issued on {} while allowed drift is {}",
this.getIssuedOn(), retrievedOnTimeAfterDrift);
return false;
}
if (this.getRetrievedOn().isAfter(this.getNotOnOrAfter())) {
logger.warn("Ticket is too late because it's retrieved on {} which is after {}.",
this.getRetrievedOn(), this.getNotOnOrAfter());
return false;
}
logger.debug("WsFed Credential is validated for {} and {}.", expectedAudience, expectedIssuer);
return true;
}
}
| apache-2.0 |
KishorAndroid/PocketHub | app/src/main/java/com/github/pockethub/android/ui/gist/StarredGistsFragment.java | 1518 | /*
* Copyright (c) 2015 PocketHub
*
* 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.github.pockethub.android.ui.gist;
import com.github.pockethub.android.core.PageIterator;
import com.github.pockethub.android.core.ResourcePager;
import com.github.pockethub.android.core.gist.GistPager;
import com.meisolsson.githubsdk.core.ServiceGenerator;
import com.meisolsson.githubsdk.model.Gist;
import com.meisolsson.githubsdk.service.gists.GistService;
/**
* Fragment to display a list of Gists
*/
public class StarredGistsFragment extends GistsFragment {
@Override
protected ResourcePager<Gist> createPager() {
return new GistPager(store) {
@Override
public PageIterator<Gist> createIterator(int page, int size) {
return new PageIterator<>(page1 ->
ServiceGenerator.createService(getActivity(), GistService.class)
.getUserStarredGists(page1), page);
}
};
}
}
| apache-2.0 |
ykrasik/jaci | jaci-reflection-java/src/main/java/com/github/ykrasik/jaci/reflection/JavaReflectionMethod.java | 3513 | /******************************************************************************
* Copyright (C) 2016 Yevgeny Krasik *
* *
* 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.github.ykrasik.jaci.reflection;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
/**
* Reflection information about a method, through the Java reflection API.
*
* @author Yevgeny Krasik
*/
public class JavaReflectionMethod implements ReflectionMethod {
private final Method method;
private final List<ReflectionParameter> parameters;
public JavaReflectionMethod(Method method) {
this.method = Objects.requireNonNull(method, "method");
this.parameters = computeParameters();
}
private List<ReflectionParameter> computeParameters() {
final Class<?>[] parameterTypes = method.getParameterTypes();
final Annotation[][] parameterAnnotations = method.getParameterAnnotations();
final List<ReflectionParameter> params = new ArrayList<>(parameterTypes.length);
for (int i = 0; i < parameterTypes.length; i++) {
final Class<?> parameterType = parameterTypes[i];
final Annotation[] annotations = parameterAnnotations[i];
params.add(new ReflectionParameter(parameterType, annotations, i));
}
return Collections.unmodifiableList(params);
}
@Override
public Object invoke(Object obj, Object... args) throws Exception { return method.invoke(obj, args); }
@Override
public void setAccessible(boolean flag) throws SecurityException { method.setAccessible(flag); }
@Override
public Class<?> getDeclaringClass() { return method.getDeclaringClass(); }
@Override
public String getName() { return method.getName(); }
@Override
public <A extends Annotation> A getAnnotation(Class<A> annotationClass) { return method.getAnnotation(annotationClass); }
@Override
public List<ReflectionParameter> getParameters() { return parameters; }
@Override
public Class<?> getReturnType() { return method.getReturnType(); }
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("JavaReflectionMethod{");
sb.append("method=").append(method);
sb.append(", parameters=").append(parameters);
sb.append('}');
return sb.toString();
}
}
| apache-2.0 |
codingWang/PinWheel | app/src/test/java/com/pinwheel/ExampleUnitTest.java | 305 | package com.pinwheel;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | apache-2.0 |
gamerson/liferay-blade-samples | liferay-workspace/apps/service-builder/basic/basic-test/src/main/java/com/liferay/blade/samples/servicebuilder/test/AddTestData.java | 1788 | /**
* Copyright 2000-present Liferay, 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.liferay.blade.samples.servicebuilder.test;
import com.liferay.blade.basic.model.Foo;
import com.liferay.blade.basic.service.FooLocalService;
import com.liferay.blade.basic.service.FooLocalServiceUtil;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import java.util.Date;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
/**
* @author Lawrence Lee
*/
@Component(immediate = true)
public class AddTestData {
@Activate
public void addTestData() {
Foo foo = FooLocalServiceUtil.createFoo(0);
foo.setField1("createFooEntryField1");
foo.setField2(true);
foo.setField3(1);
Date createDate = new Date();
foo.setField4(createDate);
foo.setField5("createFooEntryField5");
foo.isNew();
Foo fooEntry = FooLocalServiceUtil.addFoo(foo);
if (!fooEntry.getField2()) {
_log.error("Test Failed");
}
FooLocalServiceUtil.deleteFoo(fooEntry);
}
private static final Log _log = LogFactoryUtil.getLog(AddTestData.class);
@Reference
private FooLocalService _fooLocalService;
} | apache-2.0 |
lesaint/experimenting-annotation-processing | experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_4335.java | 151 | package fr.javatronic.blog.massive.annotation1.sub1;
import fr.javatronic.blog.processor.Annotation_001;
@Annotation_001
public class Class_4335 {
}
| apache-2.0 |
hlecuanda/paco | Paco/src/com/pacoapp/paco/ui/ExperimentExecutor.java | 29265 | /*
* Copyright 2011 Google 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.pacoapp.paco.ui;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.joda.time.DateTime;
import org.joda.time.Seconds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.android.apps.paco.questioncondparser.Binding;
import com.google.android.apps.paco.questioncondparser.Environment;
import com.google.android.apps.paco.questioncondparser.ExpressionEvaluator;
import com.pacoapp.paco.R;
import com.pacoapp.paco.model.Event;
import com.pacoapp.paco.model.EventUtil;
import com.pacoapp.paco.model.Experiment;
import com.pacoapp.paco.model.ExperimentProviderUtil;
import com.pacoapp.paco.model.NotificationHolder;
import com.pacoapp.paco.model.Output;
import com.pacoapp.paco.net.SyncService;
import com.pacoapp.paco.sensors.android.BroadcastTriggerReceiver;
import com.pacoapp.paco.shared.model2.ExperimentGroup;
import com.pacoapp.paco.shared.model2.Input2;
import com.pacoapp.paco.shared.util.ExperimentHelper;
import com.pacoapp.paco.triggering.AndroidEsmSignalStore;
import com.pacoapp.paco.triggering.BeeperService;
import com.pacoapp.paco.triggering.ExperimentExpirationManagerService;
import com.pacoapp.paco.triggering.NotificationCreator;
import com.pacoapp.paco.utils.IntentExtraHelper;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.ColorDrawable;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.speech.RecognizerIntent;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
public class ExperimentExecutor extends ActionBarActivity implements ChangeListener, LocationListener, ExperimentLoadingActivity {
private static Logger Log = LoggerFactory.getLogger(ExperimentExecutor.class);
public static final String FORM_DURATION_IN_SECONDS = "Form Duration";
private Experiment experiment;
private ExperimentGroup experimentGroup;
private Long actionTriggerId;
private Long actionId;
private Long actionTriggerSpecId;
private Long notificationHolderId;
private boolean shouldExpireNotificationHolder;
private Long scheduledTime = 0L;
private ExperimentProviderUtil experimentProviderUtil;
private List<InputLayout> inputs = new ArrayList<InputLayout>();
private LayoutInflater inflater;
private LinearLayout mainLayout;
private OptionsMenu optionsMenu;
private Object updateLock = new Object();
private ArrayList<InputLayout> locationInputs;
private Location location;
private View buttonView;
private Button doOnPhoneButton;
private Button doOnWebButton;
private List<SpeechRecognitionListener> speechRecognitionListeners = new ArrayList<SpeechRecognitionListener>();
public static final int RESULT_SPEECH = 3;
private LinearLayout inputsScrollPane;
private DateTime formOpenTime;
private Long timeoutMillis;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.debug("ExperimentExecutor onCreate");
ActionBar actionBar = getSupportActionBar();
actionBar.setLogo(R.drawable.ic_launcher);
actionBar.setDisplayUseLogoEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
// actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setBackgroundDrawable(new ColorDrawable(0xff4A53B3));
experimentProviderUtil = new ExperimentProviderUtil(this);
if (experiment == null || experimentGroup == null) {
Log.debug("ExperimentExecutor experiment or group null. Loading from Intent");
IntentExtraHelper.loadExperimentInfoFromIntent(this, getIntent(), experimentProviderUtil);
}
loadNotificationData();
if (experiment == null || experimentGroup == null) {
displayNoExperimentMessage();
} else {
actionBar.setTitle(experiment.getExperimentDAO().getTitle());
if (scheduledTime == null || scheduledTime == 0l) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
optionsMenu = new OptionsMenu(this, getExperiment().getExperimentDAO().getId(), scheduledTime != null
&& scheduledTime != 0L);
mainLayout = (LinearLayout) inflater.inflate(R.layout.experiment_executor, null);
setContentView(mainLayout);
inputsScrollPane = (LinearLayout) findViewById(R.id.ScrollViewChild);
displayExperimentGroupTitle();
((LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE)).inflate(R.layout.experiment_web_recommended_buttons,
mainLayout, true);
buttonView = findViewById(R.id.ExecutorButtonLayout);
buttonView.setVisibility(View.GONE);
doOnPhoneButton = (Button) findViewById(R.id.DoOnPhoneButton);
doOnPhoneButton.setVisibility(View.GONE);
// doOnPhoneButton.setOnClickListener(new OnClickListener() {
// public void onClick(View v) {
// buttonView.setVisibility(View.GONE);
// //mainLayout.removeView(buttonView);
// scrollView.setVisibility(View.VISIBLE);
// showForm();
// }
// });
doOnWebButton = (Button) findViewById(R.id.DoOnWebButtonButton);
doOnWebButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
deleteNotification();
finish();
}
});
// if (experimentGroup.getEndOfDayGroup()) {
// renderWebRecommendedMessage();
// } else {
if (experimentGroup.getEndOfDayGroup() ||
(experimentGroup.getCustomRendering() != null && experimentGroup.getCustomRendering())) {
Intent customExecutorIntent = new Intent(this, ExperimentExecutorCustomRendering.class);
Bundle extras = getIntent().getExtras();
if (extras != null) {
customExecutorIntent.putExtras(extras);
}
startActivity(customExecutorIntent);
finish();
} else {
showForm();
}
// }
}
}
private void renderWebRecommendedMessage() {
final ScrollView scrollView = (ScrollView)findViewById(R.id.ScrollView01);
scrollView.setVisibility(View.GONE);
buttonView.setVisibility(View.VISIBLE);
}
private void loadNotificationData() {
Bundle extras = getIntent().getExtras();
NotificationHolder notificationHolder = null;
if (extras != null) {
notificationHolderId = extras.getLong(NotificationCreator.NOTIFICATION_ID);
notificationHolder = experimentProviderUtil.getNotificationById(notificationHolderId);
timeoutMillis = null;
if (notificationHolder != null) {
experiment = experimentProviderUtil.getExperimentByServerId(notificationHolder.getExperimentId());
experimentGroup = getExperiment().getExperimentDAO().getGroupByName(notificationHolder.getExperimentGroupName());
actionTriggerId = notificationHolder.getActionTriggerId();
actionId = notificationHolder.getActionId();
actionTriggerSpecId = notificationHolder.getActionTriggerSpecId();
scheduledTime = notificationHolder.getAlarmTime();
Log.info("Starting experimentExecutor from signal: " + getExperiment().getExperimentDAO().getTitle() +". alarmTime: " + new DateTime(scheduledTime).toString());
timeoutMillis = notificationHolder.getTimeoutMillis();
} else {
scheduledTime = null;
}
if (isExpiredEsmPing(timeoutMillis)) {
Log.debug("ExperimentExecutor loadNotificationData ping is alread expired");
Toast.makeText(this, R.string.survey_expired, Toast.LENGTH_LONG).show();
finish();
}
}
if (notificationHolder == null) {
lookForActiveNotificationForExperiment();
}
}
/**
* If the user is self-reporting there might still be an active notification for this experiment. If so, we should
* add its scheduleTime into this response. There should only ever be one.
*/
private void lookForActiveNotificationForExperiment() {
NotificationHolder notificationHolder = null;
if (getExperiment() == null) {
return;
}
final long experimentServerId = getExperiment().getExperimentDAO().getId().longValue();
List<NotificationHolder> notificationHolders = experimentProviderUtil.getNotificationsFor(experimentServerId, experimentGroup.getName());
if (notificationHolders != null && !notificationHolders.isEmpty()) {
notificationHolder = notificationHolders.get(0); // TODO can we ever have more than one for a group?
}
if (notificationHolder != null) {
experiment = experimentProviderUtil.getExperimentByServerId(notificationHolder.getExperimentId());
experimentGroup = getExperiment().getExperimentDAO().getGroupByName(notificationHolder.getExperimentGroupName());
if (notificationHolder.isActive(new DateTime())) {
notificationHolderId = notificationHolder.getId();
scheduledTime = notificationHolder.getAlarmTime();
shouldExpireNotificationHolder = true;
Log.info("ExperimentExecutor: Self reporting but found active notification: " + getExperiment().getExperimentDAO().getTitle() +". alarmTime: " + new DateTime(scheduledTime).toString());
} else {
Log.debug("Timing out notification that has expired.");
NotificationCreator.create(this).timeoutNotification(notificationHolder);
}
}
}
@Override
protected void onResume() {
super.onResume();
Log.debug("ExperimentExecutor onResume");
registerLocationListenerIfNecessary();
if (mainLayout != null) {
mainLayout.clearFocus();
if (inputs != null && inputs.size() > 0) {
InputLayout firstInput = inputs.get(0);
if (firstInput.getInput().getResponseType().equals(Input2.OPEN_TEXT)) {
firstInput.requestFocus();
}
}
}
}
@Override
protected void onPause() {
super.onPause();
Log.debug("ExperimentExecutor onPause");
for (InputLayout layout : inputs) {
layout.onPause();
}
unregisterLocationListenerIfNecessary();
}
private void unregisterLocationListenerIfNecessary() {
if (locationInputs.size() > 0) {
locationInputs.clear();
unregisterLocationListener();
}
}
private void registerLocationListenerIfNecessary() {
locationInputs = new ArrayList<InputLayout>();
for (InputLayout input : inputs) {
if (input.getInput().getResponseType().equals(Input2.LOCATION)) {
locationInputs.add(input);
}
}
if (locationInputs.size() > 0) {
registerLocationListener();
}
}
// Location
private void registerLocationListener() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!lm.isProviderEnabled("gps")) {
new AlertDialog.Builder(this)
.setMessage(R.string.gps_message)
.setCancelable(true)
.setPositiveButton(R.string.enable_button, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
launchGpsSettings();
dialog.dismiss();
}
})
.setNegativeButton(R.string.cancel_button, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.create()
.show();
}
if (lm != null) {
getBestProvider(lm);
}
}
public void launchGpsSettings() {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
private void getBestProvider(LocationManager lm) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String bestProvider = lm.getBestProvider(criteria, true);
if (bestProvider != null) {
lm.requestLocationUpdates(bestProvider, 0, 0, this);
location = lm.getLastKnownLocation(bestProvider);
for (InputLayout input : locationInputs) {
input.setLocation(location);
}
} else {
new AlertDialog.Builder(this)
.setMessage(R.string.need_location)
.setCancelable(true)
.setPositiveButton(R.string.enable_button, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
launchGpsSettings();
dialog.dismiss();
}
})
.setNegativeButton(R.string.cancel_button, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.create()
.show();
}
}
public void onLocationChanged(Location location) {
this.location = location;
for (InputLayout input : locationInputs) {
input.setLocation(location);
}
}
public void onProviderDisabled(String provider) {
unregisterLocationListener();
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
getBestProvider(lm);
}
public void onProviderEnabled(String provider) {
unregisterLocationListener();
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
getBestProvider(lm);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
unregisterLocationListener();
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
getBestProvider(lm);
}
private void unregisterLocationListener() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (lm != null) {
lm.removeUpdates(this);
}
}
//End Location
private boolean isExpiredEsmPing(Long timeoutMillis) {
return (scheduledTime != null && scheduledTime != 0L && timeoutMillis != null) &&
(new DateTime(scheduledTime)).plus(timeoutMillis).isBefore(new DateTime());
}
private void showForm() {
renderInputs();
renderSaveButton();
formOpenTime = DateTime.now();
}
private void renderSaveButton() {
View saveButtonView = ((LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE)).inflate(R.layout.experiment_save_buttons,
inputsScrollPane,
true);
// inputsScrollPane.removeView(saveButtonView);
//LinearLayout saveButtonLayout = (LinearLayout)findViewById(R.id.ExecutorButtonLayout);
Button saveButton = (Button)findViewById(R.id.SaveResponseButton);
//saveButtonLayout.removeView(saveButton);
// inputsScrollPane.addView(saveButtonView);
saveButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
save();
}
});
}
private void save() {
Log.debug("ExperimentExecutor save");
try {
if (notificationHolderId == null || isExpiredEsmPing(timeoutMillis)) {
// workaround the bug with re-launching and stale scheduleTime.
// How - if there isn't a notificationHolder waiting, then this is not a response
// to a notification.
scheduledTime = 0L;
}
Event event = EventUtil.createEvent(getExperiment(), experimentGroup.getName(),
actionTriggerId, actionId, actionTriggerSpecId, scheduledTime);
gatherResponses(event);
addTiming(event);
experimentProviderUtil.insertEvent(event);
deleteNotification();
Bundle extras = getIntent().getExtras();
if (extras != null) {
extras.clear();
}
updateAlarms();
notifySyncService();
showFeedback();
finish();
} catch (IllegalStateException ise) {
new AlertDialog.Builder(this)
.setIcon(R.drawable.paco64)
.setTitle(R.string.required_answers_missing)
.setMessage(ise.getMessage()).show();
}
}
private void addTiming(Event event) {
if (formOpenTime != null) {
DateTime formFinishTime = DateTime.now();
Seconds duration = Seconds.secondsBetween(formOpenTime, formFinishTime);
Output durationResponse = new Output();
durationResponse.setAnswer(Integer.toString(duration.getSeconds()));
durationResponse.setName(FORM_DURATION_IN_SECONDS);
event.addResponse(durationResponse);
}
}
private void updateAlarms() {
startService(new Intent(this, BeeperService.class));
}
private void deleteNotification() {
if (notificationHolderId != null && notificationHolderId.longValue() != 0l) {
experimentProviderUtil.deleteNotification(notificationHolderId);
}
if (shouldExpireNotificationHolder) {
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(new Long(notificationHolderId).intValue()); //This should cancel the notification even if it's non-dismissible
shouldExpireNotificationHolder = false;
}
}
private void notifySyncService() {
startService(new Intent(this, SyncService.class));
}
public void showFeedback() {
Intent intent = new Intent(this, FeedbackActivity.class);
intent.putExtras(getIntent().getExtras());
intent.putExtra(Experiment.EXPERIMENT_SERVER_ID_EXTRA_KEY, experiment.getExperimentDAO().getId());
intent.putExtra(Experiment.EXPERIMENT_GROUP_NAME_EXTRA_KEY, experimentGroup.getName());
startActivity(intent);
}
private void gatherResponses(Event event) throws IllegalStateException {
Environment interpreter = updateInterpreter(null);
ExpressionEvaluator main = new ExpressionEvaluator(interpreter);
for (InputLayout inputView : inputs) {
Input2 input = inputView.getInput();
try {
if (input.getConditional() != null && input.getConditional() == true && !main.parse(input.getConditionExpression())) {
continue;
}
} catch (IllegalArgumentException iae) {
Log.error("Parsing problem: " + iae.getMessage());
continue;
}
Output responseForInput = new Output();
String answer = inputView.getValueAsString();
if (input.getRequired() && (answer == null || answer.length() == 0 || answer.equals("-1") /*||
(input.getResponseType().equals(Input.LIST) && answer.equals("0"))*/)) {
throw new IllegalStateException(getString(R.string.must_answer) + input.getText());
}
responseForInput.setAnswer(answer);
responseForInput.setName(input.getName());
event.addResponse(responseForInput);
}
}
private void renderInputs() {
for (Input2 input : experimentGroup.getInputs()) {
final InputLayout inputView = renderInput(input);
inputs.add(inputView);
inputsScrollPane.addView(inputView);
inputView.addChangeListener(this);
if (input.getResponseType().equals(Input2.OPEN_TEXT)) {
final TextView componentWithValue = (TextView)inputView.getComponentWithValue();
componentWithValue.setImeOptions(EditorInfo.IME_ACTION_DONE);
componentWithValue.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
// hide virtual keyboard
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(inputView.getComponentWithValue().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
return true;
}
return false;
}
});
}
}
}
// private void setNextActionOnOpenTexts() {
// int size = inputs.size() - 1;
// for (int i = 0; i < size; i++) {
// InputLayout inputLayout = inputs.get(i);
// if (inputLayout.getInput().getResponseType().equals(Input.OPEN_TEXT)) {
// EditText openText = ((EditText)inputLayout.getComponentWithValue());
// openText.setImeOptions(EditorInfo.IME_ACTION_NEXT);
// openText.setImeActionLabel("Next", EditorInfo.IME_ACTION_NEXT);
// }
// }
//
// }
/**
* Note this is a simple version geared towards questions
* with text and then some input type for the response.
* In the future, it might make sense to create an InputView class
* that has control of displaying the prompt (Question text),
* and the input type. It just has an api that allows you to
* retrieve the value that was selected. This could make it
* easy to create interesting media inputs, or sensor inputs with
* no display.
*
* @param input
* @return
*/
private InputLayout renderInput(Input2 input) {
return createInputViewGroup(input);
}
private InputLayout createInputViewGroup(Input2 input) {
return new InputLayout(this, input);
}
private void displayExperimentGroupTitle() {
final TextView groupNameTextView = (TextView)findViewById(R.id.experiment_title);
String name = experimentGroup.getName();
if (name == null || experiment.getExperimentDAO().getGroups().size() == 1) {
groupNameTextView.setVisibility(View.GONE);
} else {
groupNameTextView.setText(name);
}
}
private void displayNoExperimentMessage() {
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mainLayout = (LinearLayout) inflater.inflate(R.layout.could_not_load_experiment, null);
setContentView(mainLayout);
}
public void setExperimentGroup(ExperimentGroup group) {
this.experimentGroup = group;
}
public Experiment getExperiment() {
return experiment;
}
public void setExperiment(Experiment experiment) {
this.experiment = experiment;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (optionsMenu != null) {
return optionsMenu.init(menu);
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return optionsMenu.onOptionsItemSelected(item);
}
public void stopExperiment() {
deleteExperiment();
finish();
}
public void deleteExperiment() {
NotificationCreator nc = NotificationCreator.create(this);
nc.timeoutNotificationsForExperiment(experiment.getExperimentDAO().getId());
createStopEvent(experiment);
experimentProviderUtil.deleteExperiment(experiment.getId());
if (ExperimentHelper.shouldWatchProcesses(experiment.getExperimentDAO())) {
BroadcastTriggerReceiver.initPollingAndLoggingPreference(this);
}
new AndroidEsmSignalStore(this).deleteAllSignalsForSurvey(experiment.getExperimentDAO().getId());
startService(new Intent(this, BeeperService.class));
startService(new Intent(this, ExperimentExpirationManagerService.class));
}
/**
* Creates a pacot for stopping an experiment
*
* @param experiment
*/
private void createStopEvent(Experiment experiment) {
Event event = new Event();
event.setExperimentId(experiment.getId());
event.setServerExperimentId(experiment.getExperimentDAO().getId());
event.setExperimentName(experiment.getExperimentDAO().getTitle());
event.setExperimentVersion(experiment.getExperimentDAO().getVersion());
event.setResponseTime(new DateTime());
Output responseForInput = new Output();
responseForInput.setAnswer("false");
responseForInput.setName("joined");
event.addResponse(responseForInput);
experimentProviderUtil.insertEvent(event);
startService(new Intent(this, SyncService.class));
}
public void onChange(InputLayout input) {
synchronized (updateLock) {
Environment interpreter = updateInterpreter(input);
ExpressionEvaluator main = new ExpressionEvaluator(interpreter);
for (InputLayout inputLayout : inputs) {
inputLayout.checkConditionalExpression(main);
}
}
}
private Environment updateInterpreter(InputLayout input) {
Environment interpreter = null;
// todo make interpreter a field to optimize updates.
if (interpreter == null) {
interpreter = new Environment();
for (InputLayout inputLayout : inputs) {
interpreter.addInput(createBindingFromInputView(inputLayout));
}
}
// else {
// if (input != null) {
// interpreter.addInput(createBindingFromInputView(input));
// }
// }
return interpreter;
}
private Binding createBindingFromInputView(InputLayout inputLayout) {
String inputName = inputLayout.getInputName();
Class responseType = inputLayout.getResponseType();
Object value = inputLayout.getValue();
Binding binding = new Binding(inputName, responseType, value);
return binding;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_SPEECH) {
if (resultCode == RESULT_OK) {
handleSpeechRecognitionActivityResult(resultCode, data);
} else {
speechRecognitionListeners.clear();
}
} else if (requestCode >= InputLayout.CAMERA_REQUEST_CODE && resultCode == RESULT_OK) { // camera picture
for (InputLayout inputLayout : inputs) {
inputLayout.cameraPictureTaken(requestCode);
}
} else if (resultCode == RESULT_OK) { //gallery picture
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
try {
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
for (InputLayout inputLayout : inputs) {
inputLayout.galleryPicturePicked(filePath, requestCode);
}
} catch (Exception e) {
Log.info("Exception in gallery picking: " + e.getMessage());
e.printStackTrace();
}
}
}
private void handleSpeechRecognitionActivityResult(int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && null != data) {
ArrayList<String> guesses = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
notifySpeechRecognitionListeners(guesses);
}
}
private void notifySpeechRecognitionListeners(List<String> guesses) {
List<SpeechRecognitionListener> copyOfSpeechListeners = new ArrayList<SpeechRecognitionListener>(speechRecognitionListeners);
for (SpeechRecognitionListener listener : copyOfSpeechListeners) {
listener.speechRetrieved(guesses);
}
}
public void removeSpeechRecognitionListener(SpeechRecognitionListener listener) {
speechRecognitionListeners.remove(listener);
}
public void startSpeechRecognition(SpeechRecognitionListener listener) {
//speechRecognitionListeners.clear(); // just in case they canceled the last recognition (android gives us no feedback)
speechRecognitionListeners.add(listener);
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, Locale.getDefault().getDisplayName());
try {
startActivityForResult(intent, RESULT_SPEECH);
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(), R.string.oops_your_device_doesn_t_support_speech_to_text, Toast.LENGTH_SHORT);
t.show();
}
}
}
| apache-2.0 |
gerrit-review/gerrit | java/com/google/gerrit/server/query/change/RegexPathPredicate.java | 1361 | // 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.google.gerrit.server.query.change;
import com.google.gerrit.server.index.change.ChangeField;
import com.google.gerrit.server.util.RegexListSearcher;
import com.google.gwtorm.server.OrmException;
import java.io.IOException;
import java.util.List;
public class RegexPathPredicate extends ChangeRegexPredicate {
public RegexPathPredicate(String re) {
super(ChangeField.PATH, re);
}
@Override
public boolean match(ChangeData object) throws OrmException {
List<String> files;
try {
files = object.currentFilePaths();
} catch (IOException e) {
throw new OrmException(e);
}
return RegexListSearcher.ofStrings(getValue()).hasMatch(files);
}
@Override
public int getCost() {
return 1;
}
}
| apache-2.0 |
IBM-Bluemix/bluetag | bluetag-tag/src/com/bluetag/api/tag/resources/CORSHeader.java | 1069 | package com.bluetag.api.tag.resources;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
public class CORSHeader implements Filter {
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse servletResponse = (HttpServletResponse) response;
servletResponse.setHeader("Access-Control-Allow-Origin", "*");
servletResponse.setHeader("Access-Control-Allow-Headers", "Content-Type");
servletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT");
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
| apache-2.0 |
LordAkkarin/BaseDefense | src/main/java/org/evilco/mc/defense/common/network/DefenseStationRegisterUserPacket.java | 3669 | /*
* Copyright (C) 2014 Evil-Co <http://wwww.evil-co.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.evilco.mc.defense.common.network;
import com.google.common.base.Charsets;
import io.netty.buffer.ByteBuf;
/**
* Allows sending updates about new registered users.
* @author Johannes Donath <johannesd@evil-co.com>
* @copyright Copyright (C) 2014 Evil-Co <http://www.evil-co.org>
*/
public class DefenseStationRegisterUserPacket extends AbstractDefensePacket {
/**
* Indicates whether the packet is sent for the whitelist or blacklist.
*/
protected boolean blacklist = false;
/**
* Stores the username to register.
*/
protected String username = null;
/**
* Stores the tile entity x coordinate.
*/
protected int xCoord = 0;
/**
* Stores the tile entity y coordinate.
*/
protected int yCoord = 0;
/**
* Stores the tile entity z coordinate.
*/
protected int zCoord = 0;
/**
* Constructs a new DefenseStationRegisterUserPacket.
* @param username The username.
*/
public DefenseStationRegisterUserPacket (String username, boolean blacklist, int x, int y, int z) {
super ();
this.username = username;
this.blacklist = blacklist;
this.xCoord = x;
this.yCoord = y;
this.zCoord = z;
}
/**
* Constructs a new DefenseStationRegisterUserPacket from a serialized packet buffer.
* @param buffer The packet buffer.
*/
public DefenseStationRegisterUserPacket (ByteBuf buffer) {
super (buffer);
// read coordinates
this.xCoord = buffer.readInt ();
this.yCoord = buffer.readInt ();
this.zCoord = buffer.readInt ();
// read mode
this.blacklist = buffer.readBoolean ();
// read length
int length = buffer.readShort ();
// create buffer
byte[] usernameRaw = new byte[length];
// read buffer
buffer.readBytes (usernameRaw);
// convert string
this.username = new String (usernameRaw, Charsets.UTF_8);
}
/**
* Returns the list mode.
* @return The mode.
*/
public boolean isBlacklist () {
return this.blacklist;
}
/**
* Returns the username stored in this packet.
* @return The username.
*/
public String getUsername () {
return this.username;
}
/**
* Returns the X coordinate.
* @return The x coordinate.
*/
public int getX () {
return this.xCoord;
}
/**
* Returns the Y coordinate.
* @return The y coordinate.
*/
public int getY () {
return this.yCoord;
}
/**
* Returns the Z coordinate.
* @return The z coordinate.
*/
public int getZ () {
return this.zCoord;
}
/**
* {@inheritDoc}
*/
@Override
public void write (ByteBuf buffer) {
// convert string to byte[]
byte[] usernameRaw = this.username.getBytes (Charsets.UTF_8);
// write coordinates
buffer.writeInt (this.xCoord);
buffer.writeInt (this.yCoord);
buffer.writeInt (this.zCoord);
// write mode
buffer.writeBoolean (this.blacklist);
// write length
buffer.writeShort (usernameRaw.length);
// write data
buffer.writeBytes (usernameRaw);
}
} | apache-2.0 |