text
stringlengths
7
1.01M
package com.learn.chapter04.lazyLoad.util; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException; import java.io.InputStream; import java.util.logging.Level; /** * */ public class SqlSessionFactoryUtil { //类线程锁 private static final Class CLASS_LOCK = SqlSessionFactoryUtil.class; //SqlSessionFactory对象 private static SqlSessionFactory sqlSessionFactory = null; private static SqlSessionFactory getInstance() { String resource = "chapter04/lazyLoad/mybatis-config.xml"; InputStream inputStream = null; try { inputStream = Resources.getResourceAsStream(resource); } catch (IOException e) { java.util.logging.Logger.getLogger(SqlSessionFactoryUtil .class.getName()).log(Level.SEVERE, null, e); } synchronized (CLASS_LOCK) { if (sqlSessionFactory == null) { sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } } return sqlSessionFactory; } public static SqlSession openSqlSession() { if (sqlSessionFactory == null) { getInstance(); } return sqlSessionFactory.openSession(); } }
package org.axonframework.springboot; import org.axonframework.eventsourcing.eventstore.EmbeddedEventStore; import org.axonframework.eventsourcing.eventstore.EventStorageEngine; import org.axonframework.eventsourcing.eventstore.EventStore; import org.axonframework.eventsourcing.eventstore.jpa.JpaEventStorageEngine; import org.axonframework.springboot.autoconfig.AxonServerAutoConfiguration; import org.junit.jupiter.api.*; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.EnableMBeanExport; import org.springframework.jmx.support.RegistrationPolicy; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.junit.jupiter.api.Assertions.*; /** * Tests JPA EventStore auto-configuration * * @author Sara Pellegrini */ @ExtendWith(SpringExtension.class) @ContextConfiguration @EnableAutoConfiguration(exclude = {AxonServerAutoConfiguration.class}) @EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING) class JpaEventStoreAutoConfigurationWithoutAxonServerTest { @Autowired private EventStorageEngine eventStorageEngine; @Autowired private EventStore eventStore; @Test void testEventStore() { assertTrue(eventStorageEngine instanceof JpaEventStorageEngine); assertTrue(eventStore instanceof EmbeddedEventStore); } }
/** * */ package edu.incense.android.sensor; import java.util.List; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.net.wifi.WifiManager.WifiLock; import android.provider.Settings; import android.util.Log; import edu.incense.android.datatask.data.Data; import edu.incense.android.datatask.data.WifiData; /** * @author mxpxgx * */ public class WifiConnectionSensor extends Sensor { public final static String TAG = "WifiConnectionSensor"; public final static String ATT_ISCONNECTED = "isConnected"; private boolean connected; private WifiConfiguration connectedConfig; private WifiInfo connectedWifiInfo; private WifiManager wifiManager; public WifiConnectionSensor(Context context) { super(context); setName("WiFi"); // WifiManager initiation String service = Context.WIFI_SERVICE; wifiManager = (WifiManager) context.getSystemService(service); // Initiate other attributes connectedConfig = null; connectedWifiInfo = null; } @Override public void start() { super.start(); setSensing(true); enableWifi(); connectedConfig = getConnectedConfig(); if (connectedConfig != null) { connectedWifiInfo = wifiManager.getConnectionInfo(); setConnected(true); } else { // Generate empty data Data newData = new WifiData(); newData.getExtras().putBoolean(ATT_ISCONNECTED, false); currentData = newData; } registerBroadcastReceivers(); forceWifiToStayOn(); } @Override public void stop() { super.stop(); setSensing(false); unregisterBroadcastReceivers(); disableWifi(); letWifiToTurnOff(); } private WifiLock wifiLock; private void forceWifiToStayOn(){ // Set WiFi sleep policy to never Settings.System.putInt(getContext().getContentResolver(), Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_NEVER); WifiLock wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL , "MyWifiLock"); if(!wifiLock.isHeld()){ wifiLock.acquire(); } } private void letWifiToTurnOff(){ // Set WiFi sleep policy to default Settings.System.putInt(getContext().getContentResolver(), Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT); wifiLock.release(); } /** * Enable wifi, if needed */ boolean wasEnabled = false; private void enableWifi() { wasEnabled = wifiManager.isWifiEnabled(); if (!wasEnabled) { if (wifiManager.getWifiState() != WifiManager.WIFI_STATE_ENABLING) { wifiManager.setWifiEnabled(true); } } } private void disableWifi() { if (wifiManager.isWifiEnabled() && !wasEnabled) { if (wifiManager.getWifiState() != WifiManager.WIFI_STATE_DISABLING) { wifiManager.setWifiEnabled(false); } } } private void registerBroadcastReceivers() { // Register connection monitor IntentFilter intentFilter2 = new IntentFilter( ConnectivityManager.CONNECTIVITY_ACTION); getContext().registerReceiver(this.connectionMonitor, intentFilter2); } private void unregisterBroadcastReceivers() { getContext().unregisterReceiver(this.connectionMonitor); } /** * Gets the ssid of the currently connected access point * * @param ssid * @return */ private WifiConfiguration getConnectedConfig() { List<WifiConfiguration> configList = wifiManager.getConfiguredNetworks(); for (WifiConfiguration config : configList) { Log.d(TAG, config.SSID + ", status: " + config.status); if (config.status == WifiConfiguration.Status.CURRENT) { return config; } } return null; } private void setConnected(boolean connected) { if (connectedWifiInfo != null) { this.connected = connected; Data newData = new WifiData(connectedWifiInfo); newData.getExtras().putBoolean(ATT_ISCONNECTED, connected); currentData = newData; } } private boolean isConnected() { return connected; } /** * This BroadcastReceiver checks if the WiFi connection was lost or * established. */ private BroadcastReceiver connectionMonitor = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals( android.net.ConnectivityManager.CONNECTIVITY_ACTION)) { NetworkInfo netInfo = (NetworkInfo) intent .getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); NetworkInfo.State state = netInfo.getState(); boolean disconnected = (state == NetworkInfo.State.DISCONNECTED || state == NetworkInfo.State.SUSPENDED); boolean isWifi = (netInfo.getType() == ConnectivityManager.TYPE_WIFI); if (isConnected() && disconnected && isWifi) { Log.d(TAG, "WiFi connection lost!"); setConnected(false); // Toast.makeText(context, "WiFi connection lost", // Toast.LENGTH_LONG).show(); //TODO should try to reconnect } if (!isConnected() && !disconnected && isWifi) { Log.d(TAG, "WiFi connection established!"); connectedWifiInfo = wifiManager.getConnectionInfo(); setConnected(true); // Toast.makeText(context, "WiFi connection established", // Toast.LENGTH_LONG).show(); } } } }; }
package com.stm.main.base.view; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import com.stm.R; import com.stm.common.dao.User; import butterknife.OnClick; /** * Created by ㅇㅇ on 2017-06-07. */ public interface MainView { void showMessage(String message); void showLocationPermission(); void onChangeForUserCreateFragmentAndNotificationFragment(Fragment fragment); void showProgressDialog(); void goneProgressDialog(); void setTabAdapterNotifyDataSetChanged(); void setTabAdapterUser(User user); void setTabAdapter(User user); void setTabLayout(); ViewPager getViewPager(); void setToolbar(); void onChangeForUserFragmentAndNotificationFragment(Fragment fragment); void onClickSearch(); void navigateToSearchActivity(); }
package u21g; public class DatabasePath { private static DatabasePath databasePathInstance = new DatabasePath(); public static DatabasePath getInstance() { return databasePathInstance; } private String dbPath; private DatabasePath() { } public String getPath() { return dbPath; } public void setPath(String databasePath) { this.dbPath = databasePath; } }
/* Copyright 2006 Benjamin Livshits 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. */ /** @author Benjamin Livshits <livshits@cs.stanford.edu> $Id: Collections12.java,v 1.1 2006/04/21 17:14:26 livshits Exp $ */ package securibench.micro.collections; import java.io.IOException; import java.io.PrintWriter; import java.util.LinkedList; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import securibench.micro.BasicTestCase; import securibench.micro.MicroTestCase; /** * @servlet description = "collection copying through an array" * @servlet vuln_count = "1" * */ public class Collections12 extends BasicTestCase implements MicroTestCase { private static final String FIELD_NAME = "name"; protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { String s1 = req.getParameter(FIELD_NAME); LinkedList c1 = new LinkedList(); c1.addLast(s1); Object[] array = c1.toArray(); PrintWriter writer = resp.getWriter(); writer.println(array[0]); /* BAD */ } public String getDescription() { return "collection copying through an array"; } public int getVulnerabilityCount() { return 1; } }
/* * Ory APIs * Documentation for all public and administrative Ory APIs. Administrative APIs can only be accessed with a valid Personal Access Token. Public APIs are mostly used in browsers. * * The version of the OpenAPI document: v0.0.1-alpha.42 * Contact: support@ory.sh * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package sh.ory.model; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import sh.ory.model.UiText; /** * UiNodeAnchorAttributes */ @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2022-01-07T20:26:34.917598036Z[Etc/UTC]") public class UiNodeAnchorAttributes { public static final String SERIALIZED_NAME_HREF = "href"; @SerializedName(SERIALIZED_NAME_HREF) private String href; public static final String SERIALIZED_NAME_ID = "id"; @SerializedName(SERIALIZED_NAME_ID) private String id; public static final String SERIALIZED_NAME_NODE_TYPE = "node_type"; @SerializedName(SERIALIZED_NAME_NODE_TYPE) private String nodeType; public static final String SERIALIZED_NAME_TITLE = "title"; @SerializedName(SERIALIZED_NAME_TITLE) private UiText title; public UiNodeAnchorAttributes href(String href) { this.href = href; return this; } /** * The link&#39;s href (destination) URL. format: uri * @return href **/ @javax.annotation.Nonnull @ApiModelProperty(required = true, value = "The link's href (destination) URL. format: uri") public String getHref() { return href; } public void setHref(String href) { this.href = href; } public UiNodeAnchorAttributes id(String id) { this.id = id; return this; } /** * A unique identifier * @return id **/ @javax.annotation.Nonnull @ApiModelProperty(required = true, value = "A unique identifier") public String getId() { return id; } public void setId(String id) { this.id = id; } public UiNodeAnchorAttributes nodeType(String nodeType) { this.nodeType = nodeType; return this; } /** * Get nodeType * @return nodeType **/ @javax.annotation.Nonnull @ApiModelProperty(required = true, value = "") public String getNodeType() { return nodeType; } public void setNodeType(String nodeType) { this.nodeType = nodeType; } public UiNodeAnchorAttributes title(UiText title) { this.title = title; return this; } /** * Get title * @return title **/ @javax.annotation.Nonnull @ApiModelProperty(required = true, value = "") public UiText getTitle() { return title; } public void setTitle(UiText title) { this.title = title; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } UiNodeAnchorAttributes uiNodeAnchorAttributes = (UiNodeAnchorAttributes) o; return Objects.equals(this.href, uiNodeAnchorAttributes.href) && Objects.equals(this.id, uiNodeAnchorAttributes.id) && Objects.equals(this.nodeType, uiNodeAnchorAttributes.nodeType) && Objects.equals(this.title, uiNodeAnchorAttributes.title); } @Override public int hashCode() { return Objects.hash(href, id, nodeType, title); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class UiNodeAnchorAttributes {\n"); sb.append(" href: ").append(toIndentedString(href)).append("\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" nodeType: ").append(toIndentedString(nodeType)).append("\n"); sb.append(" title: ").append(toIndentedString(title)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
package com.alipay.api.request; import com.alipay.api.domain.AlipayCommerceMedicalInstcardBindModel; import java.util.Map; import com.alipay.api.AlipayRequest; import com.alipay.api.internal.util.AlipayHashMap; import com.alipay.api.response.AlipayCommerceMedicalInstcardBindResponse; import com.alipay.api.AlipayObject; /** * ALIPAY API: alipay.commerce.medical.instcard.bind request * * @author auto create * @since 1.0, 2018-09-13 13:56:21 */ public class AlipayCommerceMedicalInstcardBindRequest implements AlipayRequest<AlipayCommerceMedicalInstcardBindResponse> { private AlipayHashMap udfParams; // add user-defined text parameters private String apiVersion="1.0"; /** * 用于支付宝用户通过医院服务窗绑定当地社保卡 */ private String bizContent; public void setBizContent(String bizContent) { this.bizContent = bizContent; } public String getBizContent() { return this.bizContent; } private String terminalType; private String terminalInfo; private String prodCode; private String notifyUrl; private String returnUrl; private boolean needEncrypt=false; private AlipayObject bizModel=null; public String getNotifyUrl() { return this.notifyUrl; } public void setNotifyUrl(String notifyUrl) { this.notifyUrl = notifyUrl; } public String getReturnUrl() { return this.returnUrl; } public void setReturnUrl(String returnUrl) { this.returnUrl = returnUrl; } public String getApiVersion() { return this.apiVersion; } public void setApiVersion(String apiVersion) { this.apiVersion = apiVersion; } public void setTerminalType(String terminalType){ this.terminalType=terminalType; } public String getTerminalType(){ return this.terminalType; } public void setTerminalInfo(String terminalInfo){ this.terminalInfo=terminalInfo; } public String getTerminalInfo(){ return this.terminalInfo; } public void setProdCode(String prodCode) { this.prodCode=prodCode; } public String getProdCode() { return this.prodCode; } public String getApiMethodName() { return "alipay.commerce.medical.instcard.bind"; } public Map<String, String> getTextParams() { AlipayHashMap txtParams = new AlipayHashMap(); txtParams.put("biz_content", this.bizContent); if(udfParams != null) { txtParams.putAll(this.udfParams); } return txtParams; } public void putOtherTextParam(String key, String value) { if(this.udfParams == null) { this.udfParams = new AlipayHashMap(); } this.udfParams.put(key, value); } public Class<AlipayCommerceMedicalInstcardBindResponse> getResponseClass() { return AlipayCommerceMedicalInstcardBindResponse.class; } public boolean isNeedEncrypt() { return this.needEncrypt; } public void setNeedEncrypt(boolean needEncrypt) { this.needEncrypt=needEncrypt; } public AlipayObject getBizModel() { return this.bizModel; } public void setBizModel(AlipayObject bizModel) { this.bizModel=bizModel; } }
package com.example.bttracker; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; public class ReminderBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // TODO: This method is called when the BroadcastReceiver is receiving // an Intent broadcast. Intent notificationIntent = new Intent(context, LogActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(context,0,notificationIntent,0); NotificationCompat.Builder builder = new NotificationCompat.Builder(context,"BT_Tracker_Channel") .setSmallIcon(R.mipmap.ic_launcher_round) .setContentTitle("Notification from BT Tracker") .setContentText("Please log your body temperature now") .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setContentIntent(contentIntent); NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); notificationManager.notify(200,builder.build()); } }
/** * ***************************************************************************** * * <p>Copyright FUJITSU LIMITED 2020 * * <p>Creation Date: 13 Oct 2020 * * <p>***************************************************************************** */ package org.oscm.app.vmware.business; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.internal.verification.VerificationModeFactory; import org.oscm.app.vmware.business.model.DistributedVirtualSwitch; import org.oscm.app.vmware.business.model.Portgroup; import org.oscm.app.vmware.remote.vmware.ManagedObjectAccessor; import org.oscm.app.vmware.remote.vmware.ServiceConnection; import org.oscm.app.vmware.remote.vmware.VMwareClient; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.vmware.vim25.DistributedVirtualSwitchPortConnection; import com.vmware.vim25.ManagedObjectReference; import com.vmware.vim25.NetworkSummary; import com.vmware.vim25.ServiceContent; import com.vmware.vim25.VimPortType; import com.vmware.vim25.VirtualDevice; import com.vmware.vim25.VirtualDeviceBackingInfo; import com.vmware.vim25.VirtualEthernetCard; import com.vmware.vim25.VirtualEthernetCardDistributedVirtualPortBackingInfo; import com.vmware.vim25.VirtualHardware; import com.vmware.vim25.VirtualMachineConfigInfo; import com.vmware.vim25.VirtualMachineConfigSpec; import com.vmware.vim25.VirtualMachineRuntimeInfo; /** @author worf */ @RunWith(PowerMockRunner.class) @PrepareForTest(NetworkManager.class) public class NetworkManagerTest { @Mock VMwareClient vmw; @Mock ManagedObjectReference vmwInstance; @Mock ManagedObjectReference mor; @Mock ManagedObjectAccessor moa; @Mock VirtualMachineConfigInfo vmci; @Mock VMPropertyHandler paramHandler; @Mock VirtualMachineConfigSpec vmConfigSpec; @Mock ServiceContent serviceContent; @Mock VimPortType vimPortType; @Mock ServiceConnection serviceConnection; @Before public void setUp() throws Exception { PowerMockito.spy(NetworkManager.class); MockitoAnnotations.initMocks(this); initMocks(); } private void initMocks() throws Exception { doReturn(moa).when(vmw).getServiceUtil(); doReturn(vmci).when(moa).getDynamicProperty(vmwInstance, "config"); doReturn(serviceConnection).when(vmw).getConnection(); doReturn(serviceContent).when(serviceConnection).getServiceContent(); doReturn(vimPortType).when(serviceConnection).getService(); } @Test public void getNumberOfNICs() throws Exception { // given VirtualEthernetCard etc1 = new VirtualEthernetCard(); VirtualEthernetCard etc2 = new VirtualEthernetCard(); List<VirtualEthernetCard> etcs = new ArrayList<VirtualEthernetCard>(); etcs.add(etc1); etcs.add(etc2); PowerMockito.doReturn(etcs).when(NetworkManager.class, "getNetworkAdapter", vmci); // when int result = NetworkManager.getNumberOfNICs(vmw, vmwInstance); // then assertEquals(2, result); } @Test public void getNetworkName() throws Exception { // given NetworkSummary summary = mock(NetworkSummary.class); List<ManagedObjectReference> mors = new ArrayList<ManagedObjectReference>(); mors.add(mor); doReturn(mors).when(moa).getDynamicProperty(vmwInstance, "network"); doReturn("test").when(moa).getDynamicProperty(mor, "name"); doReturn(summary).when(moa).getDynamicProperty(mor, "summary"); // when String result = NetworkManager.getNetworkName(vmw, vmwInstance, 1); // then assertEquals("test", result); } @Test(expected = Exception.class) public void getNetworkName_exception() throws Exception { // given NetworkSummary summary = mock(NetworkSummary.class); List<ManagedObjectReference> mors = new ArrayList<ManagedObjectReference>(); mors.add(mor); doReturn(mors).when(moa).getDynamicProperty(vmwInstance, "network"); doReturn(null).when(moa).getDynamicProperty(mor, "name"); doReturn(summary).when(moa).getDynamicProperty(mor, "summary"); // when NetworkManager.getNetworkName(vmw, vmwInstance, 1); } @Test(expected = Exception.class) public void configureNetworkAdapter_differentNumbersOfNics() throws Exception { // given VirtualEthernetCard etc1 = new VirtualEthernetCard(); VirtualEthernetCard etc2 = new VirtualEthernetCard(); List<VirtualEthernetCard> etcs = new ArrayList<VirtualEthernetCard>(); etcs.add(etc1); etcs.add(etc2); PowerMockito.doReturn(etcs).when(NetworkManager.class, "getNetworkAdapter", vmci); doReturn(1).when(paramHandler).getServiceSetting(VMPropertyHandler.TS_NUMBER_OF_NICS); // when NetworkManager.configureNetworkAdapter(vmw, vmConfigSpec, paramHandler, vmwInstance); // then } @Test(expected = Exception.class) public void configureNetworkAdapter_portgroup_noSwitchSpecified() throws Exception { // given PortgroupIpSettings pis = mock(PortgroupIpSettings.class); Portgroup pg = mock(Portgroup.class); DistributedVirtualSwitch dvs = mock(DistributedVirtualSwitch.class); VirtualEthernetCard etc1 = new VirtualEthernetCard(); List<VirtualEthernetCard> etcs = new ArrayList<VirtualEthernetCard>(); etcs.add(etc1); PowerMockito.doReturn(etcs).when(NetworkManager.class, "getNetworkAdapter", vmci); PowerMockito.doReturn(pis) .when(NetworkManager.class, "createPortgroupIpSettings", paramHandler, 1); doReturn("1").when(paramHandler).getServiceSetting(VMPropertyHandler.TS_NUMBER_OF_NICS); doReturn("test").when(paramHandler).getNetworkAdapter(1); doReturn("test").when(paramHandler).getPortGroup(1); doReturn("test").when(paramHandler).getSwitchUUID(1); doReturn(pg).when(pis).getPortgroup(); doReturn(dvs).when(pis).getDvs(); doReturn("test").when(dvs).getUuid(); doReturn("").when(pg).getUuid(); // when NetworkManager.configureNetworkAdapter(vmw, vmConfigSpec, paramHandler, vmwInstance); // then } @Test public void configureNetworkAdapter_portgroup() throws Exception { // given PortgroupIpSettings pis = mock(PortgroupIpSettings.class); Portgroup pg = mock(Portgroup.class); DistributedVirtualSwitch dvs = mock(DistributedVirtualSwitch.class); VirtualDevice device = mock(VirtualDevice.class); VirtualEthernetCard etc1 = new VirtualEthernetCard(); List<VirtualEthernetCard> etcs = new ArrayList<VirtualEthernetCard>(); etcs.add(etc1); PowerMockito.doReturn(etcs).when(NetworkManager.class, "getNetworkAdapter", vmci); PowerMockito.doReturn(pis) .when(NetworkManager.class, "createPortgroupIpSettings", paramHandler, 1); PowerMockito.doReturn(mor) .when(NetworkManager.class, "getPortGroupFromHost", vmw, vmwInstance, etc1, "test", "test"); PowerMockito.doNothing() .when(NetworkManager.class, "replaceNetworkAdapter", vmConfigSpec, device, mor, "test"); doReturn("1").when(paramHandler).getServiceSetting(VMPropertyHandler.TS_NUMBER_OF_NICS); doReturn("test").when(paramHandler).getNetworkAdapter(1); doReturn("test").when(paramHandler).getPortGroup(1); doReturn("test").when(paramHandler).getSwitchUUID(1); doReturn(pg).when(pis).getPortgroup(); doReturn(dvs).when(pis).getDvs(); doReturn("test").when(dvs).getUuid(); doReturn("test").when(pg).getUuid(); // when NetworkManager.configureNetworkAdapter(vmw, vmConfigSpec, paramHandler, vmwInstance); // then PowerMockito.verifyStatic(VerificationModeFactory.times(1)); NetworkManager.replaceNetworkAdapter(any(), any(), any(), anyString()); } @Test public void configureNetworkAdapter_newNetworkName() throws Exception { // given VirtualDevice device = mock(VirtualDevice.class); VirtualEthernetCard etc1 = new VirtualEthernetCard(); List<VirtualEthernetCard> etcs = new ArrayList<VirtualEthernetCard>(); etcs.add(etc1); PowerMockito.doReturn(etcs).when(NetworkManager.class, "getNetworkAdapter", vmci); PowerMockito.doReturn(mor) .when(NetworkManager.class, "getNetworkFromHost", vmw, vmwInstance, etc1, "test"); PowerMockito.doReturn("test1") .when(NetworkManager.class, "getNetworkName", vmw, vmwInstance, 1); PowerMockito.doNothing() .when(NetworkManager.class, "replaceNetworkAdapter", vmConfigSpec, device, mor, "test"); doReturn("1").when(paramHandler).getServiceSetting(VMPropertyHandler.TS_NUMBER_OF_NICS); doReturn("test").when(paramHandler).getNetworkAdapter(1); doReturn("").when(paramHandler).getPortGroup(1); doReturn("").when(paramHandler).getSwitchUUID(1); // when NetworkManager.configureNetworkAdapter(vmw, vmConfigSpec, paramHandler, vmwInstance); // then PowerMockito.verifyStatic(VerificationModeFactory.times(1)); NetworkManager.replaceNetworkAdapter(any(), any(), any(), anyString()); } @Test public void configureNetworkAdapter() throws Exception { // given VirtualEthernetCard etc1 = new VirtualEthernetCard(); List<VirtualEthernetCard> etcs = new ArrayList<VirtualEthernetCard>(); etcs.add(etc1); PowerMockito.doReturn(etcs).when(NetworkManager.class, "getNetworkAdapter", vmci); PowerMockito.doReturn(mor) .when(NetworkManager.class, "getNetworkFromHost", vmw, vmwInstance, etc1, "test"); PowerMockito.doReturn("test").when(NetworkManager.class, "getNetworkName", vmw, vmwInstance, 1); PowerMockito.doNothing().when(NetworkManager.class, "connectNIC", vmConfigSpec, etc1); doReturn("1").when(paramHandler).getServiceSetting(VMPropertyHandler.TS_NUMBER_OF_NICS); doReturn("test").when(paramHandler).getNetworkAdapter(1); doReturn("").when(paramHandler).getPortGroup(1); doReturn("").when(paramHandler).getSwitchUUID(1); // when NetworkManager.configureNetworkAdapter(vmw, vmConfigSpec, paramHandler, vmwInstance); // then PowerMockito.verifyStatic(VerificationModeFactory.times(1)); NetworkManager.connectNIC(any(), any()); } @Test public void getPortGroupFromHost() throws Exception { // given VirtualEthernetCard etc = new VirtualEthernetCard(); List<ManagedObjectReference> moas = new ArrayList<ManagedObjectReference>(); moas.add(mor); VirtualDevice vd = new VirtualDevice(); ManagedObjectReference hostRef = mock(ManagedObjectReference.class); ManagedObjectReference sw = mock(ManagedObjectReference.class); VirtualMachineRuntimeInfo vmRuntimeInfo = mock(VirtualMachineRuntimeInfo.class); doReturn(moas).when(moa).getDynamicProperty(sw, "portgroup"); doReturn("key").when(moa).getDynamicProperty(mor, "key"); doReturn(vmRuntimeInfo).when(moa).getDynamicProperty(vmwInstance, "runtime"); doReturn(sw).when(vimPortType).queryDvsByUuid(any(), anyString()); doReturn(hostRef).when(vmRuntimeInfo).getHost(); PowerMockito.doReturn(vd).when(NetworkManager.class, "prepareDvNicDevice", etc, mor, "key"); // when NetworkManager.getPortGroupFromHost(vmw, vmwInstance, etc, "switch", "key"); // then PowerMockito.verifyStatic(VerificationModeFactory.times(1)); NetworkManager.prepareDvNicDevice(any(), any(), anyString()); } @Test(expected = Exception.class) public void getPortGroupFromHost_excpetion() throws Exception { // given VirtualEthernetCard etc = new VirtualEthernetCard(); List<ManagedObjectReference> moas = new ArrayList<ManagedObjectReference>(); moas.add(mor); VirtualDevice vd = new VirtualDevice(); ManagedObjectReference hostRef = mock(ManagedObjectReference.class); ManagedObjectReference sw = mock(ManagedObjectReference.class); VirtualMachineRuntimeInfo vmRuntimeInfo = mock(VirtualMachineRuntimeInfo.class); doReturn(moas).when(moa).getDynamicProperty(sw, "portgroup"); doReturn("key").when(moa).getDynamicProperty(mor, "key"); doReturn(vmRuntimeInfo).when(moa).getDynamicProperty(vmwInstance, "runtime"); doReturn(sw).when(vimPortType).queryDvsByUuid(any(), anyString()); doReturn(hostRef).when(vmRuntimeInfo).getHost(); PowerMockito.doReturn(vd).when(NetworkManager.class, "prepareDvNicDevice", etc, mor, "key"); // when NetworkManager.getPortGroupFromHost(vmw, vmwInstance, etc, "switch", "group"); } @Test public void getNetworkFromHost() throws Exception { // given VirtualEthernetCard etc = new VirtualEthernetCard(); List<ManagedObjectReference> networkRefList = new ArrayList<ManagedObjectReference>(); networkRefList.add(mor); VirtualMachineRuntimeInfo vmRuntimeInfo = mock(VirtualMachineRuntimeInfo.class); ManagedObjectReference hostRef = mock(ManagedObjectReference.class); doReturn(vmRuntimeInfo).when(moa).getDynamicProperty(vmwInstance, "runtime"); doReturn(networkRefList).when(moa).getDynamicProperty(hostRef, "network"); doReturn("test").when(moa).getDynamicProperty(mor, "name"); doReturn(hostRef).when(vmRuntimeInfo).getHost(); // when ManagedObjectReference result = NetworkManager.getNetworkFromHost(vmw, vmwInstance, etc, "test"); // then assertEquals(mor, result); } @Test(expected = Exception.class) public void getNetworkFromHost_exception() throws Exception { // given VirtualEthernetCard etc = new VirtualEthernetCard(); List<ManagedObjectReference> networkRefList = new ArrayList<ManagedObjectReference>(); networkRefList.add(mor); VirtualMachineRuntimeInfo vmRuntimeInfo = mock(VirtualMachineRuntimeInfo.class); ManagedObjectReference hostRef = mock(ManagedObjectReference.class); doReturn(vmRuntimeInfo).when(moa).getDynamicProperty(vmwInstance, "runtime"); doReturn(networkRefList).when(moa).getDynamicProperty(hostRef, "network"); doReturn("test1").when(moa).getDynamicProperty(mor, "name"); doReturn(hostRef).when(vmRuntimeInfo).getHost(); // when ManagedObjectReference result = NetworkManager.getNetworkFromHost(vmw, vmwInstance, etc, "test"); // then assertEquals(mor, result); } @Test public void prepareDvNicDevice() throws Exception { // given VirtualEthernetCard card = new VirtualEthernetCard(); VirtualEthernetCardDistributedVirtualPortBackingInfo dvPortBacking = new VirtualEthernetCardDistributedVirtualPortBackingInfo(); DistributedVirtualSwitchPortConnection dvPortConnection = new DistributedVirtualSwitchPortConnection(); PowerMockito.doReturn(dvPortBacking) .when(NetworkManager.class, "createVirtualEthernetCardDistributedVirtualPortBackingInfo"); PowerMockito.doReturn(dvPortConnection) .when(NetworkManager.class, "createDistributedVirtualSwitchPortConnection"); // when VirtualDevice result = NetworkManager.prepareDvNicDevice(card, mor, "uuid"); // then assertEquals(card, result); } @Test public void getNetworkAdapter() { // given VirtualHardware hardware = mock(VirtualHardware.class); List<VirtualDevice> devices = new ArrayList<VirtualDevice>(); VirtualEthernetCard card = new VirtualEthernetCard(); devices.add(card); doReturn(hardware).when(vmci).getHardware(); doReturn(devices).when(hardware).getDevice(); // when List<VirtualEthernetCard> expected = NetworkManager.getNetworkAdapter(vmci); // then assertEquals(card, expected.get(0)); } @Test public void replaceNetworkAdapter_portgroup() throws Exception { // given VirtualDevice oldNIC = mock(VirtualDevice.class); VirtualEthernetCardDistributedVirtualPortBackingInfo vdbi = mock(VirtualEthernetCardDistributedVirtualPortBackingInfo.class); VirtualEthernetCardDistributedVirtualPortBackingInfo dvPortBacking = new VirtualEthernetCardDistributedVirtualPortBackingInfo(); DistributedVirtualSwitchPortConnection dvPortConnection = mock(DistributedVirtualSwitchPortConnection.class); PowerMockito.doReturn(dvPortBacking) .when(NetworkManager.class, "createVirtualEthernetCardDistributedVirtualPortBackingInfo"); PowerMockito.doReturn(dvPortConnection) .when(NetworkManager.class, "createDistributedVirtualSwitchPortConnection"); doReturn(vdbi).when(oldNIC).getBacking(); doReturn(dvPortConnection).when(vdbi).getPort(); doReturn("portKey").when(dvPortConnection).getPortgroupKey(); doReturn("switchUUID").when(dvPortConnection).getSwitchUuid(); // when NetworkManager.replaceNetworkAdapter(vmConfigSpec, oldNIC, mor, "testNetwork"); // then PowerMockito.verifyStatic(VerificationModeFactory.times(1)); NetworkManager.connectNIC(any(), any()); } @Test public void replaceNetworkAdapter() throws Exception { // given VirtualDevice oldNIC = mock(VirtualDevice.class); VirtualDeviceBackingInfo vdbi = mock(VirtualDeviceBackingInfo.class); doReturn(vdbi).when(oldNIC).getBacking(); // when NetworkManager.replaceNetworkAdapter(vmConfigSpec, oldNIC, mor, "testNetwork"); // then PowerMockito.verifyStatic(VerificationModeFactory.times(1)); NetworkManager.connectNIC(any(), any()); } }
/* * %CopyrightBegin% * * Copyright Ericsson AB 2000-2016. 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. * * %CopyrightEnd% */ package erlang; /** * Provides a Java representation of Erlang booleans, which are special cases of * atoms with values 'true' and 'false'. */ public class OtpErlangBoolean extends OtpErlangAtom { // don't change this! static final long serialVersionUID = 1087178844844988393L; /** * Create a boolean from the given value * * @param t * the boolean value to represent as an atom. */ public OtpErlangBoolean(final boolean t) { super(t); } /** * Create a boolean from a stream containing an atom encoded in Erlang * external format. The value of the boolean will be true if the atom * represented by the stream is "true" without regard to case. For other * atom values, the boolean will have the value false. * * @exception OtpErlangDecodeException * if the buffer does not contain a valid external * representation of an Erlang atom. */ public OtpErlangBoolean(final OtpInputStream buf) throws OtpErlangDecodeException { super(buf); } }
package com.amadeus; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; public class AmadeusTest { /** * Amadeus Test. */ @Test public void testBuilder() { Amadeus.builder("id", "secret"); assertTrue(true, "should return a Configuration"); } @Test public void testBuilderWithNullClientId() { assertThrows(NullPointerException.class, () -> Amadeus.builder(null, "secret").build()); } @Test public void testBuilderWithNullClientSecret() { assertThrows(NullPointerException.class, () -> Amadeus.builder("client", null).build()); } @Test public void testBuilderWithEnvironment() { Map<String,String> environment = new HashMap<String,String>() { { put("AMADEUS_CLIENT_ID", "123"); put("AMADEUS_CLIENT_SECRET", "234"); put("AMADEUS_LOG_LEVEL", "debug"); put("AMADEUS_PORT", "123"); put("AMADEUS_HOST", "my.custom.host.com"); } }; Amadeus.builder(environment); assertTrue(true, "should return a Configuration"); Amadeus amadeus = Amadeus.builder(environment).build(); assertEquals(amadeus.getConfiguration().getLogLevel(), "debug"); assertEquals(amadeus.getConfiguration().getPort(), 123); assertEquals(amadeus.getConfiguration().getHost(), "my.custom.host.com"); } @Test public void testBuilderWithInvalidEnvironment() { //Given Map<String,String> environment = new HashMap<>(); //System.getenv(); environment.put("AMADEUS_CLIENT_ID", "MY_CLIENT_ID"); environment.put("AMADEUS_CLIENT_SECRET", "MY_CLIENT_SECRET"); //When boolean result = Amadeus.builder(environment).build() instanceof Amadeus; //Then assertTrue(result, "should return a Configuration"); } @Test public void testVersion() { assertEquals(Amadeus.VERSION, "5.9.0", "should have a version number"); } }
/* * Copyright 2016-2021 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.greengrass.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrass-2017-06-07/DisassociateRoleFromGroup" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DisassociateRoleFromGroupResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** The time, in milliseconds since the epoch, when the role was disassociated from the group. */ private String disassociatedAt; /** * The time, in milliseconds since the epoch, when the role was disassociated from the group. * * @param disassociatedAt * The time, in milliseconds since the epoch, when the role was disassociated from the group. */ public void setDisassociatedAt(String disassociatedAt) { this.disassociatedAt = disassociatedAt; } /** * The time, in milliseconds since the epoch, when the role was disassociated from the group. * * @return The time, in milliseconds since the epoch, when the role was disassociated from the group. */ public String getDisassociatedAt() { return this.disassociatedAt; } /** * The time, in milliseconds since the epoch, when the role was disassociated from the group. * * @param disassociatedAt * The time, in milliseconds since the epoch, when the role was disassociated from the group. * @return Returns a reference to this object so that method calls can be chained together. */ public DisassociateRoleFromGroupResult withDisassociatedAt(String disassociatedAt) { setDisassociatedAt(disassociatedAt); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getDisassociatedAt() != null) sb.append("DisassociatedAt: ").append(getDisassociatedAt()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DisassociateRoleFromGroupResult == false) return false; DisassociateRoleFromGroupResult other = (DisassociateRoleFromGroupResult) obj; if (other.getDisassociatedAt() == null ^ this.getDisassociatedAt() == null) return false; if (other.getDisassociatedAt() != null && other.getDisassociatedAt().equals(this.getDisassociatedAt()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getDisassociatedAt() == null) ? 0 : getDisassociatedAt().hashCode()); return hashCode; } @Override public DisassociateRoleFromGroupResult clone() { try { return (DisassociateRoleFromGroupResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
package downfall.monsters; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.MathUtils; import com.esotericsoftware.spine.AnimationState; import com.megacrit.cardcrawl.actions.AbstractGameAction; import com.megacrit.cardcrawl.actions.animations.VFXAction; import com.megacrit.cardcrawl.actions.common.*; import com.megacrit.cardcrawl.actions.unique.CanLoseAction; import com.megacrit.cardcrawl.cards.DamageInfo; import com.megacrit.cardcrawl.cards.colorless.PanicButton; import com.megacrit.cardcrawl.core.CardCrawlGame; import com.megacrit.cardcrawl.core.Settings; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.helpers.ImageMaster; import com.megacrit.cardcrawl.monsters.AbstractMonster; import com.megacrit.cardcrawl.powers.BarricadePower; import com.megacrit.cardcrawl.powers.NoBlockPower; import com.megacrit.cardcrawl.powers.StrengthPower; import com.megacrit.cardcrawl.vfx.combat.SmokeBombEffect; import downfall.actions.ForceWaitAction; import downfall.actions.MerchantThrowGoldAction; import downfall.downfallMod; import downfall.powers.SoulStealPower; import downfall.vfx.GainSingleSoulEffect; import downfall.vfx.SoulStealEffect; /* First Turn - Panic Button Second Turn - Throw Coins 2x5 Third Turn - Escape, gain 1 strength Strength and HP retains from fight to fight On death, gain 100 Souls, 1 random Cards, 1 colorless card, 1 random Relic, 1 Potion. Act 3 Event with a Shopkeeper boss using colorless cards, only if you killed him. Neow revives him. Bandage Up Blind Dramatic Entrance Good Instincts Panacea Panic Button Swift Strike Trip Apotheosis Hand of Greed Magnetism Mayhem Panache Sadistic Nature The Bomb Evil Mode villain cards */ public class FleeingMerchant extends AbstractMonster { public static final String ID = downfallMod.makeID("FleeingMerchant"); public static final String NAME = CardCrawlGame.languagePack.getUIString("RunHistoryPathNodes").TEXT[8]; public static final String[] DIALOG = { }; public static final String PANICBUTTONNAME = CardCrawlGame.languagePack.getCardStrings(PanicButton.ID).NAME; public static final String SOULSTEALNAME = CardCrawlGame.languagePack.getMonsterStrings(ID).MOVES[0]; public static final float DRAW_X = Settings.WIDTH * 0.5F + 34.0F * Settings.scale; public static final float DRAW_Y = AbstractDungeon.floorY - 109.0F * Settings.scale; private static final int START_HP = 400; public static int CURRENT_HP = 400; public static int CURRENT_STRENGTH = 0; public static int CURRENT_SOULS = 0; public static boolean DEAD = false; public static boolean ESCAPED = false; // Move bytes private static byte ATTACK = 0; private static byte DEFEND = 1; private static byte ESCAPE = 2; private static byte SOULSTEAL = 3; private int turn = 0; private boolean boss = false; public FleeingMerchant() { super(NAME, ID, START_HP, -10.0F, -30.0F, 180.0F, 150.0F, null, 0.0F, 0.0F); drawX = 1260.0F * Settings.scale; drawY = 370.0F * Settings.scale; loadAnimation("images/npcs/merchant/skeleton.atlas", "images/npcs/merchant/skeleton.json", 1.0F); AnimationState.TrackEntry e = state.setAnimation(0, "idle", true); e.setTime(e.getEndTime() * MathUtils.random()); e.setTimeScale(1.0F); type = EnemyType.NORMAL; dialogX = -200.0F * Settings.scale; dialogY = 10.0F * Settings.scale; gold = 100; halfDead = false; damage.add(new DamageInfo(this, 2)); setHp(400); this.currentHealth = CURRENT_HP; } @Override public void render(SpriteBatch sb) { if (!boss) { if (!isDeadOrEscaped() || AbstractDungeon.getCurrRoom().cannotLose) { sb.setColor(Color.WHITE); sb.draw(ImageMaster.MERCHANT_RUG_IMG, DRAW_X, DRAW_Y, 512.0F * Settings.scale, 512.0F * Settings.scale); } } super.render(sb); } @Override public void usePreBattleAction() { AbstractDungeon.getCurrRoom().eliteTrigger = true; //AbstractDungeon.getCurrRoom().cannotLose = true; AbstractDungeon.actionManager.addToBottom(new ApplyPowerAction(this, this, new BarricadePower(this))); //AbstractDungeon.actionManager.addToTop(new TalkAction(this, (abuse >= 3 ? DIALOG[2] : DIALOG[0]), 0.5F, 3.0F)); if (CURRENT_STRENGTH > 0) { AbstractDungeon.actionManager.addToBottom(new ApplyPowerAction(this, this, new StrengthPower(this, CURRENT_STRENGTH), CURRENT_STRENGTH)); } if (CURRENT_SOULS > 0) { this.addToBot(new ApplyPowerAction(this, this, new SoulStealPower(this, CURRENT_SOULS), CURRENT_SOULS)); } addToBot(new AbstractGameAction() { @Override public void update() { isDone = true; ESCAPED = false; } }); } @Override public void takeTurn() { if (nextMove == ESCAPE) { CURRENT_HP = this.currentHealth; AbstractDungeon.getCurrRoom().mugged = true; FleeingMerchant.ESCAPED = true; this.addToBot(new CanLoseAction()); this.addToBot(new VFXAction(new SmokeBombEffect(hb.cX, hb.cY))); this.addToBot(new EscapeAction(this)); this.addToBot(new SetMoveAction(this, ESCAPE, Intent.ESCAPE)); int roll = MathUtils.random(2); if (roll == 0) { CardCrawlGame.sound.play("VO_MERCHANT_KA"); } else if (roll == 1) { CardCrawlGame.sound.play("VO_MERCHANT_KB"); } else { CardCrawlGame.sound.play("VO_MERCHANT_KC"); } } else if (nextMove == ATTACK) { this.addToBot(new MerchantThrowGoldAction(AbstractDungeon.player, this, 5, false)); this.addToBot(new ForceWaitAction(1.6f)); for (int i = 0; i < 5; ++i) { this.addToBot(new DamageAction(AbstractDungeon.player, damage.get(0), true)); } int roll = MathUtils.random(2); if (roll == 0) { CardCrawlGame.sound.play("VO_MERCHANT_MA"); } else if (roll == 1) { CardCrawlGame.sound.play("VO_MERCHANT_MB"); } else { CardCrawlGame.sound.play("VO_MERCHANT_MC"); } } else if (nextMove == DEFEND) { this.addToBot(new GainBlockAction(this, this, 30)); this.addToBot(new ApplyPowerAction(this, this, new NoBlockPower(this, 1, true), 1)); int roll = MathUtils.random(2); if (roll == 0) { CardCrawlGame.sound.play("VO_MERCHANT_2A"); } else if (roll == 1) { CardCrawlGame.sound.play("VO_MERCHANT_2B"); } else { CardCrawlGame.sound.play("VO_MERCHANT_2C"); } } else if (nextMove == SOULSTEAL) { this.addToBot((new VFXAction(new SoulStealEffect(AbstractDungeon.player.hb.cX, AbstractDungeon.player.hb.cY, this.hb.cX, this.hb.cY), 0.5F))); this.addToBot(new ApplyPowerAction(this, this, new StrengthPower(this, 1), 1)); CURRENT_STRENGTH += 1; if (AbstractDungeon.player.gold >= 15) { this.addToBot(new ApplyPowerAction(this, this, new SoulStealPower(this, 15), 15)); CURRENT_SOULS += 15; } else { this.addToBot(new ApplyPowerAction(this, this, new SoulStealPower(this, AbstractDungeon.player.gold), AbstractDungeon.player.gold)); CURRENT_SOULS += AbstractDungeon.player.gold; } AbstractDungeon.player.gold -= Math.min(AbstractDungeon.player.gold, 15); int roll = MathUtils.random(2); if (roll == 0) { CardCrawlGame.sound.play("VO_MERCHANT_3A"); } else if (roll == 1) { CardCrawlGame.sound.play("VO_MERCHANT_3B"); } else { CardCrawlGame.sound.play("VO_MERCHANT_3C"); } } if (turn >= 0) { ++turn; } this.addToBot(new RollMoveAction(this)); } @Override protected void getMove(int num) { if (turn == 0) { setMove(PANICBUTTONNAME, DEFEND, Intent.DEFEND); return; } if (turn == 1) { setMove(ATTACK, Intent.ATTACK, ((DamageInfo) this.damage.get(0)).base, 5, true); return; } if (turn == 2) { setMove(SOULSTEALNAME, SOULSTEAL, Intent.BUFF); return; } if (turn == 3) { setMove(ESCAPE, Intent.ESCAPE); return; } } @Override public void die() { /* AbstractDungeon.getCurrRoom().rewardAllowed = false; AbstractDungeon.getCurrRoom().rewards.clear(); */ int increaseGold = 300; if (FleeingMerchant.CURRENT_SOULS > 0) increaseGold += FleeingMerchant.CURRENT_SOULS; AbstractDungeon.player.gainGold(increaseGold); CardCrawlGame.sound.playA("GOLD_JINGLE", -0.1F); CardCrawlGame.sound.playA("GOLD_JINGLE", .1F); for (int i = 0; i < increaseGold; i++) { AbstractDungeon.effectList.add(new GainSingleSoulEffect(this, this.hb.cX, this.hb.cY, AbstractDungeon.player.hb.cX, AbstractDungeon.player.hb.cY, true)); } super.die(); this.deathTimer += ((0.01F * increaseGold) - 1F); DEAD = true; helpDied = true; } @Override public void escape() { super.escape(); } public static boolean helpEscaped = false; public static boolean helpDied = false; @Override public void update() { super.update(); if (escaped && !ESCAPED) { ESCAPED = true; helpEscaped = true; } } /* @Override public void dispose() { AbstractDungeon.player.releaseCard(); AbstractDungeon.getCurrRoom().phase = AbstractRoom.RoomPhase.COMPLETE; //AbstractDungeon.combatRewardScreen.open(); if (DEAD) { AbstractDungeon.getCurrRoom().endBattle(); AbstractRoom tRoom = new HeartShopRoom(false); AbstractDungeon.currMapNode.setRoom(tRoom); AbstractDungeon.scene.nextRoom(tRoom); CardCrawlGame.fadeIn(1.5F); AbstractDungeon.rs = AbstractDungeon.RenderScene.NORMAL; tRoom.onPlayerEntry(); AbstractDungeon.player.hand.clear(); AbstractDungeon.player.drawPile.clear(); AbstractDungeon.player.limbo.clear(); AbstractDungeon.player.discardPile.clear(); AbstractDungeon.player.exhaustPile.clear(); AbstractDungeon.closeCurrentScreen(); } super.dispose(); } */ }
package io.sdb.model.base; import com.jfinal.plugin.activerecord.Model; import com.jfinal.plugin.activerecord.IBean; /** * Generated by JFinal, do not modify this file. */ @SuppressWarnings("serial") public abstract class BaseDeliveryCorp<M extends BaseDeliveryCorp<M>> extends Model<M> implements IBean { public void setCode(java.lang.String code) { set("code", code); } public java.lang.String getCode() { return getStr("code"); } public void setName(java.lang.String name) { set("name", name); } public java.lang.String getName() { return getStr("name"); } public void setUrl(java.lang.String url) { set("url", url); } public java.lang.String getUrl() { return getStr("url"); } }
/* * Copyright 2013 The Netty Project * * The Netty 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 io.netty.util.concurrent; import io.netty.util.internal.InternalThreadLocalMap; import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.StringUtil; import io.netty.util.internal.SystemPropertyUtil; import io.netty.util.internal.ThrowableUtil; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; import static io.netty.util.internal.ObjectUtil.checkNotNull; import static java.util.concurrent.TimeUnit.MILLISECONDS; public class DefaultPromise<V> extends AbstractFuture<V> implements Promise<V> { // 正常日志的日志句柄,InternalLogger是Netty内部封装的日志接口 private static final InternalLogger logger = InternalLoggerFactory.getInstance(DefaultPromise.class); // 任务拒绝执行时候的日志句柄 - Promise需要作为一个任务提交到线程中执行,如果任务拒绝则使用此日志句柄打印日志 private static final InternalLogger rejectedExecutionLogger = InternalLoggerFactory.getInstance(DefaultPromise.class.getName() + ".rejectedExecution"); // 监听器的最大栈深度,默认值为8,这个值是防止嵌套回调调用的时候栈深度过大导致内存溢出 private static final int MAX_LISTENER_STACK_DEPTH = Math.min(8, SystemPropertyUtil.getInt("io.netty.defaultPromise.maxListenerStackDepth", 8)); // 结果更新器,用于CAS更新结果result的值 @SuppressWarnings("rawtypes") private static final AtomicReferenceFieldUpdater<DefaultPromise, Object> RESULT_UPDATER = AtomicReferenceFieldUpdater.newUpdater(DefaultPromise.class, Object.class, "result"); // 用于填充result的值,当设置结果result传入null,Promise执行成功,用这个值去表示成功的结果 private static final Object SUCCESS = new Object(); // 用于填充result的值,表示Promise不能被取消 private static final Object UNCANCELLABLE = new Object(); // CancellationException实例的持有器,用于判断Promise取消状态和抛出CancellationException private static final CauseHolder CANCELLATION_CAUSE_HOLDER = new CauseHolder(ThrowableUtil.unknownStackTrace( new CancellationException(), DefaultPromise.class, "cancel(...)")); // CANCELLATION_CAUSE_HOLDER的异常栈信息元素数组 private static final StackTraceElement[] CANCELLATION_STACK = CANCELLATION_CAUSE_HOLDER.cause.getStackTrace(); private volatile Object result; private final EventExecutor executor; /** * One or more listeners. Can be a {@link GenericFutureListener} or a {@link DefaultFutureListeners}. * If {@code null}, it means either 1) no listeners were added yet or 2) all listeners were notified. * * Threading - synchronized(this). We must support adding listeners when there is no EventExecutor. * * 监听器集合,可能是单个GenericFutureListener实例或者DefaultFutureListeners */ private Object listeners; /** * Threading - synchronized(this). We are required to hold the monitor to use Java's underlying wait()/notifyAll(). */ private short waiters; /** * Threading - synchronized(this). We must prevent concurrent notification and FIFO listener notification if the * executor changes. * * 标记是否正在回调监听器 */ private boolean notifyingListeners; /** * Creates a new instance. * * It is preferable to use {@link EventExecutor#newPromise()} to create a new promise * * @param executor * the {@link EventExecutor} which is used to notify the promise once it is complete. * It is assumed this executor will protect against {@link StackOverflowError} exceptions. * The executor may be used to avoid {@link StackOverflowError} by executing a {@link Runnable} if the stack * depth exceeds a threshold. * * 构造函数依赖于EventExecutor * */ public DefaultPromise(EventExecutor executor) { this.executor = checkNotNull(executor, "executor"); } /** * See {@link #executor()} for expectations of the executor. */ protected DefaultPromise() { // only for subclasses executor = null; } @Override public Promise<V> setSuccess(V result) { if (setSuccess0(result)) { return this; } throw new IllegalStateException("complete already: " + this); } @Override public boolean trySuccess(V result) { return setSuccess0(result); } @Override public Promise<V> setFailure(Throwable cause) { if (setFailure0(cause)) { return this; } throw new IllegalStateException("complete already: " + this, cause); } @Override public boolean tryFailure(Throwable cause) { return setFailure0(cause); } @Override public boolean setUncancellable() { // 通过结果更新器CAS更新result为UNCANCELLABLE,期望旧值为null,更新值为UNCANCELLABLE属性,如果成功则返回true if (RESULT_UPDATER.compareAndSet(this, null, UNCANCELLABLE)) { return true; } Object result = this.result; return !isDone0(result) || !isCancelled0(result); } @Override public boolean isSuccess() { Object result = this.result; return result != null && result != UNCANCELLABLE && !(result instanceof CauseHolder); } @Override public boolean isCancellable() { // 是否可取消的,result为null说明Promise处于初始化状态尚未执行,则认为可以取消 return result == null; } private static final class LeanCancellationException extends CancellationException { private static final long serialVersionUID = 2794674970981187807L; @Override public Throwable fillInStackTrace() { setStackTrace(CANCELLATION_STACK); return this; } @Override public String toString() { return CancellationException.class.getName(); } } @Override public Throwable cause() { return cause0(result); } private Throwable cause0(Object result) { // result非CauseHolder类型,则直接返回null if (!(result instanceof CauseHolder)) { return null; } // 如果result为CANCELLATION_CAUSE_HOLDER(静态CancellationException的持有) if (result == CANCELLATION_CAUSE_HOLDER) { CancellationException ce = new LeanCancellationException(); // 如果CAS更新结果result为LeanCancellationException新实例则返回 if (RESULT_UPDATER.compareAndSet(this, CANCELLATION_CAUSE_HOLDER, new CauseHolder(ce))) { return ce; } result = this.result; } return ((CauseHolder) result).cause; } @Override public Promise<V> addListener(GenericFutureListener<? extends Future<? super V>> listener) { checkNotNull(listener, "listener"); // 加锁,锁定的对象是Promise实例自身 synchronized (this) { /** * 添加监听器 {@link #addListener0(GenericFutureListener)} */ addListener0(listener); } // 如果Promise实例已经执行完毕,则通知监听器进行回调 if (isDone()) { notifyListeners(); } return this; } @Override public Promise<V> addListeners(GenericFutureListener<? extends Future<? super V>>... listeners) { checkNotNull(listeners, "listeners"); synchronized (this) { // 遍历入参数组添加监听器,有空元素直接跳出 for (GenericFutureListener<? extends Future<? super V>> listener : listeners) { if (listener == null) { break; } addListener0(listener); } } // 如果Promise实例已经执行完毕,则通知监听器进行回调 if (isDone()) { /** * 通知监听者 {@link #notifyListeners()} */ notifyListeners(); } return this; } @Override public Promise<V> removeListener(final GenericFutureListener<? extends Future<? super V>> listener) { checkNotNull(listener, "listener"); synchronized (this) { removeListener0(listener); } return this; } @Override public Promise<V> removeListeners(final GenericFutureListener<? extends Future<? super V>>... listeners) { checkNotNull(listeners, "listeners"); synchronized (this) { for (GenericFutureListener<? extends Future<? super V>> listener : listeners) { if (listener == null) { break; } removeListener0(listener); } } return this; } @Override public Promise<V> await() throws InterruptedException { // 如果异常完成,直接返回。 if (isDone()) { return this; } // 线程中断, if (Thread.interrupted()) { throw new InterruptedException(toString()); } /** * 检查死循环, Netty 做的一个校验。 * 呼应了前面提到的一个坑,或者说注意点——不要用NIO线程执行 await或者sync 方法,会导致死锁,所以 Netty做了一个校验能及时抛出异常提醒用户: */ checkDeadLock(); // 加锁,加锁对象是当前Promise实例 synchronized (this) { while (!isDone()) { // 递增计数器(用于记录有多少个线程在等待该promise返回结果) incWaiters(); try { // 这里调用的是Object#wait()方法进行阻塞,如果线程被中断会抛出 InterruptedException wait(); } finally { // 递减计数器 decWaiters(); } } } return this; } @Override public Promise<V> awaitUninterruptibly() { // 如果Promise执行完毕,直接返回 if (isDone()) { return this; } // 死锁检测 checkDeadLock(); boolean interrupted = false; // 加锁,加锁对象是当前Promise实例 synchronized (this) { // 这里设置一个死循环,终止条件是isDone()为true while (!isDone()) { // 等待线程数加1 incWaiters(); try { // 这里调用的是Object#wait()方法进行阻塞,捕获了InterruptedException异常,如果抛出InterruptedException记录线程的中断状态到interrupted wait(); } catch (InterruptedException e) { // Interrupted while waiting. interrupted = true; } finally { // 解除阻塞后等待线程数减1 decWaiters(); } } } if (interrupted) { Thread.currentThread().interrupt(); } return this; } @Override public boolean await(long timeout, TimeUnit unit) throws InterruptedException { return await0(unit.toNanos(timeout), true); } @Override public boolean await(long timeoutMillis) throws InterruptedException { return await0(MILLISECONDS.toNanos(timeoutMillis), true); } @Override public boolean awaitUninterruptibly(long timeout, TimeUnit unit) { try { return await0(unit.toNanos(timeout), false); } catch (InterruptedException e) { // Should not be raised at all. throw new InternalError(); } } @Override public boolean awaitUninterruptibly(long timeoutMillis) { try { return await0(MILLISECONDS.toNanos(timeoutMillis), false); } catch (InterruptedException e) { // Should not be raised at all. throw new InternalError(); } } @SuppressWarnings("unchecked") @Override public V getNow() { Object result = this.result; if (result instanceof CauseHolder || result == SUCCESS || result == UNCANCELLABLE) { return null; } return (V) result; } @SuppressWarnings("unchecked") @Override public V get() throws InterruptedException, ExecutionException { Object result = this.result; if (!isDone0(result)) { await(); result = this.result; } if (result == SUCCESS || result == UNCANCELLABLE) { return null; } Throwable cause = cause0(result); if (cause == null) { return (V) result; } if (cause instanceof CancellationException) { throw (CancellationException) cause; } throw new ExecutionException(cause); } @SuppressWarnings("unchecked") @Override public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { Object result = this.result; if (!isDone0(result)) { if (!await(timeout, unit)) { throw new TimeoutException(); } result = this.result; } if (result == SUCCESS || result == UNCANCELLABLE) { return null; } Throwable cause = cause0(result); if (cause == null) { return (V) result; } if (cause instanceof CancellationException) { throw (CancellationException) cause; } throw new ExecutionException(cause); } /** * {@inheritDoc} * * @param mayInterruptIfRunning this value has no effect in this implementation. */ @Override public boolean cancel(boolean mayInterruptIfRunning) { if (RESULT_UPDATER.compareAndSet(this, null, CANCELLATION_CAUSE_HOLDER)) { if (checkNotifyWaiters()) { notifyListeners(); } return true; } return false; } @Override public boolean isCancelled() { return isCancelled0(result); } @Override public boolean isDone() { return isDone0(result); } @Override public Promise<V> sync() throws InterruptedException { /** * 阻塞等待 {@link #await()} */ await(); /** * 如果有异常则抛出 {@link #rethrowIfFailed()} */ rethrowIfFailed(); return this; } @Override public Promise<V> syncUninterruptibly() { /** * 同步永久阻塞等待 - 响应中断 {@link #awaitUninterruptibly()} */ awaitUninterruptibly(); // 塞等待解除,如果执行存在异常,则直接抛出 rethrowIfFailed(); return this; } @Override public String toString() { return toStringBuilder().toString(); } protected StringBuilder toStringBuilder() { StringBuilder buf = new StringBuilder(64) .append(StringUtil.simpleClassName(this)) .append('@') .append(Integer.toHexString(hashCode())); Object result = this.result; if (result == SUCCESS) { buf.append("(success)"); } else if (result == UNCANCELLABLE) { buf.append("(uncancellable)"); } else if (result instanceof CauseHolder) { buf.append("(failure: ") .append(((CauseHolder) result).cause) .append(')'); } else if (result != null) { buf.append("(success: ") .append(result) .append(')'); } else { buf.append("(incomplete)"); } return buf; } /** * Get the executor used to notify listeners when this promise is complete. * <p> * It is assumed this executor will protect against {@link StackOverflowError} exceptions. * The executor may be used to avoid {@link StackOverflowError} by executing a {@link Runnable} if the stack * depth exceeds a threshold. * @return The executor used to notify listeners when this promise is complete. */ protected EventExecutor executor() { return executor; } protected void checkDeadLock() { EventExecutor e = executor(); if (e != null && e.inEventLoop()) { throw new BlockingOperationException(toString()); } } /** * Notify a listener that a future has completed. * <p> * This method has a fixed depth of {@link #MAX_LISTENER_STACK_DEPTH} that will limit recursion to prevent * {@link StackOverflowError} and will stop notifying listeners added after this threshold is exceeded. * @param eventExecutor the executor to use to notify the listener {@code listener}. * @param future the future that is complete. * @param listener the listener to notify. */ protected static void notifyListener( EventExecutor eventExecutor, final Future<?> future, final GenericFutureListener<?> listener) { notifyListenerWithStackOverFlowProtection( checkNotNull(eventExecutor, "eventExecutor"), checkNotNull(future, "future"), checkNotNull(listener, "listener")); } private void notifyListeners() { EventExecutor executor = executor(); // 当前执行线程是事件循环线程,那么直接同步调用,简单来说就是调用notifyListeners()方法的线程和EventExecutor是同一个线程 if (executor.inEventLoop()) { // 下面的ThreadLocal和listenerStackDepth是调用栈深度保护相关 final InternalThreadLocalMap threadLocals = InternalThreadLocalMap.get(); final int stackDepth = threadLocals.futureListenerStackDepth(); if (stackDepth < MAX_LISTENER_STACK_DEPTH) { threadLocals.setFutureListenerStackDepth(stackDepth + 1); try { notifyListenersNow(); } finally { threadLocals.setFutureListenerStackDepth(stackDepth); } return; } } // 当前执行线程不是事件循环线程,则把notifyListenersNow()包装为Runnable实例放到EventExecutor中执行 safeExecute(executor, new Runnable() { @Override public void run() { notifyListenersNow(); } }); } /** * The logic in this method should be identical to {@link #notifyListeners()} but * cannot share code because the listener(s) cannot be cached for an instance of {@link DefaultPromise} since the * listener(s) may be changed and is protected by a synchronized operation. */ private static void notifyListenerWithStackOverFlowProtection(final EventExecutor executor, final Future<?> future, final GenericFutureListener<?> listener) { if (executor.inEventLoop()) { final InternalThreadLocalMap threadLocals = InternalThreadLocalMap.get(); final int stackDepth = threadLocals.futureListenerStackDepth(); if (stackDepth < MAX_LISTENER_STACK_DEPTH) { threadLocals.setFutureListenerStackDepth(stackDepth + 1); try { notifyListener0(future, listener); } finally { threadLocals.setFutureListenerStackDepth(stackDepth); } return; } } safeExecute(executor, new Runnable() { @Override public void run() { notifyListener0(future, listener); } }); } private void notifyListenersNow() { Object listeners; synchronized (this) { // Only proceed if there are listeners to notify and we are not already notifying listeners. if (notifyingListeners || this.listeners == null) { return; } notifyingListeners = true; listeners = this.listeners; this.listeners = null; } for (;;) { if (listeners instanceof DefaultFutureListeners) { notifyListeners0((DefaultFutureListeners) listeners); } else { notifyListener0(this, (GenericFutureListener<?>) listeners); } synchronized (this) { if (this.listeners == null) { // Nothing can throw from within this method, so setting notifyingListeners back to false does not // need to be in a finally block. notifyingListeners = false; return; } listeners = this.listeners; this.listeners = null; } } } private void notifyListeners0(DefaultFutureListeners listeners) { GenericFutureListener<?>[] a = listeners.listeners(); int size = listeners.size(); for (int i = 0; i < size; i ++) { notifyListener0(this, a[i]); } } @SuppressWarnings({ "unchecked", "rawtypes" }) private static void notifyListener0(Future future, GenericFutureListener l) { try { l.operationComplete(future); } catch (Throwable t) { if (logger.isWarnEnabled()) { logger.warn("An exception was thrown by " + l.getClass().getName() + ".operationComplete()", t); } } } private void addListener0(GenericFutureListener<? extends Future<? super V>> listener) { // 如果Promise实例持有listeners为null,则直接设置为入参listener if (listeners == null) { listeners = listener; } else if (listeners instanceof DefaultFutureListeners) { // 如果当前Promise实例持有listeners的是DefaultFutureListeners类型,则调用它的add()方法进行添加 ((DefaultFutureListeners) listeners).add(listener); } else { // 步入这里说明当前Promise实例持有listeners为单个GenericFutureListener实例,需要转换为DefaultFutureListeners实例 listeners = new DefaultFutureListeners((GenericFutureListener<?>) listeners, listener); } } private void removeListener0(GenericFutureListener<? extends Future<? super V>> listener) { if (listeners instanceof DefaultFutureListeners) { ((DefaultFutureListeners) listeners).remove(listener); } else if (listeners == listener) { listeners = null; } } private boolean setSuccess0(V result) { return setValue0(result == null ? SUCCESS : result); } private boolean setFailure0(Throwable cause) { return setValue0(new CauseHolder(checkNotNull(cause, "cause"))); } private boolean setValue0(Object objResult) { if (RESULT_UPDATER.compareAndSet(this, null, objResult) || RESULT_UPDATER.compareAndSet(this, UNCANCELLABLE, objResult)) { if (checkNotifyWaiters()) { notifyListeners(); } return true; } return false; } /** * Check if there are any waiters and if so notify these. * @return {@code true} if there are any listeners attached to the promise, {@code false} otherwise. */ private synchronized boolean checkNotifyWaiters() { if (waiters > 0) { notifyAll(); } return listeners != null; } private void incWaiters() { if (waiters == Short.MAX_VALUE) { throw new IllegalStateException("too many waiters: " + this); } ++waiters; } private void decWaiters() { --waiters; } private void rethrowIfFailed() { Throwable cause = cause(); if (cause == null) { return; } PlatformDependent.throwException(cause); } private boolean await0(long timeoutNanos, boolean interruptable) throws InterruptedException { if (isDone()) { return true; } // 如果超时时限小于0那么返回isDone()的结果 if (timeoutNanos <= 0) { return isDone(); } // 如果允许中断,当前线程的中断标志位为true,则抛出InterruptedException if (interruptable && Thread.interrupted()) { throw new InterruptedException(toString()); } // 死锁检查 checkDeadLock(); // 记录当前的纳秒时间戳 long startTime = System.nanoTime(); // 等待时间的长度 - 单位为纳秒 long waitTime = timeoutNanos; boolean interrupted = false; try { for (;;) { synchronized (this) { // 如果Promise执行完毕,直接返回true - 这一步是先验判断,命中了就不需要阻塞等待 if (isDone()) { return true; } incWaiters(); try { wait(waitTime / 1000000, (int) (waitTime % 1000000)); } catch (InterruptedException e) { if (interruptable) { throw e; } else { interrupted = true; } } finally { decWaiters(); } } if (isDone()) { return true; } else { waitTime = timeoutNanos - (System.nanoTime() - startTime); if (waitTime <= 0) { return isDone(); } } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } /** * Notify all progressive listeners. * <p> * No attempt is made to ensure notification order if multiple calls are made to this method before * the original invocation completes. * <p> * This will do an iteration over all listeners to get all of type {@link GenericProgressiveFutureListener}s. * @param progress the new progress. * @param total the total progress. */ @SuppressWarnings("unchecked") void notifyProgressiveListeners(final long progress, final long total) { final Object listeners = progressiveListeners(); if (listeners == null) { return; } final ProgressiveFuture<V> self = (ProgressiveFuture<V>) this; EventExecutor executor = executor(); if (executor.inEventLoop()) { if (listeners instanceof GenericProgressiveFutureListener[]) { notifyProgressiveListeners0( self, (GenericProgressiveFutureListener<?>[]) listeners, progress, total); } else { notifyProgressiveListener0( self, (GenericProgressiveFutureListener<ProgressiveFuture<V>>) listeners, progress, total); } } else { if (listeners instanceof GenericProgressiveFutureListener[]) { final GenericProgressiveFutureListener<?>[] array = (GenericProgressiveFutureListener<?>[]) listeners; safeExecute(executor, new Runnable() { @Override public void run() { notifyProgressiveListeners0(self, array, progress, total); } }); } else { final GenericProgressiveFutureListener<ProgressiveFuture<V>> l = (GenericProgressiveFutureListener<ProgressiveFuture<V>>) listeners; safeExecute(executor, new Runnable() { @Override public void run() { notifyProgressiveListener0(self, l, progress, total); } }); } } } /** * Returns a {@link GenericProgressiveFutureListener}, an array of {@link GenericProgressiveFutureListener}, or * {@code null}. */ private synchronized Object progressiveListeners() { Object listeners = this.listeners; if (listeners == null) { // No listeners added return null; } if (listeners instanceof DefaultFutureListeners) { // Copy DefaultFutureListeners into an array of listeners. DefaultFutureListeners dfl = (DefaultFutureListeners) listeners; int progressiveSize = dfl.progressiveSize(); switch (progressiveSize) { case 0: return null; case 1: for (GenericFutureListener<?> l: dfl.listeners()) { if (l instanceof GenericProgressiveFutureListener) { return l; } } return null; } GenericFutureListener<?>[] array = dfl.listeners(); GenericProgressiveFutureListener<?>[] copy = new GenericProgressiveFutureListener[progressiveSize]; for (int i = 0, j = 0; j < progressiveSize; i ++) { GenericFutureListener<?> l = array[i]; if (l instanceof GenericProgressiveFutureListener) { copy[j ++] = (GenericProgressiveFutureListener<?>) l; } } return copy; } else if (listeners instanceof GenericProgressiveFutureListener) { return listeners; } else { // Only one listener was added and it's not a progressive listener. return null; } } private static void notifyProgressiveListeners0( ProgressiveFuture<?> future, GenericProgressiveFutureListener<?>[] listeners, long progress, long total) { for (GenericProgressiveFutureListener<?> l: listeners) { if (l == null) { break; } notifyProgressiveListener0(future, l, progress, total); } } @SuppressWarnings({ "unchecked", "rawtypes" }) private static void notifyProgressiveListener0( ProgressiveFuture future, GenericProgressiveFutureListener l, long progress, long total) { try { l.operationProgressed(future, progress, total); } catch (Throwable t) { if (logger.isWarnEnabled()) { logger.warn("An exception was thrown by " + l.getClass().getName() + ".operationProgressed()", t); } } } private static boolean isCancelled0(Object result) { return result instanceof CauseHolder && ((CauseHolder) result).cause instanceof CancellationException; } private static boolean isDone0(Object result) { return result != null && result != UNCANCELLABLE; } private static final class CauseHolder { final Throwable cause; CauseHolder(Throwable cause) { this.cause = cause; } } private static void safeExecute(EventExecutor executor, Runnable task) { try { executor.execute(task); } catch (Throwable t) { rejectedExecutionLogger.error("Failed to submit a listener notification task. Event loop shut down?", t); } } }
// Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.engine.rendering.nui.layers.mainMenu; import org.terasology.engine.i18n.TranslationSystem; import org.terasology.engine.identity.storageServiceClient.IdentityConflict; import org.terasology.engine.identity.storageServiceClient.IdentityConflictSolution; import org.terasology.engine.identity.storageServiceClient.StorageServiceWorker; import org.terasology.engine.rendering.nui.NUIManager; public final class IdentityConflictHelper { private StorageServiceWorker storageServiceWorker; private NUIManager nuiManager; private TranslationSystem translationSystem; public IdentityConflictHelper(StorageServiceWorker storageServiceWorker, NUIManager nuiManager, TranslationSystem translationSystem) { this.storageServiceWorker = storageServiceWorker; this.nuiManager = nuiManager; this.translationSystem = translationSystem; } public void runSolver() { if (storageServiceWorker.hasConflictingIdentities()) { IdentityConflict conflict = storageServiceWorker.getNextConflict(); ThreeButtonPopup conflictPopup = nuiManager.pushScreen(ThreeButtonPopup.ASSET_URI, ThreeButtonPopup.class); String message = String.format(translationSystem.translate("${engine:menu#storage-service-conflict-message}"), conflict.getServerId(), conflict.getLocalId(), conflict.getRemoteId()); conflictPopup.setMessage(translationSystem.translate("${engine:menu#warning}"), message); conflictPopup.setLeftButton(translationSystem.translate("${engine:menu#storage-service-conflict-keep-local}"), () -> solveAndShowNext(IdentityConflictSolution.KEEP_LOCAL)); conflictPopup.setCenterButton(translationSystem.translate("${engine:menu#storage-service-conflict-keep-remote}"), () -> solveAndShowNext(IdentityConflictSolution.KEEP_REMOTE)); conflictPopup.setRightButton(translationSystem.translate("${engine:menu#storage-service-conflict-ignore}"), () -> solveAndShowNext(IdentityConflictSolution.IGNORE)); } } private void solveAndShowNext(IdentityConflictSolution solution) { storageServiceWorker.solveNextConflict(solution); runSolver(); } }
package cn.xxt.customwidget.thinkinginjava.collection.set_17_6; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; import java.util.TreeSet; /** * @Author zhq * @Date 2019-11-07-10:08 * @Description * @Email 1457453696@qq.com */ public class TypesForSets { static <T> Set<T> fill(Set<T> set, Class<T> type) { try { for (int i = 0; i < 10; i++) { set.add(type.getConstructor(int.class).newInstance(i)); } } catch (Exception e) { throw new RuntimeException(e); } return set; } static <T> void test(Set<T> set, Class<T> type) { fill(set, type); fill(set, type); fill(set, type); System.out.println(set); } public static void main(String[] args) { test(new HashSet<HashType>(), HashType.class); test(new LinkedHashSet<HashType>(), HashType.class); test(new TreeSet<TreeType>(), TreeType.class); test(new HashSet<SetType>(), SetType.class); test(new HashSet<TreeType>(), TreeType.class); test(new LinkedHashSet<SetType>(), SetType.class); test(new LinkedHashSet<TreeType>(), TreeType.class); try { test(new TreeSet<SetType>(), SetType.class); } catch (Exception e) { System.out.println(e.getMessage()); } try { test(new TreeSet<HashType>(), HashType.class); } catch (Exception e) { System.out.println(e.getMessage()); } } }
package p; //renaming A.m to fred class A{ int fred(int m){ return fred(fred(m)); } }
/* * Copyright (c) 2015 Markus Poeschl * * 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.poeschl.apps.tryandremove.utils; import android.app.Application; import android.content.SharedPreferences; import android.content.pm.PackageManager; import org.robolectric.Robolectric; import org.robolectric.shadows.ShadowPreferenceManager; import dagger.Module; import dagger.Provides; /** * Created by Markus Pöschl on 21.01.2015. */ @Module( library = true ) public class RobolectricModule { @RoboMock @Provides SharedPreferences provideSharedPreferences(@RoboMock Application application) { return ShadowPreferenceManager.getDefaultSharedPreferences(application.getApplicationContext()); } @RoboMock @Provides PackageManager providePackageManager() { return Robolectric.application.getPackageManager(); } @RoboMock @Provides Application providesApplication() { return Robolectric.application; } }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // 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: 2020.01.27 at 07:41:16 AM EST // package aero.aixm; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlValue; /** * <p>Java class for CodeVerticalReferenceType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="CodeVerticalReferenceType"> * &lt;simpleContent> * &lt;extension base="&lt;http://www.aixm.aero/schema/5.1>CodeVerticalReferenceBaseType"> * &lt;attribute name="nilReason" type="{http://www.opengis.net/gml/3.2}NilReasonEnumeration" /> * &lt;/extension> * &lt;/simpleContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "CodeVerticalReferenceType", propOrder = { "value" }) public class CodeVerticalReferenceType { @XmlValue protected String value; @XmlAttribute(name = "nilReason") protected String nilReason; /** * Gets the value of the value property. * * @return * possible object is * {@link String } * */ public String getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link String } * */ public void setValue(String value) { this.value = value; } public boolean isSetValue() { return (this.value!= null); } /** * Gets the value of the nilReason property. * * @return * possible object is * {@link String } * */ public String getNilReason() { return nilReason; } /** * Sets the value of the nilReason property. * * @param value * allowed object is * {@link String } * */ public void setNilReason(String value) { this.nilReason = value; } public boolean isSetNilReason() { return (this.nilReason!= null); } }
package com.novaventure.survivalessentials.registry.WeaponsAndTools.Knives; import net.minecraft.item.SwordItem; import net.minecraft.item.ToolMaterial; import static com.novaventure.survivalessentials.registry.Initializers.ItemGroups.EQUIPMENT_GROUP; public class GoldKnifeBase extends SwordItem { public GoldKnifeBase(ToolMaterial GoldToolMaterialKnife) { super(GoldToolMaterialKnife, 0, -3.0f, new Settings().group(EQUIPMENT_GROUP)); } }
/* * 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.cyclop.web.components.infodialog; import java.util.HashMap; import java.util.Map; import org.apache.wicket.AttributeModifier; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.IModel; import org.apache.wicket.util.template.PackageTextTemplate; import org.cyclop.web.common.JsTextTemplate; /** @author Maciej Miklas */ public class InfoDialog extends Panel { private final static JsTextTemplate INFO_JS = new JsTextTemplate(new PackageTextTemplate(InfoDialog.class, "infoDialog.js")); private WebMarkupContainer infoDialog; private final StringModel titleModel; private final StringModel messageModel; public InfoDialog(String id) { super(id); titleModel = new StringModel(); messageModel = new StringModel(); } @Override protected void onInitialize() { super.onInitialize(); infoDialog = new WebMarkupContainer("infoDialog"); infoDialog.setVisible(false); infoDialog.setOutputMarkupPlaceholderTag(true); infoDialog.add(new AttributeModifier("title", titleModel)); add(infoDialog); Label message = new Label("message", messageModel); infoDialog.add(message); } public void open(AjaxRequestTarget target, String linkNameToDisable, String title, String message) { titleModel.setObject(title); messageModel.setObject(message); infoDialog.setVisible(true); target.add(infoDialog); Map<String, String> jsVariables = new HashMap<>(); jsVariables.put("infoDialogId", "#" + infoDialog.getMarkupId()); jsVariables.put("linkNameToDisable", "#" + linkNameToDisable); String jsContent = INFO_JS.asString(jsVariables); target.appendJavaScript(jsContent); } private final static class StringModel implements IModel<String> { private String value = ""; @Override public String getObject() { return value; } @Override public void setObject(String object) { this.value = object; } @Override public void detach() { } } }
package org.apache.http.client; import org.apache.http.protocol.HttpContext; @Deprecated public abstract interface UserTokenHandler { public abstract Object getUserToken(HttpContext paramHttpContext); } /* Location: /Users/gaoht/Downloads/zirom/classes-dex2jar.jar!/org/apache/http/client/UserTokenHandler.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
package com.project.convertedCode.servlets.vendor.swiftmailer.swiftmailer.lib.dependency_maps; import com.runtimeconverter.runtime.includes.RuntimeIncludable; import com.runtimeconverter.runtime.includes.RuntimeConverterServlet; import com.runtimeconverter.runtime.RuntimeEnv; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.annotation.WebServlet; @WebServlet("/vendor/swiftmailer/swiftmailer/lib/dependency_maps/transport_deps.php") public class servlet_transport_deps_php extends RuntimeConverterServlet { protected final RuntimeIncludable getInclude() { return com.project .convertedCode .includes .vendor .swiftmailer .swiftmailer .lib .dependency_maps .file_transport_deps_php .instance; } protected final RuntimeEnv getRuntimeEnv( String httpRequestType, HttpServletRequest req, HttpServletResponse resp) { return new com.project.convertedCode.main.ConvertedProjectRuntimeEnv( req, resp, this.getInclude()); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.lorainelab.igb.data.model.action; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.StringProperty; import javafx.scene.Node; import javafx.scene.input.KeyCombination; /** * * @author dcnorris */ public interface IgbAction { ObjectProperty<KeyCombination> acceleratorProperty(); BooleanProperty disabledProperty(); KeyCombination getAccelerator(); Node getGraphic(); ObjectProperty<Node> graphicProperty(); boolean isDisabled(); void setAccelerator(KeyCombination value); void setDisabled(boolean value); void setGraphic(Node value); StringProperty textProperty(); String getText(); void setText(String value); }
/** * 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.camel.component.ribbon.processor; import java.util.Map; import java.util.concurrent.RejectedExecutionException; import com.netflix.client.config.IClientConfig; import com.netflix.client.config.IClientConfigKey; import com.netflix.loadbalancer.DummyPing; import com.netflix.loadbalancer.IPing; import com.netflix.loadbalancer.IRule; import com.netflix.loadbalancer.PollingServerListUpdater; import com.netflix.loadbalancer.RoundRobinRule; import com.netflix.loadbalancer.Server; import com.netflix.loadbalancer.ServerList; import com.netflix.loadbalancer.ServerListUpdater; import com.netflix.loadbalancer.ZoneAwareLoadBalancer; import org.apache.camel.AsyncCallback; import org.apache.camel.AsyncProcessor; import org.apache.camel.CamelContext; import org.apache.camel.CamelContextAware; import org.apache.camel.Exchange; import org.apache.camel.ExchangePattern; import org.apache.camel.Traceable; import org.apache.camel.component.ribbon.RibbonConfiguration; import org.apache.camel.impl.remote.DefaultServiceCallExpression; import org.apache.camel.impl.remote.ServiceCallConstants; import org.apache.camel.processor.SendDynamicProcessor; import org.apache.camel.spi.IdAware; import org.apache.camel.spi.ServiceCallServerListStrategy; import org.apache.camel.support.ServiceSupport; import org.apache.camel.util.AsyncProcessorHelper; import org.apache.camel.util.ServiceHelper; import org.apache.camel.util.StringHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Ribbon based implementation of the the ServiceCall EIP. */ public class RibbonServiceCallProcessor extends ServiceSupport implements AsyncProcessor, CamelContextAware, Traceable, IdAware { private static final Logger LOG = LoggerFactory.getLogger(RibbonServiceCallProcessor.class); private CamelContext camelContext; private String id; private final String name; private final String scheme; private final String contextPath; private final String uri; private final ExchangePattern exchangePattern; private final RibbonConfiguration configuration; private ServiceCallServerListStrategy<RibbonServer> serverListStrategy; private ZoneAwareLoadBalancer<RibbonServer> ribbonLoadBalancer; private IRule rule; private IPing ping; private final DefaultServiceCallExpression serviceCallExpression; private Map<String, String> ribbonClientConfig; private SendDynamicProcessor processor; public RibbonServiceCallProcessor(String name, String uri, String scheme, ExchangePattern exchangePattern, RibbonConfiguration configuration) { // setup from the provided name which can contain scheme and context-path information as well String serviceName; if (name.contains("/")) { serviceName = StringHelper.before(name, "/"); this.contextPath = StringHelper.after(name, "/"); } else if (name.contains("?")) { serviceName = StringHelper.before(name, "?"); this.contextPath = StringHelper.after(name, "?"); } else { serviceName = name; this.contextPath = null; } if (serviceName.contains(":")) { this.scheme = StringHelper.before(serviceName, ":"); this.name = StringHelper.after(serviceName, ":"); } else { this.scheme = scheme; this.name = serviceName; } this.uri = uri; this.exchangePattern = exchangePattern; this.configuration = configuration; this.rule = configuration.getRule(); this.ping = configuration.getPing(); this.serviceCallExpression = new DefaultServiceCallExpression(this.name, this.scheme, this.contextPath, this.uri); } @Override public void process(Exchange exchange) throws Exception { AsyncProcessorHelper.process(this, exchange); } @Override public boolean process(Exchange exchange, AsyncCallback callback) { Server server = null; try { // let the client load balancer chose which server to use server = ribbonLoadBalancer.chooseServer(); if (server == null) { exchange.setException(new RejectedExecutionException("No active services with name " + name)); } } catch (Throwable e) { exchange.setException(e); } if (exchange.getException() != null) { callback.done(true); return true; } String ip = server.getHost(); int port = server.getPort(); LOG.debug("Service {} active at server: {}:{}", name, ip, port); // set selected server as header exchange.getIn().setHeader(ServiceCallConstants.SERVER_IP, ip); exchange.getIn().setHeader(ServiceCallConstants.SERVER_PORT, port); exchange.getIn().setHeader(ServiceCallConstants.SERVICE_NAME, name); // use the dynamic send processor to call the service return processor.process(exchange, callback); } @Override public CamelContext getCamelContext() { return camelContext; } @Override public void setCamelContext(CamelContext camelContext) { this.camelContext = camelContext; } @Override public String getId() { return id; } @Override public void setId(String id) { this.id = id; } @Override public String getTraceLabel() { return "kubernetes"; } public ServiceCallServerListStrategy getServerListStrategy() { return serverListStrategy; } public void setServerListStrategy(ServiceCallServerListStrategy serverListStrategy) { this.serverListStrategy = serverListStrategy; } public IRule getRule() { return rule; } public void setRule(IRule rule) { this.rule = rule; } public IPing getPing() { return ping; } public void setPing(IPing ping) { this.ping = ping; } public Map<String, String> getRibbonClientConfig() { return ribbonClientConfig; } public void setRibbonClientConfig(Map<String, String> ribbonClientConfig) { this.ribbonClientConfig = ribbonClientConfig; } @Override @SuppressWarnings("unchecked") protected void doStart() throws Exception { StringHelper.notEmpty(name, "name", this); if (serverListStrategy == null) { serverListStrategy = new RibbonServiceCallStaticServerListStrategy(); } if (!(serverListStrategy instanceof ServerList)) { throw new IllegalArgumentException("ServerListStrategy must be instanceof com.netflix.loadbalancer.ServerList but is of type: " + serverListStrategy.getClass().getName()); } if (rule == null) { // use round robin rule by default rule = new RoundRobinRule(); } if (ping == null) { // use dummy ping by default ping = new DummyPing(); } // setup client config IClientConfig config = IClientConfig.Builder.newBuilder(name).build(); if (ribbonClientConfig != null) { for (Map.Entry<String, String> entry : ribbonClientConfig.entrySet()) { IClientConfigKey key = IClientConfigKey.Keys.valueOf(entry.getKey()); String value = entry.getValue(); LOG.debug("RibbonClientConfig: {}={}", key.key(), value); config.set(key, entry.getValue()); } } ServerListUpdater updater = new PollingServerListUpdater(config); ribbonLoadBalancer = new ZoneAwareLoadBalancer<>(config, rule, ping, (ServerList<RibbonServer>) serverListStrategy, null, updater); LOG.info("RibbonServiceCall with service name: {} is using load balancer: {} and server list: {}", name, ribbonLoadBalancer, serverListStrategy); processor = new SendDynamicProcessor(uri, serviceCallExpression); processor.setCamelContext(getCamelContext()); if (exchangePattern != null) { processor.setPattern(exchangePattern); } ServiceHelper.startServices(serverListStrategy, processor); } @Override protected void doStop() throws Exception { ServiceHelper.stopServices(processor, serverListStrategy); } }
/* * Copyright 2002-2016 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.web.reactive.result.method.annotation; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.CompletableFuture; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import org.junit.Test; import org.reactivestreams.Publisher; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import rx.Completable; import rx.Observable; import rx.Single; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.core.ParameterizedTypeReference; import org.springframework.core.ResolvableType; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DataBufferFactory; import org.springframework.core.io.buffer.DefaultDataBufferFactory; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.codec.json.Jackson2JsonEncoder; import org.springframework.http.server.reactive.ZeroCopyIntegrationTests; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.reactive.config.WebReactiveConfiguration; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.springframework.http.MediaType.APPLICATION_XML; /** * {@code @RequestMapping} integration tests focusing on serialization and * deserialization of the request and response body. * * @author Rossen Stoyanchev * @author Sebastien Deleuze */ public class RequestMappingMessageConversionIntegrationTests extends AbstractRequestMappingIntegrationTests { private static final ParameterizedTypeReference<List<Person>> PERSON_LIST = new ParameterizedTypeReference<List<Person>>() {}; private static final MediaType JSON = MediaType.APPLICATION_JSON; @Override protected ApplicationContext initApplicationContext() { AnnotationConfigApplicationContext wac = new AnnotationConfigApplicationContext(); wac.register(WebConfig.class); wac.refresh(); return wac; } @Test public void byteBufferResponseBodyWithPublisher() throws Exception { Person expected = new Person("Robert"); assertEquals(expected, performGet("/raw-response/publisher", JSON, Person.class).getBody()); } @Test public void byteBufferResponseBodyWithFlux() throws Exception { String expected = "Hello!"; assertEquals(expected, performGet("/raw-response/flux", null, String.class).getBody()); } @Test public void byteBufferResponseBodyWithObservable() throws Exception { String expected = "Hello!"; assertEquals(expected, performGet("/raw-response/observable", null, String.class).getBody()); } @Test public void personResponseBody() throws Exception { Person expected = new Person("Robert"); assertEquals(expected, performGet("/person-response/person", JSON, Person.class).getBody()); } @Test public void personResponseBodyWithCompletableFuture() throws Exception { Person expected = new Person("Robert"); assertEquals(expected, performGet("/person-response/completable-future", JSON, Person.class).getBody()); } @Test public void personResponseBodyWithMono() throws Exception { Person expected = new Person("Robert"); assertEquals(expected, performGet("/person-response/mono", JSON, Person.class).getBody()); } @Test public void personResponseBodyWithSingle() throws Exception { Person expected = new Person("Robert"); assertEquals(expected, performGet("/person-response/single", JSON, Person.class).getBody()); } @Test public void personResponseBodyWithMonoResponseEntity() throws Exception { Person expected = new Person("Robert"); assertEquals(expected, performGet("/person-response/mono-response-entity", JSON, Person.class).getBody()); } @Test public void personResponseBodyWithList() throws Exception { List<?> expected = asList(new Person("Robert"), new Person("Marie")); assertEquals(expected, performGet("/person-response/list", JSON, PERSON_LIST).getBody()); } @Test public void personResponseBodyWithPublisher() throws Exception { List<?> expected = asList(new Person("Robert"), new Person("Marie")); assertEquals(expected, performGet("/person-response/publisher", JSON, PERSON_LIST).getBody()); } @Test public void personResponseBodyWithFlux() throws Exception { List<?> expected = asList(new Person("Robert"), new Person("Marie")); assertEquals(expected, performGet("/person-response/flux", JSON, PERSON_LIST).getBody()); } @Test public void personResponseBodyWithObservable() throws Exception { List<?> expected = asList(new Person("Robert"), new Person("Marie")); assertEquals(expected, performGet("/person-response/observable", JSON, PERSON_LIST).getBody()); } @Test public void resource() throws Exception { ResponseEntity<byte[]> response = performGet("/resource", null, byte[].class); assertEquals(HttpStatus.OK, response.getStatusCode()); assertTrue(response.hasBody()); assertEquals(951, response.getHeaders().getContentLength()); assertEquals(951, response.getBody().length); assertEquals(new MediaType("image", "x-png"), response.getHeaders().getContentType()); } @Test public void personTransform() throws Exception { assertEquals(new Person("ROBERT"), performPost("/person-transform/person", JSON, new Person("Robert"), JSON, Person.class).getBody()); } @Test public void personTransformWithCompletableFuture() throws Exception { assertEquals(new Person("ROBERT"), performPost("/person-transform/completable-future", JSON, new Person("Robert"), JSON, Person.class).getBody()); } @Test public void personTransformWithMono() throws Exception { assertEquals(new Person("ROBERT"), performPost("/person-transform/mono", JSON, new Person("Robert"), JSON, Person.class).getBody()); } @Test public void personTransformWithSingle() throws Exception { assertEquals(new Person("ROBERT"), performPost("/person-transform/single", JSON, new Person("Robert"), JSON, Person.class).getBody()); } @Test public void personTransformWithPublisher() throws Exception { List<?> req = asList(new Person("Robert"), new Person("Marie")); List<?> res = asList(new Person("ROBERT"), new Person("MARIE")); assertEquals(res, performPost("/person-transform/publisher", JSON, req, JSON, PERSON_LIST).getBody()); } @Test public void personTransformWithFlux() throws Exception { List<?> req = asList(new Person("Robert"), new Person("Marie")); List<?> res = asList(new Person("ROBERT"), new Person("MARIE")); assertEquals(res, performPost("/person-transform/flux", JSON, req, JSON, PERSON_LIST).getBody()); } @Test public void personTransformWithObservable() throws Exception { List<?> req = asList(new Person("Robert"), new Person("Marie")); List<?> res = asList(new Person("ROBERT"), new Person("MARIE")); assertEquals(res, performPost("/person-transform/observable", JSON, req, JSON, PERSON_LIST).getBody()); } @Test public void personCreateWithPublisherJson() throws Exception { ResponseEntity<Void> entity = performPost("/person-create/publisher", JSON, asList(new Person("Robert"), new Person("Marie")), null, Void.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertEquals(2, getApplicationContext().getBean(PersonCreateController.class).persons.size()); } @Test public void personCreateWithPublisherXml() throws Exception { People people = new People(new Person("Robert"), new Person("Marie")); ResponseEntity<Void> response = performPost("/person-create/publisher", APPLICATION_XML, people, null, Void.class); assertEquals(HttpStatus.OK, response.getStatusCode()); assertEquals(2, getApplicationContext().getBean(PersonCreateController.class).persons.size()); } @Test public void personCreateWithMono() throws Exception { ResponseEntity<Void> entity = performPost( "/person-create/mono", JSON, new Person("Robert"), null, Void.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertEquals(1, getApplicationContext().getBean(PersonCreateController.class).persons.size()); } @Test public void personCreateWithSingle() throws Exception { ResponseEntity<Void> entity = performPost( "/person-create/single", JSON, new Person("Robert"), null, Void.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertEquals(1, getApplicationContext().getBean(PersonCreateController.class).persons.size()); } @Test public void personCreateWithFluxJson() throws Exception { ResponseEntity<Void> entity = performPost("/person-create/flux", JSON, asList(new Person("Robert"), new Person("Marie")), null, Void.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertEquals(2, getApplicationContext().getBean(PersonCreateController.class).persons.size()); } @Test public void personCreateWithFluxXml() throws Exception { People people = new People(new Person("Robert"), new Person("Marie")); ResponseEntity<Void> response = performPost("/person-create/flux", APPLICATION_XML, people, null, Void.class); assertEquals(HttpStatus.OK, response.getStatusCode()); assertEquals(2, getApplicationContext().getBean(PersonCreateController.class).persons.size()); } @Test public void personCreateWithObservableJson() throws Exception { ResponseEntity<Void> entity = performPost("/person-create/observable", JSON, asList(new Person("Robert"), new Person("Marie")), null, Void.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertEquals(2, getApplicationContext().getBean(PersonCreateController.class).persons.size()); } @Test public void personCreateWithObservableXml() throws Exception { People people = new People(new Person("Robert"), new Person("Marie")); ResponseEntity<Void> response = performPost("/person-create/observable", APPLICATION_XML, people, null, Void.class); assertEquals(HttpStatus.OK, response.getStatusCode()); assertEquals(2, getApplicationContext().getBean(PersonCreateController.class).persons.size()); } @Configuration @ComponentScan(resourcePattern = "**/RequestMappingMessageConversionIntegrationTests$*.class") @SuppressWarnings({"unused", "WeakerAccess"}) static class WebConfig extends WebReactiveConfiguration { } @RestController @RequestMapping("/raw-response") @SuppressWarnings("unused") private static class RawResponseBodyController { @GetMapping("/publisher") public Publisher<ByteBuffer> getPublisher() { DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory(); Jackson2JsonEncoder encoder = new Jackson2JsonEncoder(); return encoder.encode(Mono.just(new Person("Robert")), dataBufferFactory, ResolvableType.forClass(Person.class), JSON).map(DataBuffer::asByteBuffer); } @GetMapping("/flux") public Flux<ByteBuffer> getFlux() { return Flux.just(ByteBuffer.wrap("Hello!".getBytes())); } @GetMapping("/observable") public Observable<ByteBuffer> getObservable() { return Observable.just(ByteBuffer.wrap("Hello!".getBytes())); } } @RestController @RequestMapping("/person-response") @SuppressWarnings("unused") private static class PersonResponseBodyController { @GetMapping("/person") public Person getPerson() { return new Person("Robert"); } @GetMapping("/completable-future") public CompletableFuture<Person> getCompletableFuture() { return CompletableFuture.completedFuture(new Person("Robert")); } @GetMapping("/mono") public Mono<Person> getMono() { return Mono.just(new Person("Robert")); } @GetMapping("/single") public Single<Person> getSingle() { return Single.just(new Person("Robert")); } @GetMapping("/mono-response-entity") public ResponseEntity<Mono<Person>> getMonoResponseEntity() { Mono<Person> body = Mono.just(new Person("Robert")); return ResponseEntity.ok(body); } @GetMapping("/list") public List<Person> getList() { return asList(new Person("Robert"), new Person("Marie")); } @GetMapping("/publisher") public Publisher<Person> getPublisher() { return Flux.just(new Person("Robert"), new Person("Marie")); } @GetMapping("/flux") public Flux<Person> getFlux() { return Flux.just(new Person("Robert"), new Person("Marie")); } @GetMapping("/observable") public Observable<Person> getObservable() { return Observable.just(new Person("Robert"), new Person("Marie")); } } @RestController @SuppressWarnings("unused") private static class ResourceController { @GetMapping("/resource") public Resource resource() { return new ClassPathResource("spring.png", ZeroCopyIntegrationTests.class); } } @RestController @RequestMapping("/person-transform") @SuppressWarnings("unused") private static class PersonTransformationController { @PostMapping("/person") public Person transformPerson(@RequestBody Person person) { return new Person(person.getName().toUpperCase()); } @PostMapping("/completable-future") public CompletableFuture<Person> transformCompletableFuture( @RequestBody CompletableFuture<Person> personFuture) { return personFuture.thenApply(person -> new Person(person.getName().toUpperCase())); } @PostMapping("/mono") public Mono<Person> transformMono(@RequestBody Mono<Person> personFuture) { return personFuture.map(person -> new Person(person.getName().toUpperCase())); } @PostMapping("/single") public Single<Person> transformSingle(@RequestBody Single<Person> personFuture) { return personFuture.map(person -> new Person(person.getName().toUpperCase())); } @PostMapping("/publisher") public Publisher<Person> transformPublisher(@RequestBody Publisher<Person> persons) { return Flux .from(persons) .map(person -> new Person(person.getName().toUpperCase())); } @PostMapping("/flux") public Flux<Person> transformFlux(@RequestBody Flux<Person> persons) { return persons.map(person -> new Person(person.getName().toUpperCase())); } @PostMapping("/observable") public Observable<Person> transformObservable(@RequestBody Observable<Person> persons) { return persons.map(person -> new Person(person.getName().toUpperCase())); } } @RestController @RequestMapping("/person-create") @SuppressWarnings("unused") private static class PersonCreateController { final List<Person> persons = new ArrayList<>(); @PostMapping("/publisher") public Publisher<Void> createWithPublisher(@RequestBody Publisher<Person> publisher) { return Flux.from(publisher).doOnNext(persons::add).then(); } @PostMapping("/mono") public Mono<Void> createWithMono(@RequestBody Mono<Person> mono) { return mono.doOnNext(persons::add).then(); } @PostMapping("/single") public Completable createWithSingle(@RequestBody Single<Person> single) { return single.map(persons::add).toCompletable(); } @PostMapping("/flux") public Mono<Void> createWithFlux(@RequestBody Flux<Person> flux) { return flux.doOnNext(persons::add).then(); } @PostMapping("/observable") public Observable<Void> createWithObservable(@RequestBody Observable<Person> observable) { return observable.toList().doOnNext(persons::addAll).flatMap(document -> Observable.empty()); } } @XmlRootElement @SuppressWarnings("WeakerAccess") private static class Person { private String name; @SuppressWarnings("unused") public Person() { } public Person(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Person person = (Person) o; return !(this.name != null ? !this.name.equals(person.name) : person.name != null); } @Override public int hashCode() { return this.name != null ? this.name.hashCode() : 0; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + '}'; } } @XmlRootElement @SuppressWarnings({"WeakerAccess", "unused"}) private static class People { private List<Person> persons = new ArrayList<>(); public People() { } public People(Person... persons) { this.persons.addAll(Arrays.asList(persons)); } @XmlElement public List<Person> getPerson() { return this.persons; } } }
/* * Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of NVIDIA CORPORATION nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.nvidia.grcuda.functions; import com.nvidia.grcuda.gpu.CUDARuntime; import com.oracle.truffle.api.interop.InteropException; public class ExternalFunctionFactory { private final String name; private final String symbolName; private final String namespace; private final String nfiSignature; public ExternalFunctionFactory(String name, String namespace, String symbolName, String nfiSignature) { this.name = name; this.namespace = namespace; this.symbolName = symbolName; this.nfiSignature = nfiSignature; } public String getName() { return name; } public String getNamespace() { return namespace; } public String getSymbolName() { return symbolName; } public String getNFISignature() { return nfiSignature; } public ExternalFunction makeFunction(CUDARuntime cudaRuntime, String libraryPath) { try { return new ExternalFunction(name, namespace, cudaRuntime.getSymbol(libraryPath, symbolName, nfiSignature)); } catch (InteropException e) { throw new RuntimeException(e); } } }
/* * Copyright 2002-2016 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.beans.propertyeditors; import java.io.Reader; import org.junit.Test; import org.springframework.util.ClassUtils; import static org.junit.Assert.*; /** * Unit tests for the {@link ReaderEditor} class. * * @author Juergen Hoeller * @since 4.2 */ public class ReaderEditorTests { @Test(expected = IllegalArgumentException.class) public void testCtorWithNullResourceEditor() throws Exception { new ReaderEditor(null); } @Test public void testSunnyDay() throws Exception { Reader reader = null; try { String resource = "classpath:" + ClassUtils.classPackageAsResourcePath(getClass()) + "/" + ClassUtils.getShortName(getClass()) + ".class"; ReaderEditor editor = new ReaderEditor(); editor.setAsText(resource); Object value = editor.getValue(); assertNotNull(value); assertTrue(value instanceof Reader); reader = (Reader) value; assertTrue(reader.ready()); } finally { if (reader != null) { reader.close(); } } } @Test(expected = IllegalArgumentException.class) public void testWhenResourceDoesNotExist() throws Exception { String resource = "classpath:bingo!"; ReaderEditor editor = new ReaderEditor(); editor.setAsText(resource); } @Test public void testGetAsTextReturnsNullByDefault() throws Exception { assertNull(new ReaderEditor().getAsText()); String resource = "classpath:" + ClassUtils.classPackageAsResourcePath(getClass()) + "/" + ClassUtils.getShortName(getClass()) + ".class"; ReaderEditor editor = new ReaderEditor(); editor.setAsText(resource); assertNull(editor.getAsText()); } }
// Copyright 2015 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.google.devtools.build.android.ziputils; import com.google.common.base.Preconditions; import java.util.Collection; import java.util.HashMap; import java.util.Map; class Splitter { private static final String ARCHIVE_FILE_SEPARATOR = "/"; private final int numberOfShards; private final Map<String, Integer> assigned; private int size = 0; private int shard = 0; private String currPath = null; private int remaining; private int idealSize; private int almostFull; /** * Creates a splitter for splitting an expected number of entries into * a given number of shards. The current shard is shard 0. */ public Splitter(int numberOfShards, int expectedSize) { this.numberOfShards = numberOfShards; this.remaining = expectedSize; this.assigned = new HashMap<>(); idealSize = remaining / (numberOfShards - shard); // Before you change this, please do the math. // It's not always perfect, but designed to keep shards reasonably balanced in most cases. int limit = Math.min(Math.min(10, (idealSize + 3) / 4), (int) Math.log(numberOfShards)); almostFull = idealSize - limit; } /** * Forces mapping of the given entries to be that of the current shard. * The estimated number of remaining entries to process is adjusted, * by subtracting the number of as-of-yet unassigned entries from the * filter. */ public void assign(Collection<String> filter) { if (filter != null) { for (String s : filter) { if (!assigned.containsKey(s)) { remaining--; } assigned.put(s, shard); } size = filter.size(); } } /** * Forces increment of the current shard. May be called externally. * Typically right after calling {@link #assign(java.util.Collection)}. */ public void nextShard() { if (shard < numberOfShards - 1) { shard++; size = 0; addEntries(0); } } /** * Adjusts the number of estimated entries to be process by the given count. */ public void addEntries(int count) { this.remaining += count; idealSize = numberOfShards > shard ? remaining / (numberOfShards - shard) : remaining; // Before you change this, please do the math. // It's not always perfect, but designed to keep shards reasonably balanced in most cases. int limit = Math.min(Math.min(10, (idealSize + 3) / 4), (int) Math.log(numberOfShards)); almostFull = idealSize - limit; } /** * Assigns the given entry to an output file. */ public int assign(String path) { Preconditions.checkState(shard < numberOfShards, "Too many shards!"); Integer assignment = assigned.get(path); if (assignment != null) { return assignment; } remaining--; // last shard, no choice if (shard == numberOfShards - 1) { size++; assigned.put(currPath, shard); return shard; } // Forced split to try to avoid empty shards if (remaining < numberOfShards - shard - 1) { if (size > 0) { nextShard(); } size++; assigned.put(currPath, shard); return shard; } String prevPath = currPath; currPath = path; // If current shard is at least "almost full", check for package boundary? if (prevPath != null && size >= almostFull) { int i = currPath.lastIndexOf(ARCHIVE_FILE_SEPARATOR); String dir = i > 0 ? currPath.substring(0, i) : "."; i = prevPath.lastIndexOf(ARCHIVE_FILE_SEPARATOR); String prevDir = i > 0 ? prevPath.substring(0, i) : "."; if (!dir.equals(prevDir)) { nextShard(); } } assigned.put(currPath, shard); size++; return shard; } }
package cn.delei.distributed.lock.jedis; import cn.delei.util.PrintUtil; import cn.hutool.core.lang.Assert; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * Application 入口 * * @author deleiguo */ @SpringBootApplication public class JedisApplication { private final static DateTimeFormatter format = DateTimeFormatter.ofPattern("HH:mm:ss"); /** * Main方式启动方法 * * @param args */ public static void main(String[] args) { // Spring Boot 启动入口 ApplicationContext context = SpringApplication.run(JedisApplication.class, args); jedisTest(context); } private static void jedisTest(ApplicationContext context) { JedisPool jedisPool = context.getBean("jedisPool", JedisPool.class); Assert.notNull(jedisPool); int size = 10; final CountDownLatch startLatch = new CountDownLatch(1); final CountDownLatch countDownLatch = new CountDownLatch(size); String lockKey = "lock_order"; String lockValue = 100 + ""; for (int i = 0; i < size; i++) { new Thread(() -> { String threadName = Thread.currentThread().getName(); System.out.printf("==> %s\t%s:\t ready\n", format.format(LocalTime.now()), threadName); try { startLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } Jedis jedis = jedisPool.getResource(); Assert.notNull(jedis); try { // 获取锁 boolean resultFlag = JedisUtil.lock(jedis, lockKey, lockValue, 20000, 5, 1000); System.out.printf("==> %s\t%s:\t %s\n", format.format(LocalTime.now()), threadName, resultFlag); if (resultFlag) { // 如果成功获取锁,进行业务操作 TimeUnit.SECONDS.sleep(2); } } catch (Exception e) { e.printStackTrace(); } finally { JedisUtil.releaseLock(jedis, lockKey, lockValue); jedis.close(); countDownLatch.countDown(); } }, "DD-Thread-" + i).start(); } try { TimeUnit.SECONDS.sleep(3); PrintUtil.printDivider(); PrintUtil.printDivider(format.format(LocalTime.now())); startLatch.countDown(); countDownLatch.await(); } catch (Exception e) { e.printStackTrace(); } } }
package dtos; import lombok.Data; @Data public class SellersDto { private Long id; private String title; private String country_code; }
/* * Copyright (c) 2005-2012 Clark & Parsia, LLC. <http://www.clarkparsia.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.complexible.common.io.block; import com.complexible.common.base.Copyable; import com.google.common.base.Preconditions; /** * Formatting specification of a block defining the markers, indentation level, and newlines. * * @author Evren Sirin */ public class BlockSpec implements Copyable<BlockSpec> { public static final BlockSpec INDENTED = new BlockSpec().immutable(); private boolean mutable = true; private String title = null; private String beginMarker = null; private String endMarker = null; private int indentSize = -1; private boolean newLineBeforeBegin = false; private boolean newLineAfterBegin = false; private boolean newLineBeforeEnd = false; private boolean newLineAfterEnd = false; private void assertMutable() { Preconditions.checkState(mutable, "This object is immutable"); } public BlockSpec indentSize(int indentSize) { assertMutable(); this.indentSize = indentSize; return this; } public BlockSpec marker(BlockMarker marker) { assertMutable(); beginMarker = marker == null ? null : marker.getBegin(); endMarker = marker == null ? null : marker.getEnd(); return this; } public BlockSpec marker(String beginMarker, String endMarker) { assertMutable(); this.beginMarker = beginMarker; this.endMarker = endMarker; return this; } public BlockSpec newLineAfterBegin(boolean enabled) { assertMutable(); newLineAfterBegin = enabled; return this; } public BlockSpec newLineAfterEnd(boolean enabled) { assertMutable(); newLineAfterEnd = enabled; return this; } public BlockSpec newLineBeforeBegin(boolean enabled) { assertMutable(); newLineBeforeBegin = enabled; return this; } public BlockSpec newLineBeforeEnd(boolean enabled) { assertMutable(); newLineBeforeEnd = enabled; return this; } public BlockSpec title(String title) { assertMutable(); this.title = title; return this; } public String getTitle() { return title; } public String getBeginMarker() { return beginMarker; } public String getEndMarker() { return endMarker; } public int getIndentSize() { return indentSize; } public boolean isNewLineBeforeBegin() { return newLineBeforeBegin; } public boolean isNewLineAfterBegin() { return newLineAfterBegin; } public boolean isNewLineBeforeEnd() { return newLineBeforeEnd; } public boolean isNewLineAfterEnd() { return newLineAfterEnd; } @Override public BlockSpec copy() { return new BlockSpec().title(title).marker(beginMarker, endMarker).indentSize(indentSize) .newLineBeforeBegin(newLineBeforeBegin).newLineAfterBegin(newLineAfterBegin) .newLineBeforeEnd(newLineBeforeEnd).newLineAfterEnd(newLineAfterEnd); } public BlockSpec immutable() { BlockSpec spec = copy(); spec.mutable = false; return spec; } }
package de.blafoo.bingo; import java.util.ArrayList; import java.util.BitSet; import java.util.Collections; import java.util.List; import com.vaadin.flow.component.AttachEvent; import com.vaadin.flow.component.ClickEvent; import com.vaadin.flow.component.ComponentEventListener; import com.vaadin.flow.component.DetachEvent; import com.vaadin.flow.component.UI; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.dialog.Dialog; import com.vaadin.flow.component.html.H1; import com.vaadin.flow.component.html.H2; import com.vaadin.flow.component.html.H6; import com.vaadin.flow.component.html.Image; import com.vaadin.flow.component.html.Label; import com.vaadin.flow.component.notification.Notification; import com.vaadin.flow.component.notification.NotificationVariant; import com.vaadin.flow.component.orderedlayout.FlexComponent; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.component.page.Push; import com.vaadin.flow.component.textfield.TextField; import com.vaadin.flow.router.Route; import com.vaadin.flow.server.PWA; import com.vaadin.flow.shared.Registration; @Route @Push @PWA(name = "bingo-mk", shortName = "bingo-mk") public class MainView extends VerticalLayout implements ComponentEventListener<ClickEvent<Button>> { private static final long serialVersionUID = -8778411782845391587L; private List<BitSet> matrix; /** Anzahl Spalten */ private final static int numberOfCols = 4; /** Anzahl Zeilen */ private final static int numberOfRows = 4; /** Name des Spielers */ private String name = "anonym"; private Registration broadcasterRegistration; public MainView() { add(new H2("Bingo")); add(new Label("Langeweile bei Besprechungen im täglichen Büroalltag oder zu viel Bullshit? Mit diesem Spiel geht das vorbei. Einfach beim Bingo-Spielen aufmerksam zuhören. Fällt eines der auf dem Spielfeld gelisteten Worte, kann dieses markiert werden. Eine komplette Reihe horizontal, vertikal oder diagonal? Bingo!")); add(new H6("")); // Name des Spielers final TextField spieler = new TextField(); spieler.setPlaceholder(name); spieler.setLabel("Name"); spieler.addValueChangeListener(e -> { name = e.getValue(); }); add(spieler); // Bingo-Tableau createBingoGrid(this); } /** * Bingo-Tableau erzeugen * @param parent */ private void createBingoGrid(VerticalLayout parent) { List<String> data = BingoModel.getData("Besprechungen"); Collections.shuffle(data); HorizontalLayout layout = new HorizontalLayout(); matrix = new ArrayList<>(); for ( int row = 0; row < numberOfRows; row++) { matrix.add(new BitSet(numberOfCols)); } for ( int col = 0; col < numberOfCols; col++) { createBingoCol(layout, col, data.subList(numberOfRows * col, numberOfRows * (col+1))); } parent.add(layout); } /** * Eine "Spalte" erzeugen * @param parent * @param col * @param colData */ private void createBingoCol(HorizontalLayout parent, int col, List<String> colData) { VerticalLayout layout = new VerticalLayout(); // Abstände um die Buttons minimieren layout.setPadding(false); layout.setMargin(false); layout.setSpacing(false); layout.setDefaultHorizontalComponentAlignment(FlexComponent.Alignment.STRETCH); layout.setWidth("25%"); int row = 0; for ( String content : colData) { BingoButton button = new BingoButton(col, row, content, this); // per Default haben Buttons nur die minimal notwendige Größe button.setHeight("75px"); button.setWidth("175px"); layout.add(button); row++; } parent.add(layout); } /** * Callback vom BingoButton. Wird beim Click auf ein Feld ausgelöst. */ @Override public void onComponentEvent(ClickEvent<Button> event) { BingoButton button = (BingoButton) event.getSource(); if ( button.isChecked()) { matrix.get(button.getRow()).set(button.getCol()); } else { matrix.get(button.getRow()).clear(button.getCol()); } checkBingo(); } /** * Gibt es eine 'komplette' Reihe? */ private void checkBingo() { // horizontal for (BitSet col : matrix) { if ( col.cardinality() == numberOfCols) { bingo(); } } // vertikal for ( int col = 0; col < numberOfCols; col++) { boolean isRowComplete = true; for ( int row = 0; row < numberOfRows; row++) { if ( !matrix.get(row).get(col) ) { isRowComplete = false; break; } } if ( isRowComplete) { bingo(); } } // vertikal LO->RU boolean isComplete = true; for ( int col = 0; col < numberOfCols; col++) { if ( !matrix.get(col).get(col) ) { isComplete = false; break; } } if ( isComplete) { bingo(); } // vertikal LU->RO isComplete = true; for ( int col = 0; col < numberOfCols; col++) { if ( !matrix.get(numberOfRows-col-1).get(col) ) { isComplete = false; break; } } if ( isComplete) { bingo(); } } /** * Eine Reihe ist komplett. Wir können in Jubel ausbrechen! */ private void bingo() { Dialog bingo = new Dialog(); H1 h1 = new H1("BINGO!"); h1.getStyle().set("text-align", "center"); Image image = new Image("/images/bingo.png", "Bingo!"); AudioPlayer player = new AudioPlayer("/images/bingo.m4a", true); bingo.add(h1, image, player); bingo.open(); Broadcaster.broadcast(name); } @Override protected void onAttach(AttachEvent attachEvent) { UI ui = attachEvent.getUI(); broadcasterRegistration = Broadcaster.register(newMessage -> { ui.access(() -> showNotification("BINGO! '" + newMessage + "' hat gewonnen!", NotificationVariant.LUMO_SUCCESS)); }); } @Override protected void onDetach(DetachEvent detachEvent) { broadcasterRegistration.remove(); broadcasterRegistration = null; } private void showNotification(String text, NotificationVariant variant) { Notification notification = new Notification(text); if ( variant != null ) { notification.addThemeVariants(variant); } notification.setDuration(5000); notification.open(); } }
package com.github.nalukit.nalu.processor.common.ui.controllerWithComposite03; import com.github.nalukit.nalu.client.Router; import com.github.nalukit.nalu.client.component.AbstractComponentController; import com.github.nalukit.nalu.client.exception.RoutingInterceptionException; import com.github.nalukit.nalu.client.internal.AbstractControllerCreator; import com.github.nalukit.nalu.client.internal.ClientLogger; import com.github.nalukit.nalu.client.internal.application.ControllerFactory; import com.github.nalukit.nalu.client.internal.application.ControllerInstance; import com.github.nalukit.nalu.client.internal.application.IsControllerCreator; import com.github.nalukit.nalu.processor.common.MockContext; import java.lang.Object; import java.lang.Override; import java.lang.String; import java.lang.StringBuilder; import org.gwtproject.event.shared.SimpleEventBus; public final class ControllerWithComposite03CreatorImpl extends AbstractControllerCreator<MockContext> implements IsControllerCreator { public ControllerWithComposite03CreatorImpl(Router router, MockContext context, SimpleEventBus eventBus) { super(router, context, eventBus); } @Override public ControllerInstance create() { StringBuilder sb01 = new StringBuilder(); ControllerInstance controllerInstance = new ControllerInstance(); controllerInstance.setControllerClassName("com.github.nalukit.nalu.processor.common.ui.controllerWithComposite03.ControllerWithComposite03"); AbstractComponentController<?, ?, ?> storedController = ControllerFactory.get().getControllerFormStore("com.github.nalukit.nalu.processor.common.ui.controllerWithComposite03.ControllerWithComposite03"); if (storedController == null) { sb01.append("controller >>com.github.nalukit.nalu.processor.common.ui.controllerWithComposite03.ControllerWithComposite03<< --> will be created"); ClientLogger.get().logSimple(sb01.toString(), 3); ControllerWithComposite03 controller = new ControllerWithComposite03(); controllerInstance.setController(controller); controllerInstance.setCached(false); controller.setContext(context); controller.setEventBus(eventBus); controller.setRouter(router); controller.setCached(false); sb01 = new StringBuilder(); sb01.append("controller >>").append(controller.getClass().getCanonicalName()).append("<< --> created and data injected"); ClientLogger.get().logDetailed(sb01.toString(), 4); } else { sb01.append("controller >>").append(storedController.getClass().getCanonicalName()).append("<< --> found in cache -> REUSE!"); ClientLogger.get().logDetailed(sb01.toString(), 4); controllerInstance.setController(storedController); controllerInstance.setCached(true); controllerInstance.getController().setCached(true); } return controllerInstance; } @Override public void onFinishCreating(Object object) throws RoutingInterceptionException { ControllerWithComposite03 controller = (ControllerWithComposite03) object; StringBuilder sb01 = new StringBuilder(); IComponent03 component = new Component03(); sb01 = new StringBuilder(); sb01.append("component >>com.github.nalukit.nalu.processor.common.ui.controllerWithComposite03.Component03<< --> created using new"); ClientLogger.get().logDetailed(sb01.toString(), 4); component.setController(controller); sb01 = new StringBuilder(); sb01.append("component >>").append(component.getClass().getCanonicalName()).append("<< --> created and controller instance injected"); ClientLogger.get().logDetailed(sb01.toString(), 4); controller.setComponent(component); sb01 = new StringBuilder(); sb01.append("controller >>").append(controller.getClass().getCanonicalName()).append("<< --> instance of >>").append(component.getClass().getCanonicalName()).append("<< injected"); ClientLogger.get().logDetailed(sb01.toString(), 4); component.render(); sb01 = new StringBuilder(); sb01.append("component >>").append(component.getClass().getCanonicalName()).append("<< --> rendered"); ClientLogger.get().logDetailed(sb01.toString(), 4); component.bind(); sb01 = new StringBuilder(); sb01.append("component >>").append(component.getClass().getCanonicalName()).append("<< --> bound"); ClientLogger.get().logDetailed(sb01.toString(), 4); ClientLogger.get().logSimple("controller >>com.github.nalukit.nalu.processor.common.ui.controllerWithComposite03.Component03<< created for route >>/mockShell/route03/*<<", 3); } @Override public void setParameter(Object object, String... params) throws RoutingInterceptionException { ControllerWithComposite03 controller = (ControllerWithComposite03) object; StringBuilder sb01 = new StringBuilder(); if (params != null) { if (params.length >= 1) { sb01 = new StringBuilder(); sb01.append("controller >>").append(controller.getClass().getCanonicalName()).append("<< --> using method >>setParameter03<< to set value >>").append(params[0]).append("<<"); ClientLogger.get().logDetailed(sb01.toString(), 4); controller.setParameter03(params[0]); } } } }
package org.apereo.cas.authentication.attribute; import org.apereo.cas.services.RegisteredService; import org.apereo.cas.util.LoggingUtils; import org.apereo.cas.util.ResourceUtils; import org.apereo.cas.util.function.FunctionUtils; import org.apereo.cas.util.io.FileWatcherService; import org.apereo.cas.util.serialization.JacksonObjectMapperFactory; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.ToString; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; import org.hjson.JsonValue; import org.jooq.lambda.Unchecked; import org.springframework.beans.factory.DisposableBean; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import java.io.File; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.TreeMap; import java.util.function.Predicate; /** * This is {@link DefaultAttributeDefinitionStore}. * * @author Misagh Moayyed * @author Travis Schmidt * @since 6.2.0 */ @Slf4j @EqualsAndHashCode(of = "attributeDefinitions") @ToString(of = "attributeDefinitions") public class DefaultAttributeDefinitionStore implements AttributeDefinitionStore, DisposableBean, AutoCloseable { private static final ObjectMapper MAPPER = JacksonObjectMapperFactory.builder() .defaultTypingEnabled(true).build().toObjectMapper(); private final Map<String, AttributeDefinition> attributeDefinitions = new TreeMap<>(); private FileWatcherService storeWatcherService; @Setter @Getter private String scope = StringUtils.EMPTY; public DefaultAttributeDefinitionStore(final Resource resource) throws Exception { if (ResourceUtils.doesResourceExist(resource)) { loadAttributeDefinitionsFromInputStream(resource); if (ResourceUtils.isFile(resource)) { this.storeWatcherService = new FileWatcherService(resource.getFile(), Unchecked.consumer(file -> loadAttributeDefinitionsFromInputStream(new FileSystemResource(file)))); this.storeWatcherService.start(getClass().getSimpleName()); } } } public DefaultAttributeDefinitionStore(final AttributeDefinition... defns) { Arrays.stream(defns).forEach(this::registerAttributeDefinition); } @Override public AttributeDefinitionStore registerAttributeDefinition(final AttributeDefinition defn) { return registerAttributeDefinition(defn.getKey(), defn); } @Override public AttributeDefinitionStore registerAttributeDefinition(final String key, final AttributeDefinition defn) { LOGGER.trace("Registering attribute definition [{}] by key [{}]", defn, key); if (StringUtils.isNotBlank(defn.getKey()) && !StringUtils.equalsIgnoreCase(defn.getKey(), key)) { LOGGER.warn("Attribute definition contains a key property [{}] that differs from its registering key [{}]. " + "This is likely due to misconfiguration of the attribute definition, and CAS will use the key property [{}] " + "to register the attribute definition in the attribute store", defn.getKey(), key, defn.getKey()); attributeDefinitions.put(defn.getKey(), defn); } else { attributeDefinitions.put(key, defn); } return this; } @Override public AttributeDefinitionStore removeAttributeDefinition(final String key) { LOGGER.debug("Removing attribute definition by key [{}]", key); if (this.attributeDefinitions.containsKey(key)) { val defn = this.attributeDefinitions.remove(key); LOGGER.debug("Attribute definition [{}] has been removed from the definition store", defn); } else { LOGGER.debug("Attribute definition with the registered key [{}] was not found and the store was not altered", key); } return this; } @Override public Optional<AttributeDefinition> locateAttributeDefinition(final String key) { LOGGER.trace("Locating attribute definition for [{}]", key); return Optional.ofNullable(attributeDefinitions.get(key)); } @Override public <T extends AttributeDefinition> Optional<T> locateAttributeDefinition(final String key, final Class<T> clazz) { LOGGER.trace("Locating attribute definition for [{}]", key); val attributeDefinition = attributeDefinitions.get(key); if (attributeDefinition != null && clazz.isAssignableFrom(attributeDefinition.getClass())) { return Optional.of((T) attributeDefinition); } return Optional.empty(); } @Override public <T extends AttributeDefinition> Optional<T> locateAttributeDefinition(final Predicate<AttributeDefinition> predicate) { return attributeDefinitions.values() .stream() .filter(predicate) .map(defn -> (T) defn) .findFirst(); } @Override public Collection<AttributeDefinition> getAttributeDefinitions() { return attributeDefinitions.values(); } @Override public Optional<Pair<AttributeDefinition, List<Object>>> resolveAttributeValues( final String key, final List<Object> attributeValues, final RegisteredService registeredService, final Map<String, List<Object>> attributes) { val result = locateAttributeDefinition(key); if (result.isEmpty()) { return Optional.empty(); } val definition = result.get(); val currentValues = definition.resolveAttributeValues(attributeValues, this.scope, registeredService, attributes); return Optional.of(Pair.of(definition, currentValues)); } @Override public boolean isEmpty() { return attributeDefinitions.isEmpty(); } /** * To. * * @param resource the resource * @return the attribute definition store */ public AttributeDefinitionStore to(final File resource) { return FunctionUtils.doUnchecked(() -> { val json = MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(this.attributeDefinitions); LOGGER.trace("Storing attribute definitions as [{}] to [{}]", json, resource); try (val writer = Files.newBufferedWriter(resource.toPath(), StandardCharsets.UTF_8)) { writer.write(json); writer.flush(); } return this; }); } @Override public void close() { if (this.storeWatcherService != null) { this.storeWatcherService.close(); } } @Override public void destroy() { close(); } private void loadAttributeDefinitionsFromInputStream(final Resource resource) { try { LOGGER.trace("Loading attribute definitions from [{}]", resource); val json = new String(resource.getInputStream().readAllBytes(), StandardCharsets.UTF_8); LOGGER.trace("Loaded attribute definitions [{}] from [{}]", json, resource); val map = MAPPER.readValue(JsonValue.readHjson(json).toString(), new TypeReference<Map<String, AttributeDefinition>>() { }); map.forEach(this::registerAttributeDefinition); } catch (final Exception e) { LoggingUtils.warn(LOGGER, e); } finally { LOGGER.debug("Loaded [{}] attribute definition(s).", attributeDefinitions.size()); } } }
package org.opendatakit.briefcase.model; import com.brsanthu.googleanalytics.EventHit; import com.brsanthu.googleanalytics.GoogleAnalytics; import org.opendatakit.briefcase.buildconfig.BuildConfig; /** * This class is used to send usage information to ODK's Google Analytics account. * * <P>A library built by 'brsanthu' is utilized to streamline the * process of contacting Google's Measurement Protocol API.</P> * <P>This class also implements the Singleton pattern.</P> * * @author Joao Paulo Knox * @see <a href="https://github.com/brsanthu/google-analytics-java">google-analytics-java</a> */ public class BriefcaseAnalytics { private static final String GOOGLE_TRACKING_ID = BriefcasePreferences.GOOGLE_TRACKING_ID; private static final String UNIQUE_USER_ID = BriefcasePreferences.getUniqueUserID(); private static final String EVENT_CATEGORY = "ODK Briefcase"; private static final String APPLICATION_NAME = BuildConfig.NAME; private static final String APPLICATION_VERSION = BuildConfig.VERSION; private final GoogleAnalytics googleAnalytics = new GoogleAnalytics(GOOGLE_TRACKING_ID); public BriefcaseAnalytics() { } /** * Sends usage information to Google Analytics, only if the user has consented, * or if they are enabling or disabling tracking. The information is modeled using an {@link EventHit} object. * * @param action (required) name of the event itself. * @param label (optional) an open-ended label. * @param value (optional) an open-ended value. Must be an integer. * @param always whether to track the event even when the tracking is turned off * (such as when we record that they have changed the tracking preference). Usually false. */ public void trackEvent(String action, String label, Integer value, boolean always) { if (always || BriefcasePreferences.getBriefcaseTrackingConsentProperty()) { EventHit eventHit = new EventHit(); eventHit.trackingId(GOOGLE_TRACKING_ID); eventHit.clientId(UNIQUE_USER_ID); eventHit.dataSource(System.getProperty("os.name")); eventHit.applicationName(APPLICATION_NAME); eventHit.applicationVersion(APPLICATION_VERSION); eventHit.eventCategory(EVENT_CATEGORY); eventHit.eventAction(action); eventHit.eventLabel(label); eventHit.eventValue(value); googleAnalytics.postAsync(eventHit); } } /** * Track this application's startup event. */ public void trackStartup() { trackEvent("Application-Startup", null, null, false); } /** * Tracks the user giving/withdrawing their consent for usage tracking, and saves the new preference. */ public void trackConsentDecision(boolean givesConsent) { BriefcasePreferences.setBriefcaseTrackingConsentProperty(givesConsent); trackEvent(givesConsent ? "Tracking-Enabled" : "Tracking-Disabled", null, null, true); } }
/* * Copyright 2020 Prathab Murugan * * 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.myhome.controllers.response; import java.util.HashSet; import java.util.Set; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @NoArgsConstructor @AllArgsConstructor @Getter @Setter public class AddCommunityHouseResponse { private Set<String> houses = new HashSet<>(); }
package com.shen.rpc.core.annotation; /** * @author shenjianeng * @date 2018/12/4 */ public enum RpcMode { /** * 服务端 */ SERVER, /** * 客户端 */ CLIENT, /** * 即为是服务端又是客户端 */ SERVER_AND_CLIENT }
package cn.yueshutong.springbootstartercurrentlimiting.core; public interface RateLimiter { String message = "<pre>The specified service is not currently available.</pre>"; boolean tryAcquire(); boolean tryAcquireFailed(); }
/* * 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.isis.applib; import java.io.InputStream; import java.util.Map; import java.util.Properties; public class PropertyResource { private final Class<?> propertiesFileContext; private final String propertiesFile; PropertyResource(final Class<?> propertiesFileContext, final String propertiesFile) { this.propertiesFileContext = propertiesFileContext; this.propertiesFile = propertiesFile; } Class<?> getPropertiesFileContext() { return propertiesFileContext; } String getPropertiesFile() { return propertiesFile; } void loadPropsInto( final Map<String, String> props) { final Properties properties = new Properties(); try { try (final InputStream stream = propertiesFileContext.getResourceAsStream(propertiesFile)) { properties.load(stream); for (Object key : properties.keySet()) { final Object value = properties.get(key); if (key instanceof String && value instanceof String) { props.put((String) key, (String) value); } } } } catch (Exception e) { throw new RuntimeException( String.format("Failed to load '%s' file relative to %s", getPropertiesFile(), getPropertiesFileContext().getName()), e); } } }
// Targeted by JavaCPP version 1.5.6: DO NOT EDIT THIS FILE package org.bytedeco.pytorch; import org.bytedeco.pytorch.Allocator; import org.bytedeco.pytorch.Function; import org.bytedeco.pytorch.Module; import java.nio.*; import org.bytedeco.javacpp.*; import org.bytedeco.javacpp.annotation.*; import static org.bytedeco.javacpp.presets.javacpp.*; import static org.bytedeco.openblas.global.openblas_nolapack.*; import static org.bytedeco.openblas.global.openblas.*; import static org.bytedeco.pytorch.global.torch.*; @Name("torch::nn::ModuleHolder<torch::nn::MaxUnpool2dImpl>") @NoOffset @Properties(inherit = org.bytedeco.pytorch.presets.torch.class) public class MaxUnpool2dImplModuleHolder extends Pointer { static { Loader.load(); } /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */ public MaxUnpool2dImplModuleHolder(Pointer p) { super(p); } /// /** Default constructs the contained module if if has a default constructor, * else produces a static error. * * NOTE: This uses the behavior of template * classes in C++ that constructors (or any methods) are only compiled when * actually used. */ /** Constructs the {@code ModuleHolder} with an empty contained value. Access to * the underlying module is not permitted and will throw an exception, until * a value is assigned. */ /* implicit */ public MaxUnpool2dImplModuleHolder(@ByVal @Cast("std::nullptr_t*") PointerPointer arg0) { super((Pointer)null); allocate(arg0); } private native void allocate(@ByVal @Cast("std::nullptr_t*") PointerPointer arg0); /** Constructs the {@code ModuleHolder} with a contained module, forwarding all * arguments to its constructor. */ /** Constructs the {@code ModuleHolder} from a pointer to the contained type. * Example: {@code Linear(std::make_shared<LinearImpl>(...))}. */ /* implicit */ public MaxUnpool2dImplModuleHolder(@SharedPtr @Cast({"", "std::shared_ptr<torch::nn::MaxUnpool2dImpl>"}) MaxUnpool2dImpl module) { super((Pointer)null); allocate(module); } private native void allocate(@SharedPtr @Cast({"", "std::shared_ptr<torch::nn::MaxUnpool2dImpl>"}) MaxUnpool2dImpl module); /** Returns true if the {@code ModuleHolder} contains a module, or false if it is * {@code nullptr}. */ public native @Cast("bool") @Name("operator bool") @NoException(true) boolean asBoolean(); /** Forwards to the contained module. */ public native @Name("operator ->") MaxUnpool2dImpl access(); /** Forwards to the contained module. */ /** Returns a reference to the contained module. */ public native @ByRef @Name("operator *") MaxUnpool2dImpl multiply(); /** Returns a const reference to the contained module. */ /** Returns a shared pointer to the underlying module. */ public native @SharedPtr @Cast({"", "std::shared_ptr<torch::nn::MaxUnpool2dImpl>"}) MaxUnpool2dImpl ptr(); /** Returns a pointer to the underlying module. */ public native MaxUnpool2dImpl get(); /** Returns a const pointer to the underlying module. */ /** Calls the {@code forward()} method of the contained module. */ /** Forwards to the subscript operator of the contained module. * NOTE: std::forward is qualified to prevent VS2017 emitting * error C2872: 'std': ambiguous symbol */ /** Returns true if the {@code ModuleHolder} does not contain a module. */ public native @Cast("bool") @NoException(true) boolean is_empty(); }
/* * Copyright 2020-2021 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 * * 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 org.springframework.batch.core.launch.support; import org.junit.Assert; import org.junit.Test; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.JobParametersBuilder; import org.springframework.jdbc.support.incrementer.DataFieldMaxValueIncrementer; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * @author Mahmoud Ben Hassine */ public class DataFieldMaxValueJobParametersIncrementerTests { private final DataFieldMaxValueIncrementer incrementer = mock(DataFieldMaxValueIncrementer.class); @Test public void testInvalidKey() { DataFieldMaxValueJobParametersIncrementer jobParametersIncrementer = new DataFieldMaxValueJobParametersIncrementer(this.incrementer); try { jobParametersIncrementer.setKey(""); fail("Must fail if the key is empty"); } catch (IllegalArgumentException exception) { Assert.assertEquals("key must not be null or empty", exception.getMessage()); } } @Test public void testInvalidDataFieldMaxValueIncrementer() { try { new DataFieldMaxValueJobParametersIncrementer(null); fail("Must fail if the incrementer is null"); } catch (IllegalArgumentException exception) { Assert.assertEquals("dataFieldMaxValueIncrementer must not be null", exception.getMessage()); } } @Test public void testGetNext() { // given JobParameters jobParameters = new JobParameters(); when(this.incrementer.nextLongValue()).thenReturn(10L); DataFieldMaxValueJobParametersIncrementer jobParametersIncrementer = new DataFieldMaxValueJobParametersIncrementer(this.incrementer); // when JobParameters nextParameters = jobParametersIncrementer.getNext(jobParameters); // then Long runId = nextParameters.getLong("run.id"); Assert.assertEquals(Long.valueOf(10L) ,runId); } @Test public void testGetNextAppend() { // given JobParameters jobParameters = new JobParametersBuilder() .addString("foo", "bar") .toJobParameters(); when(this.incrementer.nextLongValue()).thenReturn(10L); DataFieldMaxValueJobParametersIncrementer jobParametersIncrementer = new DataFieldMaxValueJobParametersIncrementer(this.incrementer); // when JobParameters nextParameters = jobParametersIncrementer.getNext(jobParameters); // then Long runId = nextParameters.getLong("run.id"); String foo = nextParameters.getString("foo"); Assert.assertEquals(Long.valueOf(10L) ,runId); Assert.assertEquals("bar" ,foo); } @Test public void testGetNextOverride() { // given JobParameters jobParameters = new JobParametersBuilder() .addLong("run.id", 1L) .toJobParameters(); when(this.incrementer.nextLongValue()).thenReturn(10L); DataFieldMaxValueJobParametersIncrementer jobParametersIncrementer = new DataFieldMaxValueJobParametersIncrementer(this.incrementer); // when JobParameters nextParameters = jobParametersIncrementer.getNext(jobParameters); // then Long runId = nextParameters.getLong("run.id"); Assert.assertEquals(Long.valueOf(10L) ,runId); } }
package net.mybluemix.parteg.fornecedor; import org.junit.*; import static org.junit.Assert.*; // JUnit 4.3 public class TestCases_All_Transitions{ public static junit.framework.Test suite(){ return new junit.framework.JUnit4TestAdapter(TestCases_All_Transitions.class); } @Test public void test1() { Estoquista oTestObject = new Estoquista(); Integer nomeVal16 = 725257; Boolean ativoVal16 = true; Integer cnpjVal16 = -621408; Integer emailVal16 = -90454; Integer telefoneVal16 = -445014; Integer prazoEntregaDiasVal16 = -182846; Integer endereco_PaisVal16 = 656764; Integer endereco_EstadoVal16 = 382597; Integer endereco_CidadeVal16 = -432984; Integer endereco_LogradouroVal16 = 56400; Integer endereco_CEPVal16 = -402958; oTestObject.handleEvent("inicializarEvent"); assertEquals(true, (oTestObject.state == State.mostrandoAtivos)); oTestObject.handleEvent("mostrarInativosEvent"); assertEquals(true, (oTestObject.state == State.mostrandoInativos)); oTestObject.handleEvent("mostrarAtivosEvent"); assertEquals(true, (oTestObject.state == State.mostrandoAtivos)); oTestObject.handleEvent("alterarEvent", ativoVal16, cnpjVal16, nomeVal16, emailVal16, telefoneVal16, prazoEntregaDiasVal16, endereco_PaisVal16, endereco_EstadoVal16, endereco_CidadeVal16, endereco_LogradouroVal16, endereco_CEPVal16); assertEquals(true, (oTestObject.ativo.booleanValue() == ativoVal16.booleanValue())); assertEquals(true, (oTestObject.cnpj.intValue() == cnpjVal16.intValue())); assertEquals(true, (oTestObject.nome.intValue() == nomeVal16.intValue())); assertEquals(true, (oTestObject.email.intValue() == emailVal16.intValue())); assertEquals(true, (oTestObject.telefone.intValue() == telefoneVal16.intValue())); assertEquals(true, (oTestObject.prazoEntregaDias.intValue() == prazoEntregaDiasVal16.intValue())); assertEquals(true, (oTestObject.endereco_Pais.intValue() == endereco_PaisVal16.intValue())); assertEquals(true, (oTestObject.endereco_Estado.intValue() == endereco_EstadoVal16.intValue())); assertEquals(true, (oTestObject.endereco_Cidade.intValue() == endereco_CidadeVal16.intValue())); assertEquals(true, (oTestObject.endereco_Logradouro.intValue() == endereco_LogradouroVal16.intValue())); assertEquals(true, (oTestObject.endereco_CEP.intValue() == endereco_CEPVal16.intValue())); assertEquals(true, (oTestObject.state == State.alterando)); assertEquals(true, (oTestObject.status.booleanValue() == true)); assertEquals(true, (oTestObject.nome.intValue() > 0)); oTestObject.handleEvent("fazerAlteracoesAtivosEvent"); assertEquals(true, (oTestObject.state == State.mostrandoAtivos)); } @Test public void test2() { Estoquista oTestObject = new Estoquista(); Integer nomeVal16 = 1; Boolean ativoVal16 = true; Integer cnpjVal16 = -621408; Integer emailVal16 = -90454; Integer telefoneVal16 = -445014; Integer prazoEntregaDiasVal16 = -182846; Integer endereco_PaisVal16 = 656764; Integer endereco_EstadoVal16 = 382597; Integer endereco_CidadeVal16 = -432984; Integer endereco_LogradouroVal16 = 56400; Integer endereco_CEPVal16 = -402958; oTestObject.handleEvent("inicializarEvent"); assertEquals(true, (oTestObject.state == State.mostrandoAtivos)); oTestObject.handleEvent("mostrarInativosEvent"); assertEquals(true, (oTestObject.state == State.mostrandoInativos)); oTestObject.handleEvent("mostrarAtivosEvent"); assertEquals(true, (oTestObject.state == State.mostrandoAtivos)); oTestObject.handleEvent("alterarEvent", ativoVal16, cnpjVal16, nomeVal16, emailVal16, telefoneVal16, prazoEntregaDiasVal16, endereco_PaisVal16, endereco_EstadoVal16, endereco_CidadeVal16, endereco_LogradouroVal16, endereco_CEPVal16); assertEquals(true, (oTestObject.ativo.booleanValue() == ativoVal16.booleanValue())); assertEquals(true, (oTestObject.cnpj.intValue() == cnpjVal16.intValue())); assertEquals(true, (oTestObject.nome.intValue() == nomeVal16.intValue())); assertEquals(true, (oTestObject.email.intValue() == emailVal16.intValue())); assertEquals(true, (oTestObject.telefone.intValue() == telefoneVal16.intValue())); assertEquals(true, (oTestObject.prazoEntregaDias.intValue() == prazoEntregaDiasVal16.intValue())); assertEquals(true, (oTestObject.endereco_Pais.intValue() == endereco_PaisVal16.intValue())); assertEquals(true, (oTestObject.endereco_Estado.intValue() == endereco_EstadoVal16.intValue())); assertEquals(true, (oTestObject.endereco_Cidade.intValue() == endereco_CidadeVal16.intValue())); assertEquals(true, (oTestObject.endereco_Logradouro.intValue() == endereco_LogradouroVal16.intValue())); assertEquals(true, (oTestObject.endereco_CEP.intValue() == endereco_CEPVal16.intValue())); assertEquals(true, (oTestObject.state == State.alterando)); assertEquals(true, (oTestObject.status.booleanValue() == true)); assertEquals(true, (oTestObject.nome.intValue() > 0)); oTestObject.handleEvent("fazerAlteracoesAtivosEvent"); assertEquals(true, (oTestObject.state == State.mostrandoAtivos)); } @Test public void test3() { Estoquista oTestObject = new Estoquista(); Integer nomeVal14 = 547352; Boolean ativoVal14 = true; Integer cnpjVal14 = 183844; Integer emailVal14 = -518827; Integer telefoneVal14 = 193527; Integer prazoEntregaDiasVal14 = 95863; Integer endereco_PaisVal14 = -42839; Integer endereco_EstadoVal14 = 63524; Integer endereco_CidadeVal14 = -284887; Integer endereco_LogradouroVal14 = -607030; Integer endereco_CEPVal14 = 209826; oTestObject.handleEvent("inicializarEvent"); assertEquals(true, (oTestObject.state == State.mostrandoAtivos)); oTestObject.handleEvent("mostrarInativosEvent"); assertEquals(true, (oTestObject.state == State.mostrandoInativos)); oTestObject.handleEvent("alterarEvent", ativoVal14, cnpjVal14, nomeVal14, emailVal14, telefoneVal14, prazoEntregaDiasVal14, endereco_PaisVal14, endereco_EstadoVal14, endereco_CidadeVal14, endereco_LogradouroVal14, endereco_CEPVal14); assertEquals(true, (oTestObject.ativo.booleanValue() == ativoVal14.booleanValue())); assertEquals(true, (oTestObject.cnpj.intValue() == cnpjVal14.intValue())); assertEquals(true, (oTestObject.nome.intValue() == nomeVal14.intValue())); assertEquals(true, (oTestObject.email.intValue() == emailVal14.intValue())); assertEquals(true, (oTestObject.telefone.intValue() == telefoneVal14.intValue())); assertEquals(true, (oTestObject.prazoEntregaDias.intValue() == prazoEntregaDiasVal14.intValue())); assertEquals(true, (oTestObject.endereco_Pais.intValue() == endereco_PaisVal14.intValue())); assertEquals(true, (oTestObject.endereco_Estado.intValue() == endereco_EstadoVal14.intValue())); assertEquals(true, (oTestObject.endereco_Cidade.intValue() == endereco_CidadeVal14.intValue())); assertEquals(true, (oTestObject.endereco_Logradouro.intValue() == endereco_LogradouroVal14.intValue())); assertEquals(true, (oTestObject.endereco_CEP.intValue() == endereco_CEPVal14.intValue())); assertEquals(true, (oTestObject.state == State.alterando)); assertEquals(true, (oTestObject.status.booleanValue() == false)); assertEquals(true, (oTestObject.nome.intValue() > 0)); oTestObject.handleEvent("fazerAlteracoesInativosEvent"); assertEquals(true, (oTestObject.state == State.mostrandoInativos)); } @Test public void test4() { Estoquista oTestObject = new Estoquista(); Integer nomeVal14 = 1; Boolean ativoVal14 = true; Integer cnpjVal14 = 183844; Integer emailVal14 = -518827; Integer telefoneVal14 = 193527; Integer prazoEntregaDiasVal14 = 95863; Integer endereco_PaisVal14 = -42839; Integer endereco_EstadoVal14 = 63524; Integer endereco_CidadeVal14 = -284887; Integer endereco_LogradouroVal14 = -607030; Integer endereco_CEPVal14 = 209826; oTestObject.handleEvent("inicializarEvent"); assertEquals(true, (oTestObject.state == State.mostrandoAtivos)); oTestObject.handleEvent("mostrarInativosEvent"); assertEquals(true, (oTestObject.state == State.mostrandoInativos)); oTestObject.handleEvent("alterarEvent", ativoVal14, cnpjVal14, nomeVal14, emailVal14, telefoneVal14, prazoEntregaDiasVal14, endereco_PaisVal14, endereco_EstadoVal14, endereco_CidadeVal14, endereco_LogradouroVal14, endereco_CEPVal14); assertEquals(true, (oTestObject.ativo.booleanValue() == ativoVal14.booleanValue())); assertEquals(true, (oTestObject.cnpj.intValue() == cnpjVal14.intValue())); assertEquals(true, (oTestObject.nome.intValue() == nomeVal14.intValue())); assertEquals(true, (oTestObject.email.intValue() == emailVal14.intValue())); assertEquals(true, (oTestObject.telefone.intValue() == telefoneVal14.intValue())); assertEquals(true, (oTestObject.prazoEntregaDias.intValue() == prazoEntregaDiasVal14.intValue())); assertEquals(true, (oTestObject.endereco_Pais.intValue() == endereco_PaisVal14.intValue())); assertEquals(true, (oTestObject.endereco_Estado.intValue() == endereco_EstadoVal14.intValue())); assertEquals(true, (oTestObject.endereco_Cidade.intValue() == endereco_CidadeVal14.intValue())); assertEquals(true, (oTestObject.endereco_Logradouro.intValue() == endereco_LogradouroVal14.intValue())); assertEquals(true, (oTestObject.endereco_CEP.intValue() == endereco_CEPVal14.intValue())); assertEquals(true, (oTestObject.state == State.alterando)); assertEquals(true, (oTestObject.status.booleanValue() == false)); assertEquals(true, (oTestObject.nome.intValue() > 0)); oTestObject.handleEvent("fazerAlteracoesInativosEvent"); assertEquals(true, (oTestObject.state == State.mostrandoInativos)); } @Test public void test5() { Estoquista oTestObject = new Estoquista(); Integer nomeVal6 = 499908; Boolean ativoVal6 = true; Integer cnpjVal6 = 333335; Integer emailVal6 = 48974; Integer telefoneVal6 = -66538; Integer prazoEntregaDiasVal6 = -201915; Integer endereco_PaisVal6 = 40937; Integer endereco_EstadoVal6 = 501934; Integer endereco_CidadeVal6 = -517183; Integer endereco_LogradouroVal6 = 186365; Integer endereco_CEPVal6 = 67580; oTestObject.handleEvent("inicializarEvent"); assertEquals(true, (oTestObject.state == State.mostrandoAtivos)); oTestObject.handleEvent("mostrarInativosEvent"); assertEquals(true, (oTestObject.state == State.mostrandoInativos)); oTestObject.handleEvent("mostrarAtivosEvent"); assertEquals(true, (oTestObject.state == State.mostrandoAtivos)); oTestObject.handleEvent("cadastrarEvent", ativoVal6, cnpjVal6, nomeVal6, emailVal6, telefoneVal6, prazoEntregaDiasVal6, endereco_PaisVal6, endereco_EstadoVal6, endereco_CidadeVal6, endereco_LogradouroVal6, endereco_CEPVal6); assertEquals(true, (oTestObject.ativo.booleanValue() == ativoVal6.booleanValue())); assertEquals(true, (oTestObject.cnpj.intValue() == cnpjVal6.intValue())); assertEquals(true, (oTestObject.nome.intValue() == nomeVal6.intValue())); assertEquals(true, (oTestObject.email.intValue() == emailVal6.intValue())); assertEquals(true, (oTestObject.telefone.intValue() == telefoneVal6.intValue())); assertEquals(true, (oTestObject.prazoEntregaDias.intValue() == prazoEntregaDiasVal6.intValue())); assertEquals(true, (oTestObject.endereco_Pais.intValue() == endereco_PaisVal6.intValue())); assertEquals(true, (oTestObject.endereco_Estado.intValue() == endereco_EstadoVal6.intValue())); assertEquals(true, (oTestObject.endereco_Cidade.intValue() == endereco_CidadeVal6.intValue())); assertEquals(true, (oTestObject.endereco_Logradouro.intValue() == endereco_LogradouroVal6.intValue())); assertEquals(true, (oTestObject.endereco_CEP.intValue() == endereco_CEPVal6.intValue())); assertEquals(true, (oTestObject.state == State.cadastrando)); assertEquals(true, (oTestObject.status.booleanValue() == true)); assertEquals(true, (oTestObject.nome.intValue() > 0)); oTestObject.handleEvent("fazerCadastroAtivosEvent"); assertEquals(true, (oTestObject.state == State.mostrandoAtivos)); } @Test public void test6() { Estoquista oTestObject = new Estoquista(); Integer nomeVal6 = 1; Boolean ativoVal6 = true; Integer cnpjVal6 = 333335; Integer emailVal6 = 48974; Integer telefoneVal6 = -66538; Integer prazoEntregaDiasVal6 = -201915; Integer endereco_PaisVal6 = 40937; Integer endereco_EstadoVal6 = 501934; Integer endereco_CidadeVal6 = -517183; Integer endereco_LogradouroVal6 = 186365; Integer endereco_CEPVal6 = 67580; oTestObject.handleEvent("inicializarEvent"); assertEquals(true, (oTestObject.state == State.mostrandoAtivos)); oTestObject.handleEvent("mostrarInativosEvent"); assertEquals(true, (oTestObject.state == State.mostrandoInativos)); oTestObject.handleEvent("mostrarAtivosEvent"); assertEquals(true, (oTestObject.state == State.mostrandoAtivos)); oTestObject.handleEvent("cadastrarEvent", ativoVal6, cnpjVal6, nomeVal6, emailVal6, telefoneVal6, prazoEntregaDiasVal6, endereco_PaisVal6, endereco_EstadoVal6, endereco_CidadeVal6, endereco_LogradouroVal6, endereco_CEPVal6); assertEquals(true, (oTestObject.ativo.booleanValue() == ativoVal6.booleanValue())); assertEquals(true, (oTestObject.cnpj.intValue() == cnpjVal6.intValue())); assertEquals(true, (oTestObject.nome.intValue() == nomeVal6.intValue())); assertEquals(true, (oTestObject.email.intValue() == emailVal6.intValue())); assertEquals(true, (oTestObject.telefone.intValue() == telefoneVal6.intValue())); assertEquals(true, (oTestObject.prazoEntregaDias.intValue() == prazoEntregaDiasVal6.intValue())); assertEquals(true, (oTestObject.endereco_Pais.intValue() == endereco_PaisVal6.intValue())); assertEquals(true, (oTestObject.endereco_Estado.intValue() == endereco_EstadoVal6.intValue())); assertEquals(true, (oTestObject.endereco_Cidade.intValue() == endereco_CidadeVal6.intValue())); assertEquals(true, (oTestObject.endereco_Logradouro.intValue() == endereco_LogradouroVal6.intValue())); assertEquals(true, (oTestObject.endereco_CEP.intValue() == endereco_CEPVal6.intValue())); assertEquals(true, (oTestObject.state == State.cadastrando)); assertEquals(true, (oTestObject.status.booleanValue() == true)); assertEquals(true, (oTestObject.nome.intValue() > 0)); oTestObject.handleEvent("fazerCadastroAtivosEvent"); assertEquals(true, (oTestObject.state == State.mostrandoAtivos)); } @Test public void test7() { Estoquista oTestObject = new Estoquista(); Integer nomeVal4 = 239127; Boolean ativoVal4 = true; Integer cnpjVal4 = 247646; Integer emailVal4 = 536192; Integer telefoneVal4 = 415748; Integer prazoEntregaDiasVal4 = 173062; Integer endereco_PaisVal4 = -218917; Integer endereco_EstadoVal4 = -176857; Integer endereco_CidadeVal4 = -28855; Integer endereco_LogradouroVal4 = -714326; Integer endereco_CEPVal4 = 303497; oTestObject.handleEvent("inicializarEvent"); assertEquals(true, (oTestObject.state == State.mostrandoAtivos)); oTestObject.handleEvent("mostrarInativosEvent"); assertEquals(true, (oTestObject.state == State.mostrandoInativos)); oTestObject.handleEvent("cadastrarEvent", ativoVal4, cnpjVal4, nomeVal4, emailVal4, telefoneVal4, prazoEntregaDiasVal4, endereco_PaisVal4, endereco_EstadoVal4, endereco_CidadeVal4, endereco_LogradouroVal4, endereco_CEPVal4); assertEquals(true, (oTestObject.ativo.booleanValue() == ativoVal4.booleanValue())); assertEquals(true, (oTestObject.cnpj.intValue() == cnpjVal4.intValue())); assertEquals(true, (oTestObject.nome.intValue() == nomeVal4.intValue())); assertEquals(true, (oTestObject.email.intValue() == emailVal4.intValue())); assertEquals(true, (oTestObject.telefone.intValue() == telefoneVal4.intValue())); assertEquals(true, (oTestObject.prazoEntregaDias.intValue() == prazoEntregaDiasVal4.intValue())); assertEquals(true, (oTestObject.endereco_Pais.intValue() == endereco_PaisVal4.intValue())); assertEquals(true, (oTestObject.endereco_Estado.intValue() == endereco_EstadoVal4.intValue())); assertEquals(true, (oTestObject.endereco_Cidade.intValue() == endereco_CidadeVal4.intValue())); assertEquals(true, (oTestObject.endereco_Logradouro.intValue() == endereco_LogradouroVal4.intValue())); assertEquals(true, (oTestObject.endereco_CEP.intValue() == endereco_CEPVal4.intValue())); assertEquals(true, (oTestObject.state == State.cadastrando)); assertEquals(true, (oTestObject.status.booleanValue() == false)); assertEquals(true, (oTestObject.nome.intValue() > 0)); oTestObject.handleEvent("fazerCadastroInativosEvent"); assertEquals(true, (oTestObject.state == State.mostrandoInativos)); } @Test public void test8() { Estoquista oTestObject = new Estoquista(); Integer nomeVal4 = 1; Boolean ativoVal4 = true; Integer cnpjVal4 = 247646; Integer emailVal4 = 536192; Integer telefoneVal4 = 415748; Integer prazoEntregaDiasVal4 = 173062; Integer endereco_PaisVal4 = -218917; Integer endereco_EstadoVal4 = -176857; Integer endereco_CidadeVal4 = -28855; Integer endereco_LogradouroVal4 = -714326; Integer endereco_CEPVal4 = 303497; oTestObject.handleEvent("inicializarEvent"); assertEquals(true, (oTestObject.state == State.mostrandoAtivos)); oTestObject.handleEvent("mostrarInativosEvent"); assertEquals(true, (oTestObject.state == State.mostrandoInativos)); oTestObject.handleEvent("cadastrarEvent", ativoVal4, cnpjVal4, nomeVal4, emailVal4, telefoneVal4, prazoEntregaDiasVal4, endereco_PaisVal4, endereco_EstadoVal4, endereco_CidadeVal4, endereco_LogradouroVal4, endereco_CEPVal4); assertEquals(true, (oTestObject.ativo.booleanValue() == ativoVal4.booleanValue())); assertEquals(true, (oTestObject.cnpj.intValue() == cnpjVal4.intValue())); assertEquals(true, (oTestObject.nome.intValue() == nomeVal4.intValue())); assertEquals(true, (oTestObject.email.intValue() == emailVal4.intValue())); assertEquals(true, (oTestObject.telefone.intValue() == telefoneVal4.intValue())); assertEquals(true, (oTestObject.prazoEntregaDias.intValue() == prazoEntregaDiasVal4.intValue())); assertEquals(true, (oTestObject.endereco_Pais.intValue() == endereco_PaisVal4.intValue())); assertEquals(true, (oTestObject.endereco_Estado.intValue() == endereco_EstadoVal4.intValue())); assertEquals(true, (oTestObject.endereco_Cidade.intValue() == endereco_CidadeVal4.intValue())); assertEquals(true, (oTestObject.endereco_Logradouro.intValue() == endereco_LogradouroVal4.intValue())); assertEquals(true, (oTestObject.endereco_CEP.intValue() == endereco_CEPVal4.intValue())); assertEquals(true, (oTestObject.state == State.cadastrando)); assertEquals(true, (oTestObject.status.booleanValue() == false)); assertEquals(true, (oTestObject.nome.intValue() > 0)); oTestObject.handleEvent("fazerCadastroInativosEvent"); assertEquals(true, (oTestObject.state == State.mostrandoInativos)); } }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.mapper.attachments; import org.elasticsearch.common.Base64; import org.elasticsearch.common.compress.CompressedXContent; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.index.MapperTestUtils; import org.elasticsearch.index.mapper.DocumentMapper; import org.elasticsearch.index.mapper.DocumentMapperParser; import org.elasticsearch.index.mapper.MapperService; import org.elasticsearch.index.mapper.ParsedDocument; import org.elasticsearch.index.mapper.core.DateFieldMapper; import org.elasticsearch.index.mapper.core.TextFieldMapper; import org.junit.Before; import java.nio.charset.StandardCharsets; import static org.elasticsearch.test.StreamsUtils.copyToStringFromClasspath; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.startsWith; /** * */ public class MultifieldAttachmentMapperTests extends AttachmentUnitTestCase { private DocumentMapperParser mapperParser; @Before public void setupMapperParser() throws Exception { mapperParser = MapperTestUtils.newMapperService(createTempDir(), Settings.EMPTY, getIndicesModuleWithRegisteredAttachmentMapper()).documentMapperParser(); } public void testSimpleMappings() throws Exception { String mapping = copyToStringFromClasspath("/org/elasticsearch/index/mapper/attachment/test/unit/multifield/multifield-mapping.json"); DocumentMapper docMapper = mapperParser.parse("person", new CompressedXContent(mapping)); assertThat(docMapper.mappers().getMapper("file.content"), instanceOf(TextFieldMapper.class)); assertThat(docMapper.mappers().getMapper("file.content.suggest"), instanceOf(TextFieldMapper.class)); assertThat(docMapper.mappers().getMapper("file.date"), instanceOf(DateFieldMapper.class)); assertThat(docMapper.mappers().getMapper("file.date.string"), instanceOf(TextFieldMapper.class)); assertThat(docMapper.mappers().getMapper("file.title"), instanceOf(TextFieldMapper.class)); assertThat(docMapper.mappers().getMapper("file.title.suggest"), instanceOf(TextFieldMapper.class)); assertThat(docMapper.mappers().getMapper("file.name"), instanceOf(TextFieldMapper.class)); assertThat(docMapper.mappers().getMapper("file.name.suggest"), instanceOf(TextFieldMapper.class)); assertThat(docMapper.mappers().getMapper("file.author"), instanceOf(TextFieldMapper.class)); assertThat(docMapper.mappers().getMapper("file.author.suggest"), instanceOf(TextFieldMapper.class)); assertThat(docMapper.mappers().getMapper("file.keywords"), instanceOf(TextFieldMapper.class)); assertThat(docMapper.mappers().getMapper("file.keywords.suggest"), instanceOf(TextFieldMapper.class)); assertThat(docMapper.mappers().getMapper("file.content_type"), instanceOf(TextFieldMapper.class)); assertThat(docMapper.mappers().getMapper("file.content_type.suggest"), instanceOf(TextFieldMapper.class)); } public void testExternalValues() throws Exception { String originalText = "This is an elasticsearch mapper attachment test."; String forcedName = "dummyname.txt"; String bytes = Base64.encodeBytes(originalText.getBytes(StandardCharsets.ISO_8859_1)); MapperService mapperService = MapperTestUtils.newMapperService(createTempDir(), Settings.EMPTY, getIndicesModuleWithRegisteredAttachmentMapper()); String mapping = copyToStringFromClasspath("/org/elasticsearch/index/mapper/attachment/test/unit/multifield/multifield-mapping.json"); DocumentMapper documentMapper = mapperService.documentMapperParser().parse("person", new CompressedXContent(mapping)); ParsedDocument doc = documentMapper.parse("person", "person", "1", XContentFactory.jsonBuilder() .startObject() .field("file", bytes) .endObject() .bytes()); assertThat(doc.rootDoc().getField("file.content"), notNullValue()); assertThat(doc.rootDoc().getField("file.content").stringValue(), is(originalText + "\n")); assertThat(doc.rootDoc().getField("file.content_type"), notNullValue()); assertThat(doc.rootDoc().getField("file.content_type").stringValue(), startsWith("text/plain;")); assertThat(doc.rootDoc().getField("file.content_type.suggest"), notNullValue()); assertThat(doc.rootDoc().getField("file.content_type.suggest").stringValue(), startsWith("text/plain;")); assertThat(doc.rootDoc().getField("file.content_length"), notNullValue()); assertThat(doc.rootDoc().getField("file.content_length").numericValue().intValue(), is(originalText.length())); assertThat(doc.rootDoc().getField("file.content.suggest"), notNullValue()); assertThat(doc.rootDoc().getField("file.content.suggest").stringValue(), is(originalText + "\n")); // Let's force some values doc = documentMapper.parse("person", "person", "1", XContentFactory.jsonBuilder() .startObject() .startObject("file") .field("_content", bytes) .field("_name", forcedName) .endObject() .endObject() .bytes()); assertThat(doc.rootDoc().getField("file.content"), notNullValue()); assertThat(doc.rootDoc().getField("file.content").stringValue(), is(originalText + "\n")); assertThat(doc.rootDoc().getField("file.content_type"), notNullValue()); assertThat(doc.rootDoc().getField("file.content_type").stringValue(), startsWith("text/plain;")); assertThat(doc.rootDoc().getField("file.content_type.suggest"), notNullValue()); assertThat(doc.rootDoc().getField("file.content_type.suggest").stringValue(), startsWith("text/plain;")); assertThat(doc.rootDoc().getField("file.content_length"), notNullValue()); assertThat(doc.rootDoc().getField("file.content_length").numericValue().intValue(), is(originalText.length())); assertThat(doc.rootDoc().getField("file.content.suggest"), notNullValue()); assertThat(doc.rootDoc().getField("file.content.suggest").stringValue(), is(originalText + "\n")); assertThat(doc.rootDoc().getField("file.name"), notNullValue()); assertThat(doc.rootDoc().getField("file.name").stringValue(), is(forcedName)); // In mapping we have default store:false assertThat(doc.rootDoc().getField("file.name").fieldType().stored(), is(false)); assertThat(doc.rootDoc().getField("file.name.suggest"), notNullValue()); assertThat(doc.rootDoc().getField("file.name.suggest").stringValue(), is(forcedName)); // In mapping we set store:true for suggest subfield assertThat(doc.rootDoc().getField("file.name.suggest").fieldType().stored(), is(true)); } public void testAllExternalValues() throws Exception { String originalText = "This is an elasticsearch mapper attachment test."; String forcedName = randomAsciiOfLength(20); String forcedLanguage = randomAsciiOfLength(20); String forcedContentType = randomAsciiOfLength(20); String bytes = Base64.encodeBytes(originalText.getBytes(StandardCharsets.ISO_8859_1)); MapperService mapperService = MapperTestUtils.newMapperService(createTempDir(), Settings.builder().put(AttachmentMapper.INDEX_ATTACHMENT_DETECT_LANGUAGE_SETTING.getKey(), true).build(), getIndicesModuleWithRegisteredAttachmentMapper()); String mapping = copyToStringFromClasspath("/org/elasticsearch/index/mapper/attachment/test/unit/multifield/multifield-mapping.json"); DocumentMapper documentMapper = mapperService.documentMapperParser().parse("person", new CompressedXContent(mapping)); ParsedDocument doc = documentMapper.parse("person", "person", "1", XContentFactory.jsonBuilder() .startObject() .startObject("file") .field("_content", bytes) .field("_name", forcedName) .field("_language", forcedLanguage) .field("_content_type", forcedContentType) .endObject() .endObject() .bytes()); // Note that we don't support forcing values for _title and _keywords assertThat(doc.rootDoc().getField("file.content"), notNullValue()); assertThat(doc.rootDoc().getField("file.content").stringValue(), is(originalText + "\n")); assertThat(doc.rootDoc().getField("file.name"), notNullValue()); assertThat(doc.rootDoc().getField("file.name").stringValue(), is(forcedName)); assertThat(doc.rootDoc().getField("file.language"), notNullValue()); assertThat(doc.rootDoc().getField("file.language").stringValue(), is(forcedLanguage)); assertThat(doc.rootDoc().getField("file.content_type"), notNullValue()); assertThat(doc.rootDoc().getField("file.content_type").stringValue(), is(forcedContentType)); } }
package com.omega.amazehing.game.entity.system; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.badlogic.ashley.core.ComponentMapper; import com.badlogic.ashley.core.Engine; import com.badlogic.ashley.core.Entity; import com.badlogic.ashley.core.EntitySystem; import com.badlogic.ashley.core.Family; import com.badlogic.ashley.utils.ImmutableArray; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Buttons; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import com.omega.amazehing.Constants; import com.omega.amazehing.game.entity.EntityEngine; import com.omega.amazehing.game.entity.component.ComponentMapperHandler; import com.omega.amazehing.game.entity.component.InteractionComponent; import com.omega.amazehing.game.entity.component.transform.PositionComponent; import com.omega.amazehing.game.entity.component.transform.SizeComponent; import com.omega.amazehing.game.entity.system.render.CameraSystem; import com.omega.amazehing.game.input.action.interaction.AbstractInteraction; public class InteractiveObjectSystem extends EntitySystem { private static final Logger logger = LoggerFactory.getLogger(InteractiveObjectSystem.class); private EntityEngine engine; private ImmutableArray<Entity> entities; private boolean update = true; private boolean lastLeftCLick; private boolean lastRightClick; private boolean leftClick; private boolean rightClick; private Vector3 unprojectVect; private Entity lastActivated; private static final ComponentMapper<PositionComponent> posMapper = ComponentMapperHandler .getPositionMapper(); private static final ComponentMapper<SizeComponent> scaleMapper = ComponentMapperHandler .getSizeMapper(); private static final ComponentMapper<InteractionComponent> interactionMapper = ComponentMapperHandler .getInteractionMapper(); private Entity lastOvered; public InteractiveObjectSystem() { super(Constants.Game.System.INTERACTIVE_OBJECT_SYSTEM_PRIORITY); } @SuppressWarnings("unchecked") @Override public void addedToEngine(Engine engine) { this.engine = (EntityEngine) engine; entities = engine.getEntitiesFor(Family.all(InteractionComponent.class).get()); unprojectVect = new Vector3(); } @Override public void update(float deltaTime) { if (!update) { return; } CameraSystem _cameraSystem = engine.getSystem(CameraSystem.class); Camera _cam = _cameraSystem.getMainCamera(); unprojectVect.set(Gdx.input.getX(), Gdx.input.getY(), 0f); _cam.unproject(unprojectVect); float _x = unprojectVect.x; float _y = unprojectVect.y; boolean _isProcessed = false; for (Entity _e : entities) { InteractionComponent _interactionComp = interactionMapper.get(_e); AbstractInteraction _interaction = _interactionComp.getInteraction(); boolean _isOver = isOver(_e, _x, _y); if (_isOver && lastOvered != _e) { _interaction.onOver(_e, true); lastOvered = _e; _isProcessed = true; } else if (!_isOver && lastOvered == _e) { _interaction.onOver(_e, false); lastOvered = null; _isProcessed = true; } if (_isOver && leftClick && leftClick != lastLeftCLick) { Gdx.app.debug("Interaction", "Activated"); _interaction.onLeftCLick(_e, true); lastActivated = _e; _isProcessed = true; } else if (!leftClick && lastActivated == _e) { _interaction.onLeftCLick(_e, false); lastActivated = null; _isProcessed = true; } if (_isProcessed) { break; } } lastLeftCLick = leftClick; lastRightClick = rightClick; } private boolean isOver(Entity entity, float x, float y) { PositionComponent _posComp = posMapper.get(entity); SizeComponent _scaleComp = scaleMapper.get(entity); Vector2 _entityPos = _posComp.getPosition(); float _halfWidth = _scaleComp.getWidth() * 0.5f; float _halfHeight = _scaleComp.getHeight() * 0.5f; if (x < _entityPos.x - _halfWidth || x > _entityPos.x + _halfWidth || y < _entityPos.y - _halfHeight || y > _entityPos.y + _halfHeight) { return false; } return true; } public boolean fire(int button, boolean isDown) { if (!update) { return false; } switch (button) { case Buttons.LEFT: leftClick = isDown; return true; case Buttons.RIGHT: rightClick = isDown; return true; default: return false; } } public void setUpdate(boolean canUpdate) { update = canUpdate; } public void reset() { fire(Buttons.LEFT, false); fire(Buttons.RIGHT, false); setUpdate(false); } }
package net.agilepartner.workshops.cqrs.domain; import java.util.UUID; import net.agilepartner.workshops.cqrs.core.Command; public class CheckInventoryItemIn extends Command { private static final long serialVersionUID = 1L; public int quantity; public static CheckInventoryItemIn create(UUID aggregateId, int quantity) { CheckInventoryItemIn cmd = new CheckInventoryItemIn(); cmd.id = UUID.randomUUID(); cmd.aggregateId = aggregateId; cmd.quantity = quantity; return cmd; } }
private static String encryptMD5(String password, Long digestSeed) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.reset(); digest.update(password.getBytes("UTF-8")); digest.update(digestSeed.toString().getBytes("UTF-8")); byte[] messageDigest = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { hexString.append(Integer.toHexString(0xff & messageDigest[i])); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (NullPointerException e) { return new StringBuffer().toString(); } }
package com.nature.third.vo.flow; import java.io.Serializable; public class ThirdPropertieVo implements Serializable { private static final long serialVersionUID = 1L; private String name; private String value; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
package gitapi.callablecommitsapi.codesamplemodification; import domain.code.investigatedcallable.InvestigatedCallable; import gitapi.callablecommitsapi.fileversionsapi.FileVersion; import lombok.AccessLevel; import lombok.NoArgsConstructor; import java.util.ArrayList; import java.util.List; import java.util.Optional; @NoArgsConstructor(access = AccessLevel.PRIVATE) public class CodeSampleModificationsProvider { public static List<CodeSampleModification> from(InvestigatedCallable currentCodeSample, List<FileVersion> fileVersions) { List<CodeSampleModification> codeSampleModifications = new ArrayList<>(); boolean existInPreviousVersion = true; for (int currentVersion = 0; currentVersion < fileVersions.size() - 1 && existInPreviousVersion; currentVersion++) { int previousVersion = currentVersion + 1; FileVersion currentFileVersion = fileVersions.get(currentVersion); FileVersion previousFileVersion = fileVersions.get(previousVersion); String currentHash = currentFileVersion.getHash(); Optional<InvestigatedCallable> previousCodeSampleOptional = findPreviousCodeSample(currentCodeSample, previousFileVersion, currentFileVersion); CodeSampleModification codeSampleModification; if (previousCodeSampleOptional.isPresent()) { InvestigatedCallable previousCodeSample = previousCodeSampleOptional.get(); codeSampleModification = getCodeSampleModification(currentHash, currentCodeSample, previousCodeSample); currentCodeSample = previousCodeSample; } else { existInPreviousVersion = false; codeSampleModification = getModificationCreatingCodeSample(currentHash, currentCodeSample); } codeSampleModifications.add(codeSampleModification); } if (existInPreviousVersion) { FileVersion lastFileVersion = fileVersions.get(fileVersions.size() - 1); String hash = lastFileVersion.getHash(); CodeSampleModification codeSampleModification = getModificationCreatingCodeSample(hash, currentCodeSample); codeSampleModifications.add(codeSampleModification); } return codeSampleModifications; } private static Optional<InvestigatedCallable> findPreviousCodeSample(InvestigatedCallable currentCodeSample, FileVersion previousFileVersion, FileVersion currentFileVersion) { try { return currentCodeSample.findPreviousCodeSample(previousFileVersion, currentFileVersion); } catch (Exception e) { return Optional.empty(); } } private static CodeSampleModification getCodeSampleModification(String hash, InvestigatedCallable currentCodeSample, InvestigatedCallable previousCodeSample) { List<String> codeLinesFromCurrentVersion = currentCodeSample.getCodeLines(); List<String> codeLinesFromPreviousVersion = previousCodeSample.getCodeLines(); return CodeSampleModificationMapper.from(hash, codeLinesFromCurrentVersion, codeLinesFromPreviousVersion); } private static CodeSampleModification getModificationCreatingCodeSample(String hash, InvestigatedCallable currentCodeSample) { List<String> codeLinesFromCurrentVersion = currentCodeSample.getCodeLines(); return CodeSampleModificationMapper.from(hash, codeLinesFromCurrentVersion); } }
/* * Copyright 2002-2010 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.web.servlet.tags.form; import java.beans.PropertyEditorSupport; import java.io.StringReader; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import javax.servlet.jsp.tagext.Tag; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.springframework.beans.Colour; import org.springframework.beans.Pet; import org.springframework.beans.TestBean; import org.springframework.beans.propertyeditors.StringTrimmerEditor; import org.springframework.format.Formatter; import org.springframework.format.support.FormattingConversionService; import org.springframework.util.ObjectUtils; import org.springframework.validation.BeanPropertyBindingResult; import org.springframework.validation.BindingResult; /** * @author Thomas Risberg * @author Mark Fisher * @author Juergen Hoeller * @author Benjamin Hoffmann * @author Jeremy Grelle */ public class CheckboxesTagTests extends AbstractFormTagTests { private CheckboxesTag tag; private TestBean bean; protected void onSetUp() { this.tag = new CheckboxesTag() { protected TagWriter createTagWriter() { return new TagWriter(getWriter()); } }; this.tag.setPageContext(getPageContext()); } public void testWithMultiValueArray() throws Exception { this.tag.setPath("stringArray"); this.tag.setItems(new Object[] {"foo", "bar", "baz"}); int result = this.tag.doStartTag(); assertEquals(Tag.SKIP_BODY, result); String output = getOutput(); // wrap the output so it is valid XML output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element spanElement1 = (Element) document.getRootElement().elements().get(0); Element checkboxElement1 = (Element) spanElement1.elements().get(0); assertEquals("input", checkboxElement1.getName()); assertEquals("checkbox", checkboxElement1.attribute("type").getValue()); assertEquals("stringArray", checkboxElement1.attribute("name").getValue()); assertEquals("checked", checkboxElement1.attribute("checked").getValue()); assertEquals("foo", checkboxElement1.attribute("value").getValue()); assertEquals("foo", spanElement1.getStringValue()); Element spanElement2 = (Element) document.getRootElement().elements().get(1); Element checkboxElement2 = (Element) spanElement2.elements().get(0); assertEquals("input", checkboxElement2.getName()); assertEquals("checkbox", checkboxElement2.attribute("type").getValue()); assertEquals("stringArray", checkboxElement2.attribute("name").getValue()); assertEquals("checked", checkboxElement2.attribute("checked").getValue()); assertEquals("bar", checkboxElement2.attribute("value").getValue()); assertEquals("bar", spanElement2.getStringValue()); Element spanElement3 = (Element) document.getRootElement().elements().get(2); Element checkboxElement3 = (Element) spanElement3.elements().get(0); assertEquals("input", checkboxElement3.getName()); assertEquals("checkbox", checkboxElement3.attribute("type").getValue()); assertEquals("stringArray", checkboxElement3.attribute("name").getValue()); assertNull("not checked", checkboxElement3.attribute("checked")); assertEquals("baz", checkboxElement3.attribute("value").getValue()); assertEquals("baz", spanElement3.getStringValue()); } public void testWithMultiValueArrayAndDynamicAttributes() throws Exception { String dynamicAttribute1 = "attr1"; String dynamicAttribute2 = "attr2"; this.tag.setPath("stringArray"); this.tag.setItems(new Object[] {"foo", "bar", "baz"}); this.tag.setDynamicAttribute(null, dynamicAttribute1, dynamicAttribute1); this.tag.setDynamicAttribute(null, dynamicAttribute2, dynamicAttribute2); int result = this.tag.doStartTag(); assertEquals(Tag.SKIP_BODY, result); String output = getOutput(); // wrap the output so it is valid XML output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element spanElement1 = (Element) document.getRootElement().elements().get(0); Element checkboxElement1 = (Element) spanElement1.elements().get(0); assertEquals("input", checkboxElement1.getName()); assertEquals("checkbox", checkboxElement1.attribute("type").getValue()); assertEquals("stringArray", checkboxElement1.attribute("name").getValue()); assertEquals("checked", checkboxElement1.attribute("checked").getValue()); assertEquals("foo", checkboxElement1.attribute("value").getValue()); assertEquals("foo", spanElement1.getStringValue()); assertEquals(dynamicAttribute1, checkboxElement1.attribute(dynamicAttribute1).getValue()); assertEquals(dynamicAttribute2, checkboxElement1.attribute(dynamicAttribute2).getValue()); Element spanElement2 = (Element) document.getRootElement().elements().get(1); Element checkboxElement2 = (Element) spanElement2.elements().get(0); assertEquals("input", checkboxElement2.getName()); assertEquals("checkbox", checkboxElement2.attribute("type").getValue()); assertEquals("stringArray", checkboxElement2.attribute("name").getValue()); assertEquals("checked", checkboxElement2.attribute("checked").getValue()); assertEquals("bar", checkboxElement2.attribute("value").getValue()); assertEquals("bar", spanElement2.getStringValue()); assertEquals(dynamicAttribute1, checkboxElement2.attribute(dynamicAttribute1).getValue()); assertEquals(dynamicAttribute2, checkboxElement2.attribute(dynamicAttribute2).getValue()); Element spanElement3 = (Element) document.getRootElement().elements().get(2); Element checkboxElement3 = (Element) spanElement3.elements().get(0); assertEquals("input", checkboxElement3.getName()); assertEquals("checkbox", checkboxElement3.attribute("type").getValue()); assertEquals("stringArray", checkboxElement3.attribute("name").getValue()); assertNull("not checked", checkboxElement3.attribute("checked")); assertEquals("baz", checkboxElement3.attribute("value").getValue()); assertEquals("baz", spanElement3.getStringValue()); assertEquals(dynamicAttribute1, checkboxElement3.attribute(dynamicAttribute1).getValue()); assertEquals(dynamicAttribute2, checkboxElement3.attribute(dynamicAttribute2).getValue()); } public void testWithMultiValueArrayWithDelimiter() throws Exception { this.tag.setDelimiter("<br/>"); this.tag.setPath("stringArray"); this.tag.setItems(new Object[] {"foo", "bar", "baz"}); int result = this.tag.doStartTag(); assertEquals(Tag.SKIP_BODY, result); String output = getOutput(); // wrap the output so it is valid XML output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element spanElement1 = (Element) document.getRootElement().elements().get(0); Element delimiterElement1 = spanElement1.element("br"); assertNull(delimiterElement1); Element checkboxElement1 = (Element) spanElement1.elements().get(0); assertEquals("input", checkboxElement1.getName()); assertEquals("checkbox", checkboxElement1.attribute("type").getValue()); assertEquals("stringArray", checkboxElement1.attribute("name").getValue()); assertEquals("checked", checkboxElement1.attribute("checked").getValue()); assertEquals("foo", checkboxElement1.attribute("value").getValue()); assertEquals("foo", spanElement1.getStringValue()); Element spanElement2 = (Element) document.getRootElement().elements().get(1); Element delimiterElement2 = (Element) spanElement2.elements().get(0); assertEquals("br", delimiterElement2.getName()); Element checkboxElement2 = (Element) spanElement2.elements().get(1); assertEquals("input", checkboxElement2.getName()); assertEquals("checkbox", checkboxElement2.attribute("type").getValue()); assertEquals("stringArray", checkboxElement2.attribute("name").getValue()); assertEquals("checked", checkboxElement2.attribute("checked").getValue()); assertEquals("bar", checkboxElement2.attribute("value").getValue()); assertEquals("bar", spanElement2.getStringValue()); Element spanElement3 = (Element) document.getRootElement().elements().get(2); Element delimiterElement3 = (Element) spanElement3.elements().get(0); assertEquals("br", delimiterElement3.getName()); Element checkboxElement3 = (Element) spanElement3.elements().get(1); assertEquals("input", checkboxElement3.getName()); assertEquals("checkbox", checkboxElement3.attribute("type").getValue()); assertEquals("stringArray", checkboxElement3.attribute("name").getValue()); assertNull("not checked", checkboxElement3.attribute("checked")); assertEquals("baz", checkboxElement3.attribute("value").getValue()); assertEquals("baz", spanElement3.getStringValue()); } public void testWithMultiValueMap() throws Exception { this.tag.setPath("stringArray"); Map m = new LinkedHashMap(); m.put("foo", "FOO"); m.put("bar", "BAR"); m.put("baz", "BAZ"); this.tag.setItems(m); int result = this.tag.doStartTag(); assertEquals(Tag.SKIP_BODY, result); String output = getOutput(); // wrap the output so it is valid XML output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element spanElement1 = (Element) document.getRootElement().elements().get(0); Element checkboxElement1 = (Element) spanElement1.elements().get(0); assertEquals("input", checkboxElement1.getName()); assertEquals("checkbox", checkboxElement1.attribute("type").getValue()); assertEquals("stringArray", checkboxElement1.attribute("name").getValue()); assertEquals("checked", checkboxElement1.attribute("checked").getValue()); assertEquals("foo", checkboxElement1.attribute("value").getValue()); assertEquals("FOO", spanElement1.getStringValue()); Element spanElement2 = (Element) document.getRootElement().elements().get(1); Element checkboxElement2 = (Element) spanElement2.elements().get(0); assertEquals("input", checkboxElement2.getName()); assertEquals("checkbox", checkboxElement2.attribute("type").getValue()); assertEquals("stringArray", checkboxElement2.attribute("name").getValue()); assertEquals("checked", checkboxElement2.attribute("checked").getValue()); assertEquals("bar", checkboxElement2.attribute("value").getValue()); assertEquals("BAR", spanElement2.getStringValue()); Element spanElement3 = (Element) document.getRootElement().elements().get(2); Element checkboxElement3 = (Element) spanElement3.elements().get(0); assertEquals("input", checkboxElement3.getName()); assertEquals("checkbox", checkboxElement3.attribute("type").getValue()); assertEquals("stringArray", checkboxElement3.attribute("name").getValue()); assertNull("not checked", checkboxElement3.attribute("checked")); assertEquals("baz", checkboxElement3.attribute("value").getValue()); assertEquals("BAZ", spanElement3.getStringValue()); } public void testWithPetItemsMap() throws Exception { this.tag.setPath("someSet"); Map m = new LinkedHashMap(); m.put(new ItemPet("PET1"), "PET1Label"); m.put(new ItemPet("PET2"), "PET2Label"); m.put(new ItemPet("PET3"), "PET3Label"); this.tag.setItems(m); tag.setItemValue("name"); int result = this.tag.doStartTag(); assertEquals(Tag.SKIP_BODY, result); String output = getOutput(); // wrap the output so it is valid XML output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element spanElement1 = (Element) document.getRootElement().elements().get(0); Element checkboxElement1 = (Element) spanElement1.elements().get(0); assertEquals("input", checkboxElement1.getName()); assertEquals("checkbox", checkboxElement1.attribute("type").getValue()); assertEquals("someSet", checkboxElement1.attribute("name").getValue()); assertEquals("checked", checkboxElement1.attribute("checked").getValue()); assertEquals("PET1", checkboxElement1.attribute("value").getValue()); assertEquals("PET1Label", spanElement1.getStringValue()); Element spanElement2 = (Element) document.getRootElement().elements().get(1); Element checkboxElement2 = (Element) spanElement2.elements().get(0); assertEquals("input", checkboxElement2.getName()); assertEquals("checkbox", checkboxElement2.attribute("type").getValue()); assertEquals("someSet", checkboxElement2.attribute("name").getValue()); assertEquals("checked", checkboxElement2.attribute("checked").getValue()); assertEquals("PET2", checkboxElement2.attribute("value").getValue()); assertEquals("PET2Label", spanElement2.getStringValue()); Element spanElement3 = (Element) document.getRootElement().elements().get(2); Element checkboxElement3 = (Element) spanElement3.elements().get(0); assertEquals("input", checkboxElement3.getName()); assertEquals("checkbox", checkboxElement3.attribute("type").getValue()); assertEquals("someSet", checkboxElement3.attribute("name").getValue()); assertNull("not checked", checkboxElement3.attribute("checked")); assertEquals("PET3", checkboxElement3.attribute("value").getValue()); assertEquals("PET3Label", spanElement3.getStringValue()); } public void testWithMultiValueMapWithDelimiter() throws Exception { String delimiter = " | "; this.tag.setDelimiter(delimiter); this.tag.setPath("stringArray"); Map m = new LinkedHashMap(); m.put("foo", "FOO"); m.put("bar", "BAR"); m.put("baz", "BAZ"); this.tag.setItems(m); int result = this.tag.doStartTag(); assertEquals(Tag.SKIP_BODY, result); String output = getOutput(); // wrap the output so it is valid XML output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element spanElement1 = (Element) document.getRootElement().elements().get(0); Element checkboxElement1 = (Element) spanElement1.elements().get(0); assertEquals("input", checkboxElement1.getName()); assertEquals("checkbox", checkboxElement1.attribute("type").getValue()); assertEquals("stringArray", checkboxElement1.attribute("name").getValue()); assertEquals("checked", checkboxElement1.attribute("checked").getValue()); assertEquals("foo", checkboxElement1.attribute("value").getValue()); assertEquals("FOO", spanElement1.getStringValue()); Element spanElement2 = (Element) document.getRootElement().elements().get(1); Element checkboxElement2 = (Element) spanElement2.elements().get(0); assertEquals("input", checkboxElement2.getName()); assertEquals("checkbox", checkboxElement2.attribute("type").getValue()); assertEquals("stringArray", checkboxElement2.attribute("name").getValue()); assertEquals("checked", checkboxElement2.attribute("checked").getValue()); assertEquals("bar", checkboxElement2.attribute("value").getValue()); assertEquals(delimiter + "BAR", spanElement2.getStringValue()); Element spanElement3 = (Element) document.getRootElement().elements().get(2); Element checkboxElement3 = (Element) spanElement3.elements().get(0); assertEquals("input", checkboxElement3.getName()); assertEquals("checkbox", checkboxElement3.attribute("type").getValue()); assertEquals("stringArray", checkboxElement3.attribute("name").getValue()); assertNull("not checked", checkboxElement3.attribute("checked")); assertEquals("baz", checkboxElement3.attribute("value").getValue()); assertEquals(delimiter + "BAZ", spanElement3.getStringValue()); } public void testWithMultiValueWithEditor() throws Exception { this.tag.setPath("stringArray"); this.tag.setItems(new Object[] {" foo", " bar", " baz"}); BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(this.bean, COMMAND_NAME); MyStringTrimmerEditor editor = new MyStringTrimmerEditor(); bindingResult.getPropertyEditorRegistry().registerCustomEditor(String.class, editor); getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, bindingResult); int result = this.tag.doStartTag(); assertEquals(Tag.SKIP_BODY, result); assertEquals(3, editor.allProcessedValues.size()); String output = getOutput(); // wrap the output so it is valid XML output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element spanElement1 = (Element) document.getRootElement().elements().get(0); Element checkboxElement1 = (Element) spanElement1.elements().get(0); assertEquals("input", checkboxElement1.getName()); assertEquals("checkbox", checkboxElement1.attribute("type").getValue()); assertEquals("stringArray", checkboxElement1.attribute("name").getValue()); assertEquals("checked", checkboxElement1.attribute("checked").getValue()); assertEquals(" foo", checkboxElement1.attribute("value").getValue()); Element spanElement2 = (Element) document.getRootElement().elements().get(1); Element checkboxElement2 = (Element) spanElement2.elements().get(0); assertEquals("input", checkboxElement2.getName()); assertEquals("checkbox", checkboxElement2.attribute("type").getValue()); assertEquals("stringArray", checkboxElement2.attribute("name").getValue()); assertEquals("checked", checkboxElement2.attribute("checked").getValue()); assertEquals(" bar", checkboxElement2.attribute("value").getValue()); Element spanElement3 = (Element) document.getRootElement().elements().get(2); Element checkboxElement3 = (Element) spanElement3.elements().get(0); assertEquals("input", checkboxElement3.getName()); assertEquals("checkbox", checkboxElement3.attribute("type").getValue()); assertEquals("stringArray", checkboxElement3.attribute("name").getValue()); assertNull("not checked", checkboxElement3.attribute("checked")); assertEquals(" baz", checkboxElement3.attribute("value").getValue()); } public void testWithMultiValueWithReverseEditor() throws Exception { this.tag.setPath("stringArray"); this.tag.setItems(new Object[] {"FOO", "BAR", "BAZ"}); BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(this.bean, COMMAND_NAME); MyLowerCaseEditor editor = new MyLowerCaseEditor(); bindingResult.getPropertyEditorRegistry().registerCustomEditor(String.class, editor); getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, bindingResult); int result = this.tag.doStartTag(); assertEquals(Tag.SKIP_BODY, result); String output = getOutput(); // wrap the output so it is valid XML output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element spanElement1 = (Element) document.getRootElement().elements().get(0); Element checkboxElement1 = (Element) spanElement1.elements().get(0); assertEquals("input", checkboxElement1.getName()); assertEquals("checkbox", checkboxElement1.attribute("type").getValue()); assertEquals("stringArray", checkboxElement1.attribute("name").getValue()); assertEquals("checked", checkboxElement1.attribute("checked").getValue()); assertEquals("FOO", checkboxElement1.attribute("value").getValue()); Element spanElement2 = (Element) document.getRootElement().elements().get(1); Element checkboxElement2 = (Element) spanElement2.elements().get(0); assertEquals("input", checkboxElement2.getName()); assertEquals("checkbox", checkboxElement2.attribute("type").getValue()); assertEquals("stringArray", checkboxElement2.attribute("name").getValue()); assertEquals("checked", checkboxElement2.attribute("checked").getValue()); assertEquals("BAR", checkboxElement2.attribute("value").getValue()); Element spanElement3 = (Element) document.getRootElement().elements().get(2); Element checkboxElement3 = (Element) spanElement3.elements().get(0); assertEquals("input", checkboxElement3.getName()); assertEquals("checkbox", checkboxElement3.attribute("type").getValue()); assertEquals("stringArray", checkboxElement3.attribute("name").getValue()); assertNull("not checked", checkboxElement3.attribute("checked")); assertEquals("BAZ", checkboxElement3.attribute("value").getValue()); } public void testWithMultiValueWithFormatter() throws Exception { this.tag.setPath("stringArray"); this.tag.setItems(new Object[] {" foo", " bar", " baz"}); BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(this.bean, COMMAND_NAME); FormattingConversionService cs = new FormattingConversionService(); cs.addFormatterForFieldType(String.class, new Formatter<String>() { public String print(String object, Locale locale) { return object; } public String parse(String text, Locale locale) throws ParseException { return text.trim(); } }); bindingResult.initConversion(cs); getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, bindingResult); int result = this.tag.doStartTag(); assertEquals(Tag.SKIP_BODY, result); String output = getOutput(); // wrap the output so it is valid XML output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element spanElement1 = (Element) document.getRootElement().elements().get(0); Element checkboxElement1 = (Element) spanElement1.elements().get(0); assertEquals("input", checkboxElement1.getName()); assertEquals("checkbox", checkboxElement1.attribute("type").getValue()); assertEquals("stringArray", checkboxElement1.attribute("name").getValue()); assertEquals("checked", checkboxElement1.attribute("checked").getValue()); assertEquals(" foo", checkboxElement1.attribute("value").getValue()); Element spanElement2 = (Element) document.getRootElement().elements().get(1); Element checkboxElement2 = (Element) spanElement2.elements().get(0); assertEquals("input", checkboxElement2.getName()); assertEquals("checkbox", checkboxElement2.attribute("type").getValue()); assertEquals("stringArray", checkboxElement2.attribute("name").getValue()); assertEquals("checked", checkboxElement2.attribute("checked").getValue()); assertEquals(" bar", checkboxElement2.attribute("value").getValue()); Element spanElement3 = (Element) document.getRootElement().elements().get(2); Element checkboxElement3 = (Element) spanElement3.elements().get(0); assertEquals("input", checkboxElement3.getName()); assertEquals("checkbox", checkboxElement3.attribute("type").getValue()); assertEquals("stringArray", checkboxElement3.attribute("name").getValue()); assertNull("not checked", checkboxElement3.attribute("checked")); assertEquals(" baz", checkboxElement3.attribute("value").getValue()); } public void testCollectionOfPets() throws Exception { this.tag.setPath("pets"); List allPets = new ArrayList(); allPets.add(new ItemPet("Rudiger")); allPets.add(new ItemPet("Spot")); allPets.add(new ItemPet("Checkers")); allPets.add(new ItemPet("Fluffy")); allPets.add(new ItemPet("Mufty")); this.tag.setItems(allPets); this.tag.setItemValue("name"); this.tag.setItemLabel("label"); int result = this.tag.doStartTag(); assertEquals(Tag.SKIP_BODY, result); String output = getOutput(); // wrap the output so it is valid XML output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element spanElement1 = (Element) document.getRootElement().elements().get(0); Element checkboxElement1 = (Element) spanElement1.elements().get(0); assertEquals("input", checkboxElement1.getName()); assertEquals("checkbox", checkboxElement1.attribute("type").getValue()); assertEquals("pets", checkboxElement1.attribute("name").getValue()); assertEquals("checked", checkboxElement1.attribute("checked").getValue()); assertEquals("Rudiger", checkboxElement1.attribute("value").getValue()); assertEquals("RUDIGER", spanElement1.getStringValue()); Element spanElement2 = (Element) document.getRootElement().elements().get(1); Element checkboxElement2 = (Element) spanElement2.elements().get(0); assertEquals("input", checkboxElement2.getName()); assertEquals("checkbox", checkboxElement2.attribute("type").getValue()); assertEquals("pets", checkboxElement2.attribute("name").getValue()); assertEquals("checked", checkboxElement2.attribute("checked").getValue()); assertEquals("Spot", checkboxElement2.attribute("value").getValue()); assertEquals("SPOT", spanElement2.getStringValue()); Element spanElement3 = (Element) document.getRootElement().elements().get(2); Element checkboxElement3 = (Element) spanElement3.elements().get(0); assertEquals("input", checkboxElement3.getName()); assertEquals("checkbox", checkboxElement3.attribute("type").getValue()); assertEquals("pets", checkboxElement3.attribute("name").getValue()); assertNull("not checked", checkboxElement3.attribute("checked")); assertEquals("Checkers", checkboxElement3.attribute("value").getValue()); assertEquals("CHECKERS", spanElement3.getStringValue()); Element spanElement4 = (Element) document.getRootElement().elements().get(3); Element checkboxElement4 = (Element) spanElement4.elements().get(0); assertEquals("input", checkboxElement4.getName()); assertEquals("checkbox", checkboxElement4.attribute("type").getValue()); assertEquals("pets", checkboxElement4.attribute("name").getValue()); assertEquals("checked", checkboxElement4.attribute("checked").getValue()); assertEquals("Fluffy", checkboxElement4.attribute("value").getValue()); assertEquals("FLUFFY", spanElement4.getStringValue()); Element spanElement5 = (Element) document.getRootElement().elements().get(4); Element checkboxElement5 = (Element) spanElement5.elements().get(0); assertEquals("input", checkboxElement5.getName()); assertEquals("checkbox", checkboxElement5.attribute("type").getValue()); assertEquals("pets", checkboxElement5.attribute("name").getValue()); assertEquals("checked", checkboxElement5.attribute("checked").getValue()); assertEquals("Mufty", checkboxElement5.attribute("value").getValue()); assertEquals("MUFTY", spanElement5.getStringValue()); } /** * Test case where items toString() doesn't fit the item ID */ public void testCollectionOfItemPets() throws Exception { this.tag.setPath("someSet"); List allPets = new ArrayList(); allPets.add(new ItemPet("PET1")); allPets.add(new ItemPet("PET2")); allPets.add(new ItemPet("PET3")); this.tag.setItems(allPets); this.tag.setItemValue("name"); this.tag.setItemLabel("label"); int result = this.tag.doStartTag(); assertEquals(Tag.SKIP_BODY, result); String output = getOutput(); // wrap the output so it is valid XML output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element spanElement1 = (Element) document.getRootElement().elements().get(0); Element checkboxElement1 = (Element) spanElement1.elements().get(0); assertEquals("input", checkboxElement1.getName()); assertEquals("checkbox", checkboxElement1.attribute("type").getValue()); assertEquals("someSet", checkboxElement1.attribute("name").getValue()); assertNotNull("should be checked", checkboxElement1.attribute("checked")); assertEquals("checked", checkboxElement1.attribute("checked").getValue()); assertEquals("PET1", checkboxElement1.attribute("value").getValue()); assertEquals("PET1", spanElement1.getStringValue()); Element spanElement2 = (Element) document.getRootElement().elements().get(1); Element checkboxElement2 = (Element) spanElement2.elements().get(0); assertEquals("input", checkboxElement2.getName()); assertEquals("checkbox", checkboxElement2.attribute("type").getValue()); assertEquals("someSet", checkboxElement2.attribute("name").getValue()); assertNotNull("should be checked", checkboxElement2.attribute("checked")); assertEquals("checked", checkboxElement2.attribute("checked").getValue()); assertEquals("PET2", checkboxElement2.attribute("value").getValue()); assertEquals("PET2", spanElement2.getStringValue()); Element spanElement3 = (Element) document.getRootElement().elements().get(2); Element checkboxElement3 = (Element) spanElement3.elements().get(0); assertEquals("input", checkboxElement3.getName()); assertEquals("checkbox", checkboxElement3.attribute("type").getValue()); assertEquals("someSet", checkboxElement3.attribute("name").getValue()); assertNull("not checked", checkboxElement3.attribute("checked")); assertEquals("PET3", checkboxElement3.attribute("value").getValue()); assertEquals("PET3", spanElement3.getStringValue()); } public void testCollectionOfPetsWithEditor() throws Exception { this.tag.setPath("pets"); List allPets = new ArrayList(); allPets.add(new ItemPet("Rudiger")); allPets.add(new ItemPet("Spot")); allPets.add(new ItemPet("Checkers")); allPets.add(new ItemPet("Fluffy")); allPets.add(new ItemPet("Mufty")); this.tag.setItems(allPets); this.tag.setItemLabel("label"); this.tag.setId("myId"); BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(this.bean, COMMAND_NAME); PropertyEditorSupport editor = new ItemPet.CustomEditor(); bindingResult.getPropertyEditorRegistry().registerCustomEditor(ItemPet.class, editor); getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, bindingResult); int result = this.tag.doStartTag(); assertEquals(Tag.SKIP_BODY, result); String output = getOutput(); // wrap the output so it is valid XML output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element spanElement1 = (Element) document.getRootElement().elements().get(0); Element checkboxElement1 = (Element) spanElement1.elements().get(0); assertEquals("input", checkboxElement1.getName()); assertEquals("checkbox", checkboxElement1.attribute("type").getValue()); assertEquals("pets", checkboxElement1.attribute("name").getValue()); assertEquals("checked", checkboxElement1.attribute("checked").getValue()); assertEquals("Rudiger", checkboxElement1.attribute("value").getValue()); assertEquals("RUDIGER", spanElement1.getStringValue()); Element spanElement2 = (Element) document.getRootElement().elements().get(1); Element checkboxElement2 = (Element) spanElement2.elements().get(0); assertEquals("input", checkboxElement2.getName()); assertEquals("checkbox", checkboxElement2.attribute("type").getValue()); assertEquals("pets", checkboxElement2.attribute("name").getValue()); assertEquals("checked", checkboxElement2.attribute("checked").getValue()); assertEquals("Spot", checkboxElement2.attribute("value").getValue()); assertEquals("SPOT", spanElement2.getStringValue()); Element spanElement3 = (Element) document.getRootElement().elements().get(2); Element checkboxElement3 = (Element) spanElement3.elements().get(0); assertEquals("input", checkboxElement3.getName()); assertEquals("checkbox", checkboxElement3.attribute("type").getValue()); assertEquals("pets", checkboxElement3.attribute("name").getValue()); assertNull("not checked", checkboxElement3.attribute("checked")); assertEquals("Checkers", checkboxElement3.attribute("value").getValue()); assertEquals("CHECKERS", spanElement3.getStringValue()); Element spanElement4 = (Element) document.getRootElement().elements().get(3); Element checkboxElement4 = (Element) spanElement4.elements().get(0); assertEquals("input", checkboxElement4.getName()); assertEquals("checkbox", checkboxElement4.attribute("type").getValue()); assertEquals("pets", checkboxElement4.attribute("name").getValue()); assertEquals("checked", checkboxElement4.attribute("checked").getValue()); assertEquals("Fluffy", checkboxElement4.attribute("value").getValue()); assertEquals("FLUFFY", spanElement4.getStringValue()); Element spanElement5 = (Element) document.getRootElement().elements().get(4); Element checkboxElement5 = (Element) spanElement5.elements().get(0); assertEquals("input", checkboxElement5.getName()); assertEquals("checkbox", checkboxElement5.attribute("type").getValue()); assertEquals("pets", checkboxElement5.attribute("name").getValue()); assertEquals("checked", checkboxElement5.attribute("checked").getValue()); assertEquals("Mufty", checkboxElement5.attribute("value").getValue()); assertEquals("MUFTY", spanElement5.getStringValue()); } public void testWithNullValue() throws Exception { try { this.tag.setPath("name"); this.tag.doStartTag(); fail("Should not be able to render with a null value when binding to a non-boolean."); } catch (IllegalArgumentException ex) { // success } } public void testHiddenElementOmittedOnDisabled() throws Exception { this.tag.setPath("stringArray"); this.tag.setItems(new Object[] {"foo", "bar", "baz"}); this.tag.setDisabled("true"); int result = this.tag.doStartTag(); assertEquals(Tag.SKIP_BODY, result); String output = getOutput(); // wrap the output so it is valid XML output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element rootElement = document.getRootElement(); assertEquals("Both tag and hidden element rendered incorrectly", 3, rootElement.elements().size()); Element spanElement = (Element) document.getRootElement().elements().get(0); Element checkboxElement = (Element) spanElement.elements().get(0); assertEquals("input", checkboxElement.getName()); assertEquals("checkbox", checkboxElement.attribute("type").getValue()); assertEquals("stringArray", checkboxElement.attribute("name").getValue()); assertEquals("checked", checkboxElement.attribute("checked").getValue()); assertEquals("disabled", checkboxElement.attribute("disabled").getValue()); assertEquals("foo", checkboxElement.attribute("value").getValue()); } public void testSpanElementCustomizable() throws Exception { this.tag.setPath("stringArray"); this.tag.setItems(new Object[] {"foo", "bar", "baz"}); this.tag.setElement("element"); int result = this.tag.doStartTag(); assertEquals(Tag.SKIP_BODY, result); String output = getOutput(); // wrap the output so it is valid XML output = "<doc>" + output + "</doc>"; SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(output)); Element spanElement = (Element) document.getRootElement().elements().get(0); assertEquals("element", spanElement.getName()); } private Date getDate() { Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, 10); cal.set(Calendar.MONTH, 10); cal.set(Calendar.DATE, 10); cal.set(Calendar.HOUR, 10); cal.set(Calendar.MINUTE, 10); cal.set(Calendar.SECOND, 10); return cal.getTime(); } protected TestBean createTestBean() { List colours = new ArrayList(); colours.add(Colour.BLUE); colours.add(Colour.RED); colours.add(Colour.GREEN); List pets = new ArrayList(); pets.add(new Pet("Rudiger")); pets.add(new Pet("Spot")); pets.add(new Pet("Fluffy")); pets.add(new Pet("Mufty")); Set someObjects = new HashSet(); someObjects.add(new ItemPet("PET1")); someObjects.add(new ItemPet("PET2")); this.bean = new TestBean(); this.bean.setDate(getDate()); this.bean.setName("Rob Harrop"); this.bean.setJedi(true); this.bean.setSomeBoolean(new Boolean(true)); this.bean.setStringArray(new String[] {"bar", "foo"}); this.bean.setSomeIntegerArray(new Integer[] {new Integer(2), new Integer(1)}); this.bean.setOtherColours(colours); this.bean.setPets(pets); this.bean.setSomeSet(someObjects); List list = new ArrayList(); list.add("foo"); list.add("bar"); this.bean.setSomeList(list); return this.bean; } private static class MyStringTrimmerEditor extends StringTrimmerEditor { public final Set allProcessedValues = new HashSet(); public MyStringTrimmerEditor() { super(false); } public void setAsText(String text) { super.setAsText(text); this.allProcessedValues.add(getValue()); } } private static class MyLowerCaseEditor extends PropertyEditorSupport { public void setAsText(String text) throws IllegalArgumentException { setValue(text.toLowerCase()); } public String getAsText() { return ObjectUtils.nullSafeToString(getValue()).toUpperCase(); } } }
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 集团预算信息 * * @author auto create * @since 1.0, 2021-08-06 10:17:57 */ public class GroupBudgetSummaryDTO extends AlipayObject { private static final long serialVersionUID = 5872221481537731598L; /** * 预算受益部门编码 */ @ApiField("benefiting_dept") private String benefitingDept; /** * 预算受益部门 */ @ApiField("benefiting_dept_name") private String benefitingDeptName; /** * bg编码 */ @ApiField("bg_code") private String bgCode; /** * bu编码 */ @ApiField("bu_code") private String buCode; /** * 预算科目编码 */ @ApiField("budget_account") private String budgetAccount; /** * 预算科目名称 */ @ApiField("budget_account_name") private String budgetAccountName; /** * 集团预算年份 */ @ApiField("budget_fy") private String budgetFy; /** * 集团预算编码,由GB开头 */ @ApiField("group_budget_code") private String groupBudgetCode; /** * 预算编制部门编码 */ @ApiField("making_dept") private String makingDept; /** * 预算编制部门 */ @ApiField("making_dept_name") private String makingDeptName; /** * 剩余可用金额(单位:元) */ @ApiField("remain_amount") private String remainAmount; /** * 剩余可用金额币种 */ @ApiField("remain_amount_currency") private String remainAmountCurrency; public String getBenefitingDept() { return this.benefitingDept; } public void setBenefitingDept(String benefitingDept) { this.benefitingDept = benefitingDept; } public String getBenefitingDeptName() { return this.benefitingDeptName; } public void setBenefitingDeptName(String benefitingDeptName) { this.benefitingDeptName = benefitingDeptName; } public String getBgCode() { return this.bgCode; } public void setBgCode(String bgCode) { this.bgCode = bgCode; } public String getBuCode() { return this.buCode; } public void setBuCode(String buCode) { this.buCode = buCode; } public String getBudgetAccount() { return this.budgetAccount; } public void setBudgetAccount(String budgetAccount) { this.budgetAccount = budgetAccount; } public String getBudgetAccountName() { return this.budgetAccountName; } public void setBudgetAccountName(String budgetAccountName) { this.budgetAccountName = budgetAccountName; } public String getBudgetFy() { return this.budgetFy; } public void setBudgetFy(String budgetFy) { this.budgetFy = budgetFy; } public String getGroupBudgetCode() { return this.groupBudgetCode; } public void setGroupBudgetCode(String groupBudgetCode) { this.groupBudgetCode = groupBudgetCode; } public String getMakingDept() { return this.makingDept; } public void setMakingDept(String makingDept) { this.makingDept = makingDept; } public String getMakingDeptName() { return this.makingDeptName; } public void setMakingDeptName(String makingDeptName) { this.makingDeptName = makingDeptName; } public String getRemainAmount() { return this.remainAmount; } public void setRemainAmount(String remainAmount) { this.remainAmount = remainAmount; } public String getRemainAmountCurrency() { return this.remainAmountCurrency; } public void setRemainAmountCurrency(String remainAmountCurrency) { this.remainAmountCurrency = remainAmountCurrency; } }
/* * Copyright 2003-2010 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.codehaus.groovy.util; import java.lang.ref.PhantomReference; import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; public enum ReferenceType { SOFT { @Override protected <T,V extends Finalizable> Reference<T,V> createReference(T value, V handler, ReferenceQueue queue) { return new SoftRef(value, handler, queue); } }, WEAK { @Override protected <T,V extends Finalizable> Reference<T,V> createReference(T value, V handler, ReferenceQueue queue) { return new WeakRef(value, handler, queue); } }, PHANTOM { @Override protected <T,V extends Finalizable> Reference<T,V> createReference(T value, V handler, ReferenceQueue queue) { return new PhantomRef(value, handler, queue); } }, HARD { @Override protected <T,V extends Finalizable> Reference<T,V> createReference(T value, V handler, ReferenceQueue queue) { return new HardRef(value, handler, queue); } }; protected abstract <T,V extends Finalizable> Reference<T,V> createReference(T value, V handler, ReferenceQueue queue); private static class SoftRef<TT,V extends Finalizable> extends SoftReference<TT> implements Reference<TT,V> { private final V handler; public SoftRef(TT referent, V handler, ReferenceQueue<? super TT> q) { super(referent, q); this.handler = handler; } public V getHandler() { return handler; } } private static class WeakRef<TT,V extends Finalizable> extends WeakReference<TT> implements Reference<TT,V> { private final V handler; public WeakRef(TT referent, V handler, ReferenceQueue<? super TT> q) { super(referent, q); this.handler = handler; } public V getHandler() { return handler; } } private static class PhantomRef<TT,V extends Finalizable> extends PhantomReference<TT> implements Reference<TT,V> { private final V handler; public PhantomRef(TT referent, V handler, ReferenceQueue<? super TT> q) { super(referent, q); this.handler = handler; } public V getHandler() { return handler; } } private static class HardRef<TT,V extends Finalizable> implements Reference<TT,V> { private TT ref; private final V handler; public HardRef(TT referent, V handler, ReferenceQueue<? super TT> q) { this.ref = referent; this.handler = handler; } public V getHandler() { return handler; } public TT get() { return ref; } public void clear() { ref = null; } } }
/* * Copyright 2017 John Grosh <john.a.grosh@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.jagrosh.jmusicbot.commands.general; import com.jagrosh.jdautilities.command.Command; import com.jagrosh.jdautilities.command.CommandEvent; import com.jagrosh.jmusicbot.Bot; import com.jagrosh.jmusicbot.settings.RepeatMode; import com.jagrosh.jmusicbot.settings.Settings; import com.jagrosh.jmusicbot.utils.FormatUtil; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.MessageBuilder; import net.dv8tion.jda.api.entities.Role; import net.dv8tion.jda.api.entities.TextChannel; import net.dv8tion.jda.api.entities.VoiceChannel; /** * * @author John Grosh <john.a.grosh@gmail.com> */ public class SettingsCmd extends Command { private final static String EMOJI = "\uD83C\uDFA7"; // 🎧 public SettingsCmd(Bot bot) { this.name = "settings"; this.help = "shows the bots settings"; this.aliases = bot.getConfig().getAliases(this.name); this.guildOnly = true; } @Override protected void execute(CommandEvent event) { Settings s = event.getClient().getSettingsFor(event.getGuild()); MessageBuilder builder = new MessageBuilder() .append(EMOJI + " **") .append(FormatUtil.filter(event.getSelfUser().getName())) .append("** settings:"); TextChannel tchan = s.getTextChannel(event.getGuild()); VoiceChannel vchan = s.getVoiceChannel(event.getGuild()); Role role = s.getRole(event.getGuild()); EmbedBuilder ebuilder = new EmbedBuilder() .setColor(event.getSelfMember().getColor()) .setDescription("Text Channel: " + (tchan == null ? "Any" : "**#" + tchan.getName() + "**") + "\nVoice Channel: " + (vchan == null ? "Any" : "**" + vchan.getName() + "**") + "\nDJ Role: " + (role == null ? "None" : "**" + role.getName() + "**") + "\nCustom Prefix: " + (s.getPrefix() == null ? "None" : "`" + s.getPrefix() + "`") + "\nRepeat Mode: " + (s.getRepeatMode() == RepeatMode.OFF ? s.getRepeatMode().getUserFriendlyName() : "**"+s.getRepeatMode().getUserFriendlyName()+"**") + "\nDefault Playlist: " + (s.getDefaultPlaylist() == null ? "None" : "**" + s.getDefaultPlaylist() + "**") ) .setFooter(event.getJDA().getGuilds().size() + " servers | " + event.getJDA().getGuilds().stream().filter(g -> g.getSelfMember().getVoiceState().inVoiceChannel()).count() + " audio connections", null); event.getChannel().sendMessage(builder.setEmbed(ebuilder.build()).build()).queue(); } }
/** * This program and the accompanying materials * are made available under the terms of the License * which accompanies this distribution in the file LICENSE.txt */ package com.archimatetool.editor.diagram.actions; import org.eclipse.gef.ui.actions.GEFActionConstants; import org.eclipse.jface.action.Action; import com.archimatetool.editor.preferences.IPreferenceConstants; import com.archimatetool.editor.preferences.Preferences; /** * Toggle the Snap Guide Lines * * @author Phillip Beauvoir */ public class ToggleSnapToAlignmentGuidesAction extends Action { public ToggleSnapToAlignmentGuidesAction() { super(Messages.ToggleSnapToAlignmentGuidesAction_0, AS_CHECK_BOX); setToolTipText(getText()); setId(GEFActionConstants.TOGGLE_SNAP_TO_GEOMETRY); setActionDefinitionId(GEFActionConstants.TOGGLE_SNAP_TO_GEOMETRY); setChecked(isChecked()); } @Override public boolean isChecked() { return Preferences.doShowGuideLines(); } @Override public void run() { Preferences.STORE.setValue(IPreferenceConstants.GRID_SHOW_GUIDELINES, !isChecked()); } }
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * gradle plugin from the resource data it found. It * should not be modified by hand. */ package androidx.activity; public final class R { private R() {} public static final class attr { private attr() {} public static final int alpha = 0x7f03002b; public static final int font = 0x7f030123; public static final int fontProviderAuthority = 0x7f030125; public static final int fontProviderCerts = 0x7f030126; public static final int fontProviderFetchStrategy = 0x7f030127; public static final int fontProviderFetchTimeout = 0x7f030128; public static final int fontProviderPackage = 0x7f030129; public static final int fontProviderQuery = 0x7f03012a; public static final int fontStyle = 0x7f03012b; public static final int fontVariationSettings = 0x7f03012c; public static final int fontWeight = 0x7f03012d; public static final int ttcIndex = 0x7f030284; } public static final class color { private color() {} public static final int notification_action_color_filter = 0x7f0500a7; public static final int notification_icon_bg_color = 0x7f0500a8; public static final int ripple_material_light = 0x7f0500b2; public static final int secondary_text_default_material_light = 0x7f0500b4; } public static final class dimen { private dimen() {} public static final int compat_button_inset_horizontal_material = 0x7f060053; public static final int compat_button_inset_vertical_material = 0x7f060054; public static final int compat_button_padding_horizontal_material = 0x7f060055; public static final int compat_button_padding_vertical_material = 0x7f060056; public static final int compat_control_corner_material = 0x7f060057; public static final int compat_notification_large_icon_max_height = 0x7f060058; public static final int compat_notification_large_icon_max_width = 0x7f060059; public static final int notification_action_icon_size = 0x7f06012e; public static final int notification_action_text_size = 0x7f06012f; public static final int notification_big_circle_margin = 0x7f060130; public static final int notification_content_margin_start = 0x7f060131; public static final int notification_large_icon_height = 0x7f060132; public static final int notification_large_icon_width = 0x7f060133; public static final int notification_main_column_padding_top = 0x7f060134; public static final int notification_media_narrow_margin = 0x7f060135; public static final int notification_right_icon_size = 0x7f060136; public static final int notification_right_side_padding_top = 0x7f060137; public static final int notification_small_icon_background_padding = 0x7f060138; public static final int notification_small_icon_size_as_large = 0x7f060139; public static final int notification_subtext_size = 0x7f06013a; public static final int notification_top_pad = 0x7f06013b; public static final int notification_top_pad_large_text = 0x7f06013c; } public static final class drawable { private drawable() {} public static final int notification_action_background = 0x7f070081; public static final int notification_bg = 0x7f070082; public static final int notification_bg_low = 0x7f070083; public static final int notification_bg_low_normal = 0x7f070084; public static final int notification_bg_low_pressed = 0x7f070085; public static final int notification_bg_normal = 0x7f070086; public static final int notification_bg_normal_pressed = 0x7f070087; public static final int notification_icon_background = 0x7f070088; public static final int notification_template_icon_bg = 0x7f070089; public static final int notification_template_icon_low_bg = 0x7f07008a; public static final int notification_tile_bg = 0x7f07008b; public static final int notify_panel_notification_icon_bg = 0x7f07008c; } public static final class id { private id() {} public static final int accessibility_action_clickable_span = 0x7f08000a; public static final int accessibility_custom_action_0 = 0x7f08000c; public static final int accessibility_custom_action_1 = 0x7f08000d; public static final int accessibility_custom_action_10 = 0x7f08000e; public static final int accessibility_custom_action_11 = 0x7f08000f; public static final int accessibility_custom_action_12 = 0x7f080010; public static final int accessibility_custom_action_13 = 0x7f080011; public static final int accessibility_custom_action_14 = 0x7f080012; public static final int accessibility_custom_action_15 = 0x7f080013; public static final int accessibility_custom_action_16 = 0x7f080014; public static final int accessibility_custom_action_17 = 0x7f080015; public static final int accessibility_custom_action_18 = 0x7f080016; public static final int accessibility_custom_action_19 = 0x7f080017; public static final int accessibility_custom_action_2 = 0x7f080018; public static final int accessibility_custom_action_20 = 0x7f080019; public static final int accessibility_custom_action_21 = 0x7f08001a; public static final int accessibility_custom_action_22 = 0x7f08001b; public static final int accessibility_custom_action_23 = 0x7f08001c; public static final int accessibility_custom_action_24 = 0x7f08001d; public static final int accessibility_custom_action_25 = 0x7f08001e; public static final int accessibility_custom_action_26 = 0x7f08001f; public static final int accessibility_custom_action_27 = 0x7f080020; public static final int accessibility_custom_action_28 = 0x7f080021; public static final int accessibility_custom_action_29 = 0x7f080022; public static final int accessibility_custom_action_3 = 0x7f080023; public static final int accessibility_custom_action_30 = 0x7f080024; public static final int accessibility_custom_action_31 = 0x7f080025; public static final int accessibility_custom_action_4 = 0x7f080026; public static final int accessibility_custom_action_5 = 0x7f080027; public static final int accessibility_custom_action_6 = 0x7f080028; public static final int accessibility_custom_action_7 = 0x7f080029; public static final int accessibility_custom_action_8 = 0x7f08002a; public static final int accessibility_custom_action_9 = 0x7f08002b; public static final int action_container = 0x7f080038; public static final int action_divider = 0x7f08003a; public static final int action_image = 0x7f08003b; public static final int action_text = 0x7f080041; public static final int actions = 0x7f080042; public static final int async = 0x7f080048; public static final int blocking = 0x7f08004c; public static final int chronometer = 0x7f08005a; public static final int dialog_button = 0x7f08006f; public static final int forever = 0x7f080088; public static final int icon = 0x7f080092; public static final int icon_group = 0x7f080093; public static final int info = 0x7f080096; public static final int italic = 0x7f080097; public static final int line1 = 0x7f08009c; public static final int line3 = 0x7f08009d; public static final int normal = 0x7f0800c4; public static final int notification_background = 0x7f0800c5; public static final int notification_main_column = 0x7f0800c6; public static final int notification_main_column_container = 0x7f0800c7; public static final int right_icon = 0x7f0800d8; public static final int right_side = 0x7f0800d9; public static final int tag_accessibility_actions = 0x7f08010f; public static final int tag_accessibility_clickable_spans = 0x7f080110; public static final int tag_accessibility_heading = 0x7f080111; public static final int tag_accessibility_pane_title = 0x7f080112; public static final int tag_screen_reader_focusable = 0x7f080113; public static final int tag_transition_group = 0x7f080114; public static final int tag_unhandled_key_event_manager = 0x7f080115; public static final int tag_unhandled_key_listeners = 0x7f080116; public static final int text = 0x7f080119; public static final int text2 = 0x7f08011a; public static final int time = 0x7f080124; public static final int title = 0x7f080125; } public static final class integer { private integer() {} public static final int status_bar_notification_info_maxnum = 0x7f090018; } public static final class layout { private layout() {} public static final int custom_dialog = 0x7f0b001c; public static final int notification_action = 0x7f0b004a; public static final int notification_action_tombstone = 0x7f0b004b; public static final int notification_template_custom_big = 0x7f0b004c; public static final int notification_template_icon_group = 0x7f0b004d; public static final int notification_template_part_chronometer = 0x7f0b004e; public static final int notification_template_part_time = 0x7f0b004f; } public static final class string { private string() {} public static final int status_bar_notification_info_overflow = 0x7f0e0083; } public static final class style { private style() {} public static final int TextAppearance_Compat_Notification = 0x7f0f0161; public static final int TextAppearance_Compat_Notification_Info = 0x7f0f0162; public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0f0163; public static final int TextAppearance_Compat_Notification_Time = 0x7f0f0164; public static final int TextAppearance_Compat_Notification_Title = 0x7f0f0165; public static final int Widget_Compat_NotificationActionContainer = 0x7f0f024b; public static final int Widget_Compat_NotificationActionText = 0x7f0f024c; } public static final class styleable { private styleable() {} public static final int[] ColorStateListItem = { 0x10101a5, 0x101031f, 0x7f03002b }; public static final int ColorStateListItem_android_color = 0; public static final int ColorStateListItem_android_alpha = 1; public static final int ColorStateListItem_alpha = 2; public static final int[] FontFamily = { 0x7f030125, 0x7f030126, 0x7f030127, 0x7f030128, 0x7f030129, 0x7f03012a }; public static final int FontFamily_fontProviderAuthority = 0; public static final int FontFamily_fontProviderCerts = 1; public static final int FontFamily_fontProviderFetchStrategy = 2; public static final int FontFamily_fontProviderFetchTimeout = 3; public static final int FontFamily_fontProviderPackage = 4; public static final int FontFamily_fontProviderQuery = 5; public static final int[] FontFamilyFont = { 0x1010532, 0x1010533, 0x101053f, 0x101056f, 0x1010570, 0x7f030123, 0x7f03012b, 0x7f03012c, 0x7f03012d, 0x7f030284 }; public static final int FontFamilyFont_android_font = 0; public static final int FontFamilyFont_android_fontWeight = 1; public static final int FontFamilyFont_android_fontStyle = 2; public static final int FontFamilyFont_android_ttcIndex = 3; public static final int FontFamilyFont_android_fontVariationSettings = 4; public static final int FontFamilyFont_font = 5; public static final int FontFamilyFont_fontStyle = 6; public static final int FontFamilyFont_fontVariationSettings = 7; public static final int FontFamilyFont_fontWeight = 8; public static final int FontFamilyFont_ttcIndex = 9; public static final int[] GradientColor = { 0x101019d, 0x101019e, 0x10101a1, 0x10101a2, 0x10101a3, 0x10101a4, 0x1010201, 0x101020b, 0x1010510, 0x1010511, 0x1010512, 0x1010513 }; public static final int GradientColor_android_startColor = 0; public static final int GradientColor_android_endColor = 1; public static final int GradientColor_android_type = 2; public static final int GradientColor_android_centerX = 3; public static final int GradientColor_android_centerY = 4; public static final int GradientColor_android_gradientRadius = 5; public static final int GradientColor_android_tileMode = 6; public static final int GradientColor_android_centerColor = 7; public static final int GradientColor_android_startX = 8; public static final int GradientColor_android_startY = 9; public static final int GradientColor_android_endX = 10; public static final int GradientColor_android_endY = 11; public static final int[] GradientColorItem = { 0x10101a5, 0x1010514 }; public static final int GradientColorItem_android_color = 0; public static final int GradientColorItem_android_offset = 1; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package CriadoresServelets; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author gusta */ @WebServlet(name = "CriaTelaRespondePagamento", urlPatterns = {"/RespondePagamento"}) public class CriaTelaRespondePagamento extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); RequestDispatcher dispatcher = request.getRequestDispatcher("/A_TELAS_JSP/TelaRespostaPag.jsp"); dispatcher.forward(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
/** * Audit specific code. */ package com.sallefy.config.audit;
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE113_HTTP_Response_Splitting__Property_addHeaderServlet_73b.java Label Definition File: CWE113_HTTP_Response_Splitting.label.xml Template File: sources-sinks-73b.tmpl.java */ /* * @description * CWE: 113 HTTP Response Splitting * BadSource: Property Read data from a system property * GoodSource: A hardcoded string * Sinks: addHeaderServlet * GoodSink: URLEncode input * BadSink : querystring to addHeader() * Flow Variant: 73 Data flow: data passed in a LinkedList from one method to another in different source files in the same package * * */ package testcases.CWE113_HTTP_Response_Splitting.s02; import testcasesupport.*; import java.util.LinkedList; import javax.servlet.http.*; import java.net.URLEncoder; public class CWE113_HTTP_Response_Splitting__Property_addHeaderServlet_73b { public void badSink(LinkedList<String> dataLinkedList , HttpServletRequest request, HttpServletResponse response) throws Throwable { String data = dataLinkedList.remove(2); /* POTENTIAL FLAW: Input from file not verified */ if (data != null) { response.addHeader("Location", "/author.jsp?lang=" + data); } } /* goodG2B() - use GoodSource and BadSink */ public void goodG2BSink(LinkedList<String> dataLinkedList , HttpServletRequest request, HttpServletResponse response) throws Throwable { String data = dataLinkedList.remove(2); /* POTENTIAL FLAW: Input from file not verified */ if (data != null) { response.addHeader("Location", "/author.jsp?lang=" + data); } } /* goodB2G() - use BadSource and GoodSink */ public void goodB2GSink(LinkedList<String> dataLinkedList , HttpServletRequest request, HttpServletResponse response) throws Throwable { String data = dataLinkedList.remove(2); /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */ if (data != null) { data = URLEncoder.encode(data, "UTF-8"); response.addHeader("Location", "/author.jsp?lang=" + data); } } }
/* * 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.servicecomb.demo.pojo.client; public interface SchemeInterfacePojo { int reduce(int a, int b); int add(int a, int b); }
/** * Copyright 2014-2021 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 com.webank.webase.node.mgr.user; import com.webank.webase.node.mgr.base.annotation.CurrentAccount; import com.webank.webase.node.mgr.base.annotation.entity.CurrentAccountInfo; import com.webank.webase.node.mgr.base.code.ConstantCode; import com.webank.webase.node.mgr.base.controller.BaseController; import com.webank.webase.node.mgr.base.entity.BasePageResponse; import com.webank.webase.node.mgr.base.entity.BaseResponse; import com.webank.webase.node.mgr.base.enums.CheckUserExist; import com.webank.webase.node.mgr.base.enums.RoleType; import com.webank.webase.node.mgr.base.exception.NodeMgrException; import com.webank.webase.node.mgr.config.properties.ConstantProperties; import com.webank.webase.node.mgr.tools.HttpRequestTools; import com.webank.webase.node.mgr.tools.JsonTools; import com.webank.webase.node.mgr.tools.NodeMgrTools; import com.webank.webase.node.mgr.tools.PemUtils; import com.webank.webase.node.mgr.cert.entity.FileContentHandle; import com.webank.webase.node.mgr.user.entity.BindUserInputParam; import com.webank.webase.node.mgr.user.entity.KeyPair; import com.webank.webase.node.mgr.user.entity.NewUserInputParam; import com.webank.webase.node.mgr.user.entity.ReqBindPrivateKey; import com.webank.webase.node.mgr.user.entity.ReqExport; import com.webank.webase.node.mgr.user.entity.ReqImportPem; import com.webank.webase.node.mgr.user.entity.ReqImportPrivateKey; import com.webank.webase.node.mgr.user.entity.TbUser; import com.webank.webase.node.mgr.user.entity.UpdateUserInputParam; import com.webank.webase.node.mgr.user.entity.UserParam; import java.time.Duration; import java.time.Instant; import java.util.List; import java.util.Optional; import javax.validation.Valid; import lombok.extern.log4j.Log4j2; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.InputStreamResource; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; /** * Key pair manage */ @Log4j2 @RestController @RequestMapping("user") public class UserController extends BaseController { @Autowired private UserService userService; /** * add new user info. */ @PostMapping(value = "/userInfo") @PreAuthorize(ConstantProperties.HAS_ROLE_ADMIN_OR_DEVELOPER) public BaseResponse addUserInfo(@RequestBody @Valid NewUserInputParam user, @CurrentAccount CurrentAccountInfo currentAccountInfo, BindingResult result) throws NodeMgrException { checkBindResult(result); BaseResponse baseResponse = new BaseResponse(ConstantCode.SUCCESS); Instant startTime = Instant.now(); log.info("start addUserInfo startTime:{},currentAccount:{},NewUserInputParam:{}", startTime.toEpochMilli(), currentAccountInfo, user); // add user row TbUser userRow = userService.addUserInfoLocal(user.getGroupId(), user.getUserName(), currentAccountInfo.getAccount(), user.getDescription(), user.getUserType(), null); baseResponse.setData(userRow); log.info("end addUserInfo useTime:{} result:{}", Duration.between(startTime, Instant.now()).toMillis(), JsonTools.toJSONString(baseResponse)); return baseResponse; } /** * bind user info. (add public key user, different from bind private key) */ @PostMapping(value = "/bind") @PreAuthorize(ConstantProperties.HAS_ROLE_ADMIN_OR_DEVELOPER) public BaseResponse bindUserInfo(@RequestBody @Valid BindUserInputParam user, @CurrentAccount CurrentAccountInfo currentAccountInfo, BindingResult result) throws NodeMgrException { checkBindResult(result); BaseResponse baseResponse = new BaseResponse(ConstantCode.SUCCESS); Instant startTime = Instant.now(); log.info("start bindUserInfo startTime:{},currentAccount:{},BindUserInputParam:{}", startTime.toEpochMilli(), currentAccountInfo, user); // query user row TbUser userRow = userService.bindUserInfo(user, currentAccountInfo.getAccount(), CheckUserExist.TURE.getValue()); baseResponse.setData(userRow); log.info("end bindUserInfo useTime:{} result:{}", Duration.between(startTime, Instant.now()).toMillis(), JsonTools.toJSONString(baseResponse)); return baseResponse; } /** * update user info of description */ @PutMapping(value = "/userInfo") @PreAuthorize(ConstantProperties.HAS_ROLE_ADMIN_OR_DEVELOPER) public BaseResponse updateUserInfo(@RequestBody @Valid UpdateUserInputParam user, BindingResult result) throws NodeMgrException { checkBindResult(result); BaseResponse baseResponse = new BaseResponse(ConstantCode.SUCCESS); Instant startTime = Instant.now(); log.info("start updateUserInfo startTime:{} User:{}", startTime.toEpochMilli(), JsonTools.toJSONString(user)); // update user row userService.updateUser(user); // query user row TbUser userRow = userService.queryByUserId(user.getUserId()); baseResponse.setData(userRow); log.info("end updateUserInfo useTime:{} result:{}", Duration.between(startTime, Instant.now()).toMillis(), JsonTools.toJSONString(baseResponse)); return baseResponse; } /** * query user info list. */ @GetMapping(value = "/userList/{groupId}/{pageNumber}/{pageSize}") public BasePageResponse userList(@PathVariable("groupId") Integer groupId, @PathVariable("pageNumber") Integer pageNumber, @PathVariable("pageSize") Integer pageSize, @RequestParam(value = "userParam", required = false) String commParam, @CurrentAccount CurrentAccountInfo currentAccountInfo) throws NodeMgrException { BasePageResponse pageResponse = new BasePageResponse(ConstantCode.SUCCESS); Instant startTime = Instant.now(); log.info("start userList startTime:{},currentAccountInfo:{} groupId:{} pageNumber:{} pageSize:{} commParam:{}", startTime.toEpochMilli(), currentAccountInfo, groupId, pageNumber, pageSize, commParam); String account = RoleType.DEVELOPER.getValue().intValue() == currentAccountInfo.getRoleId().intValue() ? currentAccountInfo.getAccount() : null; UserParam param = new UserParam(); param.setGroupId(groupId); param.setAccount(account); param.setCommParam(commParam); param.setPageSize(pageSize); Integer count = userService.countOfUser(param); if (count != null && count > 0) { Integer start = Optional.ofNullable(pageNumber).map(page -> (page - 1) * pageSize).orElse(null); param.setStart(start); param.setPageSize(pageSize); List<TbUser> listOfUser = userService.queryUserList(param); pageResponse.setData(listOfUser); pageResponse.setTotalCount(count); } log.info("end userList useTime:{} result:{}", Duration.between(startTime, Instant.now()).toMillis(), JsonTools.toJSONString(pageResponse)); return pageResponse; } @PostMapping("/import") @PreAuthorize(ConstantProperties.HAS_ROLE_ADMIN_OR_DEVELOPER) public BaseResponse importPrivateKey(@Valid @RequestBody ReqImportPrivateKey reqImport, @CurrentAccount CurrentAccountInfo currentAccountInfo, BindingResult result) { checkBindResult(result); BaseResponse baseResponse = new BaseResponse(ConstantCode.SUCCESS); Instant startTime = Instant.now(); log.info("start importPrivateKey startTime:{},currentAccount:{},reqImport:{}", startTime.toEpochMilli(), currentAccountInfo, reqImport); // encoded by web in base64 String privateKeyEncoded = reqImport.getPrivateKey(); // add user row TbUser userRow = userService.addUserInfoLocal(reqImport.getGroupId(), reqImport.getUserName(), currentAccountInfo.getAccount(), reqImport.getDescription(), reqImport.getUserType(), privateKeyEncoded); baseResponse.setData(userRow); log.info("end importPrivateKey useTime:{} result:{}", Duration.between(startTime, Instant.now()).toMillis(), JsonTools.toJSONString(baseResponse)); return baseResponse; } @PostMapping("/importPem") @PreAuthorize(ConstantProperties.HAS_ROLE_ADMIN_OR_DEVELOPER) public BaseResponse importPemPrivateKey(@Valid @RequestBody ReqImportPem reqImportPem, @CurrentAccount CurrentAccountInfo currentAccountInfo, BindingResult result) { checkBindResult(result); BaseResponse baseResponse = new BaseResponse(ConstantCode.SUCCESS); Instant startTime = Instant.now(); log.info("start importPemPrivateKey startTime:{},currentAccount:{}", startTime.toEpochMilli(), currentAccountInfo); String pemContent = reqImportPem.getPemContent(); if (!pemContent.startsWith(PemUtils.crtContentHeadNoLF)) { throw new NodeMgrException(ConstantCode.PEM_FORMAT_ERROR); } // import reqImportPem.setAccount(currentAccountInfo.getAccount()); TbUser userRow = userService.importPem(reqImportPem, CheckUserExist.TURE.getValue()); baseResponse.setData(userRow); log.info("end importPemPrivateKey useTime:{} result:{}", Duration.between(startTime, Instant.now()).toMillis(), JsonTools.toJSONString(baseResponse)); return baseResponse; } @PostMapping("/importP12") @PreAuthorize(ConstantProperties.HAS_ROLE_ADMIN_OR_DEVELOPER) public BaseResponse importP12PrivateKey(@RequestParam MultipartFile p12File, @RequestParam(required = false, defaultValue = "") String p12Password, @RequestParam Integer groupId, @RequestParam String userName, @RequestParam(required = false) String description, @CurrentAccount CurrentAccountInfo currentAccountInfo) { BaseResponse baseResponse = new BaseResponse(ConstantCode.SUCCESS); Instant startTime = Instant.now(); log.info("start importP12PrivateKey startTime:{},currentAccount:{}", startTime.toEpochMilli(), currentAccountInfo); if (!NodeMgrTools.notContainsChinese(p12Password)) { throw new NodeMgrException(ConstantCode.P12_PASSWORD_NOT_CHINESE); } if (p12File.getSize() == 0) { throw new NodeMgrException(ConstantCode.P12_FILE_ERROR); } TbUser userRow = userService.importKeyStoreFromP12(p12File, p12Password, groupId, userName, currentAccountInfo.getAccount(), description, CheckUserExist.TURE.getValue()); baseResponse.setData(userRow); log.info("end importPemPrivateKey useTime:{} result:{}", Duration.between(startTime, Instant.now()).toMillis(), JsonTools.toJSONString(baseResponse)); return new BaseResponse(ConstantCode.SUCCESS); } @PostMapping(value = "/exportPem") @PreAuthorize(ConstantProperties.HAS_ROLE_ADMIN_OR_DEVELOPER) public ResponseEntity<InputStreamResource> exportPemUserFromSign(@RequestBody ReqExport param, @CurrentAccount CurrentAccountInfo currentAccount) throws NodeMgrException { Instant startTime = Instant.now(); log.info("start exportPemUserFromSign startTime:{} param:{},currentAccount:{}", startTime.toEpochMilli(), param, currentAccount); Integer groupId = param.getGroupId(); String signUserId = param.getSignUserId(); String account = currentAccount.getAccount(); Integer roleId = currentAccount.getRoleId(); FileContentHandle fileContentHandle = userService.exportPemFromSign(groupId, signUserId, account, roleId); log.info("end exportPemUserFromSign useTime:{} fileContentHandle:{}", Duration.between(startTime, Instant.now()).toMillis(), JsonTools.toJSONString(fileContentHandle)); return ResponseEntity.ok().headers(HttpRequestTools.headers(fileContentHandle.getFileName())) .body(new InputStreamResource(fileContentHandle.getInputStream())); } @PostMapping(value = "/exportP12") @PreAuthorize(ConstantProperties.HAS_ROLE_ADMIN_OR_DEVELOPER) public ResponseEntity<InputStreamResource> exportP12UserFromSign(@RequestBody ReqExport param, @CurrentAccount CurrentAccountInfo currentAccount) throws NodeMgrException { Instant startTime = Instant.now(); log.info("start exportP12UserFromSign startTime:{} param:{},currentAccount:{}", startTime.toEpochMilli(), param, currentAccount); Integer groupId = param.getGroupId(); String signUserId = param.getSignUserId(); String p12PasswordEncoded = param.getP12Password(); if (!NodeMgrTools.notContainsChinese(p12PasswordEncoded)) { throw new NodeMgrException(ConstantCode.P12_PASSWORD_NOT_CHINESE); } // account info String account = currentAccount.getAccount(); Integer roleId = currentAccount.getRoleId(); FileContentHandle fileContentHandle = userService.exportP12FromSign(groupId, signUserId, p12PasswordEncoded, account, roleId); log.info("end exportP12UserFromSign useTime:{} result:{}", Duration.between(startTime, Instant.now()).toMillis(), JsonTools.toJSONString(fileContentHandle)); return ResponseEntity.ok().headers(HttpRequestTools.headers(fileContentHandle.getFileName())) .body(new InputStreamResource(fileContentHandle.getInputStream())); } /** * not check account, cuz this is used for app integration * @param userId * @return * @throws NodeMgrException */ @PostMapping(value = "/export/{userId}") @PreAuthorize(ConstantProperties.HAS_ROLE_ADMIN_OR_DEVELOPER) public BaseResponse exportRawUserFromSign(@PathVariable("userId") Integer userId) throws NodeMgrException { Instant startTime = Instant.now(); log.info("start exportRawUserFromSign startTime:{} userId:{}", startTime.toEpochMilli(), userId); TbUser tbUser = userService.queryUserDetail(userId); log.info("end exportRawUserFromSign useTime:{} result:{}", Duration.between(startTime, Instant.now()).toMillis(), tbUser); return new BaseResponse(ConstantCode.SUCCESS, tbUser); } @PostMapping("/bind/privateKey") @PreAuthorize(ConstantProperties.HAS_ROLE_ADMIN_OR_DEVELOPER) public BaseResponse bindPrivateKey(@Valid @RequestBody ReqBindPrivateKey reqBind, @CurrentAccount CurrentAccountInfo currentAccountInfo, BindingResult result) { checkBindResult(result); BaseResponse baseResponse = new BaseResponse(ConstantCode.SUCCESS); Instant startTime = Instant.now(); log.info("start bindPrivateKey startTime:{} userId:{},currentAccount:{}", startTime.toEpochMilli(), reqBind.getUserId(), currentAccountInfo); if (StringUtils.isBlank(reqBind.getPrivateKey())) { throw new NodeMgrException(ConstantCode.PARAM_EXCEPTION); } // add user row TbUser tbUser = userService.updateUser(reqBind, currentAccountInfo); baseResponse.setData(tbUser); log.info("end bindPrivateKey useTime:{} result:{}", Duration.between(startTime, Instant.now()).toMillis(), JsonTools.toJSONString(baseResponse)); return baseResponse; } @PostMapping("/bind/privateKey/pem") @PreAuthorize(ConstantProperties.HAS_ROLE_ADMIN_OR_DEVELOPER) public BaseResponse bindPrivateKeyByPem(@Valid @RequestBody ReqBindPrivateKey reqBindPem, @CurrentAccount CurrentAccountInfo currentAccountInfo, BindingResult result) { checkBindResult(result); BaseResponse baseResponse = new BaseResponse(ConstantCode.SUCCESS); Instant startTime = Instant.now(); log.info("start bindPrivateKeyByPem startTime:{} userId:{},currentAccount:{}", startTime.toEpochMilli(), reqBindPem.getUserId(), currentAccountInfo); String pemContent = reqBindPem.getPemContent(); if (StringUtils.isBlank(pemContent)) { throw new NodeMgrException(ConstantCode.PARAM_EXCEPTION); } if (!pemContent.startsWith(PemUtils.crtContentHeadNoLF)) { throw new NodeMgrException(ConstantCode.PEM_FORMAT_ERROR); } // add user row TbUser tbUser = userService.updateUserByPem(reqBindPem.getGroupId(), reqBindPem.getUserId(), pemContent, currentAccountInfo); baseResponse.setData(tbUser); log.info("end bindPrivateKey useTime:{} result:{}", Duration.between(startTime, Instant.now()).toMillis(), JsonTools.toJSONString(baseResponse)); return baseResponse; } @PostMapping("/bind/privateKey/p12") @PreAuthorize(ConstantProperties.HAS_ROLE_ADMIN_OR_DEVELOPER) public BaseResponse bindPrivateKeyByP12(@RequestParam MultipartFile p12File, @RequestParam(required = false, defaultValue = "") String p12Password, @RequestParam Integer groupId, @RequestParam Integer userId, @CurrentAccount CurrentAccountInfo currentAccountInfo) { BaseResponse baseResponse = new BaseResponse(ConstantCode.SUCCESS); Instant startTime = Instant.now(); log.info("start bindPrivateKeyByP12 startTime:{},currentAccount:{}", startTime.toEpochMilli(), currentAccountInfo); if (!NodeMgrTools.notContainsChinese(p12Password)) { throw new NodeMgrException(ConstantCode.P12_PASSWORD_NOT_CHINESE); } if (p12File.getSize() == 0) { throw new NodeMgrException(ConstantCode.P12_FILE_ERROR); } // add user row TbUser tbUser = userService.updateUserByP12(groupId, userId, p12File, p12Password, currentAccountInfo); baseResponse.setData(tbUser); log.info("end bindPrivateKey useTime:{} result:{}", Duration.between(startTime, Instant.now()).toMillis(), JsonTools.toJSONString(baseResponse)); return baseResponse; } }
package algorithms.a51_to_a100.a53_MaximumSubarray_Medium; public class Solution { // public int maxSubArray(int[] nums) { // if (nums == null || nums.length == 0) // return 0; // int max = Integer.MIN_VALUE; // int cur = 0; // for (int i = 0; i < nums.length; i++) { // cur += nums[i]; // max = Math.max(cur, max); // cur = cur < 0 ? 0 : cur; // } // return max; // } public int maxSubArrayWithDivideAndConquer(int[] nums) { if (nums == null || nums.length == 0) return 0; return divideAndConquerHelper(nums, 0, nums.length - 1); } public int divideAndConquerHelper(int[] nums, int left, int right) { if (left == right) return nums[left]; int mid = (left + right) / 2; int leftAns = divideAndConquerHelper(nums, left, mid); int rightAns = divideAndConquerHelper(nums, mid + 1, right); int tmp = 0; int leftSuffixMax = Integer.MIN_VALUE, rightPrefixMax = Integer.MIN_VALUE; for (int i = mid; i >= left; i--) { tmp += nums[i]; leftSuffixMax = Math.max(leftSuffixMax, tmp); } tmp = 0; for (int i = mid + 1; i <= right; i++) { tmp += nums[i]; rightPrefixMax = Math.max(rightPrefixMax, tmp); } int midAns = leftSuffixMax + rightPrefixMax; return Math.max(Math.max(leftAns, rightAns), midAns); } public static void main(String[] args) { Solution solution = new Solution(); int[] nums = new int[] { -2, 1, -3, 4, -1, 2, 1, -5, 4 }; System.out.println(solution.maxSubArrayWithDivideAndConquer(nums)); } }
package dev.widget.utils; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Path; import android.graphics.RectF; import android.os.Bundle; import android.os.Parcelable; import android.util.AttributeSet; import dev.widget.R; /** * detail: RadiusLayout 圆角属性封装处理类 * @author arvinljw */ public class RadiusAttrs { // 绘制区域 private RectF mRectF; // 绘制路径 private final Path mPath = new Path(); // 圆角范围 private float[] mRadii = new float[8]; // 圆角值 private float mRadius; private float mRadiusLeftTop; private float mRadiusLeftBottom; private float mRadiusRightTop; private float mRadiusRightBottom; /** * 初始化 * @param context {@link Context} * @param attrs {@link AttributeSet} */ public RadiusAttrs( Context context, AttributeSet attrs ) { if (context != null && attrs != null) { TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DevWidget); mRadius = a.getLayoutDimension(R.styleable.DevWidget_dev_radius, 0); mRadiusLeftTop = a.getLayoutDimension(R.styleable.DevWidget_dev_radiusLeftTop, 0); mRadiusLeftBottom = a.getLayoutDimension(R.styleable.DevWidget_dev_radiusLeftBottom, 0); mRadiusRightTop = a.getLayoutDimension(R.styleable.DevWidget_dev_radiusRightTop, 0); mRadiusRightBottom = a.getLayoutDimension(R.styleable.DevWidget_dev_radiusRightBottom, 0); a.recycle(); if (mRadius != 0) { mRadiusLeftTop = mRadius; mRadiusLeftBottom = mRadius; mRadiusRightTop = mRadius; mRadiusRightBottom = mRadius; } } resetRadius(); } /** * 重置绘制圆角值 */ private void resetRadius() { mRadii[0] = mRadii[1] = mRadiusLeftTop; mRadii[2] = mRadii[3] = mRadiusRightTop; mRadii[4] = mRadii[5] = mRadiusRightBottom; mRadii[6] = mRadii[7] = mRadiusLeftBottom; } /** * View 宽高改变时调用 * @param w 宽度 * @param h 高度 */ public void onSizeChanged( int w, int h ) { mRectF = new RectF(0, 0, w, h); } /** * 获取绘制路径 * @return {@link Path} */ public Path getPath() { mPath.reset(); if (mRectF != null) { mPath.addRoundRect(mRectF, mRadii, Path.Direction.CW); } return mPath; } // =========== // = get/set = // =========== /** * 设置圆角值 * @param radius 圆角值 */ public void setRadius(float radius) { this.mRadius = radius; this.mRadiusLeftTop = radius; this.mRadiusLeftBottom = radius; this.mRadiusRightTop = radius; this.mRadiusRightBottom = radius; resetRadius(); } /** * 设置左上圆角值 * @param radiusLeftTop 左上圆角值 */ public void setRadiusLeftTop(float radiusLeftTop) { this.mRadiusLeftTop = radiusLeftTop; resetRadius(); } /** * 设置左下圆角值 * @param radiusLeftBottom 左下圆角值 */ public void setRadiusLeftBottom(float radiusLeftBottom) { this.mRadiusLeftBottom = radiusLeftBottom; resetRadius(); } /** * 设置右上圆角值 * @param radiusRightTop 右上圆角值 */ public void setRadiusRightTop(float radiusRightTop) { this.mRadiusRightTop = radiusRightTop; resetRadius(); } /** * 设置右下圆角值 * @param radiusRightBottom 右下圆角值 */ public void setRadiusRightBottom(float radiusRightBottom) { this.mRadiusRightBottom = radiusRightBottom; resetRadius(); } // = /** * 设置左上、左下圆角值 * @param radiusLeft 左边圆角值 */ public void setRadiusLeft(int radiusLeft) { this.mRadiusLeftTop = radiusLeft; this.mRadiusLeftBottom = radiusLeft; resetRadius(); } /** * 设置右上、右下圆角值 * @param radiusRight 右边圆角值 */ public void setRadiusRight(int radiusRight) { this.mRadiusRightTop = radiusRight; this.mRadiusRightBottom = radiusRight; resetRadius(); } /** * 设置左上、右上圆角值 * @param radiusTop 上边圆角值 */ public void setRadiusTop(int radiusTop) { this.mRadiusLeftTop = radiusTop; this.mRadiusRightTop = radiusTop; resetRadius(); } /** * 设置左下、右下圆角值 * @param radiusBottom 下边圆角值 */ public void setRadiusBottom(int radiusBottom) { this.mRadiusLeftBottom = radiusBottom; this.mRadiusRightBottom = radiusBottom; resetRadius(); } // = /** * 获取圆角值 * @return 圆角值 */ public float getRadius() { return mRadius; } /** * 获取左上圆角值 * @return 左上圆角值 */ public float getRadiusLeftTop() { return mRadiusLeftTop; } /** * 获取左下圆角值 * @return 左下圆角值 */ public float getRadiusLeftBottom() { return mRadiusLeftBottom; } /** * 获取右上圆角值 * @return 右上圆角值 */ public float getRadiusRightTop() { return mRadiusRightTop; } /** * 获取右下圆角值 * @return 右下圆角值 */ public float getRadiusRightBottom() { return mRadiusRightBottom; } // ================== // = 数据恢复 / 存储 = // ================== private static final String SUPER_DATA = "super_data"; private static final String DATA_RADII = "data_radii"; public Parcelable onSaveInstanceState(Parcelable superState) { Bundle data = new Bundle(); data.putParcelable(SUPER_DATA, superState); data.putFloatArray(DATA_RADII, mRadii); return data; } public Parcelable onRestoreInstanceState(Parcelable state) { Bundle bundle = (Bundle) state; mRadii = bundle.getFloatArray(DATA_RADII); if (mRadii != null) { mRadiusLeftTop = mRadii[0]; mRadiusRightTop = mRadii[2]; mRadiusRightBottom = mRadii[4]; mRadiusLeftBottom = mRadii[6]; } return bundle.getParcelable(SUPER_DATA); } }
package CI.HTTP; import common.CommonBase; import de.dfki.baall.helper.persistence.exceptions.NotFoundInPersistenceException; import de.kosmos_lab.kosmos.client.KosmoSClient; import de.kosmos_lab.kosmos.data.Group; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.http.HttpMethod; import org.json.JSONArray; import org.json.JSONObject; import org.testng.Assert; import org.testng.annotations.Test; import javax.ejb.PostActivate; public class TestGroup { public final static String testGroupsGroupName = "testgroup1"; public final static String testGroupDevicesScopeName = "testscope3"; public final static String testGroupDevicesDeviceName = "multiscope3"; public final static String testGroupDevicesGroupName = "testgroup3"; private void assertAdminInGroup(KosmoSClient client, String group) { Assert.assertTrue(checkMyAccessTo(client, group,MyListType.Group,MyAccessType.Admin), String.format("User %s seems to NOT be admin in group %s", client.getUserName(), group)); } private void assertNotAdminInGroup(KosmoSClient client, String group) { Assert.assertFalse(checkMyAccessTo(client, group,MyListType.Group,MyAccessType.Admin), String.format("User %s seems to be admin in group %s", client.getUserName(), group)); } private void assertNotUserInGroup(KosmoSClient client, String group) { Assert.assertFalse(checkMyAccessTo(client, group,MyListType.Group,MyAccessType.User), String.format("User %s seems to be user in group %s", client.getUserName(), group)); } private void assertUserInGroup(KosmoSClient client, String group) { Assert.assertTrue(checkMyAccessTo(client, group,MyListType.Group,MyAccessType.User), String.format("User %s seems to NOT be user in group %s", client.getUserName(), group)); } private boolean checkMyAccessTo(KosmoSClient client, String name, MyListType type, MyAccessType access) { ContentResponse response; switch (type) { case Group: response = client.getResponse("/group/my", HttpMethod.GET); break; case Scope: response = client.getResponse("/scope/my", HttpMethod.GET); break; default: throw new IllegalArgumentException(String.format("Could not get information about %s", type)); } Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), 200, "list my groups failed!"); JSONObject obj = new JSONObject(response.getContentAsString()); JSONArray arr; switch (access) { case User: arr = obj.getJSONArray("user"); break; case Admin: arr = obj.getJSONArray("admin"); break; default: throw new IllegalArgumentException(String.format("Could not understand access type %s", access)); } for (int i = 0; i < arr.length(); i++) { String n = arr.getString(i); if (n.equalsIgnoreCase(name)) { return true; } } return false; } @Test(groups = {"testGroupDevices"}, dependsOnGroups = {"testScopeDevices", "testGroups"}) public void testGroupDevices() { ContentResponse response = CommonBase.clientUser.getResponse("/device/add", HttpMethod.POST, new JSONObject().put("uuid", testGroupDevicesDeviceName).put("scopes", new JSONObject().put("read", testGroupDevicesScopeName + ":read").put("del", testGroupDevicesScopeName + ":del").put("write", testGroupDevicesScopeName + ":write")).put("schema", "https://kosmos-lab.de/schema/FakeMultiSensor.json")); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), 204, "Device add did fail!"); response = CommonBase.clientUser.getResponse("/device/get?id=" + testGroupDevicesDeviceName, HttpMethod.GET); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), 200, "Device was not readable"); response = CommonBase.clientUser2.getResponse("/device/get?id=" + testGroupDevicesDeviceName, HttpMethod.GET); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), 403, "Device was readable"); response = CommonBase.clientUser.getResponse("/device/set", HttpMethod.POST, new JSONObject().put("id", testGroupDevicesDeviceName).put("currentEnvironmentTemperature", 17)); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), 200, "Device set did fail!"); response = CommonBase.clientUser2.getResponse("/device/set", HttpMethod.POST, new JSONObject().put("id", testGroupDevicesDeviceName).put("currentEnvironmentTemperature", 18)); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), 403, "Device set did NOT fail!"); response = CommonBase.clientUser2.getResponse("/device/delete", HttpMethod.DELETE, new JSONObject().put("id", testGroupDevicesDeviceName).put("currentEnvironmentTemperature", 18)); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), 403, "Device set did NOT fail!"); response = CommonBase.clientUser.getResponse("/group/add", HttpMethod.POST, new JSONObject().put("name", testGroupDevicesGroupName)); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), 204, "addgroupuser did fail!"); response = CommonBase.clientUser.getResponse("/group/adduser", HttpMethod.POST, new JSONObject().put("group", testGroupDevicesGroupName).put("user", CommonBase.clientUser2.getUserName())); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), 204, "addgroupuser did fail!"); response = CommonBase.clientUser.getResponse("/scope/addgroup", HttpMethod.POST, new JSONObject().put("scope", testGroupDevicesScopeName + ":read").put("group", testGroupDevicesGroupName)); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), 204, "addgroupuser did fail!"); response = CommonBase.clientUser2.getResponse("/device/get?id=" + testGroupDevicesDeviceName, HttpMethod.GET); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), 200, "Device was not readable"); response = CommonBase.clientUser2.getResponse("/device/set", HttpMethod.POST, new JSONObject().put("id", testGroupDevicesDeviceName).put("currentEnvironmentTemperature", 18)); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), 403, "Device set did NOT fail!"); response = CommonBase.clientUser.getResponse("/scope/addgroup", HttpMethod.POST, new JSONObject().put("scope", testGroupDevicesScopeName + ":write").put("group", testGroupDevicesGroupName)); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), 204, "scope add user did fail!"); response = CommonBase.clientUser2.getResponse("/device/set", HttpMethod.POST, new JSONObject().put("id", testGroupDevicesDeviceName).put("currentEnvironmentTemperature", 18)); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), 200, "Device set did fail!"); response = CommonBase.clientUser2.getResponse("/device/delete", HttpMethod.DELETE, new JSONObject().put("id", testGroupDevicesDeviceName).put("currentEnvironmentTemperature", 18)); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), 403, "Device delete did NOT fail!"); response = CommonBase.clientUser.getResponse("/scope/addgroup", HttpMethod.POST, new JSONObject().put("scope", testGroupDevicesScopeName + ":del").put("group", testGroupDevicesGroupName)); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), 204, "scope add user did fail!"); response = CommonBase.clientUser2.getResponse("/device/delete", HttpMethod.DELETE, new JSONObject().put("id", testGroupDevicesDeviceName).put("currentEnvironmentTemperature", 18)); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), 204, "Device delete did fail!"); response = CommonBase.clientUser.getResponse("/device/add", HttpMethod.POST, new JSONObject().put("uuid", testGroupDevicesDeviceName).put("scopes", new JSONObject().put("read", testGroupDevicesScopeName + ":read").put("del", testGroupDevicesScopeName + ":del").put("write", testGroupDevicesScopeName + ":write")).put("schema", "https://kosmos-lab.de/schema/MultiSensor.json")); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), 204, "Device add did fail!"); } @Test(groups = {"testGroups"}, dependsOnGroups = {"createUser"}) public void testGroups() { Group g; try { g = CommonBase.controller.getPersistence().getGroup(testGroupsGroupName); Assert.fail("group should not exist!"); } catch (NotFoundInPersistenceException e) { //e.printStackTrace(); } assertNotAdminInGroup(CommonBase.clientUser, testGroupsGroupName); assertNotUserInGroup(CommonBase.clientUser, testGroupsGroupName); assertNotAdminInGroup(CommonBase.clientUser2, testGroupsGroupName); assertNotUserInGroup(CommonBase.clientUser2, testGroupsGroupName); assertNotAdminInGroup(CommonBase.clientUser3, testGroupsGroupName); assertNotUserInGroup(CommonBase.clientUser3, testGroupsGroupName); ContentResponse response = CommonBase.clientUser.getResponse("/group/add", HttpMethod.POST, new JSONObject().put("name", testGroupsGroupName)); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), 204, "group add returned wrong status!"); assertAdminInGroup(CommonBase.clientUser, testGroupsGroupName); assertNotUserInGroup(CommonBase.clientUser, testGroupsGroupName); assertNotAdminInGroup(CommonBase.clientUser2, testGroupsGroupName); assertNotUserInGroup(CommonBase.clientUser2, testGroupsGroupName); assertNotAdminInGroup(CommonBase.clientUser3, testGroupsGroupName); assertNotUserInGroup(CommonBase.clientUser3, testGroupsGroupName); try { g = CommonBase.controller.getPersistence().getGroup(testGroupsGroupName); } catch (NotFoundInPersistenceException e) { //e.printStackTrace(); Assert.fail("group should exist!"); } response = CommonBase.clientUser2.getResponse("/group/adduser", HttpMethod.POST, new JSONObject().put("group", testGroupsGroupName).put("user", CommonBase.clientUser2.getUserName())); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), 403, "was able to hijack user adding"); assertNotUserInGroup(CommonBase.clientUser2, testGroupsGroupName); response = CommonBase.clientUser2.getResponse("/group/adduser", HttpMethod.POST, new JSONObject().put("group", testGroupsGroupName).put("user", CommonBase.clientUser3.getUserName())); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), 403, "was able to hijack user adding"); assertNotUserInGroup(CommonBase.clientUser3, testGroupsGroupName); response = CommonBase.clientUser.getResponse("/group/adduser", HttpMethod.POST, new JSONObject().put("group", "afaksjnfkajsnfas").put("user", CommonBase.clientUser2.getUserName())); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), 404, "group that should not exist was found"); response = CommonBase.clientUser.getResponse("/group/adduser", HttpMethod.POST, new JSONObject().put("group", testGroupsGroupName).put("user", "23592835235asdf")); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), 404, "user that should not exist was found"); response = CommonBase.clientUser.getResponse("/group/adduser", HttpMethod.POST, new JSONObject().put("group", testGroupsGroupName).put("user", CommonBase.clientUser2.getUserName())); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), 204, "could not add user to group?"); assertNotAdminInGroup(CommonBase.clientUser2, testGroupsGroupName); assertUserInGroup(CommonBase.clientUser2, testGroupsGroupName); response = CommonBase.clientUser2.getResponse("/group/adduser", HttpMethod.POST, new JSONObject().put("group", testGroupsGroupName).put("user", CommonBase.clientUser3.getUserName())); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), 403, "was able to hijack user adding"); assertNotUserInGroup(CommonBase.clientUser3, testGroupsGroupName); response = CommonBase.clientUser2.getResponse("/group/addadmin", HttpMethod.POST, new JSONObject().put("group", testGroupsGroupName).put("user", CommonBase.clientUser2.getUserName())); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), 403, "was able to hijack user adding"); assertNotAdminInGroup(CommonBase.clientUser2, testGroupsGroupName); response = CommonBase.clientUser2.getResponse("/group/addadmin", HttpMethod.POST, new JSONObject().put("group", testGroupsGroupName).put("user", CommonBase.clientUser3.getUserName())); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), 403, "was able to hijack user adding"); assertNotAdminInGroup(CommonBase.clientUser3, testGroupsGroupName); response = CommonBase.clientUser.getResponse("/group/addadmin", HttpMethod.POST, new JSONObject().put("group", testGroupsGroupName).put("user", CommonBase.clientUser2.getUserName())); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), 204, "could not add user to group?"); assertAdminInGroup(CommonBase.clientUser2, testGroupsGroupName); assertUserInGroup(CommonBase.clientUser2, testGroupsGroupName); response = CommonBase.clientUser2.getResponse("/group/deladmin", HttpMethod.POST, new JSONObject().put("group", testGroupsGroupName).put("user", CommonBase.clientUser.getUserName())); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), 204, "could not del admin from group?"); assertNotAdminInGroup(CommonBase.clientUser, testGroupsGroupName); assertNotUserInGroup(CommonBase.clientUser, testGroupsGroupName); response = CommonBase.clientUser2.getResponse("/group/adduser", HttpMethod.POST, new JSONObject().put("group", testGroupsGroupName).put("user", CommonBase.clientUser.getUserName())); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), 204, "could not add user to group?"); assertNotAdminInGroup(CommonBase.clientUser, testGroupsGroupName); assertUserInGroup(CommonBase.clientUser, testGroupsGroupName); response = CommonBase.clientUser2.getResponse("/group/deluser", HttpMethod.POST, new JSONObject().put("group", testGroupsGroupName).put("user", CommonBase.clientUser.getUserName())); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), 204, "could not add user to group?"); assertNotAdminInGroup(CommonBase.clientUser, testGroupsGroupName); assertNotUserInGroup(CommonBase.clientUser, testGroupsGroupName); response = CommonBase.clientUser2.getResponse("/group/delete", HttpMethod.POST,new JSONObject().put("group", testGroupsGroupName)); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), 204, "could not delete group?"); response = CommonBase.clientUser3.getResponse("/group/get", HttpMethod.GET,new JSONObject().put("name", testGroupsGroupName)); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), 404, "could find deleted group again"); try { g = CommonBase.controller.getPersistence().getGroup(testGroupsGroupName); Assert.fail("group should not exist!"); } catch (NotFoundInPersistenceException e) { //e.printStackTrace(); } assertNotAdminInGroup(CommonBase.clientAdmin, testGroupsGroupName); assertNotUserInGroup(CommonBase.clientAdmin, testGroupsGroupName); response = CommonBase.clientUser.getResponse("/group/add", HttpMethod.POST, new JSONObject().put("name", testGroupsGroupName)); Assert.assertNotNull(response); Assert.assertEquals(response.getStatus(), 204, "group add returned wrong status!"); try { g = CommonBase.controller.getPersistence().getGroup(testGroupsGroupName); } catch (NotFoundInPersistenceException e) { Assert.fail("group should exist!"); } } private enum MyListType {Group, Scope} private enum MyAccessType {User, Admin} }
package com.ruoyi.generator.util; import com.alibaba.fastjson.JSONObject; import com.ruoyi.common.constant.GenConstants; import com.ruoyi.common.utils.DateUtils; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.generator.domain.GenTable; import com.ruoyi.generator.domain.GenTableColumn; import org.apache.velocity.VelocityContext; import java.util.ArrayList; import java.util.HashSet; import java.util.List; /** * 模板处理工具类 * * @author ruoyi */ public class VelocityUtils { /** * 项目空间路径 */ private static final String PROJECT_PATH = "main/java"; /** * mybatis空间路径 */ private static final String MYBATIS_PATH = "main/resources/mapper"; /** * 默认上级菜单,系统工具 */ private static final String DEFAULT_PARENT_MENU_ID = "3"; /** * 设置模板变量信息 * * @return 模板列表 */ public static VelocityContext prepareContext(GenTable genTable) { String moduleName = genTable.getModuleName(); String businessName = genTable.getBusinessName(); String packageName = genTable.getPackageName(); String tplCategory = genTable.getTplCategory(); String functionName = genTable.getFunctionName(); VelocityContext velocityContext = new VelocityContext(); velocityContext.put("tplCategory", genTable.getTplCategory()); velocityContext.put("tableName", genTable.getTableName()); velocityContext.put("functionName", StringUtils.isNotEmpty(functionName) ? functionName : "【请填写功能名称】"); velocityContext.put("ClassName", genTable.getClassName()); velocityContext.put("className", StringUtils.uncapitalize(genTable.getClassName())); velocityContext.put("moduleName", genTable.getModuleName()); velocityContext.put("BusinessName", StringUtils.capitalize(genTable.getBusinessName())); velocityContext.put("businessName", genTable.getBusinessName()); velocityContext.put("basePackage", getPackagePrefix(packageName)); velocityContext.put("packageName", packageName); velocityContext.put("author", genTable.getFunctionAuthor()); velocityContext.put("datetime", DateUtils.getDate()); velocityContext.put("pkColumn", genTable.getPkColumn()); velocityContext.put("importList", getImportList(genTable)); velocityContext.put("permissionPrefix", getPermissionPrefix(moduleName, businessName)); velocityContext.put("columns", genTable.getColumns()); velocityContext.put("table", genTable); setMenuVelocityContext(velocityContext, genTable); if (GenConstants.TPL_TREE.equals(tplCategory)) { setTreeVelocityContext(velocityContext, genTable); } if (GenConstants.TPL_SUB.equals(tplCategory)) { setSubVelocityContext(velocityContext, genTable); } return velocityContext; } public static void setMenuVelocityContext(VelocityContext context, GenTable genTable) { String options = genTable.getOptions(); JSONObject paramsObj = JSONObject.parseObject(options); String parentMenuId = getParentMenuId(paramsObj); context.put("parentMenuId", parentMenuId); } public static void setTreeVelocityContext(VelocityContext context, GenTable genTable) { String options = genTable.getOptions(); JSONObject paramsObj = JSONObject.parseObject(options); String treeCode = getTreecode(paramsObj); String treeParentCode = getTreeParentCode(paramsObj); String treeName = getTreeName(paramsObj); context.put("treeCode", treeCode); context.put("treeParentCode", treeParentCode); context.put("treeName", treeName); context.put("expandColumn", getExpandColumn(genTable)); if (paramsObj.containsKey(GenConstants.TREE_PARENT_CODE)) { context.put("tree_parent_code", paramsObj.getString(GenConstants.TREE_PARENT_CODE)); } if (paramsObj.containsKey(GenConstants.TREE_NAME)) { context.put("tree_name", paramsObj.getString(GenConstants.TREE_NAME)); } } public static void setSubVelocityContext(VelocityContext context, GenTable genTable) { GenTable subTable = genTable.getSubTable(); String subTableName = genTable.getSubTableName(); String subTableFkName = genTable.getSubTableFkName(); String subClassName = genTable.getSubTable().getClassName(); String subTableFkClassName = StringUtils.convertToCamelCase(subTableFkName); context.put("subTable", subTable); context.put("subTableName", subTableName); context.put("subTableFkName", subTableFkName); context.put("subTableFkClassName", subTableFkClassName); context.put("subTableFkclassName", StringUtils.uncapitalize(subTableFkClassName)); context.put("subClassName", subClassName); context.put("subclassName", StringUtils.uncapitalize(subClassName)); context.put("subImportList", getImportList(genTable.getSubTable())); } /** * 获取模板信息 * * @return 模板列表 */ public static List<String> getTemplateList(String tplCategory) { List<String> templates = new ArrayList<String>(); templates.add("vm/java/domain.java.vm"); templates.add("vm/java/mapper.java.vm"); templates.add("vm/java/service.java.vm"); // templates.add("vm/java/serviceImpl.java.vm"); templates.add("vm/java/controller.java.vm"); templates.add("vm/xml/mapper.xml.vm"); templates.add("vm/sql/sql.vm"); templates.add("vm/js/api.js.vm"); if (GenConstants.TPL_CRUD.equals(tplCategory)) { templates.add("vm/vue/index.vue.vm"); } else if (GenConstants.TPL_TREE.equals(tplCategory)) { templates.add("vm/vue/index-tree.vue.vm"); } else if (GenConstants.TPL_SUB.equals(tplCategory)) { templates.add("vm/vue/index.vue.vm"); templates.add("vm/java/sub-domain.java.vm"); } return templates; } /** * 获取文件名 */ public static String getFileName(String template, GenTable genTable) { // 文件名称 String fileName = ""; // 包路径 String packageName = genTable.getPackageName(); // 模块名 String moduleName = genTable.getModuleName(); // 大写类名 String className = genTable.getClassName(); // 业务名称 String businessName = genTable.getBusinessName(); String javaPath = PROJECT_PATH + "/" + StringUtils.replace(packageName, ".", "/"); String mybatisPath = MYBATIS_PATH + "/" + moduleName; String vuePath = "vue"; if (template.contains("domain.java.vm")) { fileName = StringUtils.format("{}/domain/{}.java", javaPath, className); } if (template.contains("sub-domain.java.vm") && StringUtils.equals(GenConstants.TPL_SUB, genTable.getTplCategory())) { fileName = StringUtils.format("{}/domain/{}.java", javaPath, genTable.getSubTable().getClassName()); } else if (template.contains("mapper.java.vm")) { fileName = StringUtils.format("{}/mapper/{}Mapper.java", javaPath, className); } else if (template.contains("service.java.vm")) { fileName = StringUtils.format("{}/service/{}Service.java", javaPath, className); } else if (template.contains("serviceImpl.java.vm")) { fileName = StringUtils.format("{}/service/impl/{}ServiceImpl.java", javaPath, className); } else if (template.contains("controller.java.vm")) { fileName = StringUtils.format("{}/controller/{}Controller.java", javaPath, className); } else if (template.contains("mapper.xml.vm")) { fileName = StringUtils.format("{}/{}Mapper.xml", mybatisPath, className); } else if (template.contains("sql.vm")) { fileName = businessName + "Menu.sql"; } else if (template.contains("api.js.vm")) { fileName = StringUtils.format("{}/api/{}/{}.js", vuePath, moduleName, businessName); } else if (template.contains("index.vue.vm")) { fileName = StringUtils.format("{}/views/{}/{}/index.vue", vuePath, moduleName, businessName); } else if (template.contains("index-tree.vue.vm")) { fileName = StringUtils.format("{}/views/{}/{}/index.vue", vuePath, moduleName, businessName); } return fileName; } /** * 获取包前缀 * * @param packageName 包名称 * @return 包前缀名称 */ public static String getPackagePrefix(String packageName) { int lastIndex = packageName.lastIndexOf("."); String basePackage = StringUtils.substring(packageName, 0, lastIndex); return basePackage; } /** * 根据列类型获取导入包 * * @param genTable 业务表对象 * @return 返回需要导入的包列表 */ public static HashSet<String> getImportList(GenTable genTable) { List<GenTableColumn> columns = genTable.getColumns(); GenTable subGenTable = genTable.getSubTable(); HashSet<String> importList = new HashSet<String>(); if (StringUtils.isNotNull(subGenTable)) { importList.add("java.util.List"); } for (GenTableColumn column : columns) { if (!column.isSuperColumn() && GenConstants.TYPE_DATE.equals(column.getJavaType())) { importList.add("java.util.Date"); importList.add("com.fasterxml.jackson.annotation.JsonFormat"); } else if (!column.isSuperColumn() && GenConstants.TYPE_BIGDECIMAL.equals(column.getJavaType())) { importList.add("java.math.BigDecimal"); } } return importList; } /** * 获取权限前缀 * * @param moduleName 模块名称 * @param businessName 业务名称 * @return 返回权限前缀 */ public static String getPermissionPrefix(String moduleName, String businessName) { return StringUtils.format("{}:{}", moduleName, businessName); } /** * 获取上级菜单ID字段 * * @param paramsObj 生成其他选项 * @return 上级菜单ID字段 */ public static String getParentMenuId(JSONObject paramsObj) { if (StringUtils.isNotEmpty(paramsObj) && paramsObj.containsKey(GenConstants.PARENT_MENU_ID)) { return paramsObj.getString(GenConstants.PARENT_MENU_ID); } return DEFAULT_PARENT_MENU_ID; } /** * 获取树编码 * * @param paramsObj 生成其他选项 * @return 树编码 */ public static String getTreecode(JSONObject paramsObj) { if (paramsObj.containsKey(GenConstants.TREE_CODE)) { return StringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_CODE)); } return StringUtils.EMPTY; } /** * 获取树父编码 * * @param paramsObj 生成其他选项 * @return 树父编码 */ public static String getTreeParentCode(JSONObject paramsObj) { if (paramsObj.containsKey(GenConstants.TREE_PARENT_CODE)) { return StringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_PARENT_CODE)); } return StringUtils.EMPTY; } /** * 获取树名称 * * @param paramsObj 生成其他选项 * @return 树名称 */ public static String getTreeName(JSONObject paramsObj) { if (paramsObj.containsKey(GenConstants.TREE_NAME)) { return StringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_NAME)); } return StringUtils.EMPTY; } /** * 获取需要在哪一列上面显示展开按钮 * * @param genTable 业务表对象 * @return 展开按钮列序号 */ public static int getExpandColumn(GenTable genTable) { String options = genTable.getOptions(); JSONObject paramsObj = JSONObject.parseObject(options); String treeName = paramsObj.getString(GenConstants.TREE_NAME); int num = 0; for (GenTableColumn column : genTable.getColumns()) { if (column.isList()) { num++; String columnName = column.getColumnName(); if (columnName.equals(treeName)) { break; } } } return num; } }
package android.support.v4.content; import android.content.SharedPreferences.Editor; import android.os.Build.VERSION; public final class SharedPreferencesCompat { public static final class EditorCompat { private static android.support.v4.content.SharedPreferencesCompat.EditorCompat sInstance; private final Helper mHelper; private static interface Helper { void apply(Editor editor); } private static class EditorHelperApi9Impl implements Helper { private EditorHelperApi9Impl() { } public void apply(Editor editor) { EditorCompatGingerbread.apply(editor); } } private static class EditorHelperBaseImpl implements Helper { private EditorHelperBaseImpl() { } public void apply(Editor editor) { editor.commit(); } } private EditorCompat() { if (VERSION.SDK_INT >= 9) { this.mHelper = new EditorHelperApi9Impl(); } else { this.mHelper = new EditorHelperBaseImpl(); } } public static android.support.v4.content.SharedPreferencesCompat.EditorCompat getInstance() { if (sInstance == null) { sInstance = new android.support.v4.content.SharedPreferencesCompat.EditorCompat(); } return sInstance; } public final void apply(Editor editor) { this.mHelper.apply(editor); } } private SharedPreferencesCompat() { } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.appservice.models; import com.azure.core.annotation.Fluent; import com.azure.core.annotation.JsonFlatten; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.appservice.CloningInfo; import com.azure.resourcemanager.appservice.HostingEnvironmentProfile; import com.azure.resourcemanager.appservice.HostnameSslState; import com.azure.resourcemanager.appservice.ManagedServiceIdentity; import com.azure.resourcemanager.appservice.ProxyOnlyResource; import com.azure.resourcemanager.appservice.RedundancyMode; import com.azure.resourcemanager.appservice.SiteAvailabilityState; import com.azure.resourcemanager.appservice.SlotSwapStatus; import com.azure.resourcemanager.appservice.UsageState; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.time.OffsetDateTime; import java.util.List; import java.util.UUID; /** The SitePatchResource model. */ @JsonFlatten @Fluent public class SitePatchResourceInner extends ProxyOnlyResource { @JsonIgnore private final ClientLogger logger = new ClientLogger(SitePatchResourceInner.class); /* * Managed service identity. */ @JsonProperty(value = "identity") private ManagedServiceIdentity identity; /* * Current state of the app. */ @JsonProperty(value = "properties.state", access = JsonProperty.Access.WRITE_ONLY) private String state; /* * Hostnames associated with the app. */ @JsonProperty(value = "properties.hostNames", access = JsonProperty.Access.WRITE_ONLY) private List<String> hostNames; /* * Name of the repository site. */ @JsonProperty(value = "properties.repositorySiteName", access = JsonProperty.Access.WRITE_ONLY) private String repositorySiteName; /* * State indicating whether the app has exceeded its quota usage. * Read-only. */ @JsonProperty(value = "properties.usageState", access = JsonProperty.Access.WRITE_ONLY) private UsageState usageState; /* * <code>true</code> if the app is enabled; otherwise, <code>false</code>. * Setting this value to false disables the app (takes the app offline). */ @JsonProperty(value = "properties.enabled") private Boolean enabled; /* * Enabled hostnames for the app.Hostnames need to be assigned (see * HostNames) AND enabled. Otherwise, * the app is not served on those hostnames. */ @JsonProperty(value = "properties.enabledHostNames", access = JsonProperty.Access.WRITE_ONLY) private List<String> enabledHostNames; /* * Management information availability state for the app. */ @JsonProperty(value = "properties.availabilityState", access = JsonProperty.Access.WRITE_ONLY) private SiteAvailabilityState availabilityState; /* * Hostname SSL states are used to manage the SSL bindings for app's * hostnames. */ @JsonProperty(value = "properties.hostNameSslStates") private List<HostnameSslState> hostnameSslStates; /* * Resource ID of the associated App Service plan, formatted as: * "/subscriptions/{subscriptionID}/resourceGroups/{groupName}/providers/Microsoft.Web/serverfarms/{appServicePlanName}". */ @JsonProperty(value = "properties.serverFarmId") private String serverFarmId; /* * <code>true</code> if reserved; otherwise, <code>false</code>. */ @JsonProperty(value = "properties.reserved") private Boolean reserved; /* * Obsolete: Hyper-V sandbox. */ @JsonProperty(value = "properties.isXenon") private Boolean isXenon; /* * Hyper-V sandbox. */ @JsonProperty(value = "properties.hyperV") private Boolean hyperV; /* * Last time the app was modified, in UTC. Read-only. */ @JsonProperty(value = "properties.lastModifiedTimeUtc", access = JsonProperty.Access.WRITE_ONLY) private OffsetDateTime lastModifiedTimeUtc; /* * Configuration of the app. */ @JsonProperty(value = "properties.siteConfig") private SiteConfigInner siteConfig; /* * Azure Traffic Manager hostnames associated with the app. Read-only. */ @JsonProperty(value = "properties.trafficManagerHostNames", access = JsonProperty.Access.WRITE_ONLY) private List<String> trafficManagerHostNames; /* * <code>true</code> to stop SCM (KUDU) site when the app is stopped; * otherwise, <code>false</code>. The default is <code>false</code>. */ @JsonProperty(value = "properties.scmSiteAlsoStopped") private Boolean scmSiteAlsoStopped; /* * Specifies which deployment slot this app will swap into. Read-only. */ @JsonProperty(value = "properties.targetSwapSlot", access = JsonProperty.Access.WRITE_ONLY) private String targetSwapSlot; /* * App Service Environment to use for the app. */ @JsonProperty(value = "properties.hostingEnvironmentProfile") private HostingEnvironmentProfile hostingEnvironmentProfile; /* * <code>true</code> to enable client affinity; <code>false</code> to stop * sending session affinity cookies, which route client requests in the * same session to the same instance. Default is <code>true</code>. */ @JsonProperty(value = "properties.clientAffinityEnabled") private Boolean clientAffinityEnabled; /* * <code>true</code> to enable client certificate authentication (TLS * mutual authentication); otherwise, <code>false</code>. Default is * <code>false</code>. */ @JsonProperty(value = "properties.clientCertEnabled") private Boolean clientCertEnabled; /* * client certificate authentication comma-separated exclusion paths */ @JsonProperty(value = "properties.clientCertExclusionPaths") private String clientCertExclusionPaths; /* * <code>true</code> to disable the public hostnames of the app; otherwise, * <code>false</code>. * If <code>true</code>, the app is only accessible via API management * process. */ @JsonProperty(value = "properties.hostNamesDisabled") private Boolean hostNamesDisabled; /* * List of IP addresses that the app uses for outbound connections (e.g. * database access). Includes VIPs from tenants that site can be hosted * with current settings. Read-only. */ @JsonProperty(value = "properties.outboundIpAddresses", access = JsonProperty.Access.WRITE_ONLY) private String outboundIpAddresses; /* * List of IP addresses that the app uses for outbound connections (e.g. * database access). Includes VIPs from all tenants except dataComponent. * Read-only. */ @JsonProperty(value = "properties.possibleOutboundIpAddresses", access = JsonProperty.Access.WRITE_ONLY) private String possibleOutboundIpAddresses; /* * Size of the function container. */ @JsonProperty(value = "properties.containerSize") private Integer containerSize; /* * Maximum allowed daily memory-time quota (applicable on dynamic apps * only). */ @JsonProperty(value = "properties.dailyMemoryTimeQuota") private Integer dailyMemoryTimeQuota; /* * App suspended till in case memory-time quota is exceeded. */ @JsonProperty(value = "properties.suspendedTill", access = JsonProperty.Access.WRITE_ONLY) private OffsetDateTime suspendedTill; /* * Maximum number of workers. * This only applies to Functions container. */ @JsonProperty(value = "properties.maxNumberOfWorkers", access = JsonProperty.Access.WRITE_ONLY) private Integer maxNumberOfWorkers; /* * If specified during app creation, the app is cloned from a source app. */ @JsonProperty(value = "properties.cloningInfo") private CloningInfo cloningInfo; /* * Name of the resource group the app belongs to. Read-only. */ @JsonProperty(value = "properties.resourceGroup", access = JsonProperty.Access.WRITE_ONLY) private String resourceGroup; /* * <code>true</code> if the app is a default container; otherwise, * <code>false</code>. */ @JsonProperty(value = "properties.isDefaultContainer", access = JsonProperty.Access.WRITE_ONLY) private Boolean isDefaultContainer; /* * Default hostname of the app. Read-only. */ @JsonProperty(value = "properties.defaultHostName", access = JsonProperty.Access.WRITE_ONLY) private String defaultHostname; /* * Status of the last deployment slot swap operation. */ @JsonProperty(value = "properties.slotSwapStatus", access = JsonProperty.Access.WRITE_ONLY) private SlotSwapStatus slotSwapStatus; /* * HttpsOnly: configures a web site to accept only https requests. Issues * redirect for * http requests */ @JsonProperty(value = "properties.httpsOnly") private Boolean httpsOnly; /* * Site redundancy mode */ @JsonProperty(value = "properties.redundancyMode") private RedundancyMode redundancyMode; /* * Specifies an operation id if this site has a pending operation. */ @JsonProperty(value = "properties.inProgressOperationId", access = JsonProperty.Access.WRITE_ONLY) private UUID inProgressOperationId; /** * Get the identity property: Managed service identity. * * @return the identity value. */ public ManagedServiceIdentity identity() { return this.identity; } /** * Set the identity property: Managed service identity. * * @param identity the identity value to set. * @return the SitePatchResourceInner object itself. */ public SitePatchResourceInner withIdentity(ManagedServiceIdentity identity) { this.identity = identity; return this; } /** * Get the state property: Current state of the app. * * @return the state value. */ public String state() { return this.state; } /** * Get the hostNames property: Hostnames associated with the app. * * @return the hostNames value. */ public List<String> hostNames() { return this.hostNames; } /** * Get the repositorySiteName property: Name of the repository site. * * @return the repositorySiteName value. */ public String repositorySiteName() { return this.repositorySiteName; } /** * Get the usageState property: State indicating whether the app has exceeded its quota usage. Read-only. * * @return the usageState value. */ public UsageState usageState() { return this.usageState; } /** * Get the enabled property: &lt;code&gt;true&lt;/code&gt; if the app is enabled; otherwise, * &lt;code&gt;false&lt;/code&gt;. Setting this value to false disables the app (takes the app offline). * * @return the enabled value. */ public Boolean enabled() { return this.enabled; } /** * Set the enabled property: &lt;code&gt;true&lt;/code&gt; if the app is enabled; otherwise, * &lt;code&gt;false&lt;/code&gt;. Setting this value to false disables the app (takes the app offline). * * @param enabled the enabled value to set. * @return the SitePatchResourceInner object itself. */ public SitePatchResourceInner withEnabled(Boolean enabled) { this.enabled = enabled; return this; } /** * Get the enabledHostNames property: Enabled hostnames for the app.Hostnames need to be assigned (see HostNames) * AND enabled. Otherwise, the app is not served on those hostnames. * * @return the enabledHostNames value. */ public List<String> enabledHostNames() { return this.enabledHostNames; } /** * Get the availabilityState property: Management information availability state for the app. * * @return the availabilityState value. */ public SiteAvailabilityState availabilityState() { return this.availabilityState; } /** * Get the hostnameSslStates property: Hostname SSL states are used to manage the SSL bindings for app's hostnames. * * @return the hostnameSslStates value. */ public List<HostnameSslState> hostnameSslStates() { return this.hostnameSslStates; } /** * Set the hostnameSslStates property: Hostname SSL states are used to manage the SSL bindings for app's hostnames. * * @param hostnameSslStates the hostnameSslStates value to set. * @return the SitePatchResourceInner object itself. */ public SitePatchResourceInner withHostnameSslStates(List<HostnameSslState> hostnameSslStates) { this.hostnameSslStates = hostnameSslStates; return this; } /** * Get the serverFarmId property: Resource ID of the associated App Service plan, formatted as: * "/subscriptions/{subscriptionID}/resourceGroups/{groupName}/providers/Microsoft.Web/serverfarms/{appServicePlanName}". * * @return the serverFarmId value. */ public String serverFarmId() { return this.serverFarmId; } /** * Set the serverFarmId property: Resource ID of the associated App Service plan, formatted as: * "/subscriptions/{subscriptionID}/resourceGroups/{groupName}/providers/Microsoft.Web/serverfarms/{appServicePlanName}". * * @param serverFarmId the serverFarmId value to set. * @return the SitePatchResourceInner object itself. */ public SitePatchResourceInner withServerFarmId(String serverFarmId) { this.serverFarmId = serverFarmId; return this; } /** * Get the reserved property: &lt;code&gt;true&lt;/code&gt; if reserved; otherwise, &lt;code&gt;false&lt;/code&gt;. * * @return the reserved value. */ public Boolean reserved() { return this.reserved; } /** * Set the reserved property: &lt;code&gt;true&lt;/code&gt; if reserved; otherwise, &lt;code&gt;false&lt;/code&gt;. * * @param reserved the reserved value to set. * @return the SitePatchResourceInner object itself. */ public SitePatchResourceInner withReserved(Boolean reserved) { this.reserved = reserved; return this; } /** * Get the isXenon property: Obsolete: Hyper-V sandbox. * * @return the isXenon value. */ public Boolean isXenon() { return this.isXenon; } /** * Set the isXenon property: Obsolete: Hyper-V sandbox. * * @param isXenon the isXenon value to set. * @return the SitePatchResourceInner object itself. */ public SitePatchResourceInner withIsXenon(Boolean isXenon) { this.isXenon = isXenon; return this; } /** * Get the hyperV property: Hyper-V sandbox. * * @return the hyperV value. */ public Boolean hyperV() { return this.hyperV; } /** * Set the hyperV property: Hyper-V sandbox. * * @param hyperV the hyperV value to set. * @return the SitePatchResourceInner object itself. */ public SitePatchResourceInner withHyperV(Boolean hyperV) { this.hyperV = hyperV; return this; } /** * Get the lastModifiedTimeUtc property: Last time the app was modified, in UTC. Read-only. * * @return the lastModifiedTimeUtc value. */ public OffsetDateTime lastModifiedTimeUtc() { return this.lastModifiedTimeUtc; } /** * Get the siteConfig property: Configuration of the app. * * @return the siteConfig value. */ public SiteConfigInner siteConfig() { return this.siteConfig; } /** * Set the siteConfig property: Configuration of the app. * * @param siteConfig the siteConfig value to set. * @return the SitePatchResourceInner object itself. */ public SitePatchResourceInner withSiteConfig(SiteConfigInner siteConfig) { this.siteConfig = siteConfig; return this; } /** * Get the trafficManagerHostNames property: Azure Traffic Manager hostnames associated with the app. Read-only. * * @return the trafficManagerHostNames value. */ public List<String> trafficManagerHostNames() { return this.trafficManagerHostNames; } /** * Get the scmSiteAlsoStopped property: &lt;code&gt;true&lt;/code&gt; to stop SCM (KUDU) site when the app is * stopped; otherwise, &lt;code&gt;false&lt;/code&gt;. The default is &lt;code&gt;false&lt;/code&gt;. * * @return the scmSiteAlsoStopped value. */ public Boolean scmSiteAlsoStopped() { return this.scmSiteAlsoStopped; } /** * Set the scmSiteAlsoStopped property: &lt;code&gt;true&lt;/code&gt; to stop SCM (KUDU) site when the app is * stopped; otherwise, &lt;code&gt;false&lt;/code&gt;. The default is &lt;code&gt;false&lt;/code&gt;. * * @param scmSiteAlsoStopped the scmSiteAlsoStopped value to set. * @return the SitePatchResourceInner object itself. */ public SitePatchResourceInner withScmSiteAlsoStopped(Boolean scmSiteAlsoStopped) { this.scmSiteAlsoStopped = scmSiteAlsoStopped; return this; } /** * Get the targetSwapSlot property: Specifies which deployment slot this app will swap into. Read-only. * * @return the targetSwapSlot value. */ public String targetSwapSlot() { return this.targetSwapSlot; } /** * Get the hostingEnvironmentProfile property: App Service Environment to use for the app. * * @return the hostingEnvironmentProfile value. */ public HostingEnvironmentProfile hostingEnvironmentProfile() { return this.hostingEnvironmentProfile; } /** * Set the hostingEnvironmentProfile property: App Service Environment to use for the app. * * @param hostingEnvironmentProfile the hostingEnvironmentProfile value to set. * @return the SitePatchResourceInner object itself. */ public SitePatchResourceInner withHostingEnvironmentProfile(HostingEnvironmentProfile hostingEnvironmentProfile) { this.hostingEnvironmentProfile = hostingEnvironmentProfile; return this; } /** * Get the clientAffinityEnabled property: &lt;code&gt;true&lt;/code&gt; to enable client affinity; * &lt;code&gt;false&lt;/code&gt; to stop sending session affinity cookies, which route client requests in the same * session to the same instance. Default is &lt;code&gt;true&lt;/code&gt;. * * @return the clientAffinityEnabled value. */ public Boolean clientAffinityEnabled() { return this.clientAffinityEnabled; } /** * Set the clientAffinityEnabled property: &lt;code&gt;true&lt;/code&gt; to enable client affinity; * &lt;code&gt;false&lt;/code&gt; to stop sending session affinity cookies, which route client requests in the same * session to the same instance. Default is &lt;code&gt;true&lt;/code&gt;. * * @param clientAffinityEnabled the clientAffinityEnabled value to set. * @return the SitePatchResourceInner object itself. */ public SitePatchResourceInner withClientAffinityEnabled(Boolean clientAffinityEnabled) { this.clientAffinityEnabled = clientAffinityEnabled; return this; } /** * Get the clientCertEnabled property: &lt;code&gt;true&lt;/code&gt; to enable client certificate authentication * (TLS mutual authentication); otherwise, &lt;code&gt;false&lt;/code&gt;. Default is * &lt;code&gt;false&lt;/code&gt;. * * @return the clientCertEnabled value. */ public Boolean clientCertEnabled() { return this.clientCertEnabled; } /** * Set the clientCertEnabled property: &lt;code&gt;true&lt;/code&gt; to enable client certificate authentication * (TLS mutual authentication); otherwise, &lt;code&gt;false&lt;/code&gt;. Default is * &lt;code&gt;false&lt;/code&gt;. * * @param clientCertEnabled the clientCertEnabled value to set. * @return the SitePatchResourceInner object itself. */ public SitePatchResourceInner withClientCertEnabled(Boolean clientCertEnabled) { this.clientCertEnabled = clientCertEnabled; return this; } /** * Get the clientCertExclusionPaths property: client certificate authentication comma-separated exclusion paths. * * @return the clientCertExclusionPaths value. */ public String clientCertExclusionPaths() { return this.clientCertExclusionPaths; } /** * Set the clientCertExclusionPaths property: client certificate authentication comma-separated exclusion paths. * * @param clientCertExclusionPaths the clientCertExclusionPaths value to set. * @return the SitePatchResourceInner object itself. */ public SitePatchResourceInner withClientCertExclusionPaths(String clientCertExclusionPaths) { this.clientCertExclusionPaths = clientCertExclusionPaths; return this; } /** * Get the hostNamesDisabled property: &lt;code&gt;true&lt;/code&gt; to disable the public hostnames of the app; * otherwise, &lt;code&gt;false&lt;/code&gt;. If &lt;code&gt;true&lt;/code&gt;, the app is only accessible via API * management process. * * @return the hostNamesDisabled value. */ public Boolean hostNamesDisabled() { return this.hostNamesDisabled; } /** * Set the hostNamesDisabled property: &lt;code&gt;true&lt;/code&gt; to disable the public hostnames of the app; * otherwise, &lt;code&gt;false&lt;/code&gt;. If &lt;code&gt;true&lt;/code&gt;, the app is only accessible via API * management process. * * @param hostNamesDisabled the hostNamesDisabled value to set. * @return the SitePatchResourceInner object itself. */ public SitePatchResourceInner withHostNamesDisabled(Boolean hostNamesDisabled) { this.hostNamesDisabled = hostNamesDisabled; return this; } /** * Get the outboundIpAddresses property: List of IP addresses that the app uses for outbound connections (e.g. * database access). Includes VIPs from tenants that site can be hosted with current settings. Read-only. * * @return the outboundIpAddresses value. */ public String outboundIpAddresses() { return this.outboundIpAddresses; } /** * Get the possibleOutboundIpAddresses property: List of IP addresses that the app uses for outbound connections * (e.g. database access). Includes VIPs from all tenants except dataComponent. Read-only. * * @return the possibleOutboundIpAddresses value. */ public String possibleOutboundIpAddresses() { return this.possibleOutboundIpAddresses; } /** * Get the containerSize property: Size of the function container. * * @return the containerSize value. */ public Integer containerSize() { return this.containerSize; } /** * Set the containerSize property: Size of the function container. * * @param containerSize the containerSize value to set. * @return the SitePatchResourceInner object itself. */ public SitePatchResourceInner withContainerSize(Integer containerSize) { this.containerSize = containerSize; return this; } /** * Get the dailyMemoryTimeQuota property: Maximum allowed daily memory-time quota (applicable on dynamic apps only). * * @return the dailyMemoryTimeQuota value. */ public Integer dailyMemoryTimeQuota() { return this.dailyMemoryTimeQuota; } /** * Set the dailyMemoryTimeQuota property: Maximum allowed daily memory-time quota (applicable on dynamic apps only). * * @param dailyMemoryTimeQuota the dailyMemoryTimeQuota value to set. * @return the SitePatchResourceInner object itself. */ public SitePatchResourceInner withDailyMemoryTimeQuota(Integer dailyMemoryTimeQuota) { this.dailyMemoryTimeQuota = dailyMemoryTimeQuota; return this; } /** * Get the suspendedTill property: App suspended till in case memory-time quota is exceeded. * * @return the suspendedTill value. */ public OffsetDateTime suspendedTill() { return this.suspendedTill; } /** * Get the maxNumberOfWorkers property: Maximum number of workers. This only applies to Functions container. * * @return the maxNumberOfWorkers value. */ public Integer maxNumberOfWorkers() { return this.maxNumberOfWorkers; } /** * Get the cloningInfo property: If specified during app creation, the app is cloned from a source app. * * @return the cloningInfo value. */ public CloningInfo cloningInfo() { return this.cloningInfo; } /** * Set the cloningInfo property: If specified during app creation, the app is cloned from a source app. * * @param cloningInfo the cloningInfo value to set. * @return the SitePatchResourceInner object itself. */ public SitePatchResourceInner withCloningInfo(CloningInfo cloningInfo) { this.cloningInfo = cloningInfo; return this; } /** * Get the resourceGroup property: Name of the resource group the app belongs to. Read-only. * * @return the resourceGroup value. */ public String resourceGroup() { return this.resourceGroup; } /** * Get the isDefaultContainer property: &lt;code&gt;true&lt;/code&gt; if the app is a default container; otherwise, * &lt;code&gt;false&lt;/code&gt;. * * @return the isDefaultContainer value. */ public Boolean isDefaultContainer() { return this.isDefaultContainer; } /** * Get the defaultHostname property: Default hostname of the app. Read-only. * * @return the defaultHostname value. */ public String defaultHostname() { return this.defaultHostname; } /** * Get the slotSwapStatus property: Status of the last deployment slot swap operation. * * @return the slotSwapStatus value. */ public SlotSwapStatus slotSwapStatus() { return this.slotSwapStatus; } /** * Get the httpsOnly property: HttpsOnly: configures a web site to accept only https requests. Issues redirect for * http requests. * * @return the httpsOnly value. */ public Boolean httpsOnly() { return this.httpsOnly; } /** * Set the httpsOnly property: HttpsOnly: configures a web site to accept only https requests. Issues redirect for * http requests. * * @param httpsOnly the httpsOnly value to set. * @return the SitePatchResourceInner object itself. */ public SitePatchResourceInner withHttpsOnly(Boolean httpsOnly) { this.httpsOnly = httpsOnly; return this; } /** * Get the redundancyMode property: Site redundancy mode. * * @return the redundancyMode value. */ public RedundancyMode redundancyMode() { return this.redundancyMode; } /** * Set the redundancyMode property: Site redundancy mode. * * @param redundancyMode the redundancyMode value to set. * @return the SitePatchResourceInner object itself. */ public SitePatchResourceInner withRedundancyMode(RedundancyMode redundancyMode) { this.redundancyMode = redundancyMode; return this; } /** * Get the inProgressOperationId property: Specifies an operation id if this site has a pending operation. * * @return the inProgressOperationId value. */ public UUID inProgressOperationId() { return this.inProgressOperationId; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ @Override public void validate() { super.validate(); if (identity() != null) { identity().validate(); } if (hostnameSslStates() != null) { hostnameSslStates().forEach(e -> e.validate()); } if (siteConfig() != null) { siteConfig().validate(); } if (hostingEnvironmentProfile() != null) { hostingEnvironmentProfile().validate(); } if (cloningInfo() != null) { cloningInfo().validate(); } if (slotSwapStatus() != null) { slotSwapStatus().validate(); } } }
/* * Copyright (C) 2015 Twitter, 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.digits.sdk.android; import android.os.Parcel; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import static junit.framework.Assert.assertEquals; @RunWith(RobolectricGradleTestRunner.class) @Config(constants = BuildConfig.class, sdk = 21) public class AuthConfigTests { @Test public void testParcelable() throws Exception { final AuthConfig config = new AuthConfig(); config.isVoiceEnabled = true; config.tosUpdate = false; config.isEmailEnabled = true; final Parcel parcel = Parcel.obtain(); config.writeToParcel(parcel, 0); parcel.setDataPosition(0); final AuthConfig parceledConfig = AuthConfig.CREATOR.createFromParcel(parcel); assertEquals(config, parceledConfig); } }
/* * Copyright (c) 2003-2013, University of Luebeck, Institute of Computer Engineering * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Luebeck, the Institute of Computer * Engineering nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE UNIVERSITY OF LUEBECK OR THE INSTITUTE OF COMPUTER * ENGINEERING BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package de.uniluebeck.iti.rteasy.kernel; import java.util.*; import java.io.*; public class ExpressionInputBundle { private Hashtable regBusTable; ExpressionInputBundle() { regBusTable = new Hashtable(); } public boolean hasRegArrays(){ boolean stat = false; for(Enumeration en=regBusTable.keys();en.hasMoreElements();) { if(((RegBus) en.nextElement()) instanceof RegisterArray){ stat=true; } } return stat; } public LinkedList<RegBus> getRefReg(){ LinkedList<RegBus> ll = new LinkedList<RegBus>(); RegBus rb; if(hasRegArrays()){ for(Enumeration en=regBusTable.keys();en.hasMoreElements();) { RegBus r = (RegBus) en.nextElement(); if(r instanceof RegisterArray){ RegisterArray a = (RegisterArray) r; // rb = a.getReference(); // ll.add(rb); } } return ll; } else { return null; } } public BitRange getArrayWidth(int i){ BitRange br = null; int j=0; if(hasRegArrays()){ for(Enumeration en=regBusTable.keys();en.hasMoreElements();) { RegBus r = (RegBus) en.nextElement(); if(r instanceof RegisterArray){ if(i==j){ RegisterArray a = (RegisterArray) r; br=a.getBitRange(); } j+=1; } } } return br; } public void include(RegBusReference rbr) { ArrayList refList; int i; BitRange br; if(regBusTable.containsKey(rbr.regBus)) { refList = (ArrayList) regBusTable.get(rbr.regBus); i = 0; br = rbr.bitRange; // join and remove all BitRanges from list adjacent to or intersecting // with rbr.bitRange while(i<refList.size()) { if(((BitRange) refList.get(i)).joinPossibleWith(rbr.bitRange)) { br = br.joinWith((BitRange) refList.get(i)); refList.remove(i); } else i++; } // now insert new BitRange into list keeping the order i = 0; while(i<refList.size() && ((BitRange) refList.get(i)).lt(br)) i++; refList.add(i,br); } else { refList = new ArrayList(); refList.add(rbr.bitRange); regBusTable.put(rbr.regBus,refList); } } public RegBusReference map(RegBusReference rbr) { if(regBusTable.containsKey(rbr.regBus)) { ArrayList refList = (ArrayList) regBusTable.get(rbr.regBus); // search surrounding or equal BitRange to rbr.bitRange for(int i=0;i<refList.size();i++) if(((BitRange) refList.get(i)).contains(rbr.bitRange)) return new RegBusReference(rbr.regBus,(BitRange) refList.get(i)); // not found return null; } else return null; } public void emitPortDeclarations(String indent, PrintWriter out) { ArrayList refList; RegBus rb; ListIterator it; RegBus ref=null; boolean b = false; BitRange range=null; for(Enumeration en=regBusTable.keys();en.hasMoreElements();) { rb = (RegBus) en.nextElement(); refList = (ArrayList) regBusTable.get(rb); if(rb instanceof RegisterArray){ b = true; RegisterArray ra = (RegisterArray) rb; // ref = ra.getReference(); // out.println(indent+(new RegBusReference(ref,ref.offset,ref.offset+ref.width-1)).toVHDLPortDecl("IN",false,null)+";"); } for(it=refList.listIterator();it.hasNext();){ if(ref!=null){ range=(new RegBusReference(ref,ref.offset,ref.offset+ref.width-1)).bitRange; } out.println(indent+(new RegBusReference(rb,(BitRange) it.next())).toVHDLPortDecl("IN",b,range)+";");} } b=false; } public void emitOutRegArray(String indent, PrintWriter out) { ArrayList refList; RegBus rb; RegBus ref=null; for(Enumeration en=regBusTable.keys();en.hasMoreElements();) { rb = (RegBus) en.nextElement(); refList = (ArrayList) regBusTable.get(rb); if(rb instanceof RegisterArray){ RegisterArray ra = (RegisterArray) rb; // ref = ra.getReference(); // out.println(indent+(new RegBusReference(ref,ref.offset,ref.offset+ref.width-1)).toVHDLPortDecl("IN",false,null)+";"); } } } public void emitPortMap(String indent, PrintWriter out) { emitPortMap(indent,out,null); } public void emitPortMap(String indent, PrintWriter out, String port) { ArrayList refList; RegBus rb; ListIterator it; for(Enumeration en=regBusTable.keys();en.hasMoreElements();) { rb = (RegBus) en.nextElement(); refList = (ArrayList) regBusTable.get(rb); for(it=refList.listIterator();it.hasNext();) out.println(indent+(new RegBusReference(rb,(BitRange) it.next())).getVHDLPortMap(port)+","); } } }
import java.util.*; public class Solution451ViaSort { public String frequencySort(String s) { if (s == null || s.length() == 0) return ""; char[] chs = s.toCharArray(); List<String> ans = new ArrayList<>(); StringBuilder sb = new StringBuilder(); Arrays.sort(chs); sb.append(chs[0]); for (int i = 1; i < chs.length; i++) { if (chs[i] != chs[i - 1]) { ans.add(sb.toString()); sb.setLength(0); } sb.append(chs[i]); } ans.add(sb.toString()); ans.sort((String s1, String s2) -> s2.length() - s1.length()); sb.setLength(0); for (String str : ans) sb.append(str); return sb.toString(); } }
/* * 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.cassandraBloomFilters.dht; import java.io.DataInput; import java.io.IOException; import org.apache.cassandraBloomFilters.io.util.DataOutputPlus; /** * Versioned serializer where the serialization depends on partitioner. * * On serialization the partitioner is given by the entity being serialized. To deserialize the partitioner used must * be known to the calling method. */ public interface IPartitionerDependentSerializer<T> { /** * Serialize the specified type into the specified DataOutputStream instance. * * @param t type that needs to be serialized * @param out DataOutput into which serialization needs to happen. * @param version protocol version * @throws java.io.IOException if serialization fails */ public void serialize(T t, DataOutputPlus out, int version) throws IOException; /** * Deserialize into the specified DataInputStream instance. * @param in DataInput from which deserialization needs to happen. * @param p Partitioner that will be used to construct tokens. Needs to match the partitioner that was used to * serialize the token. * @param version protocol version * @return the type that was deserialized * @throws IOException if deserialization fails */ public T deserialize(DataInput in, IPartitioner p, int version) throws IOException; /** * Calculate serialized size of object without actually serializing. * @param t object to calculate serialized size * @param version protocol version * @return serialized size of object t */ public long serializedSize(T t, int version); }
/* * Copyright 2013-present Facebook, 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.facebook.buck.rules; import static org.junit.Assert.assertEquals; import com.facebook.buck.core.model.BuildTarget; import com.facebook.buck.core.rules.BuildRuleResolver; import com.facebook.buck.core.rules.SourcePathRuleFinder; import com.facebook.buck.core.rules.resolver.impl.TestBuildRuleResolver; import com.facebook.buck.core.sourcepath.DefaultBuildTargetSourcePath; import com.facebook.buck.core.sourcepath.ExplicitBuildTargetSourcePath; import com.facebook.buck.core.sourcepath.ForwardingBuildTargetSourcePath; import com.facebook.buck.core.sourcepath.PathSourcePath; import com.facebook.buck.core.sourcepath.resolver.SourcePathResolver; import com.facebook.buck.core.sourcepath.resolver.impl.DefaultSourcePathResolver; import com.facebook.buck.model.BuildTargetFactory; import com.facebook.buck.testutil.FakeProjectFilesystem; import java.nio.file.Path; import java.nio.file.Paths; import org.junit.Before; import org.junit.Test; public class ForwardingBuildTargetSourcePathTest { private BuildRuleResolver resolver; private SourcePathResolver pathResolver; @Before public void setUp() { resolver = new TestBuildRuleResolver(); pathResolver = DefaultSourcePathResolver.from(new SourcePathRuleFinder(resolver)); } @Test public void forwardsToPathSourcePath() { BuildTarget target = BuildTargetFactory.newInstance("//package:name"); Path relativePath = Paths.get("foo/bar"); ForwardingBuildTargetSourcePath sourcePath = ForwardingBuildTargetSourcePath.of( target, PathSourcePath.of(new FakeProjectFilesystem(), relativePath)); assertEquals(target, sourcePath.getTarget()); assertEquals(relativePath, pathResolver.getRelativePath(sourcePath)); } @Test public void forwardsToDefaultBuildTargetSourcePath() { BuildTarget target = BuildTargetFactory.newInstance("//package:name"); FakeBuildRule rule = new FakeBuildRule(target); rule.setOutputFile("foo/bar"); resolver.addToIndex(rule); ForwardingBuildTargetSourcePath sourcePath = ForwardingBuildTargetSourcePath.of(target, DefaultBuildTargetSourcePath.of(target)); assertEquals(target, sourcePath.getTarget()); assertEquals(rule.getOutputFile(), pathResolver.getRelativePath(sourcePath)); } @Test public void forwardsToExplicitBuildTargetSourcePath() { BuildTarget target = BuildTargetFactory.newInstance("//package:name"); FakeBuildRule rule = new FakeBuildRule(target); resolver.addToIndex(rule); Path relativePath = Paths.get("foo/bar"); ForwardingBuildTargetSourcePath sourcePath = ForwardingBuildTargetSourcePath.of( target, ExplicitBuildTargetSourcePath.of(target, relativePath)); assertEquals(target, sourcePath.getTarget()); assertEquals(relativePath, pathResolver.getRelativePath(sourcePath)); } @Test public void chains() { BuildTarget target1 = BuildTargetFactory.newInstance("//package:name"); FakeBuildRule rule1 = new FakeBuildRule(target1); resolver.addToIndex(rule1); BuildTarget target2 = BuildTargetFactory.newInstance("//package2:name2"); FakeBuildRule rule2 = new FakeBuildRule(target2); resolver.addToIndex(rule2); Path relativePath = Paths.get("foo/bar"); ForwardingBuildTargetSourcePath sourcePath = ForwardingBuildTargetSourcePath.of( target1, ForwardingBuildTargetSourcePath.of( target2, ExplicitBuildTargetSourcePath.of(target2, relativePath))); assertEquals(target1, sourcePath.getTarget()); assertEquals(relativePath, pathResolver.getRelativePath(sourcePath)); } }
/** * Copyright (C) 2015 Vince Styling * * 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.vincestyling.asqliteplus.statement; import static android.database.DatabaseUtils.appendEscapedSQLString; /** * A base class for constructing SQL statement. Internal holding a {@link StringBuilder} to representing * the SQL statement. Exposed many elegant methods to concatenating those acceptable clauses finally * complete the entire SQL statement. * <p/> * A Statement look as a String, only its toString() matter, just make sure that the {@link #toString()} * method would return the final SQL statement you want to be executing. * <p/> * <strong>Note:</strong> 'Cause this series of statement producer would never understand about the SQL * syntax, therefore this assumes you have a basic knowledge of SQL programming, you need to decide * which clause can be join together without syntax errors while performing and which cannot. * * @see com.vincestyling.asqliteplus.DBOverseer */ public class Statement { /** * the StringBuilder to representing the SQL statement. */ protected StringBuilder statement = new StringBuilder(512); /** * Appending the FROM clause with one or more table name. * * @param tables the names of the table to operating. Each name can be either a normal String * which just the table name or wrapped the table name's {@link Alias} object. * @return this statement. */ public Statement from(Object... tables) { statement.append(" FROM "); appendClauses(tables); return this; } /** * Appending the WHERE clause. * * @param operand the condition operand. Usually be a normal String which just the column name or * wrapped the column name's {@link Function}||{@link Scoping} object. It can also * be an {@link Exists}||{@link NotExists} object which carry the (NOT)EXISTS clause. * @return this statement. */ public Statement where(Object operand) { statement.append(" WHERE ").append(operand); return this; } /** * Appending the AND clause. * * @param operand the condition operand. Usually be a normal String which just the column name or * wrapped the column name's {@link Function}||{@link Scoping} object. It can also * be an {@link Exists}||{@link NotExists} object which carry the (NOT)EXISTS clause. * @return this statement. */ public Statement and(Object operand) { statement.append(" AND ").append(operand); return this; } /** * Appending the OR clause. * * @param operand the condition operand. Usually be a normal String which just the column name or * wrapped the column name's {@link Function}||{@link Scoping} object. It can also * be an {@link Exists}||{@link NotExists} object which carry the (NOT)EXISTS clause. * @return this statement. */ public Statement or(Object operand) { statement.append(" OR ").append(operand); return this; } /** * Appending the ORDER BY clause. * * @param columns the column list to be sorting. Each name can be either a normal String which just * the column name or wrapped the column name's {@link Function}||{@link Scoping} object. * @return this statement. */ public Statement orderBy(Object... columns) { statement.append(" ORDER BY "); appendClauses(columns); return this; } /** * Appending the ASCENDING order clause. * <p/> * <strong>Notice</strong>: This clause often be omitted because the * ORDER BY keyword sorts the records in ASCENDING order by default. * * @return this statement. */ public Statement asc() { statement.append(" ASC"); return this; } /** * Appending the DESCENDING order clause. * * @return this statement. */ public Statement desc() { statement.append(" DESC"); return this; } /** * Appending the GROUP BY clause. * * @param columns the column list to be grouping. Each name can be either a normal String which just * the column name or wrapped the column name's {@link Function}||{@link Scoping} object. * @return this statement. */ public Statement groupBy(Object... columns) { statement.append(" GROUP BY "); appendClauses(columns); return this; } /** * Appending the HAVING clause. * * @param column the condition column name. Can be either a normal String which just * the column name or wrapped the column name's {@link Function}||{@link Scoping} object. * @return this statement. */ public Statement having(Object column) { statement.append(" HAVING ").append(column); return this; } /** * Appending the OFFSET clause. * * @param offset the offset index. * @return this statement. */ public Statement offset(int offset) { statement.append(" OFFSET ").append(offset); return this; } /** * Appending the LIMIT clause. * * @param rowAmount the limit row amount. * @return this statement. */ public Statement limit(int rowAmount) { statement.append(" LIMIT ").append(rowAmount); return this; } /** * Appending the LIMIT-range clause. * <p/> * About the limit-offset clause, * Checking the <a href="http://sqlite.org/lang_select.html#limitoffset">SQLite documentation</a> for more details. * * @param rowAmount the limit row amount. * @param offset the offset index. * @return this statement. */ public Statement limit(int rowAmount, int offset) { limit(rowAmount); offset(offset); return this; } /** * Appending those comparison operators clause. * * @param op the operator. * @param value the comparand. * @return this statement. */ protected Statement compare(String op, Object value) { statement.append(' ').append(op).append(' '); append(value); return this; } /** * Appending the equals comparison clause. * * @param value the term's value, will auto quoting if instance of {@link String}. * @return this statement. */ public Statement eq(Object value) { return compare("=", value); } /** * Appending the non-equals comparison clause. * <p/> * <strong>Note:</strong> The non-equals operator can be either "!=" or "<>", here used "<>". * * @param value the term's value, will auto quoting if instance of {@link String}. * @return this statement. */ public Statement neq(Object value) { return compare("<>", value); } /** * Appending the greater than comparison clause. * * @param value the term's value, will auto quoting if instance of {@link String}. * @return this statement. */ public Statement gt(Object value) { return compare(">", value); } /** * Appending the equals or greater than comparison clause. * * @param value the term's value, will auto quoting if instance of {@link String}. * @return this statement. */ public Statement egt(Object value) { return compare(">=", value); } /** * Appending the less than comparison clause. * * @param value the term's value, will auto quoting if instance of {@link String}. * @return this statement. */ public Statement lt(Object value) { return compare("<", value); } /** * Appending the equals or less than comparison clause. * * @param value the term's value, will auto quoting if instance of {@link String}. * @return this statement. */ public Statement elt(Object value) { return compare("<=", value); } /** * Appending the IS NULL operator clause. * * @return this statement. */ public Statement isNull() { statement.append(" IS NULL"); return this; } /** * Appending the IS NOT NULL operator clause. * * @return this statement. */ public Statement isNotNull() { statement.append(" IS NOT NULL"); return this; } /** * Appending the IN operator clause. * * @param values apply an explicit list as terms. * @return this statement. */ public Statement in(Object... values) { statement.append(" IN ("); for (int i = 0; i < values.length; i++) { if (i > 0) statement.append(", "); append(values[i]); } statement.append(')'); return this; } /** * Appending the IN operator clause by a single sub-query. * * @param stmt apply a single sub-query as terms, the sub-query must have a single result column. * @return this statement. */ public Statement in(Statement stmt) { statement.append(" IN (").append(stmt).append(')'); return this; } /** * Appending the NOT IN operator clause. * * @param values apply an explicit list as terms. * @return this statement. */ public Statement notIn(Object... values) { statement.append(" NOT"); return in(values); } /** * Appending the NOT IN operator clause by a single sub-query. * * @param stmt apply a single sub-query as terms, the sub-query must have a single result column. * @return this statement. */ public Statement notIn(Statement stmt) { statement.append(" NOT"); return in(stmt); } /** * Appending the BETWEEN operator clause. * * @param former the former operand. * @param later the later operand. * @return this statement. */ public Statement between(Object former, Object later) { statement.append(" BETWEEN "); append(former); statement.append(" AND "); append(later); return this; } /** * Appending the LIKE operator clause. * * @param expr the former operand. * @return this statement. */ public Statement like(String expr) { statement.append(" LIKE "); appendEscapedSQLString(statement, expr); return this; } /** * Appending the LIKE operator clause by contains form. * * @param keyword the search text. * @return this statement. */ public Statement likeContains(String keyword) { return like('%' + keyword + '%'); } /** * Appending the LIKE operator clause by starts-with form. * * @param keyword the search text. * @return this statement. */ public Statement likeStartsWith(String keyword) { return like(keyword + '%'); } /** * Appending the LIKE operator clause by ends-with form. * * @param keyword the search text. * @return this statement. */ public Statement likeEndsWith(String keyword) { return like('%' + keyword); } /** * Appending the REGEXP operator clause. * <p/> * The REGEXP operator is a special syntax for the regexp() user function. * Checking the <a href="https://www.sqlite.org/lang_expr.html">SQLite documentation</a> for more details. * * @param regexp the regular expression. * @return this statement. */ public Statement regexp(CharSequence regexp) { statement.append(" REGEXP '").append(regexp).append('\''); return this; } /** * Appending the INNER JOIN clause. * <p/> * <strong>Note:</strong> In this produced statement, we have omitted the INNER keyword. * * @param table the name of the table to operating. Can be either a normal String * which just the table name or wrapped the table name's {@link Alias} object. * @return this statement. */ public Statement join(Object table) { statement.append(" JOIN ").append(table); return this; } /** * Appending the NATURAL INNER JOIN clause. * <p/> * <strong>Note:</strong> In this produced statement, we have omitted the INNER keyword. * * @param table the name of the table to operating. Can be either a normal String * which just the table name or wrapped the table name's {@link Alias} object. * @return this statement. */ public Statement naturalJoin(Object table) { statement.append(" NATURAL JOIN ").append(table); return this; } /** * Appending the CROSS INNER JOIN clause. * <p/> * <strong>Note:</strong> In this produced statement, we have omitted the INNER keyword. * * @param table the name of the table to operating. Can be either a normal String * which just the table name or wrapped the table name's {@link Alias} object. * @return this statement. */ public Statement crossJoin(Object table) { statement.append(" CROSS JOIN ").append(table); return this; } /** * Appending the LEFT OUTER JOIN clause. * <p/> * <strong>Note:</strong> In this produced statement, we have omitted the OUTER keyword. * * @param table the name of the table to operating. Can be either a normal String * which just the table name or wrapped the table name's {@link Alias} object. * @return this statement. */ public Statement leftJoin(Object table) { statement.append(" LEFT JOIN ").append(table); return this; } /** * Appending the NATURAL LEFT OUTER JOIN clause. * <p/> * <strong>Note:</strong> In this produced statement, we have omitted the OUTER keyword. * * @param table the name of the table to operating. Can be either a normal String * which just the table name or wrapped the table name's {@link Alias} object. * @return this statement. */ public Statement leftNaturalJoin(Object table) { statement.append(" NATURAL LEFT JOIN ").append(table); return this; } /** * Appending the ON sub-clause which follow the JOIN clause. * * @param column the condition column name. Can be either a normal String which just * the column name or wrapped the column name's {@link Function}||{@link Scoping} object. * @return this statement. */ public Statement on(Object column) { statement.append(" ON ").append(column); return this; } /** * Appending the USING sub-clause which follow the JOIN clause. * * @param columns the column list to be matching. * @return this statement. */ public Statement using(Object... columns) { statement.append(" USING ("); appendClauses(columns); statement.append(')'); return this; } /** * A safe way to appending a value if instance of {@link String}, include quoting the String value. * In order to preventing SQL injection, also escaping that String value which may contain single quotes. * <p/> * <strong>Note:</strong> you can wrapping a String as {@link UnescapeString} to avoiding this behaviors. * * @param value the raw value to be append, would translate to String["null"] if being <code>null</code>. * @return this statement. */ public Statement append(Object value) { append(statement, value); return this; } /** * A safe way to appending a value if instance of {@link String}, include quoting the String value. * In order to preventing SQL injection, also escaping that String value which may contain single quotes. * <p/> * <strong>Note:</strong> you can wrapping a String as {@link UnescapeString} to avoiding this behaviors. * * @param statement the StringBuilder that the SQL statement will be appended to. * @param value the raw value to be append, would translate to String["null"] if being <code>null</code>. */ protected void append(StringBuilder statement, Object value) { if (value instanceof String) { appendEscapedSQLString(statement, value.toString()); } else { statement.append(value); } } /** * Concatenates all the given clauses, separating them with commas. * * @param clauses the list of clause. Each clause usually a table name or column name, and each * name can be either a normal String which just the name or wrapped the * name's {@link Alias}||{@link Function}||{@link Scoping} object. */ protected void appendClauses(Object... clauses) { for (int i = 0; i < clauses.length; i++) { if (i > 0) statement.append(", "); statement.append(clauses[i]); } } /** * Simply clone this Statement by create a new Statement which apply the original statement. * * @return the new statement. */ public Statement copy() { Statement stmt = new Statement(); stmt.statement.append(statement); return stmt; } @Override public String toString() { return statement.toString(); } }
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.build.gradle.integration.api; import static com.android.build.gradle.integration.common.truth.TruthHelper.assertThatApk; import static com.google.common.truth.Truth.assertThat; import com.android.build.OutputFile; import com.android.build.gradle.integration.common.fixture.GradleTestProject; import com.android.builder.model.ProjectBuildOutput; import com.android.builder.model.VariantBuildOutput; import com.android.ide.common.process.ProcessException; import com.android.testutils.apk.Apk; import com.google.common.base.Charsets; import com.google.common.collect.Iterables; import com.google.common.io.Files; import java.io.IOException; import java.util.Collection; import java.util.Map; import java.util.Optional; import org.junit.Rule; import org.junit.Test; public class TransformInModuleWithKotlinTest { @Rule public GradleTestProject project = GradleTestProject.builder().fromTestProject("transformInModuleWithKotlin").create(); @Test public void testTransform() throws IOException, InterruptedException, ProcessException { // enable coverage in library as regression test for b/65345148 Files.append( "\nandroid.buildTypes.debug.testCoverageEnabled true\n", project.getSubproject("lib").getBuildFile(), Charsets.UTF_8); Map<String, ProjectBuildOutput> multi = project.executeAndReturnOutputMultiModel("clean", "assembleDebug"); ProjectBuildOutput appBuildOutput = multi.get(":app"); assertThat(appBuildOutput).isNotNull(); Collection<VariantBuildOutput> buildOutputs = appBuildOutput.getVariantsBuildOutput(); assertThat(buildOutputs).hasSize(2); Optional<VariantBuildOutput> debug = buildOutputs .stream() .filter(variantBuildOutput -> variantBuildOutput.getName().equals("debug")) .findFirst(); assertThat(debug.isPresent()).isTrue(); Collection<OutputFile> debugOutputs = debug.get().getOutputs(); assertThat(debugOutputs).hasSize(1); assertThatApk(new Apk(Iterables.getOnlyElement(debugOutputs).getOutputFile())) .hasClass("LHello;"); } }
package space.engine.delegate.map.entry; import java.util.Map; import java.util.Objects; public class DelegatingEntry<K, V> implements Map.Entry<K, V> { public Map.Entry<K, V> entry; public DelegatingEntry(Map.Entry<K, V> entry) { this.entry = entry; } @Override public K getKey() { return entry.getKey(); } @Override public V getValue() { return entry.getValue(); } @Override public V setValue(V value) { return entry.setValue(value); } @Override public int hashCode() { return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue()); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof Map.Entry)) return false; Map.Entry other = (Map.Entry) obj; return Objects.equals(getKey(), other.getKey()) && Objects.equals(getValue(), other.getValue()); } }
/* * Copyright (c) 2008-2019, Hazelcast, 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.hazelcast.client.quorum.scheduledexecutor; import com.hazelcast.client.quorum.PartitionedClusterClients; import com.hazelcast.client.test.TestHazelcastFactory; import com.hazelcast.config.Config; import com.hazelcast.quorum.scheduledexecutor.ScheduledExecutorQuorumWriteTest; import com.hazelcast.scheduledexecutor.IScheduledExecutorService; import com.hazelcast.test.HazelcastSerialParametersRunnerFactory; import com.hazelcast.test.annotation.ParallelTest; import com.hazelcast.test.annotation.QuickTest; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.UseParametersRunnerFactory; @RunWith(Parameterized.class) @UseParametersRunnerFactory(HazelcastSerialParametersRunnerFactory.class) @Category({QuickTest.class, ParallelTest.class}) public class ClientScheduledExecutorQuorumWriteTest extends ScheduledExecutorQuorumWriteTest { private static PartitionedClusterClients clients; @BeforeClass public static void setUp() { TestHazelcastFactory factory = new TestHazelcastFactory(); initTestEnvironment(new Config(), factory); clients = new PartitionedClusterClients(cluster, factory); } @AfterClass public static void tearDown() { if (clients != null) { clients.terminateAll(); } shutdownTestEnvironment(); } @Override protected IScheduledExecutorService exec(int index) { return scheduledExec(index, quorumType); } @Override protected IScheduledExecutorService exec(int index, String postfix) { return clients.client(index).getScheduledExecutorService(SCHEDULED_EXEC_NAME + quorumType.name() + postfix); } }
// This file is made available under Elastic License 2.0. // This file is based on code available under the Apache license here: // https://github.com/apache/incubator-doris/blob/master/fe/fe-core/src/main/java/org/apache/doris/analysis/SelectListItem.java // 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 com.starrocks.analysis; import com.google.common.base.Preconditions; public class SelectListItem implements ParseNode { private Expr expr; // for "[name.]*" private final TableName tblName; private final boolean isStar; private String alias; public SelectListItem(Expr expr, String alias) { super(); Preconditions.checkNotNull(expr); this.expr = expr; this.alias = alias; this.tblName = null; this.isStar = false; } public SelectListItem(TableName tblName) { super(); this.expr = null; this.tblName = tblName; this.isStar = true; } protected SelectListItem(SelectListItem other) { if (other.expr == null) { expr = null; } else { expr = other.expr.clone().reset(); } tblName = other.tblName; isStar = other.isStar; alias = other.alias; } @Override public SelectListItem clone() { return new SelectListItem(this); } // select list item corresponding to "[[db.]tbl.]*" public static SelectListItem createStarItem(TableName tblName) { return new SelectListItem(tblName); } public boolean isStar() { return isStar; } public TableName getTblName() { return tblName; } public Expr getExpr() { return expr; } public void setExpr(Expr expr) { this.expr = expr; } public String getAlias() { return alias; } public String toSql() { if (!isStar) { Preconditions.checkNotNull(expr); String aliasSql = null; if (alias != null) { aliasSql = "`" + alias + "`"; } return expr.toSql() + ((aliasSql == null) ? "" : " " + aliasSql); } else if (tblName != null) { return tblName.toString() + ".*"; } else { return "*"; } } public String toDigest() { if (!isStar) { Preconditions.checkNotNull(expr); String aliasSql = null; if (alias != null) { aliasSql = "`" + alias + "`"; } return expr.toDigest() + ((aliasSql == null) ? "" : " " + aliasSql); } else if (tblName != null) { return tblName.toString() + ".*"; } else { return "*"; } } /** * Return a column label for the select list item. */ public String toColumnLabel() { Preconditions.checkState(!isStar()); if (alias != null) { return alias; } // Abbreviate the toSql() for analytic exprs. if (expr instanceof AnalyticExpr) { AnalyticExpr analyticExpr = (AnalyticExpr) expr; return analyticExpr.getFnCall().toSql() + " OVER(...)"; } return expr.toColumnLabel(); } }
package vn.locdt.cart; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.openfeign.EnableFeignClients; @SpringBootApplication @EnableFeignClients @EnableDiscoveryClient @EnableAutoConfiguration public class CartServiceApplication { public static void main(String[] args) { SpringApplication.run(CartServiceApplication.class, args); } }
/* * Copyright (C) 2013 salesforce.com, 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 org.auraframework.def; import org.auraframework.Aura; import org.auraframework.throwable.quickfix.InvalidDefinitionException; public class ComponentDefTest extends BaseComponentDefTest<ComponentDef> { public ComponentDefTest(String name) { super(name, ComponentDef.class, "aura:component"); } /** * InvalidDefinitionException if we try to instantiate an abstract component with no providers. */ public void testAbstractNoProvider() throws Exception { try { ComponentDef cd = define(baseTag, "abstract='true'", ""); Aura.getInstanceService().getInstance(cd); fail("Should not be able to instantiate a component with no providers."); } catch (Exception e) { checkExceptionContains(e, InvalidDefinitionException.class, "cannot be instantiated directly"); } } }
package com.google.android.play.core.tasks; import java.util.concurrent.Executor; /* renamed from: com.google.android.play.core.tasks.f */ final class C2103f<ResultT> implements C2104g<ResultT> { /* renamed from: a */ private final Executor f1072a; /* access modifiers changed from: private */ /* renamed from: b */ public final Object f1073b = new Object(); /* access modifiers changed from: private */ /* renamed from: c */ public final OnSuccessListener<? super ResultT> f1074c; public C2103f(Executor executor, OnSuccessListener<? super ResultT> onSuccessListener) { this.f1072a = executor; this.f1074c = onSuccessListener; } /* renamed from: a */ public final void mo34389a(Task<ResultT> task) { if (task.isSuccessful()) { synchronized (this.f1073b) { if (this.f1074c != null) { this.f1072a.execute(new C2102e(this, task)); } } } } }
/* * Copyright (c) 2008-2018, Hazelcast, 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.hazelcast.map.impl.operation; import com.hazelcast.map.impl.MapEntries; import com.hazelcast.test.HazelcastParallelClassRunner; import com.hazelcast.test.HazelcastTestSupport; import com.hazelcast.test.annotation.ParallelTest; import com.hazelcast.test.annotation.QuickTest; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mockito.MockingDetails; import org.mockito.Mockito; import org.mockito.invocation.Invocation; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static java.lang.String.format; import static java.lang.reflect.Modifier.isAbstract; import static java.lang.reflect.Modifier.isPrivate; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; @RunWith(HazelcastParallelClassRunner.class) @Category({QuickTest.class, ParallelTest.class}) public class MapOperationProviderDelegatorTest extends HazelcastTestSupport { private MapOperationProvider operationProvider; private TestMapOperationProviderDelegator delegator; @Before public void setUp() { operationProvider = mock(MapOperationProvider.class); delegator = new TestMapOperationProviderDelegator(); } @Test public void testDelegator() throws Exception { Method[] methods = MapOperationProviderDelegator.class.getDeclaredMethods(); // invoke all methods of MapOperationProviderDelegator for (Method method : methods) { if (isAbstract(method.getModifiers()) || isPrivate(method.getModifiers())) { continue; } Object[] parameters = getParameters(method); try { method.invoke(delegator, parameters); } catch (Exception e) { System.err.println(format("Could not invoke method %s: %s", method.getName(), e.getMessage())); } } // get a list of all method invocations from Mockito List<String> methodsCalled = new ArrayList<String>(); MockingDetails mockingDetails = Mockito.mockingDetails(operationProvider); Collection<Invocation> invocations = mockingDetails.getInvocations(); for (Invocation invocation : invocations) { methodsCalled.add(invocation.getMethod().getName()); } // verify that all methods have been called on the delegated MapOperationProvider for (Method method : methods) { if (isAbstract(method.getModifiers()) || isPrivate(method.getModifiers())) { continue; } assertTrue(format("Method %s() should have been called", method.getName()), methodsCalled.contains(method.getName())); } } private Object[] getParameters(Method method) { Class<?>[] parameterTypes = method.getParameterTypes(); Object[] parameters = new Object[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { Class<?> parameterType = parameterTypes[i]; if (parameterType.isAssignableFrom(String.class)) { parameters[i] = "test"; } else if (parameterType.isAssignableFrom(Long.class) || parameterType.equals(long.class)) { parameters[i] = Long.MAX_VALUE; } else if (parameterType.isAssignableFrom(Integer.class) || parameterType.equals(int.class)) { parameters[i] = Integer.MAX_VALUE; } else if (parameterType.isAssignableFrom(Short.class) || parameterType.equals(short.class)) { parameters[i] = Short.MAX_VALUE; } else if (parameterType.isAssignableFrom(Byte.class) || parameterType.equals(byte.class)) { parameters[i] = Byte.MAX_VALUE; } else if (parameterType.isAssignableFrom(Boolean.class) || parameterType.equals(boolean.class)) { parameters[i] = true; } else if (parameterType.equals(long[].class)) { parameters[i] = new long[0]; } else if (parameterType.equals(int[].class)) { parameters[i] = new int[0]; } else if (parameterType.equals(short[].class)) { parameters[i] = new short[0]; } else if (parameterType.equals(byte[].class)) { parameters[i] = new byte[0]; } else if (parameterType.equals(boolean[].class)) { parameters[i] = new boolean[0]; } else if (parameterType.isAssignableFrom(MapEntries.class)) { parameters[i] = new MapEntries(); } else if (parameterType.equals(MapEntries[].class)) { parameters[i] = new MapEntries[0]; } else if (parameterType.equals(List[].class)) { parameters[i] = new List[0]; } else { try { parameters[i] = mock(parameterType); } catch (Exception e) { throw new IllegalStateException(format( "Cannot mock parameter of type %s of MapOperationProviderDelegator.%s() at position %d: %s", parameterType.getSimpleName(), method.getName(), i, e.getMessage())); } } } return parameters; } private class TestMapOperationProviderDelegator extends MapOperationProviderDelegator { @Override MapOperationProvider getDelegate() { return operationProvider; } } }
package com.kasukusakura.kimiroyli.test; import com.kasukusakura.kimiroyli.api.perm.PermissionContext; import com.kasukusakura.kimiroyli.api.perm.StandardPermissions; import org.junit.jupiter.api.Assertions; import sun.misc.Unsafe; import java.io.File; import java.io.IOException; import java.io.UncheckedIOException; import java.lang.invoke.MethodHandles; import java.lang.reflect.InaccessibleObjectException; import java.lang.reflect.Proxy; import java.net.*; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.security.PrivilegedAction; import java.security.PrivilegedExceptionAction; import java.util.List; import java.util.Random; import java.util.concurrent.Executors; @SuppressWarnings({"all"}) public class Testing { private static <T extends Throwable> void sneaklyThrow(Throwable throwable) throws T { throw (T) throwable; } private static <T> PrivilegedAction<T> ew(PrivilegedExceptionAction<T> action) { return () -> { try { return action.run(); } catch (RuntimeException | Error e) { throw e; } catch (Throwable throwable) { sneaklyThrow(throwable); throw new RuntimeException(throwable); } }; } public static void main(String[] args) throws Throwable { System.out.println("[TESTING] Executed"); var testingModule = Testing.class.getModule(); System.setErr(System.out); /*var allStackTraces = Thread.getAllStackTraces(); for (var thread : allStackTraces.keySet()) { System.out.println(thread); }*/ Testing.class.getDeclaredMethod("a").setAccessible(true); PermissionContext.permit(Testing.class.getModule(), StandardPermissions.PERMISSION_MANAGER); PermissionContext.permit(Testing.class.getModule(), StandardPermissions.ROOT); PermissionContext.currentContext().runWith(() -> { System.out.println(PermissionContext.currentContext()); return null; }); PermissionContext.currentContext().runAs(List.of(), ew(() -> { Assertions.assertThrowsExactly( UnsatisfiedLinkError.class, () -> System.load(new File("A").getAbsolutePath()), "Permission denied: Missing permission `NATIVE_LIBRARY_LINK`" ); Assertions.assertThrowsExactly( UnsatisfiedLinkError.class, () -> System.loadLibrary("A"), "Permission denied: Missing permission `NATIVE_LIBRARY_LINK`" ); Assertions.assertThrowsExactly( IllegalAccessException.class, () -> MethodHandles.privateLookupIn(Unsafe.class, MethodHandles.lookup()), "class com.kasukusakura.kimiroyli.test.Testing cannot access class sun.misc.Unsafe because unsafe access was limited." ); Assertions.assertThrowsExactly( InaccessibleObjectException.class, () -> Unsafe.class.getDeclaredField("theUnsafe").setAccessible(true), "class com.kasukusakura.kimiroyli.test.Testing cannot access private static final sun.misc.Unsafe sun.misc.Unsafe.theUnsafe because unsafe access was limited." ); Assertions.assertFalse( Unsafe.class.getDeclaredField("theUnsafe").trySetAccessible() ); Assertions.assertThrowsExactly( InaccessibleObjectException.class, () -> Proxy.getProxyClass(Testing.class.getClassLoader(), Class.forName("jdk.internal.access.JavaLangAccess")), "class access check failed: class com.kasukusakura.kimiroyli.test.Testing (in " + testingModule + ") cannot access interface jdk.internal.access.JavaLangAccess (in module java.base) because module java.base does not export jdk.internal.access to " + testingModule ); Assertions.assertThrowsExactly( SecurityException.class, () -> Runtime.getRuntime().exit(9), "Permission denied: Missing permission `SHUTDOWN`" ); Assertions.assertThrowsExactly( SecurityException.class, () -> Runtime.getRuntime().halt(9), "Permission denied: Missing permission `SHUTDOWN`" ); Assertions.assertThrowsExactly( SecurityException.class, () -> System.exit(9), "Permission denied: Missing permission `SHUTDOWN`" ); return null; })); Unsafe.class.getDeclaredField("theUnsafe").setAccessible(true); MethodHandles.privateLookupIn(Unsafe.class, MethodHandles.lookup()); { // Network PermissionContext.currentContext().runAs(List.of(), ew(() -> { Assertions.assertThrowsExactly( ConnectException.class, () -> new Socket("::1", 9154), "Can't connect /[0:0:0:0:0:0:0:1]:9154 because current context don't have network permission" ); Assertions.assertThrowsExactly( ConnectException.class, () -> new URL("http://[::1]:80").openConnection().connect(), "Can't connect /[0:0:0:0:0:0:0:1]:80 because current context don't have network permission" ); Assertions.assertThrowsExactly( BindException.class, () -> new DatagramSocket(9484), "Can't bind 0.0.0.0/0.0.0.0:9484 because current context don't have network permission" ); System.out.println(PermissionContext.myPermissions()); Assertions.assertThrowsExactly( UncheckedIOException.class, () -> PermissionContext.myPermissions().runAsCurrent(ew(DatagramSocket::new)).connect( InetAddress.getByAddress("localhost", new byte[]{(byte) 127, 0, 0, 1}), 1578 ), "java.net.ConnectException: Can't connect localhost/127.0.0.1:1578 because current context don't have network permission" ); return null; })); var exec = Executors.newFixedThreadPool(1); try { var httpC = HttpClient.newBuilder() .executor(exec) .build(); Assertions.assertThrows( IOException.class, () -> httpC.send( HttpRequest.newBuilder() .GET() .uri(URI.create("http://[::1]")) .build(), HttpResponse.BodyHandlers.discarding() ), "Can't connect /[0:0:0:0:0:0:0:1]:80 because current context don't have network permission" ); } finally { exec.shutdown(); } } Runtime.getRuntime().exit(0); } public static void a() { var a = new Random().nextBoolean(); if (a) { System.out.println("true"); } else { System.out.println("false"); } } }
/* * Copyright (c) 2004, PostgreSQL Global Development Group * See the LICENSE file in the project root for more information. */ // Copyright (c) 2004, Open Cloud Limited. package org.postgresql.core; import org.postgresql.PGProperty; import org.postgresql.core.v3.ConnectionFactoryImpl; import org.postgresql.util.GT; import org.postgresql.util.HostSpec; import org.postgresql.util.PSQLException; import org.postgresql.util.PSQLState; import java.io.IOException; import java.sql.SQLException; import java.util.Properties; import org.postgresql.log.Logger; import org.postgresql.log.Log; /** * Handles protocol-specific connection setup. * * @author Oliver Jowett (oliver@opencloud.com) */ public abstract class ConnectionFactory { private static Log LOGGER = Logger.getLogger(ConnectionFactory.class.getName()); /** * <p>Establishes and initializes a new connection.</p> * * <p>If the "protocolVersion" property is specified, only that protocol version is tried. Otherwise, * all protocols are tried in order, falling back to older protocols as necessary.</p> * * <p>Currently, protocol versions 3 (7.4+) is supported.</p> * * @param hostSpecs at least one host and port to connect to; multiple elements for round-robin * failover * @param user the username to authenticate with; may not be null. * @param database the database on the server to connect to; may not be null. * @param info extra properties controlling the connection; notably, "password" if present * supplies the password to authenticate with. * @return the new, initialized, connection * @throws SQLException if the connection could not be established. */ public static QueryExecutor openConnection(HostSpec[] hostSpecs, String user, String database, Properties info) throws SQLException { String protoName = PGProperty.PROTOCOL_VERSION.get(info); if (protoName == null || protoName.isEmpty() || "3".equals(protoName)) { ConnectionFactory connectionFactory = new ConnectionFactoryImpl(); QueryExecutor queryExecutor = connectionFactory.openConnectionImpl( hostSpecs, user, database, info); if (queryExecutor != null) { return queryExecutor; } } throw new PSQLException( GT.tr("A connection could not be made using the requested protocol {0}.", protoName), PSQLState.CONNECTION_UNABLE_TO_CONNECT); } /** * Implementation of {@link #openConnection} for a particular protocol version. Implemented by * subclasses of {@link ConnectionFactory}. * * @param hostSpecs at least one host and port to connect to; multiple elements for round-robin * failover * @param user the username to authenticate with; may not be null. * @param database the database on the server to connect to; may not be null. * @param info extra properties controlling the connection; notably, "password" if present * supplies the password to authenticate with. * @return the new, initialized, connection, or <code>null</code> if this protocol version is not * supported by the server. * @throws SQLException if the connection could not be established for a reason other than * protocol version incompatibility. */ public abstract QueryExecutor openConnectionImpl(HostSpec[] hostSpecs, String user, String database, Properties info) throws SQLException; /** * Safely close the given stream. * * @param newStream The stream to close. */ protected void closeStream(PGStream newStream) { if (newStream != null) { try { newStream.close(); } catch (IOException e) { LOGGER.trace("Catch IOException on close:", e); } } } }
package core.framework.internal.web.sys; import core.framework.api.json.Property; import java.util.List; /** * @author neo */ public class ListJobResponse { @Property(name = "jobs") public List<JobView> jobs; public static class JobView { @Property(name = "name") public String name; @Property(name = "jobClass") public String jobClass; @Property(name = "trigger") public String trigger; } }
package i5.las2peer.services.ocd.adapters.graphOutput; import i5.las2peer.services.ocd.adapters.AdapterException; import i5.las2peer.services.ocd.graphs.CustomGraph; import java.io.ByteArrayOutputStream; import java.io.IOException; import y.base.Edge; import y.base.EdgeCursor; import y.base.EdgeMap; import y.base.Node; import y.base.NodeCursor; import y.base.NodeMap; import y.io.GraphMLIOHandler; import y.io.graphml.GraphMLHandler; import y.io.graphml.KeyScope; import y.io.graphml.KeyType; /** * A graph output adapter for GraphML format, based on the GraphMLIOHandler of the yFiles library.. * Node names will be written into a CDATA Section in a "name" element. * Edge weights will be written into a "weight" element. * @author Sebastian * */ public class GraphMlGraphOutputAdapter extends AbstractGraphOutputAdapter { @Override public void writeGraph(CustomGraph graph) throws AdapterException { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); NodeMap nodeNames = graph.createNodeMap(); NodeCursor nodes = graph.nodes(); Node node; while(nodes.ok()) { node = nodes.node(); nodeNames.set(node, graph.getNodeName(node)); nodes.next(); } EdgeMap edgeWeights = graph.createEdgeMap(); EdgeCursor edges = graph.edges(); Edge edge; while(edges.ok()) { edge = edges.edge(); edgeWeights.set(edge, graph.getEdgeWeight(edge)); edges.next(); } GraphMLIOHandler ioh = new GraphMLIOHandler(); GraphMLHandler core = ioh.getGraphMLHandler(); core.addOutputDataProvider("name", nodeNames, KeyScope.NODE, KeyType.STRING); core.addOutputDataProvider("weight", edgeWeights, KeyScope.EDGE, KeyType.DOUBLE); try { ioh.write(graph, outStream); String outString = outStream.toString(); writer.write(outString); } catch(IOException e) { throw new AdapterException(e); } finally { try { outStream.close(); } catch(IOException e) { } try { writer.close(); } catch(IOException e) { } graph.disposeNodeMap(nodeNames); graph.disposeEdgeMap(edgeWeights); } } }
package org.hongxi.whatsmars.base.thread.base; public class JoinTest { public static void main(String[] args) { MyThread2 t = new MyThread2("black horse"); t.start(); try { t.join(); } catch (InterruptedException e) {} for (int i = 0; i < 10; i++) { System.out.println("I am Main Thread"); } } } class MyThread2 extends Thread { public MyThread2(String s) { super(s); } public void run() { for (int i = 0; i < 10; i++) { System.out.println("I am " + getName()); try { sleep(1000); } catch (InterruptedException e) { return; } } } }
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * 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.alibaba.csp.sentinel.adapter.zuul.fallback; import com.alibaba.csp.sentinel.slots.block.flow.FlowException; import org.junit.Assert; import org.junit.Test; /** * @author tiger */ public class ZuulBlockFallbackProviderTest { private String ALL_ROUTE = "*"; @Test public void testGetNullRoute() throws Exception { ZuulBlockFallbackProvider fallbackProvider = ZuulBlockFallbackManager.getFallbackProvider(null); Assert.assertEquals(fallbackProvider.getRoute(), ALL_ROUTE); } @Test public void testGetDefaultRoute() throws Exception { ZuulBlockFallbackProvider fallbackProvider = ZuulBlockFallbackManager.getFallbackProvider(ALL_ROUTE); Assert.assertEquals(fallbackProvider.getRoute(), ALL_ROUTE); } @Test public void testGetNotInCacheRoute() throws Exception { ZuulBlockFallbackProvider fallbackProvider = ZuulBlockFallbackManager.getFallbackProvider("/not/in"); Assert.assertEquals(fallbackProvider.getRoute(), ALL_ROUTE); } @Test public void testFlowControlFallbackResponse() throws Exception { ZuulBlockFallbackProvider fallbackProvider = ZuulBlockFallbackManager.getFallbackProvider(ALL_ROUTE); BlockResponse clientHttpResponse = fallbackProvider.fallbackResponse(ALL_ROUTE, new FlowException("flow exception")); Assert.assertEquals(clientHttpResponse.getCode(), 429); } @Test public void testRuntimeExceptionFallbackResponse() throws Exception { ZuulBlockFallbackProvider fallbackProvider = ZuulBlockFallbackManager.getFallbackProvider(ALL_ROUTE); BlockResponse clientHttpResponse = fallbackProvider.fallbackResponse(ALL_ROUTE, new RuntimeException()); Assert.assertEquals(clientHttpResponse.getCode(), 500); } }
package terrails.netherutils.blocks.pedestal; import net.minecraft.block.Block; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import terrails.netherutils.Constants; import terrails.netherutils.NetherUtils; import java.util.Objects; public class ItemBlockPedestal extends ItemBlock { public ItemBlockPedestal(Block block) { super(block); setRegistryName(Objects.requireNonNull(block.getRegistryName())); setHasSubtypes(true); setMaxDamage(0); } @Override public int getMetadata(int damage) { return damage; } @Override public String getUnlocalizedName(ItemStack stack) { return "tile." + NetherUtils.MOD_ID + ".pedestal_" + BlockPedestal.Type.byMetadata(stack.getMetadata()); } }
/* * 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.sis.internal.referencing.provider; import java.util.logging.Level; import java.util.logging.LogRecord; import java.io.EOFException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.file.Path; import java.nio.file.NoSuchFileException; import java.nio.channels.ReadableByteChannel; import org.opengis.util.FactoryException; import org.apache.sis.util.resources.Errors; import org.apache.sis.util.logging.Logging; import org.apache.sis.internal.system.Loggers; import org.apache.sis.internal.referencing.Resources; import org.apache.sis.referencing.factory.FactoryDataException; import org.apache.sis.referencing.factory.MissingFactoryResourceException; /** * Base class of datum shift grid loaders. * * @author Martin Desruisseaux (Geomatys) * @version 0.7 * @since 0.7 * @module */ class DatumShiftGridLoader { /** * Conversion factor from degrees to seconds. */ static final double DEGREES_TO_SECONDS = 3600; /** * Possible precision for offset values in seconds of angle. This value is used only as a hint * when attempting to compress the grid in arrays of {@code short} values. It does not hurt if * this value is wrong, as it will only cause the grid to not be compressed. * * <p>Some interesting values:</p> * <ul> * <li>1E-4 is about 3 millimetres on Earth.</li> * <li>1E-6 matches the precision found in ASCII outputs of NADCON grids.</li> * <li>1E-7 is about 1 ULP of 1 second of angle.</li> * </ul> * * We use a value of 1E-4 because more accurate values tend to cause overflows in the compression algorithm, * in which case the compression fails. With a more reasonable value, we have better chances of success. */ static final double SECOND_PRECISION = 1E-4; /** * The file to load, used for parameter declaration and if we have errors to report. */ final Path file; /** * The channel opened on the file. */ private final ReadableByteChannel channel; /** * The buffer to use for transferring data from the channel. */ final ByteBuffer buffer; /** * Creates a new loader for the given channel and an existing buffer. * * @param channel where to read data from. * @param buffer the buffer to use. * @param file path to the longitude or latitude difference file. Used for parameter declaration and error reporting. */ DatumShiftGridLoader(final ReadableByteChannel channel, final ByteBuffer buffer, final Path file) throws IOException { this.file = file; this.buffer = buffer; this.channel = channel; channel.read(buffer); buffer.flip(); } /** * Makes sure that the buffer contains at least <var>n</var> remaining bytes. * It is caller's responsibility to ensure that the given number of bytes is * not greater than the {@linkplain ByteBuffer#capacity() buffer capacity}. * * @param n the minimal number of bytes needed in the {@linkplain #buffer}. * @throws EOFException if the channel has reached the end of stream. * @throws IOException if an other kind of error occurred while reading. */ final void ensureBufferContains(int n) throws IOException { assert n >= 0 && n <= buffer.capacity() : n; n -= buffer.remaining(); if (n > 0) { buffer.compact(); do { final int c = channel.read(buffer); if (c <= 0) { if (c != 0) { throw new EOFException(Errors.format(Errors.Keys.UnexpectedEndOfFile_1, file)); } else { throw new IOException(Errors.format(Errors.Keys.CanNotRead_1, file)); } } n -= c; } while (n > 0); buffer.flip(); } } /** * Skips exactly <var>n</var> bytes. */ final void skip(int n) throws IOException { int p; while ((p = buffer.position() + n) > buffer.limit()) { n -= buffer.remaining(); buffer.clear(); ensureBufferContains(Math.min(n, buffer.capacity())); } buffer.position(p); } /** * Logs a message about a grid which is about to be loaded. * * @param caller the provider to logs as the source class. * the source method will be set to {@code "createMathTransform"}. * @param file the grid file, as a {@link String} or a {@link Path}. */ static void log(final Class<?> caller, final Object file) { final LogRecord record = Resources.forLocale(null).getLogRecord(Level.FINE, Resources.Keys.LoadingDatumShiftFile_1, file); record.setLoggerName(Loggers.COORDINATE_OPERATION); Logging.log(caller, "createMathTransform", record); } /** * Creates the exception to thrown when the provider failed to load the grid file. * * @param format the format name (e.g. "NTv2" or "NADCON"). * @param file the grid file that the subclass tried to load. * @param cause the cause of the failure to load the grid file. */ static FactoryException canNotLoad(final String format, final Path file, final Exception cause) { final String message = Errors.format(Errors.Keys.CanNotParseFile_2, format, file); if (cause instanceof NoSuchFileException) { return new MissingFactoryResourceException(message, cause); } else { return new FactoryDataException(message, cause); } } }
package org.apache.lucene.search; /* * 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. */ import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.MockAnalyzer; import org.apache.lucene.analysis.MockTokenFilter; import org.apache.lucene.analysis.MockTokenizer; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriterConfig.OpenMode; import org.apache.lucene.index.RandomIndexWriter; import org.apache.lucene.index.Term; import org.apache.lucene.search.similarities.DefaultSimilarity; import org.apache.lucene.store.Directory; import org.apache.lucene.util.LuceneTestCase; import org.apache.lucene.util.TestUtil; import org.junit.AfterClass; import org.junit.BeforeClass; /** * Tests {@link PhraseQuery}. * * @see TestPositionIncrement */ public class TestPhraseQuery extends LuceneTestCase { /** threshold for comparing floats */ public static final float SCORE_COMP_THRESH = 1e-6f; private static IndexSearcher searcher; private static IndexReader reader; private PhraseQuery query; private static Directory directory; @BeforeClass public static void beforeClass() throws Exception { directory = newDirectory(); Analyzer analyzer = new Analyzer() { @Override public TokenStreamComponents createComponents(String fieldName) { return new TokenStreamComponents(new MockTokenizer(MockTokenizer.WHITESPACE, false)); } @Override public int getPositionIncrementGap(String fieldName) { return 100; } }; RandomIndexWriter writer = new RandomIndexWriter(random(), directory, analyzer); Document doc = new Document(); doc.add(newTextField("field", "one two three four five", Field.Store.YES)); doc.add(newTextField("repeated", "this is a repeated field - first part", Field.Store.YES)); Field repeatedField = newTextField("repeated", "second part of a repeated field", Field.Store.YES); doc.add(repeatedField); doc.add(newTextField("palindrome", "one two three two one", Field.Store.YES)); writer.addDocument(doc); doc = new Document(); doc.add(newTextField("nonexist", "phrase exist notexist exist found", Field.Store.YES)); writer.addDocument(doc); doc = new Document(); doc.add(newTextField("nonexist", "phrase exist notexist exist found", Field.Store.YES)); writer.addDocument(doc); reader = writer.getReader(); writer.close(); searcher = newSearcher(reader); } @Override public void setUp() throws Exception { super.setUp(); query = new PhraseQuery(); } @AfterClass public static void afterClass() throws Exception { searcher = null; reader.close(); reader = null; directory.close(); directory = null; } public void testNotCloseEnough() throws Exception { query.setSlop(2); query.add(new Term("field", "one")); query.add(new Term("field", "five")); ScoreDoc[] hits = searcher.search(query, 1000).scoreDocs; assertEquals(0, hits.length); QueryUtils.check(random(), query,searcher); } public void testBarelyCloseEnough() throws Exception { query.setSlop(3); query.add(new Term("field", "one")); query.add(new Term("field", "five")); ScoreDoc[] hits = searcher.search(query, 1000).scoreDocs; assertEquals(1, hits.length); QueryUtils.check(random(), query,searcher); } /** * Ensures slop of 0 works for exact matches, but not reversed */ public void testExact() throws Exception { // slop is zero by default query.add(new Term("field", "four")); query.add(new Term("field", "five")); ScoreDoc[] hits = searcher.search(query, 1000).scoreDocs; assertEquals("exact match", 1, hits.length); QueryUtils.check(random(), query,searcher); query = new PhraseQuery(); query.add(new Term("field", "two")); query.add(new Term("field", "one")); hits = searcher.search(query, 1000).scoreDocs; assertEquals("reverse not exact", 0, hits.length); QueryUtils.check(random(), query,searcher); } public void testSlop1() throws Exception { // Ensures slop of 1 works with terms in order. query.setSlop(1); query.add(new Term("field", "one")); query.add(new Term("field", "two")); ScoreDoc[] hits = searcher.search(query, 1000).scoreDocs; assertEquals("in order", 1, hits.length); QueryUtils.check(random(), query,searcher); // Ensures slop of 1 does not work for phrases out of order; // must be at least 2. query = new PhraseQuery(); query.setSlop(1); query.add(new Term("field", "two")); query.add(new Term("field", "one")); hits = searcher.search(query, 1000).scoreDocs; assertEquals("reversed, slop not 2 or more", 0, hits.length); QueryUtils.check(random(), query,searcher); } /** * As long as slop is at least 2, terms can be reversed */ public void testOrderDoesntMatter() throws Exception { query.setSlop(2); // must be at least two for reverse order match query.add(new Term("field", "two")); query.add(new Term("field", "one")); ScoreDoc[] hits = searcher.search(query, 1000).scoreDocs; assertEquals("just sloppy enough", 1, hits.length); QueryUtils.check(random(), query,searcher); query = new PhraseQuery(); query.setSlop(2); query.add(new Term("field", "three")); query.add(new Term("field", "one")); hits = searcher.search(query, 1000).scoreDocs; assertEquals("not sloppy enough", 0, hits.length); QueryUtils.check(random(), query,searcher); } /** * slop is the total number of positional moves allowed * to line up a phrase */ public void testMultipleTerms() throws Exception { query.setSlop(2); query.add(new Term("field", "one")); query.add(new Term("field", "three")); query.add(new Term("field", "five")); ScoreDoc[] hits = searcher.search(query, 1000).scoreDocs; assertEquals("two total moves", 1, hits.length); QueryUtils.check(random(), query,searcher); query = new PhraseQuery(); query.setSlop(5); // it takes six moves to match this phrase query.add(new Term("field", "five")); query.add(new Term("field", "three")); query.add(new Term("field", "one")); hits = searcher.search(query, 1000).scoreDocs; assertEquals("slop of 5 not close enough", 0, hits.length); QueryUtils.check(random(), query,searcher); query.setSlop(6); hits = searcher.search(query, 1000).scoreDocs; assertEquals("slop of 6 just right", 1, hits.length); QueryUtils.check(random(), query,searcher); } public void testPhraseQueryWithStopAnalyzer() throws Exception { Directory directory = newDirectory(); Analyzer stopAnalyzer = new MockAnalyzer(random(), MockTokenizer.SIMPLE, true, MockTokenFilter.ENGLISH_STOPSET); RandomIndexWriter writer = new RandomIndexWriter(random(), directory, newIndexWriterConfig(stopAnalyzer)); Document doc = new Document(); doc.add(newTextField("field", "the stop words are here", Field.Store.YES)); writer.addDocument(doc); IndexReader reader = writer.getReader(); writer.close(); IndexSearcher searcher = newSearcher(reader); // valid exact phrase query PhraseQuery query = new PhraseQuery(); query.add(new Term("field","stop")); query.add(new Term("field","words")); ScoreDoc[] hits = searcher.search(query, 1000).scoreDocs; assertEquals(1, hits.length); QueryUtils.check(random(), query,searcher); reader.close(); directory.close(); } public void testPhraseQueryInConjunctionScorer() throws Exception { Directory directory = newDirectory(); RandomIndexWriter writer = new RandomIndexWriter(random(), directory); Document doc = new Document(); doc.add(newTextField("source", "marketing info", Field.Store.YES)); writer.addDocument(doc); doc = new Document(); doc.add(newTextField("contents", "foobar", Field.Store.YES)); doc.add(newTextField("source", "marketing info", Field.Store.YES)); writer.addDocument(doc); IndexReader reader = writer.getReader(); writer.close(); IndexSearcher searcher = newSearcher(reader); PhraseQuery phraseQuery = new PhraseQuery(); phraseQuery.add(new Term("source", "marketing")); phraseQuery.add(new Term("source", "info")); ScoreDoc[] hits = searcher.search(phraseQuery, 1000).scoreDocs; assertEquals(2, hits.length); QueryUtils.check(random(), phraseQuery,searcher); TermQuery termQuery = new TermQuery(new Term("contents","foobar")); BooleanQuery booleanQuery = new BooleanQuery(); booleanQuery.add(termQuery, BooleanClause.Occur.MUST); booleanQuery.add(phraseQuery, BooleanClause.Occur.MUST); hits = searcher.search(booleanQuery, 1000).scoreDocs; assertEquals(1, hits.length); QueryUtils.check(random(), termQuery,searcher); reader.close(); writer = new RandomIndexWriter(random(), directory, newIndexWriterConfig(new MockAnalyzer(random())).setOpenMode(OpenMode.CREATE)); doc = new Document(); doc.add(newTextField("contents", "map entry woo", Field.Store.YES)); writer.addDocument(doc); doc = new Document(); doc.add(newTextField("contents", "woo map entry", Field.Store.YES)); writer.addDocument(doc); doc = new Document(); doc.add(newTextField("contents", "map foobarword entry woo", Field.Store.YES)); writer.addDocument(doc); reader = writer.getReader(); writer.close(); searcher = newSearcher(reader); termQuery = new TermQuery(new Term("contents","woo")); phraseQuery = new PhraseQuery(); phraseQuery.add(new Term("contents","map")); phraseQuery.add(new Term("contents","entry")); hits = searcher.search(termQuery, 1000).scoreDocs; assertEquals(3, hits.length); hits = searcher.search(phraseQuery, 1000).scoreDocs; assertEquals(2, hits.length); booleanQuery = new BooleanQuery(); booleanQuery.add(termQuery, BooleanClause.Occur.MUST); booleanQuery.add(phraseQuery, BooleanClause.Occur.MUST); hits = searcher.search(booleanQuery, 1000).scoreDocs; assertEquals(2, hits.length); booleanQuery = new BooleanQuery(); booleanQuery.add(phraseQuery, BooleanClause.Occur.MUST); booleanQuery.add(termQuery, BooleanClause.Occur.MUST); hits = searcher.search(booleanQuery, 1000).scoreDocs; assertEquals(2, hits.length); QueryUtils.check(random(), booleanQuery,searcher); reader.close(); directory.close(); } public void testSlopScoring() throws IOException { Directory directory = newDirectory(); RandomIndexWriter writer = new RandomIndexWriter(random(), directory, newIndexWriterConfig(new MockAnalyzer(random())) .setMergePolicy(newLogMergePolicy()) .setSimilarity(new DefaultSimilarity())); Document doc = new Document(); doc.add(newTextField("field", "foo firstname lastname foo", Field.Store.YES)); writer.addDocument(doc); Document doc2 = new Document(); doc2.add(newTextField("field", "foo firstname zzz lastname foo", Field.Store.YES)); writer.addDocument(doc2); Document doc3 = new Document(); doc3.add(newTextField("field", "foo firstname zzz yyy lastname foo", Field.Store.YES)); writer.addDocument(doc3); IndexReader reader = writer.getReader(); writer.close(); IndexSearcher searcher = newSearcher(reader); searcher.setSimilarity(new DefaultSimilarity()); PhraseQuery query = new PhraseQuery(); query.add(new Term("field", "firstname")); query.add(new Term("field", "lastname")); query.setSlop(Integer.MAX_VALUE); ScoreDoc[] hits = searcher.search(query, 1000).scoreDocs; assertEquals(3, hits.length); // Make sure that those matches where the terms appear closer to // each other get a higher score: assertEquals(0.71, hits[0].score, 0.01); assertEquals(0, hits[0].doc); assertEquals(0.44, hits[1].score, 0.01); assertEquals(1, hits[1].doc); assertEquals(0.31, hits[2].score, 0.01); assertEquals(2, hits[2].doc); QueryUtils.check(random(), query,searcher); reader.close(); directory.close(); } public void testToString() throws Exception { PhraseQuery q = new PhraseQuery(); assertEquals("\"\"", q.toString()); q.add(new Term("field", "hi"), 1); assertEquals("field:\"? hi\"", q.toString()); q = new PhraseQuery(); // Query "this hi this is a test is" q.add(new Term("field", "hi"), 1); q.add(new Term("field", "test"), 5); assertEquals("field:\"? hi ? ? ? test\"", q.toString()); q = new PhraseQuery(); q.add(new Term("field", "hi"), 1); q.add(new Term("field", "hello"), 1); q.add(new Term("field", "test"), 5); assertEquals("field:\"? hi|hello ? ? ? test\"", q.toString()); q.setSlop(5); assertEquals("field:\"? hi|hello ? ? ? test\"~5", q.toString()); q.setBoost(2); assertEquals("field:\"? hi|hello ? ? ? test\"~5^2.0", q.toString()); } public void testWrappedPhrase() throws IOException { query.add(new Term("repeated", "first")); query.add(new Term("repeated", "part")); query.add(new Term("repeated", "second")); query.add(new Term("repeated", "part")); query.setSlop(100); ScoreDoc[] hits = searcher.search(query, 1000).scoreDocs; assertEquals("slop of 100 just right", 1, hits.length); QueryUtils.check(random(), query,searcher); query.setSlop(99); hits = searcher.search(query, 1000).scoreDocs; assertEquals("slop of 99 not enough", 0, hits.length); QueryUtils.check(random(), query,searcher); } // work on two docs like this: "phrase exist notexist exist found" public void testNonExistingPhrase() throws IOException { // phrase without repetitions that exists in 2 docs query.add(new Term("nonexist", "phrase")); query.add(new Term("nonexist", "notexist")); query.add(new Term("nonexist", "found")); query.setSlop(2); // would be found this way ScoreDoc[] hits = searcher.search(query, 1000).scoreDocs; assertEquals("phrase without repetitions exists in 2 docs", 2, hits.length); QueryUtils.check(random(), query,searcher); // phrase with repetitions that exists in 2 docs query = new PhraseQuery(); query.add(new Term("nonexist", "phrase")); query.add(new Term("nonexist", "exist")); query.add(new Term("nonexist", "exist")); query.setSlop(1); // would be found hits = searcher.search(query, 1000).scoreDocs; assertEquals("phrase with repetitions exists in two docs", 2, hits.length); QueryUtils.check(random(), query,searcher); // phrase I with repetitions that does not exist in any doc query = new PhraseQuery(); query.add(new Term("nonexist", "phrase")); query.add(new Term("nonexist", "notexist")); query.add(new Term("nonexist", "phrase")); query.setSlop(1000); // would not be found no matter how high the slop is hits = searcher.search(query, 1000).scoreDocs; assertEquals("nonexisting phrase with repetitions does not exist in any doc", 0, hits.length); QueryUtils.check(random(), query,searcher); // phrase II with repetitions that does not exist in any doc query = new PhraseQuery(); query.add(new Term("nonexist", "phrase")); query.add(new Term("nonexist", "exist")); query.add(new Term("nonexist", "exist")); query.add(new Term("nonexist", "exist")); query.setSlop(1000); // would not be found no matter how high the slop is hits = searcher.search(query, 1000).scoreDocs; assertEquals("nonexisting phrase with repetitions does not exist in any doc", 0, hits.length); QueryUtils.check(random(), query,searcher); } /** * Working on a 2 fields like this: * Field("field", "one two three four five") * Field("palindrome", "one two three two one") * Phrase of size 2 occuriong twice, once in order and once in reverse, * because doc is a palyndrome, is counted twice. * Also, in this case order in query does not matter. * Also, when an exact match is found, both sloppy scorer and exact scorer scores the same. */ public void testPalyndrome2() throws Exception { // search on non palyndrome, find phrase with no slop, using exact phrase scorer query.setSlop(0); // to use exact phrase scorer query.add(new Term("field", "two")); query.add(new Term("field", "three")); ScoreDoc[] hits = searcher.search(query, 1000).scoreDocs; assertEquals("phrase found with exact phrase scorer", 1, hits.length); float score0 = hits[0].score; //System.out.println("(exact) field: two three: "+score0); QueryUtils.check(random(), query,searcher); // search on non palyndrome, find phrase with slop 2, though no slop required here. query.setSlop(2); // to use sloppy scorer hits = searcher.search(query, 1000).scoreDocs; assertEquals("just sloppy enough", 1, hits.length); float score1 = hits[0].score; //System.out.println("(sloppy) field: two three: "+score1); assertEquals("exact scorer and sloppy scorer score the same when slop does not matter",score0, score1, SCORE_COMP_THRESH); QueryUtils.check(random(), query,searcher); // search ordered in palyndrome, find it twice query = new PhraseQuery(); query.setSlop(2); // must be at least two for both ordered and reversed to match query.add(new Term("palindrome", "two")); query.add(new Term("palindrome", "three")); hits = searcher.search(query, 1000).scoreDocs; assertEquals("just sloppy enough", 1, hits.length); //float score2 = hits[0].score; //System.out.println("palindrome: two three: "+score2); QueryUtils.check(random(), query,searcher); //commented out for sloppy-phrase efficiency (issue 736) - see SloppyPhraseScorer.phraseFreq(). //assertTrue("ordered scores higher in palindrome",score1+SCORE_COMP_THRESH<score2); // search reveresed in palyndrome, find it twice query = new PhraseQuery(); query.setSlop(2); // must be at least two for both ordered and reversed to match query.add(new Term("palindrome", "three")); query.add(new Term("palindrome", "two")); hits = searcher.search(query, 1000).scoreDocs; assertEquals("just sloppy enough", 1, hits.length); //float score3 = hits[0].score; //System.out.println("palindrome: three two: "+score3); QueryUtils.check(random(), query,searcher); //commented out for sloppy-phrase efficiency (issue 736) - see SloppyPhraseScorer.phraseFreq(). //assertTrue("reversed scores higher in palindrome",score1+SCORE_COMP_THRESH<score3); //assertEquals("ordered or reversed does not matter",score2, score3, SCORE_COMP_THRESH); } /** * Working on a 2 fields like this: * Field("field", "one two three four five") * Field("palindrome", "one two three two one") * Phrase of size 3 occuriong twice, once in order and once in reverse, * because doc is a palyndrome, is counted twice. * Also, in this case order in query does not matter. * Also, when an exact match is found, both sloppy scorer and exact scorer scores the same. */ public void testPalyndrome3() throws Exception { // search on non palyndrome, find phrase with no slop, using exact phrase scorer query.setSlop(0); // to use exact phrase scorer query.add(new Term("field", "one")); query.add(new Term("field", "two")); query.add(new Term("field", "three")); ScoreDoc[] hits = searcher.search(query, 1000).scoreDocs; assertEquals("phrase found with exact phrase scorer", 1, hits.length); float score0 = hits[0].score; //System.out.println("(exact) field: one two three: "+score0); QueryUtils.check(random(), query,searcher); // just make sure no exc: searcher.explain(query, 0); // search on non palyndrome, find phrase with slop 3, though no slop required here. query.setSlop(4); // to use sloppy scorer hits = searcher.search(query, 1000).scoreDocs; assertEquals("just sloppy enough", 1, hits.length); float score1 = hits[0].score; //System.out.println("(sloppy) field: one two three: "+score1); assertEquals("exact scorer and sloppy scorer score the same when slop does not matter",score0, score1, SCORE_COMP_THRESH); QueryUtils.check(random(), query,searcher); // search ordered in palyndrome, find it twice query = new PhraseQuery(); query.setSlop(4); // must be at least four for both ordered and reversed to match query.add(new Term("palindrome", "one")); query.add(new Term("palindrome", "two")); query.add(new Term("palindrome", "three")); hits = searcher.search(query, 1000).scoreDocs; // just make sure no exc: searcher.explain(query, 0); assertEquals("just sloppy enough", 1, hits.length); //float score2 = hits[0].score; //System.out.println("palindrome: one two three: "+score2); QueryUtils.check(random(), query,searcher); //commented out for sloppy-phrase efficiency (issue 736) - see SloppyPhraseScorer.phraseFreq(). //assertTrue("ordered scores higher in palindrome",score1+SCORE_COMP_THRESH<score2); // search reveresed in palyndrome, find it twice query = new PhraseQuery(); query.setSlop(4); // must be at least four for both ordered and reversed to match query.add(new Term("palindrome", "three")); query.add(new Term("palindrome", "two")); query.add(new Term("palindrome", "one")); hits = searcher.search(query, 1000).scoreDocs; assertEquals("just sloppy enough", 1, hits.length); //float score3 = hits[0].score; //System.out.println("palindrome: three two one: "+score3); QueryUtils.check(random(), query,searcher); //commented out for sloppy-phrase efficiency (issue 736) - see SloppyPhraseScorer.phraseFreq(). //assertTrue("reversed scores higher in palindrome",score1+SCORE_COMP_THRESH<score3); //assertEquals("ordered or reversed does not matter",score2, score3, SCORE_COMP_THRESH); } // LUCENE-1280 public void testEmptyPhraseQuery() throws Throwable { final BooleanQuery q2 = new BooleanQuery(); q2.add(new PhraseQuery(), BooleanClause.Occur.MUST); q2.toString(); } /* test that a single term is rewritten to a term query */ public void testRewrite() throws IOException { PhraseQuery pq = new PhraseQuery(); pq.add(new Term("foo", "bar")); Query rewritten = pq.rewrite(searcher.getIndexReader()); assertTrue(rewritten instanceof TermQuery); } public void testRandomPhrases() throws Exception { Directory dir = newDirectory(); Analyzer analyzer = new MockAnalyzer(random()); RandomIndexWriter w = new RandomIndexWriter(random(), dir, newIndexWriterConfig(analyzer).setMergePolicy(newLogMergePolicy())); List<List<String>> docs = new ArrayList<>(); Document d = new Document(); Field f = newTextField("f", "", Field.Store.NO); d.add(f); Random r = random(); int NUM_DOCS = atLeast(10); for (int i = 0; i < NUM_DOCS; i++) { // must be > 4096 so it spans multiple chunks int termCount = TestUtil.nextInt(random(), 4097, 8200); List<String> doc = new ArrayList<>(); StringBuilder sb = new StringBuilder(); while(doc.size() < termCount) { if (r.nextInt(5) == 1 || docs.size() == 0) { // make new non-empty-string term String term; while(true) { term = TestUtil.randomUnicodeString(r); if (term.length() > 0) { break; } } try (TokenStream ts = analyzer.tokenStream("ignore", term)) { CharTermAttribute termAttr = ts.addAttribute(CharTermAttribute.class); ts.reset(); while(ts.incrementToken()) { String text = termAttr.toString(); doc.add(text); sb.append(text).append(' '); } ts.end(); } } else { // pick existing sub-phrase List<String> lastDoc = docs.get(r.nextInt(docs.size())); int len = TestUtil.nextInt(r, 1, 10); int start = r.nextInt(lastDoc.size()-len); for(int k=start;k<start+len;k++) { String t = lastDoc.get(k); doc.add(t); sb.append(t).append(' '); } } } docs.add(doc); f.setStringValue(sb.toString()); w.addDocument(d); } IndexReader reader = w.getReader(); IndexSearcher s = newSearcher(reader); w.close(); // now search int num = atLeast(10); for(int i=0;i<num;i++) { int docID = r.nextInt(docs.size()); List<String> doc = docs.get(docID); final int numTerm = TestUtil.nextInt(r, 2, 20); final int start = r.nextInt(doc.size()-numTerm); PhraseQuery pq = new PhraseQuery(); StringBuilder sb = new StringBuilder(); for(int t=start;t<start+numTerm;t++) { pq.add(new Term("f", doc.get(t))); sb.append(doc.get(t)).append(' '); } TopDocs hits = s.search(pq, NUM_DOCS); boolean found = false; for(int j=0;j<hits.scoreDocs.length;j++) { if (hits.scoreDocs[j].doc == docID) { found = true; break; } } assertTrue("phrase '" + sb + "' not found; start=" + start + ", it=" + i + ", expected doc " + docID, found); } reader.close(); dir.close(); } public void testNegativeSlop() throws Exception { PhraseQuery query = new PhraseQuery(); query.add(new Term("field", "two")); query.add(new Term("field", "one")); try { query.setSlop(-2); fail("didn't get expected exception"); } catch (IllegalArgumentException expected) { // expected exception } } public void testNegativePosition() throws Exception { PhraseQuery query = new PhraseQuery(); try { query.add(new Term("field", "two"), -42); fail("didn't get expected exception"); } catch (IllegalArgumentException expected) { // expected exception } } public void testBackwardPositions() throws Exception { PhraseQuery query = new PhraseQuery(); query.add(new Term("field", "one"), 1); query.add(new Term("field", "two"), 5); try { query.add(new Term("field", "three"), 4); fail("didn't get expected exception"); } catch (IllegalArgumentException expected) { // expected exception } } }
package cn.zealon.readingcloud.book.domain; import lombok.Data; import java.io.Serializable; /** * 图书前后章节节点 * <p> * 图书章节数据结构,为了读取当前章时,能够方便的进入上一章、下一章, * 这里每个章节节点数据划分分为当前章、上一章、下一章,形成一个基础的双向链表 * </p> * @author: zealon * @since: 2020/5/6 */ @Data public class BookPreviousAndNextChapterNode implements Serializable { private static final Long serialVersionUID = 1L; /** 章节ID */ private Integer id; /** 章节名称 */ private String name; /** 上一章 */ BookPreviousAndNextChapterNode pre; /** 下一章 */ BookPreviousAndNextChapterNode next; public BookPreviousAndNextChapterNode(){} public BookPreviousAndNextChapterNode(Integer id, String name) { this.id = id; this.name = name; } public BookPreviousAndNextChapterNode(BookPreviousAndNextChapterNode chapterNode){ this.id = chapterNode.getId(); this.name = chapterNode.getName(); } }
package com.blogspot.toomuchcoding.book.chapter8._2_SOLID; import com.blogspot.toomuchcoding.book.chapter8.common.Person; class UpdatePersonJsonBuilder { public String build(Person person) { return "{\"name\":\"" + person.getName() + "\",\"age\":\"" + person.getAge() + "\"}"; } }
/* * Copyright (c) 2007-2014 Concurrent, Inc. All Rights Reserved. * * Project and contact information: http://www.cascading.org/ * * This file is part of the Cascading 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 cascading.tuple.collect; import java.util.Collection; import java.util.Map; import cascading.provider.CascadingFactory; import cascading.tuple.Tuple; /** * Interface TupleMapFactory allows developers to plugin alternative implementations of a "tuple map" * used to back in memory "join" and "co-group" operations. Typically these implementations are * "spillable", in that to prevent using up all memory in the JVM, after some threshold is met or event * is triggered, values are persisted to disk. * <p/> * The {@link Map} classes returned must take a {@link cascading.tuple.Tuple} as a key, and a {@link Collection} of Tuples as * a value. Further, {@link Map#get(Object)} must never return {@code null}, but on the first call to get() on the map * an empty Collection must be created and stored. * <p/> * That is, {@link Map#put(Object, Object)} is never called on the map instance internally, * only {@code map.get(groupTuple).add(valuesTuple)}. * <p/> * Using the {@link TupleCollectionFactory} to create the underlying Tuple Collections would allow that aspect * to be pluggable as well. * <p/> * If the Map implementation implements the {@link Spillable} interface, it will receive a {@link Spillable.SpillListener} * instance that calls back to the appropriate logging mechanism for the platform. This instance should be passed * down to any child Spillable types, namely an implementation of {@link SpillableTupleList}. * <p/> * The default implementation for the Hadoop platform is the {@link cascading.tuple.hadoop.collect.HadoopTupleMapFactory} * which created a {@link cascading.tuple.hadoop.collect.HadoopSpillableTupleMap} instance. * <p/> * The class {@link SpillableTupleMap} may be used as a base class. * * @see SpillableTupleMap * @see cascading.tuple.hadoop.collect.HadoopTupleMapFactory * @see TupleCollectionFactory * @see cascading.tuple.hadoop.collect.HadoopTupleCollectionFactory */ public interface TupleMapFactory<Config> extends CascadingFactory<Config, Map<Tuple, Collection<Tuple>>> { String TUPLE_MAP_FACTORY = "cascading.factory.tuple.map.classname"; }
package life.catalogue.dw.jersey.filter; import javax.ws.rs.NameBinding; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Specifies that the response varies based on accept headers. * The response will therefore be added a Vary: Accept header by binding the VaryResponseFilter */ @NameBinding @Retention(RetentionPolicy.RUNTIME) public @interface VaryAccept {}
/* * 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 com.dtstack.flinkx.classloader; /** * Represents a supplier of results. * * <p>There is no requirement that a new or distinct result be returned each * time the supplier is invoked. * * <p>This is a <a href="package-summary.html">functional interface</a> * whose functional method is {@link #get()}. * * @param <T> the type of results supplied by this supplier * * @since 1.8 */ @FunctionalInterface public interface ClassLoaderSupplier<T> { /** * Gets a result. * * @return a result */ T get(ClassLoader cl) throws Exception; }
package pokecube.core.events.pokemob.combat; import net.minecraft.entity.Entity; import net.minecraftforge.event.entity.EntityEvent; import net.minecraftforge.eventbus.api.Cancelable; import pokecube.core.interfaces.IPokemob; import pokecube.core.interfaces.capabilities.CapabilityPokemob; import pokecube.core.interfaces.entity.impl.PersistantStatusEffect.Status; /** * This event is called to apply the effects of the status. It will by default * be handled by Pokecube, with priority listener of LOWEST. Cancel this event * to prevent pokecube dealing with it<br> * <br> * These events are fired on the {@link pokecube.core.PokecubeCore#MOVE_BUS} */ @Cancelable public class StatusEvent extends EntityEvent { final Status status; final IPokemob pokemob; public StatusEvent(Entity entity, Status status) { super(entity); this.status = status; this.pokemob = CapabilityPokemob.getPokemobFor(entity); } public IPokemob getPokemob() { return this.pokemob; } public Status getStatus() { return this.status; } }
package org.jvnet.jaxb2_commons.xml.bind.model.origin; public interface MPropertyInfoOrigin { }
package org.packt.rabbitmq.book.samples.chapter2; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.ConsumerCancelledException; import com.rabbitmq.client.QueueingConsumer; import com.rabbitmq.client.ShutdownSignalException; public class CompetingReceiver { private final static String QUEUE_NAME = "event_queue"; private final static Logger LOGGER = LoggerFactory.getLogger(CompetingReceiver.class); private Connection connection = null; private Channel channel = null; public void initialize() { try { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); connection = factory.newConnection(); channel = connection.createChannel(); } catch (IOException e) { LOGGER.error(e.getMessage(), e); } } public String receive() { if (channel == null) { initialize(); } String message = null; try { channel.queueDeclare(QUEUE_NAME, false, false, false, null); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(QUEUE_NAME, true, consumer); QueueingConsumer.Delivery delivery = consumer.nextDelivery(); message = new String(delivery.getBody()); LOGGER.info("Message received: " + message); return message; } catch (IOException e) { LOGGER.error(e.getMessage(), e); } catch (ShutdownSignalException e) { LOGGER.error(e.getMessage(), e); } catch (ConsumerCancelledException e) { LOGGER.error(e.getMessage(), e); } catch (InterruptedException e) { LOGGER.error(e.getMessage(), e); } return message; } public void destroy() { if (connection != null) { try { connection.close(); } catch (IOException e) { LOGGER.warn(e.getMessage(), e); } } } }
/** * Copyright 2014-2016 CyberVision, 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. */ /** * Provides SDK compiler services */ package org.kaaproject.kaa.server.control.service.sdk.compiler;