text
stringlengths
7
1.01M
package leetcode.easy; import java.util.HashSet; import java.util.Set; /** * Created with IntelliJ IDEA. * * @Author: GuoFei * @Date: 2021/09/24/16:02 * @Description: */ public class FindRepeatNumberMain3 { public static void main(String[] args) { //findRepeatNumber(); } public static int findRepeatNumber(int [] arrs){ Set<Integer> set = new HashSet<>(); int repeat = -1; for (int arr : arrs){ if(!set.add(arr)){ repeat = arr; break; } } return repeat; } }
package org.robolectric.shadows; import static android.os.Build.VERSION_CODES.LOLLIPOP; import static android.os.Build.VERSION_CODES.M; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.robolectric.Shadows.shadowOf; import android.content.Context; import android.net.ConnectivityManager; import android.net.Network; import android.net.NetworkInfo; import android.net.NetworkRequest; import android.telephony.TelephonyManager; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RuntimeEnvironment; import org.robolectric.Shadows; import org.robolectric.TestRunners; import org.robolectric.annotation.Config; @RunWith(TestRunners.MultiApiSelfTest.class) public class ShadowConnectivityManagerTest { private ConnectivityManager connectivityManager; private ShadowNetworkInfo shadowOfActiveNetworkInfo; private ShadowConnectivityManager shadowConnectivityManager; @Before public void setUp() throws Exception { connectivityManager = (ConnectivityManager) RuntimeEnvironment.application.getSystemService(Context.CONNECTIVITY_SERVICE); shadowConnectivityManager = shadowOf(connectivityManager); shadowOfActiveNetworkInfo = shadowOf(connectivityManager.getActiveNetworkInfo()); } @Test public void getActiveNetworkInfo_shouldInitializeItself() { assertThat(connectivityManager.getActiveNetworkInfo()).isNotNull(); } @Test public void getActiveNetworkInfo_shouldReturnTrueCorrectly() { shadowOfActiveNetworkInfo.setConnectionStatus(true); assertThat(connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting()).isTrue(); assertTrue(connectivityManager.getActiveNetworkInfo().isConnected()); shadowOfActiveNetworkInfo.setConnectionStatus(false); assertThat(connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting()).isFalse(); assertThat(connectivityManager.getActiveNetworkInfo().isConnected()).isFalse(); } @Test public void getNetworkInfo_shouldReturnDefaultNetworks() throws Exception { NetworkInfo wifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); assertThat(wifi.getDetailedState()).isEqualTo(NetworkInfo.DetailedState.DISCONNECTED); NetworkInfo mobile = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); assertThat(mobile.getDetailedState()).isEqualTo(NetworkInfo.DetailedState.CONNECTED); } @Test @Config(minSdk = LOLLIPOP) public void getNetworkInfo_shouldReturnSomeForAllNetworks() throws Exception { Network[] allNetworks = connectivityManager.getAllNetworks(); for (Network network: allNetworks) { NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network); assertThat(networkInfo).isNotNull(); } } @Test @Config(minSdk = LOLLIPOP) public void getNetworkInfo_shouldReturnAddedNetwork() throws Exception { Network vpnNetwork = ShadowNetwork.newInstance(123); NetworkInfo vpnNetworkInfo = ShadowNetworkInfo.newInstance(NetworkInfo.DetailedState.CONNECTED, ConnectivityManager.TYPE_VPN, 0, true, true); shadowConnectivityManager.addNetwork(vpnNetwork, vpnNetworkInfo); NetworkInfo returnedNetworkInfo = connectivityManager.getNetworkInfo(vpnNetwork); assertThat(returnedNetworkInfo).isSameAs(vpnNetworkInfo); } @Test @Config(minSdk = LOLLIPOP) public void getNetworkInfo_shouldNotReturnRemovedNetwork() throws Exception { Network wifiNetwork = ShadowNetwork.newInstance(ShadowConnectivityManager.NET_ID_WIFI); shadowConnectivityManager.removeNetwork(wifiNetwork); NetworkInfo returnedNetworkInfo = connectivityManager.getNetworkInfo(wifiNetwork); assertThat(returnedNetworkInfo).isNull(); } @Test public void setConnectionType_shouldReturnTypeCorrectly() { shadowOfActiveNetworkInfo.setConnectionType(ConnectivityManager.TYPE_MOBILE); assertThat(ConnectivityManager.TYPE_MOBILE).isEqualTo(shadowOfActiveNetworkInfo.getType()); shadowOfActiveNetworkInfo.setConnectionType(ConnectivityManager.TYPE_WIFI); assertThat(ConnectivityManager.TYPE_WIFI).isEqualTo(shadowOfActiveNetworkInfo.getType()); } @Test public void shouldGetAndSetBackgroundDataSetting() throws Exception { assertThat(connectivityManager.getBackgroundDataSetting()).isFalse(); shadowConnectivityManager.setBackgroundDataSetting(true); assertThat(connectivityManager.getBackgroundDataSetting()).isTrue(); } @Test public void setActiveNetworkInfo_shouldSetActiveNetworkInfo() throws Exception { shadowConnectivityManager.setActiveNetworkInfo(null); assertThat(connectivityManager.getActiveNetworkInfo()).isNull(); shadowConnectivityManager.setActiveNetworkInfo(ShadowNetworkInfo.newInstance(null, ConnectivityManager.TYPE_MOBILE_HIPRI, TelephonyManager.NETWORK_TYPE_EDGE, true, false)); NetworkInfo info = connectivityManager.getActiveNetworkInfo(); assertThat(ConnectivityManager.TYPE_MOBILE_HIPRI).isEqualTo(info.getType()); assertThat(TelephonyManager.NETWORK_TYPE_EDGE).isEqualTo(info.getSubtype()); assertThat(info.isAvailable()).isTrue(); assertThat(info.isConnected()).isFalse(); } @Test @Config(minSdk = M) public void getActiveNetwork_shouldInitializeItself() { assertThat(connectivityManager.getActiveNetwork()).isNotNull(); } @Test @Config(minSdk = M) public void setActiveNetworkInfo_shouldSetActiveNetwork() throws Exception { shadowConnectivityManager.setActiveNetworkInfo(null); assertThat(connectivityManager.getActiveNetworkInfo()).isNull(); shadowConnectivityManager.setActiveNetworkInfo(ShadowNetworkInfo.newInstance(null, ConnectivityManager.TYPE_MOBILE_HIPRI, TelephonyManager.NETWORK_TYPE_EDGE, true, false)); NetworkInfo info = connectivityManager.getActiveNetworkInfo(); assertThat(ConnectivityManager.TYPE_MOBILE_HIPRI).isEqualTo(info.getType()); assertThat(TelephonyManager.NETWORK_TYPE_EDGE).isEqualTo(info.getSubtype()); assertThat(info.isAvailable()).isTrue(); assertThat(info.isConnected()).isFalse(); assertThat(shadowOf(connectivityManager.getActiveNetwork()).getNetId()).isEqualTo(info.getType()); } @Test public void getAllNetworkInfo_shouldReturnAllNetworkInterfaces() throws Exception { NetworkInfo[] infos = connectivityManager.getAllNetworkInfo(); assertThat(infos).hasSize(2); assertThat(infos).contains(connectivityManager.getActiveNetworkInfo()); shadowConnectivityManager.setActiveNetworkInfo(null); assertThat(connectivityManager.getAllNetworkInfo()).isEmpty(); } @Test @Config(minSdk = LOLLIPOP) public void getAllNetworks_shouldReturnAllNetworks() throws Exception { Network[] networks = connectivityManager.getAllNetworks(); assertThat(networks).hasSize(2); } @Test @Config(minSdk = LOLLIPOP) public void getAllNetworks_shouldReturnNoNetworksWhenCleared() throws Exception { shadowConnectivityManager.clearAllNetworks(); Network[] networks = connectivityManager.getAllNetworks(); assertThat(networks).isEmpty(); } @Test @Config(minSdk = LOLLIPOP) public void getAllNetworks_shouldReturnAddedNetworks() throws Exception { // Let's start clear. shadowConnectivityManager.clearAllNetworks(); // Add a "VPN network". Network vpnNetwork = ShadowNetwork.newInstance(123); NetworkInfo vpnNetworkInfo = ShadowNetworkInfo.newInstance(NetworkInfo.DetailedState.CONNECTED, ConnectivityManager.TYPE_VPN, 0, true, true); shadowConnectivityManager.addNetwork(vpnNetwork, vpnNetworkInfo); Network[] networks = connectivityManager.getAllNetworks(); assertThat(networks).hasSize(1); Network returnedNetwork = networks[0]; assertThat(returnedNetwork).isSameAs(vpnNetwork); NetworkInfo returnedNetworkInfo = connectivityManager.getNetworkInfo(returnedNetwork); assertThat(returnedNetworkInfo).isSameAs(vpnNetworkInfo); } @Test @Config(minSdk = LOLLIPOP) public void getAllNetworks_shouldNotReturnRemovedNetworks() throws Exception { Network wifiNetwork = ShadowNetwork.newInstance(ShadowConnectivityManager.NET_ID_WIFI); shadowConnectivityManager.removeNetwork(wifiNetwork); Network[] networks = connectivityManager.getAllNetworks(); assertThat(networks).hasSize(1); Network returnedNetwork = networks[0]; ShadowNetwork shadowReturnedNetwork = Shadows.shadowOf(returnedNetwork); assertThat(shadowReturnedNetwork.getNetId()).isNotEqualTo(ShadowConnectivityManager.NET_ID_WIFI); } @Test public void getNetworkPreference_shouldGetDefaultValue() throws Exception { assertThat(connectivityManager.getNetworkPreference()).isEqualTo(ConnectivityManager.DEFAULT_NETWORK_PREFERENCE); } @Test public void setNetworkPreference_shouldSetDefaultValue() throws Exception { connectivityManager.setNetworkPreference(ConnectivityManager.TYPE_MOBILE); assertThat(connectivityManager.getNetworkPreference()).isEqualTo(connectivityManager.getNetworkPreference()); connectivityManager.setNetworkPreference(ConnectivityManager.TYPE_WIFI); assertThat(connectivityManager.getNetworkPreference()).isEqualTo(ConnectivityManager.TYPE_WIFI); } @Test @Config(minSdk = LOLLIPOP) public void getNetworkCallbacks_shouldHaveEmptyDefault() throws Exception { assertEquals(0, shadowConnectivityManager.getNetworkCallbacks().size()); } private static ConnectivityManager.NetworkCallback createSimpleCallback() { return new ConnectivityManager.NetworkCallback() { @Override public void onAvailable(Network network) {} @Override public void onLost(Network network) {} }; } @Test @Config(minSdk = LOLLIPOP) public void registerCallback_shouldAddCallback() throws Exception { NetworkRequest.Builder builder = new NetworkRequest.Builder(); ConnectivityManager.NetworkCallback callback = createSimpleCallback(); connectivityManager.registerNetworkCallback(builder.build(), callback); assertEquals(1, shadowConnectivityManager.getNetworkCallbacks().size()); } @Test @Config(minSdk = LOLLIPOP) public void unregisterCallback_shouldRemoveCallbacks() throws Exception { NetworkRequest.Builder builder = new NetworkRequest.Builder(); // Add two different callbacks. ConnectivityManager.NetworkCallback callback1 = createSimpleCallback(); ConnectivityManager.NetworkCallback callback2 = createSimpleCallback(); connectivityManager.registerNetworkCallback(builder.build(), callback1); connectivityManager.registerNetworkCallback(builder.build(), callback2); // Remove one at the time. assertEquals(2, shadowConnectivityManager.getNetworkCallbacks().size()); connectivityManager.unregisterNetworkCallback(callback2); assertEquals(1, shadowConnectivityManager.getNetworkCallbacks().size()); connectivityManager.unregisterNetworkCallback(callback1); assertEquals(0, shadowConnectivityManager.getNetworkCallbacks().size()); } @Test(expected=IllegalArgumentException.class) @Config(minSdk = LOLLIPOP) public void unregisterCallback_shouldNotAllowNullCallback() throws Exception { // Verify that exception is thrown. connectivityManager.unregisterNetworkCallback((ConnectivityManager.NetworkCallback) null); } @Test public void isActiveNetworkMetered_defaultsToTrue() { assertThat(connectivityManager.isActiveNetworkMetered()).isTrue(); } @Test public void isActiveNetworkMetered_mobileIsMetered() { shadowConnectivityManager.setActiveNetworkInfo(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)); assertThat(connectivityManager.isActiveNetworkMetered()).isTrue(); } @Test public void isActiveNetworkMetered_nonMobileIsUnmetered() { shadowConnectivityManager.setActiveNetworkInfo(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)); assertThat(connectivityManager.isActiveNetworkMetered()).isFalse(); } @Test public void isActiveNetworkMetered_noActiveNetwork() { shadowConnectivityManager.setActiveNetworkInfo(null); assertThat(connectivityManager.isActiveNetworkMetered()).isFalse(); } }
package net.minecraft.client.gui; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiPageButtonList$GuiResponder; import net.minecraft.client.resources.I18n; public class GuiListButton extends GuiButton { private boolean field_175216_o; private String localizationStr; private final GuiPageButtonList$GuiResponder guiResponder; public GuiListButton(GuiPageButtonList$GuiResponder var1, int var2, int var3, int var4, String var5, boolean var6) { super(var2, var3, var4, 150, 20, ""); this.localizationStr = var5; this.field_175216_o = var6; this.displayString = this.buildDisplayString(); this.guiResponder = var1; } private String buildDisplayString() { return I18n.format(this.localizationStr, new Object[0]) + ": " + (this.field_175216_o?I18n.format("gui.yes", new Object[0]):I18n.format("gui.no", new Object[0])); } public void func_175212_b(boolean var1) { this.field_175216_o = var1; this.displayString = this.buildDisplayString(); this.guiResponder.func_175321_a(this.id, var1); } public boolean mousePressed(Minecraft var1, int var2, int var3) { if(super.mousePressed(var1, var2, var3)) { this.field_175216_o = !this.field_175216_o; this.displayString = this.buildDisplayString(); this.guiResponder.func_175321_a(this.id, this.field_175216_o); return true; } else { return false; } } }
import java.util.Set; import dev.iafrate.data.ReimbursementPostgres; import dev.iafrate.data.UserPostgres; import dev.iafrate.model.Reimbursement; import dev.iafrate.model.ReimbursementStatus; import dev.iafrate.model.Role; import dev.iafrate.model.User; public class testDao { public static void main(String[] args) { UserPostgres up = new UserPostgres(); ReimbursementPostgres rp = new ReimbursementPostgres(); User user1 = new User(29, "kelsey3", "40c8a0b053ee4dbe9e579ef46c6ea878", "kelsey","iafrate", "kiafrate3@gmail.com", new Role(1,"employee")); Set<Reimbursement> r = rp.getAllReimbursements(); printSet(r); Set<Reimbursement> r1 = rp.getReimbursementByUser(user1); printSet(r1); ReimbursementStatus rS0 = new ReimbursementStatus(1, "pending"); Set<Reimbursement> r2 = rp.getReimbursementsByStatus(rS0); printSet(r2); System.out.println(up.confirmCredentials("kelsey3", "password")); } public static void printSet(Set<Reimbursement> r) { for(Reimbursement r1 : r) { System.out.println(r1); } } }
/* * 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.aliyuncs.aegis.model.v20161111; import com.aliyuncs.RpcAcsRequest; /** * @author auto create * @version */ public class ModifyScreenSettingRequest extends RpcAcsRequest<ModifyScreenSettingResponse> { public ModifyScreenSettingRequest() { super("aegis", "2016-11-11", "ModifyScreenSetting", "vipaegis"); } private String screenTitle; private String screenIdSetting; public String getScreenTitle() { return this.screenTitle; } public void setScreenTitle(String screenTitle) { this.screenTitle = screenTitle; if(screenTitle != null){ putQueryParameter("ScreenTitle", screenTitle); } } public String getScreenIdSetting() { return this.screenIdSetting; } public void setScreenIdSetting(String screenIdSetting) { this.screenIdSetting = screenIdSetting; if(screenIdSetting != null){ putQueryParameter("ScreenIdSetting", screenIdSetting); } } @Override public Class<ModifyScreenSettingResponse> getResponseClass() { return ModifyScreenSettingResponse.class; } }
/* * Copyright 2018 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 io.material.catalog.picker; import io.material.catalog.R; import androidx.fragment.app.Fragment; import dagger.Provides; import dagger.android.ContributesAndroidInjector; import dagger.multibindings.IntoSet; import io.material.catalog.application.scope.ActivityScope; import io.material.catalog.application.scope.FragmentScope; import io.material.catalog.feature.Demo; import io.material.catalog.feature.DemoLandingFragment; import io.material.catalog.feature.FeatureDemo; /** A landing fragment that links to Picker demos for the Catalog app. */ public class PickerDemoLandingFragment extends DemoLandingFragment { @Override public int getTitleResId() { return R.string.cat_picker_demo_title; } @Override public int getDescriptionResId() { return R.string.cat_picker_description; } @Override public Demo getMainDemo() { return new Demo() { @Override public Fragment createFragment() { return new PickerMainDemoFragment(); } }; } /** The Dagger module for {@link PickerDemoLandingFragment} dependencies. */ @dagger.Module public abstract static class Module { @FragmentScope @ContributesAndroidInjector abstract PickerDemoLandingFragment contributeInjector(); @IntoSet @Provides @ActivityScope static FeatureDemo provideFeatureDemo() { return new FeatureDemo(R.string.cat_picker_demo_title, R.drawable.ic_dialog) { @Override public Fragment createFragment() { return new PickerDemoLandingFragment(); } }; } } }
// .result=COMPILE_FAIL public class Test { public interface TestInterface { public int functMethod(); } public static void main(String[] args) { int a; if(args[0].length() == 1) a = 4; TestInterface t = () -> a + 4; } }
/* * 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.jdbi.v3.core; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import java.util.Map; import org.jdbi.v3.core.result.ResultIterator; import org.jdbi.v3.core.rule.H2DatabaseRule; import org.jdbi.v3.core.transaction.TransactionException; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class TestClosingHandle { @Rule public H2DatabaseRule dbRule = new H2DatabaseRule(); @Rule public ExpectedException exception = ExpectedException.none(); private Handle h; @Before public void setUp() throws Exception { h = dbRule.openHandle(); } @After public void doTearDown() throws Exception { if (h != null) h.close(); } @Test public void testNotClosing() throws Exception { h.createUpdate("insert into something (id, name) values (1, 'eric')").execute(); h.createUpdate("insert into something (id, name) values (2, 'brian')").execute(); List<Map<String, Object>> results = h.createQuery("select * from something order by id").mapToMap().list(); assertThat(results).hasSize(2); assertThat(results.get(0)).containsEntry("name", "eric"); assertThat(h.isClosed()).isFalse(); } @Test public void testClosing() throws Exception { h.createUpdate("insert into something (id, name) values (1, 'eric')").execute(); h.createUpdate("insert into something (id, name) values (2, 'brian')").execute(); List<Map<String, Object>> results = h.createQuery("select * from something order by id") .cleanupHandleRollback() .mapToMap() .list(); assertThat(results).hasSize(2); assertThat(results.get(0)).containsEntry("name", "eric"); assertThat(h.isClosed()).isTrue(); } @Test public void testIterateKeepHandle() throws Exception { h.createUpdate("insert into something (id, name) values (1, 'eric')").execute(); h.createUpdate("insert into something (id, name) values (2, 'brian')").execute(); ResultIterator<Map<String, Object>> it = h.createQuery("select * from something order by id") .mapToMap() .iterator(); assertThat(it).hasSize(2); assertThat(h.isClosed()).isFalse(); } @Test public void testIterateAllTheWay() throws Exception { h.createUpdate("insert into something (id, name) values (1, 'eric')").execute(); h.createUpdate("insert into something (id, name) values (2, 'brian')").execute(); ResultIterator<Map<String, Object>> it = h.createQuery("select * from something order by id") .cleanupHandleRollback() .mapToMap() .iterator(); assertThat(it).hasSize(2); assertThat(h.isClosed()).isTrue(); } @Test public void testIteratorBehaviour() throws Exception { h.createUpdate("insert into something (id, name) values (1, 'eric')").execute(); h.createUpdate("insert into something (id, name) values (2, 'brian')").execute(); h.createUpdate("insert into something (id, name) values (3, 'john')").execute(); ResultIterator<Map<String, Object>> it = h.createQuery("select * from something order by id") .cleanupHandleRollback() .mapToMap() .iterator(); assertThat(it.hasNext()).isTrue(); assertThat(h.isClosed()).isFalse(); it.next(); assertThat(it.hasNext()).isTrue(); assertThat(h.isClosed()).isFalse(); it.next(); assertThat(it.hasNext()).isTrue(); assertThat(h.isClosed()).isFalse(); it.next(); assertThat(it.hasNext()).isFalse(); assertThat(h.isClosed()).isTrue(); } @Test public void testIteratorClose() throws Exception { h.createUpdate("insert into something (id, name) values (1, 'eric')").execute(); h.createUpdate("insert into something (id, name) values (2, 'brian')").execute(); h.createUpdate("insert into something (id, name) values (3, 'john')").execute(); ResultIterator<Map<String, Object>> it = h.createQuery("select * from something order by id") .cleanupHandleRollback() .mapToMap() .iterator(); assertThat(it.hasNext()).isTrue(); assertThat(h.isClosed()).isFalse(); it.next(); assertThat(it.hasNext()).isTrue(); assertThat(h.isClosed()).isFalse(); it.close(); assertThat(it.hasNext()).isFalse(); assertThat(h.isClosed()).isTrue(); } @Test public void testCloseWithOpenTransaction() throws Exception { h.begin(); exception.expect(TransactionException.class); try { h.close(); } finally { assertThat(h.isClosed()).isTrue(); } } }
/** * Copyright (C) 2015 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.fabric8.kubernetes.client.mock; import io.fabric8.kubernetes.api.model.PodListBuilder; import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.ConfigBuilder; import io.fabric8.kubernetes.client.DefaultKubernetesClient; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.server.mock.KubernetesServer; import org.junit.Rule; import org.junit.Test; public class HttpServerTest { @Rule public KubernetesServer server = new KubernetesServer(false); @Test public void testListWithTrustCerts() { server.expect().withPath("/api/v1/namespaces/test/pods").andReturn(200, new PodListBuilder().build()).once(); //We override the config to create a client that doesn't trust all certs. Config override = new ConfigBuilder(server.getClient().getConfiguration()).build(); KubernetesClient client = new DefaultKubernetesClient(override); client.pods().list(); } }
package com.irvil.textclassifier.dao.jdbc; import com.irvil.textclassifier.dao.CharacteristicDAOTest; import com.irvil.textclassifier.dao.jdbc.connectors.JDBCConnector; import com.irvil.textclassifier.dao.jdbc.connectors.JDBCSQLiteConnector; public class JDBCCharacteristicDAOTest extends CharacteristicDAOTest { @Override public void initializeDAO() { JDBCConnector jdbcConnector = new JDBCSQLiteConnector("./test_db/test.db"); storageCreator = new JDBCDBCreator(jdbcConnector); characteristicDAO = new JDBCCharacteristicDAO(jdbcConnector); classifiableTextDAO = new JDBCClassifiableTextDAO(jdbcConnector); vocabularyWordDAO = new JDBCVocabularyWordDAO(jdbcConnector); } }
package com.github.huifer.full.shiro.rest; import com.github.huifer.full.shiro.model.req.post.PostCreateParam; import com.github.huifer.full.shiro.model.res.ResultVO; import com.github.huifer.full.shiro.service.PostService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; 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.RestController; @RestController @RequestMapping("/post") public class PostController { @Autowired private PostService postService; @PostMapping("/") public ResultVO create(@RequestBody PostCreateParam param) { return ResultVO.success(this.postService.create(param)); } @PutMapping("/{id}") public ResultVO update(@RequestBody PostCreateParam param, @PathVariable("id") int id) { return ResultVO.success(this.postService.update(param, id)); } @DeleteMapping("/") public ResultVO delete(@PathVariable("id") int id) { return ResultVO.success(this.postService.delete(id)); } @GetMapping("/{id}") public ResultVO byId(@PathVariable("id") int id) { return ResultVO.success(this.postService.byId(id)); } }
package me.devsaki.hentoid.fragments.downloads; import android.content.Context; import android.content.Intent; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.app.ActivityOptionsCompat; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.RecyclerView; import com.annimon.stream.Stream; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.List; import eu.davidea.flexibleadapter.FlexibleAdapter; import eu.davidea.flexibleadapter.SelectableAdapter; import me.devsaki.hentoid.R; import me.devsaki.hentoid.activities.DownloadsActivity; import me.devsaki.hentoid.enums.DrawerItem; import me.devsaki.hentoid.events.UpdateEvent; import me.devsaki.hentoid.viewholders.DrawerItemFlex; import static androidx.recyclerview.widget.DividerItemDecoration.VERTICAL; public final class NavigationDrawerFragment extends Fragment { private DownloadsActivity parentActivity; private FlexibleAdapter<DrawerItemFlex> drawerAdapter; @Override public void onAttach(Context context) { super.onAttach(context); parentActivity = (DownloadsActivity) context; } @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { List<DrawerItemFlex> drawerItems = Stream.of(DrawerItem.values()) .map(DrawerItemFlex::new) .toList(); drawerAdapter = new FlexibleAdapter<>(null); drawerAdapter.setMode(SelectableAdapter.Mode.SINGLE); drawerAdapter.addListener((FlexibleAdapter.OnItemClickListener) this::onItemClick); drawerAdapter.addItems(0, drawerItems); DividerItemDecoration divider = new DividerItemDecoration(parentActivity, VERTICAL); Drawable d = ContextCompat.getDrawable(parentActivity, R.drawable.line_divider); if (d != null) divider.setDrawable(d); View view = inflater.inflate(R.layout.fragment_navigation_drawer, container, false); RecyclerView recyclerView = view.findViewById(R.id.drawer_list); recyclerView.setAdapter(drawerAdapter); recyclerView.addItemDecoration(divider); return view; } private boolean onItemClick(View view, int position) { Class activityClass = DrawerItem.values()[position].activityClass; Intent intent = new Intent(parentActivity, activityClass); Bundle bundle = ActivityOptionsCompat .makeCustomAnimation(parentActivity, R.anim.fade_in, R.anim.fade_out) .toBundle(); ContextCompat.startActivity(parentActivity, intent, bundle); parentActivity.overridePendingTransition(R.anim.fade_in, R.anim.fade_out); parentActivity.onNavigationDrawerItemClicked(); return true; } private void showFlagAboutItem() { if (drawerAdapter != null) { int aboutItemPos = DrawerItem.ABOUT.ordinal(); DrawerItemFlex item = drawerAdapter.getItem(aboutItemPos); if (item != null) { item.setFlag(true); drawerAdapter.notifyItemChanged(aboutItemPos); } } } @Subscribe(sticky = true, threadMode = ThreadMode.MAIN) public void onUpdateEvent(UpdateEvent event) { if (event.hasNewVersion) showFlagAboutItem(); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!EventBus.getDefault().isRegistered(this)) EventBus.getDefault().register(this); } @Override public void onDestroy() { super.onDestroy(); if (EventBus.getDefault().isRegistered(this)) EventBus.getDefault().unregister(this); } }
package org.opentreeoflife.taxa; import java.util.regex.Pattern; public class QualifiedId { public String prefix; public String id; private static Pattern colonPattern = Pattern.compile(":"); public QualifiedId(String prefix, String id) { if (prefix == null) throw new IllegalArgumentException("wanted non-null qid prefix"); this.prefix = prefix; this.id = id; } public QualifiedId(String qid) { String[] foo = colonPattern.split(qid, 2); if (foo.length != 2) throw new RuntimeException("ill-formed CURIEorIRI: " + qid); else if (foo[1].startsWith("//")) // IRI { this.prefix = qid; this.id = null; } else if (foo[1].length() == 0) // CURIE { this.prefix = foo[0]; this.id = null; } else // CURIE { this.prefix = foo[0]; this.id = foo[1]; } } public String getPrefix() { return prefix; } public String getId() { return id; } public String toString() { if (id == null) { if (prefix.indexOf("//") > 0) // IRI return prefix; else // CURIE return prefix + ":"; } else // CURIE return prefix + ":" + id; } public boolean equals(Object o) { if (this == o) return true; else if (o instanceof QualifiedId) { QualifiedId qid = (QualifiedId)o; if (!qid.prefix.equals(this.prefix)) return false; if (qid.id == null) return (this.id == null); if (!qid.id.equals(this.id)) return false; return true; } else return false; } public int hashCode() { if (this.id == null) return this.prefix.hashCode() + 1; else return this.prefix.hashCode() + this.id.hashCode(); } }
package com.salesmanager.core.business.utils; import java.math.BigDecimal; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Currency; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.apache.commons.validator.routines.BigDecimalValidator; import org.apache.commons.validator.routines.CurrencyValidator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import com.salesmanager.core.business.constants.Constants; import com.salesmanager.core.model.catalog.product.Product; import com.salesmanager.core.model.catalog.product.attribute.ProductAttribute; import com.salesmanager.core.model.catalog.product.availability.ProductAvailability; import com.salesmanager.core.model.catalog.product.price.FinalPrice; import com.salesmanager.core.model.catalog.product.price.ProductPrice; import com.salesmanager.core.model.merchant.MerchantStore; import com.salesmanager.core.model.order.orderproduct.OrderProduct; /** * This class determines the price that is displayed in the catalogue for a given item. * It does not calculate the total price for a given item * @author casams1 * */ @Component("priceUtil") public class ProductPriceUtils { private final static char DECIMALCOUNT = '2'; private final static char DECIMALPOINT = '.'; private final static char THOUSANDPOINT = ','; private static final Logger LOGGER = LoggerFactory.getLogger(ProductPriceUtils.class); /** * Get the price without discount * @param store * @param product * @param locale * @return */ public BigDecimal getPrice(MerchantStore store, Product product, Locale locale) { BigDecimal defaultPrice = new BigDecimal(0); Set<ProductAvailability> availabilities = product.getAvailabilities(); for(ProductAvailability availability : availabilities) { Set<ProductPrice> prices = availability.getPrices(); for(ProductPrice price : prices) { if(price.isDefaultPrice()) { defaultPrice = price.getProductPriceAmount(); } } } return defaultPrice; } /** * This method calculates the final price taking into account * all attributes included having a specified default attribute with an attribute price gt 0 * in the product object. The calculation is based * on the default price. * Attributes may be null * @param Product * @param List<ProductAttribute> * @return FinalPrice */ public FinalPrice getFinalProductPrice(Product product, List<ProductAttribute> attributes) { FinalPrice finalPrice = calculateFinalPrice(product); //attributes BigDecimal attributePrice = null; if(attributes!=null && attributes.size()>0) { for(ProductAttribute attribute : attributes) { if(attribute.getProductAttributePrice()!=null && attribute.getProductAttributePrice().doubleValue()>0) { if(attributePrice==null) { attributePrice = new BigDecimal(0); } attributePrice = attributePrice.add(attribute.getProductAttributePrice()); } } if(attributePrice!=null && attributePrice.doubleValue()>0) { BigDecimal fp = finalPrice.getFinalPrice(); fp = fp.add(attributePrice); finalPrice.setFinalPrice(fp); BigDecimal op = finalPrice.getOriginalPrice(); op = op.add(attributePrice); finalPrice.setOriginalPrice(op); BigDecimal dp = finalPrice.getDiscountedPrice(); if(dp!=null) { dp = dp.add(attributePrice); finalPrice.setDiscountedPrice(dp); } } } return finalPrice; } /** * This is the final price calculated from all configured prices * and all possibles discounts. This price does not calculate the attributes * or other prices than the default one * @param store * @param product * @param locale * @return */ public FinalPrice getFinalPrice(Product product) { FinalPrice finalPrice = calculateFinalPrice(product); //attributes BigDecimal attributePrice = null; if(product.getAttributes()!=null && product.getAttributes().size()>0) { for(ProductAttribute attribute : product.getAttributes()) { if(attribute.getAttributeDefault()) { if(attribute.getProductAttributePrice()!=null && attribute.getProductAttributePrice().doubleValue()>0) { if(attributePrice==null) { attributePrice = new BigDecimal(0); } attributePrice = attributePrice.add(attribute.getProductAttributePrice()); } } } if(attributePrice!=null && attributePrice.doubleValue()>0) { BigDecimal fp = finalPrice.getFinalPrice(); fp = fp.add(attributePrice); finalPrice.setFinalPrice(fp); BigDecimal op = finalPrice.getOriginalPrice(); op = op.add(attributePrice); finalPrice.setOriginalPrice(op); } } finalPrice.setStringPrice(this.getStringAmount(finalPrice.getFinalPrice())); return finalPrice; } /** * This is the format that will be displayed * in the admin input text fields when editing * an entity having a BigDecimal to be displayed * as a raw amount 1,299.99 * The admin user will also be force to input * the amount using that format * @param store * @param amount * @return * @throws Exception */ public String getAdminFormatedAmount(MerchantStore store, BigDecimal amount) throws Exception { if(amount==null) { return ""; } NumberFormat nf = NumberFormat.getInstance(Constants.DEFAULT_LOCALE); nf.setMaximumFractionDigits(Integer.parseInt(Character .toString(DECIMALCOUNT))); nf.setMinimumFractionDigits(Integer.parseInt(Character .toString(DECIMALCOUNT))); return nf.format(amount); } public String getStringAmount(BigDecimal amount) { if(amount==null) { return ""; } NumberFormat nf = NumberFormat.getInstance(Constants.DEFAULT_LOCALE); nf.setMaximumFractionDigits(Integer.parseInt(Character .toString(DECIMALCOUNT))); nf.setMinimumFractionDigits(Integer.parseInt(Character .toString(DECIMALCOUNT))); return nf.format(amount); } /** * This method has to be used to format store front amounts * It will display national format amount ex: * $1,345.99 * Rs.1.345.99 * or international format * USD1,345.79 * INR1,345.79 * @param store * @param amount * @return String * @throws Exception */ public String getStoreFormatedAmountWithCurrency(MerchantStore store, BigDecimal amount) throws Exception { if(amount==null) { return ""; } Currency currency = Constants.DEFAULT_CURRENCY; Locale locale = Constants.DEFAULT_LOCALE; try { currency = store.getCurrency().getCurrency(); locale = new Locale(store.getDefaultLanguage().getCode(),store.getCountry().getIsoCode()); } catch (Exception e) { LOGGER.error("Cannot create currency or locale instance for store " + store.getCode()); } NumberFormat currencyInstance = null; if(store.isCurrencyFormatNational()) { currencyInstance = NumberFormat.getCurrencyInstance(locale);//national } else { currencyInstance = NumberFormat.getCurrencyInstance();//international } currencyInstance.setCurrency(currency); return currencyInstance.format(amount.doubleValue()); } public String getFormatedAmountWithCurrency(Locale locale, com.salesmanager.core.model.reference.currency.Currency currency, BigDecimal amount) throws Exception { if(amount==null) { return ""; } Currency curr = currency.getCurrency(); NumberFormat currencyInstance = NumberFormat.getCurrencyInstance(locale); currencyInstance.setCurrency(curr); return currencyInstance.format(amount.doubleValue()); } /** * This method will return the required formated amount * with the appropriate currency * @param store * @param amount * @return * @throws Exception */ public String getAdminFormatedAmountWithCurrency(MerchantStore store, BigDecimal amount) throws Exception { if(amount==null) { return ""; } NumberFormat nf = null; Currency currency = store.getCurrency().getCurrency(); nf = NumberFormat.getInstance(Constants.DEFAULT_LOCALE); nf.setMaximumFractionDigits(Integer.parseInt(Character .toString(DECIMALCOUNT))); nf.setMinimumFractionDigits(Integer.parseInt(Character .toString(DECIMALCOUNT))); nf.setCurrency(currency); return nf.format(amount); } /** * Returns a formatted amount using Shopizer Currency * requires internal java.util.Currency populated * @param currency * @param amount * @return * @throws Exception */ public String getFormatedAmountWithCurrency(com.salesmanager.core.model.reference.currency.Currency currency, BigDecimal amount) throws Exception { if(amount==null) { return ""; } Validate.notNull(currency.getCurrency(),"Currency must be populated with java.util.Currency"); NumberFormat nf = null; Currency curr = currency.getCurrency(); nf = NumberFormat.getInstance(Constants.DEFAULT_LOCALE); nf.setMaximumFractionDigits(Integer.parseInt(Character .toString(DECIMALCOUNT))); nf.setMinimumFractionDigits(Integer.parseInt(Character .toString(DECIMALCOUNT))); nf.setCurrency(curr); return nf.format(amount); } /** * This amount will be displayed to the end user * @param store * @param amount * @param locale * @return * @throws Exception */ public String getFormatedAmountWithCurrency(MerchantStore store, BigDecimal amount, Locale locale) throws Exception { NumberFormat nf = null; Currency currency = store.getCurrency().getCurrency(); nf = NumberFormat.getInstance(locale); nf.setCurrency(currency); nf.setMaximumFractionDigits(Integer.parseInt(Character .toString(DECIMALCOUNT))); nf.setMinimumFractionDigits(Integer.parseInt(Character .toString(DECIMALCOUNT))); return nf.format(amount); } /** * Transformation of an amount of money submited by the admin * user to be inserted as a BigDecimal in the database * @param amount * @param locale * @return * @throws Exception */ public BigDecimal getAmount(String amount) throws Exception { // validations /** * 1) remove decimal and thousand * * String.replaceAll(decimalPoint, ""); String.replaceAll(thousandPoint, * ""); * * Should be able to parse to Integer */ StringBuilder newAmount = new StringBuilder(); for (int i = 0; i < amount.length(); i++) { if (amount.charAt(i) != DECIMALPOINT && amount.charAt(i) != THOUSANDPOINT) { newAmount.append(amount.charAt(i)); } } try { Integer.parseInt(newAmount.toString()); } catch (Exception e) { throw new Exception("Cannot parse " + amount); } if (!amount.contains(Character.toString(DECIMALPOINT)) && !amount.contains(Character.toString(THOUSANDPOINT)) && !amount.contains(" ")) { if (matchPositiveInteger(amount)) { BigDecimalValidator validator = CurrencyValidator.getInstance(); BigDecimal bdamount = validator.validate(amount, Locale.US); if (bdamount == null) { throw new Exception("Cannot parse " + amount); } else { return bdamount; } } else { throw new Exception("Not a positive integer " + amount); } } else { //TODO should not go this path in this current release StringBuilder pat = new StringBuilder(); if (!StringUtils.isBlank(Character.toString(THOUSANDPOINT))) { pat.append("\\d{1,3}(" + THOUSANDPOINT + "?\\d{3})*"); } pat.append("(\\" + DECIMALPOINT + "\\d{1," + DECIMALCOUNT + "})"); Pattern pattern = Pattern.compile(pat.toString()); Matcher matcher = pattern.matcher(amount); if (matcher.matches()) { Locale locale = Constants.DEFAULT_LOCALE; //TODO validate amount using old test case if (DECIMALPOINT == ',') { locale = Locale.GERMAN; } BigDecimalValidator validator = CurrencyValidator.getInstance(); return validator.validate(amount, locale); } else { throw new Exception("Cannot parse " + amount); } } } public BigDecimal getOrderProductTotalPrice(MerchantStore store, OrderProduct orderProduct) { BigDecimal finalPrice = orderProduct.getOneTimeCharge(); finalPrice = finalPrice.multiply(new BigDecimal(orderProduct.getProductQuantity())); return finalPrice; } /** * Determines if a ProductPrice has a discount * @param productPrice * @return */ public boolean hasDiscount(ProductPrice productPrice) { Date today = new Date(); //calculate discount price boolean hasDiscount = false; if(productPrice.getProductPriceSpecialStartDate()!=null || productPrice.getProductPriceSpecialEndDate()!=null) { if(productPrice.getProductPriceSpecialStartDate()!=null) { if(productPrice.getProductPriceSpecialStartDate().before(today)) { if(productPrice.getProductPriceSpecialEndDate()!=null) { if(productPrice.getProductPriceSpecialEndDate().after(today)) { hasDiscount = true; } } } } } return hasDiscount; } private boolean matchPositiveInteger(String amount) { Pattern pattern = Pattern.compile("^[+]?\\d*$"); Matcher matcher = pattern.matcher(amount); return matcher.matches(); } private FinalPrice calculateFinalPrice(Product product) { FinalPrice finalPrice = null; List<FinalPrice> otherPrices = null; Set<ProductAvailability> availabilities = product.getAvailabilities(); for(ProductAvailability availability : availabilities) { if(!StringUtils.isEmpty(availability.getRegion()) && availability.getRegion().equals(Constants.ALL_REGIONS)) {//TODO REL 2.1 accept a region Set<ProductPrice> prices = availability.getPrices(); for(ProductPrice price : prices) { FinalPrice p = finalPrice(price); if(price.isDefaultPrice()) { finalPrice = p; } else { if(otherPrices==null) { otherPrices = new ArrayList<FinalPrice>(); } otherPrices.add(p); } } } } if(finalPrice!=null) { finalPrice.setAdditionalPrices(otherPrices); } else { if(otherPrices!=null) { finalPrice = otherPrices.get(0); } } return finalPrice; } private FinalPrice finalPrice(ProductPrice price) { FinalPrice finalPrice = new FinalPrice(); BigDecimal fPrice = price.getProductPriceAmount(); BigDecimal oPrice = price.getProductPriceAmount(); Date today = new Date(); //calculate discount price boolean hasDiscount = false; if(price.getProductPriceSpecialStartDate()!=null || price.getProductPriceSpecialEndDate()!=null) { if(price.getProductPriceSpecialStartDate()!=null) { if(price.getProductPriceSpecialStartDate().before(today)) { if(price.getProductPriceSpecialEndDate()!=null) { if(price.getProductPriceSpecialEndDate().after(today)) { hasDiscount = true; fPrice = price.getProductPriceSpecialAmount(); finalPrice.setDiscountEndDate(price.getProductPriceSpecialEndDate()); } } } } if(!hasDiscount && price.getProductPriceSpecialStartDate()==null && price.getProductPriceSpecialEndDate()!=null) { if(price.getProductPriceSpecialEndDate().after(today)) { hasDiscount = true; fPrice = price.getProductPriceSpecialAmount(); finalPrice.setDiscountEndDate(price.getProductPriceSpecialEndDate()); } } } else { if(price.getProductPriceSpecialAmount()!=null && price.getProductPriceSpecialAmount().doubleValue()>0) { hasDiscount = true; fPrice = price.getProductPriceSpecialAmount(); finalPrice.setDiscountEndDate(price.getProductPriceSpecialEndDate()); } } finalPrice.setProductPrice(price); finalPrice.setFinalPrice(fPrice); finalPrice.setOriginalPrice(oPrice); if(price.isDefaultPrice()) { finalPrice.setDefaultPrice(true); } if(hasDiscount) { discountPrice(finalPrice); } return finalPrice; } private void discountPrice(FinalPrice finalPrice) { finalPrice.setDiscounted(true); double arith = finalPrice.getProductPrice().getProductPriceSpecialAmount().doubleValue() / finalPrice.getProductPrice().getProductPriceAmount().doubleValue(); double fsdiscount = 100 - (arith * 100); Float percentagediscount = new Float(fsdiscount); int percent = percentagediscount.intValue(); finalPrice.setDiscountPercent(percent); //calculate percent BigDecimal price = finalPrice.getOriginalPrice(); finalPrice.setDiscountedPrice(finalPrice.getProductPrice().getProductPriceSpecialAmount()); } }
/* * Copyright (C) 2017-2018 Dremio Corporation * * 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.dremio.exec.store.parquet; import java.util.List; import com.dremio.exec.planner.common.ScanRelBase; import com.dremio.exec.store.ScanFilter; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeName; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; /** * Implementation of {@link ScanFilter} for parquet scan. */ @JsonTypeName("ParquetScanFilter") public class ParquetScanFilter implements ScanFilter { private static final double SORTED_ADJUSTMENT = 0.1d; private static final int PRIMARY_SORT_INDEX = 0; private final List<ParquetFilterCondition> conditions; /** * Currently Parquet scan supports only one condition. * @param conditions */ @JsonCreator public ParquetScanFilter(@JsonProperty("conditions") List<ParquetFilterCondition> conditions) { Preconditions.checkArgument(conditions != null && conditions.size() == 1 && conditions.get(0) != null, "need exactly one non-null condition"); this.conditions = ImmutableList.copyOf(conditions); } /** * Get the underlying conditions * @return */ public List<ParquetFilterCondition> getConditions() { return conditions; } @Override public double getCostAdjustment(){ if(isSortedByFilterConditions(conditions.get(0))){ return SORTED_ADJUSTMENT; } else { return ScanRelBase.DEFAULT_COST_ADJUSTMENT; } } /** * Our goal here is to look at whether the provided filter conditions benefit * from the sortedness of the data. * * @param condition The condition to consider * @return Whether the conditions benefit from sortedness. Currently can only * return true if a single condition is present as we don't yet * support or benefit from pushdowns of multiple conditions. */ private static boolean isSortedByFilterConditions(ParquetFilterCondition condition){ return condition != null // we only are interested in a filter on a primary sort field && condition.getSort() == PRIMARY_SORT_INDEX; } @Override public String toString() { return conditions.toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ParquetScanFilter that = (ParquetScanFilter) o; return Objects.equal(conditions, that.conditions); } @Override public int hashCode() { return Objects.hashCode(conditions); } }
package com.newnius.streamspider.util; import java.net.URL; import java.nio.charset.Charset; /** * Created by newnius on 4/28/17. * */ public class StringUtils { /* * * handle urls with white space and Chinese characters * From: http://www.jianshu.com/p/9be694c8fee2 * */ public static String encodeUrl(URL url, Charset charset){ String query = url.getQuery(); if(query !=null) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < query.length(); i++) { char c = query.charAt(i); if (c <= 255) { sb.append(c); } else { byte[] b; try { b = String.valueOf(c).getBytes(charset); } catch (Exception ex) { b = new byte[0]; } for (byte aB : b) { int k = aB; if (k < 0) k += 256; sb.append("%").append(Integer.toHexString(k).toUpperCase()); } } } query = sb.toString(); } String res = url.getProtocol()+"://"; res+=url.getHost(); if(url.getPort()!=-1){ res+=":"+url.getPort(); } if(url.getPath()!=null){ res+=url.getPath(); } if(query != null){ res+= "?"+query; } //fix url encode bug res = res.replaceAll(" ", "%20"); return res; } }
package com.weiit.web.admin.file.service.impl; import javax.annotation.Resource; import com.weiit.core.entity.E; import org.springframework.stereotype.Service; import com.weiit.core.entity.FormMap; import com.weiit.core.mapper.BaseMapper; import com.weiit.core.service.impl.AbstractService; import com.weiit.web.admin.file.mapper.PictureMapper; import com.weiit.web.admin.file.service.PictureService; import java.util.List; /** * 图片空间实现类 * @author 半个鼠标 * @date 2017年2月14日 上午2:12:48 * @version 1.0 * @company http://www.wei-it.com */ @Service("PictureService") public class PictureServiceImpl extends AbstractService implements PictureService{ @Resource private PictureMapper pictureMapper; @Override public BaseMapper setMapper() { return pictureMapper; } @Override public int uploadFile(E param) { return pictureMapper.uploadFile(param); } @Override public List<E> getFileForPage(FormMap formMap) { return pictureMapper.getFileForPage(formMap); } @Override public List<E> getVideoList(FormMap formMap) { return pictureMapper.getVideoList(formMap); } @Override public void insertExpress(FormMap formMap) { pictureMapper.insertExpress(formMap); } }
/* * $Header: /home/cvs/jakarta-tomcat-4.0/catalina/src/share/org/apache/catalina/realm/MemoryRuleSet.java,v 1.2 2002/02/08 16:19:57 craigmcc Exp $ * $Revision: 1.2 $ * $Date: 2002/02/08 16:19:57 $ * * ==================================================================== * * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.catalina.realm; import org.apache.commons.digester.Digester; import org.apache.commons.digester.Rule; import org.apache.commons.digester.RuleSetBase; import org.xml.sax.Attributes; /** * <p><strong>RuleSet</strong> for recognizing the users defined in the * XML file processed by <code>MemoryRealm</code>.</p> * * @author Craig R. McClanahan * @version $Revision: 1.2 $ $Date: 2002/02/08 16:19:57 $ */ public class MemoryRuleSet extends RuleSetBase { // ----------------------------------------------------- Instance Variables /** * The matching pattern prefix to use for recognizing our elements. */ protected String prefix = null; // ------------------------------------------------------------ Constructor /** * Construct an instance of this <code>RuleSet</code> with the default * matching pattern prefix. */ public MemoryRuleSet() { this("tomcat-users/"); } /** * Construct an instance of this <code>RuleSet</code> with the specified * matching pattern prefix. * * @param prefix Prefix for matching pattern rules (including the * trailing slash character) */ public MemoryRuleSet(String prefix) { super(); this.namespaceURI = null; this.prefix = prefix; } // --------------------------------------------------------- Public Methods /** * <p>Add the set of Rule instances defined in this RuleSet to the * specified <code>Digester</code> instance, associating them with * our namespace URI (if any). This method should only be called * by a Digester instance.</p> * * @param digester Digester instance to which the new Rule instances * should be added. */ public void addRuleInstances(Digester digester) { digester.addRule (prefix + "user", new MemoryUserRule(digester)); } } /** * Private class used when parsing the XML database file. */ final class MemoryUserRule extends Rule { /** * Construct a new instance of this <code>Rule</code>. * * @param digester The <code>Digester</code> we are associated with. */ public MemoryUserRule(Digester digester) { super(digester); } /** * Process a <code>&lt;user&gt;</code> element from the XML database file. * * @param attributes The attribute list for this element */ public void begin(Attributes attributes) throws Exception { String username = attributes.getValue("name"); if (username == null) { username = attributes.getValue("username"); } String password = attributes.getValue("password"); String roles = attributes.getValue("roles"); MemoryRealm realm = (MemoryRealm) digester.peek(digester.getCount() - 1); realm.addUser(username, password, roles); } }
/* * The MIT License * * Copyright 2018 Intuit Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package cucumber.api.cli; /** * replaces cucumber-jvm code * * @author pthomas3 */ public class Main { public static void main(String[] args) { com.intuit.karate.cli.Main.main(args); System.exit(0); } }
/** * DSL implementation and translation to internal intermediary representation based on a JPQL syntax subset. * * @author anistor@redhat.com * @since 6.0 * * @private */ package org.infinispan.query.dsl.impl;
/** * Copyright (c) 2008, http://www.snakeyaml.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.yaml.snakeyaml.issues.issue512; import junit.framework.TestCase; import org.yaml.snakeyaml.LoaderOptions; import org.yaml.snakeyaml.Util; import org.yaml.snakeyaml.Yaml; import java.util.List; public class ListWithCommentTest extends TestCase { public void testList() { String str = Util.getLocalResource("issues/issue512.yaml"); LoaderOptions options = new LoaderOptions(); options.setProcessComments(true); Yaml yaml = new Yaml(options); List<String> obj = yaml.load(str); assertEquals(2, obj.size()); } }
package com.cognixia.jump.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.cognixia.jump.connection.ConnectionManager; import com.cognixia.jump.model.Librarian; import com.cognixia.jump.model.Book; public class LibrarianDaoImp implements LibrarianDao, BookDao { public static final Connection conn = ConnectionManager.getConnection(); private static String SELECT_ALL_LIBRARIANS = "select * from librarian"; private static String SELECT_ALL_BOOKS = "select * from book"; private static String SELECT_BOOK_BY_ISBN = "select * from book where isbn = ?"; private static String INSERT_BOOK = "insert into book(isbn,title, descr, rented, added_to_library ) values(?, ?, ?, ?, ?)"; private static String DELETE_BOOK = "delete from book where isbn = ?"; private static String UPDATE_BOOK = "update book set title = ?, rented = ?, descr = ? where isbn = ?"; private static String UPDATE_BOOK_AVAILABILITY = "update book set rented = ? where isbn = ?"; private static String UPDATE_USERNAME = "update librarian set username = ?"; private static String UPDATE_PASSWORD = "update librarian set password = ?"; private static String GET_LIBRARIAN = "SELECT * FROM librarian WHERE username = ? AND password = ?"; @Override public List<Librarian> getAllLibrarians() { List<Librarian> allLibrarians = new ArrayList<Librarian>(); try(PreparedStatement pstmt = conn.prepareStatement(SELECT_ALL_LIBRARIANS); ResultSet rs = pstmt.executeQuery() ) { while(rs.next()) { int librarian_id = rs.getInt("librarian_id"); String username = rs.getString("username"); String password = rs.getString("password"); allLibrarians.add(new Librarian(librarian_id, username, password)); } } catch(SQLException e) { e.printStackTrace(); } return allLibrarians; } @Override public List<Book> getAllBooks() { List<Book> allBooks = new ArrayList<Book>(); try (PreparedStatement pstmt = conn.prepareStatement(SELECT_ALL_BOOKS); ResultSet rs = pstmt.executeQuery()) { while (rs.next()) { String isbn = rs.getString("isbn"); String title = rs.getString("title"); boolean rented = rs.getBoolean("rented"); Date added_to_library = rs.getDate("added_to_library"); String description = rs.getString("descr"); allBooks.add(new Book(isbn, title, description, rented, added_to_library)); } } catch (SQLException e) { e.printStackTrace(); } return allBooks; } @Override public Book getBookByIsbn(String isbn) { Book book = null; try (PreparedStatement pstmt = conn.prepareStatement(SELECT_BOOK_BY_ISBN)) { System.out.println("in get by isbn"); pstmt.setString(1, isbn); ResultSet rs = pstmt.executeQuery(); if (rs.next()) { String title = rs.getString("title"); boolean rented = rs.getBoolean("rented"); Date added_to_library = rs.getDate("added_to_library"); String description = rs.getString("descr"); book = new Book(isbn, title, description, rented, added_to_library); } else { System.out.println("rs next failed"); } } catch (SQLException e) { e.printStackTrace(); } System.out.println("in get by isbn end " + book.toString()); return book; } @Override public boolean addBook(Book book) { try (PreparedStatement pstmt = conn.prepareStatement(INSERT_BOOK)) { pstmt.setString(1, book.getIsbn()); pstmt.setString(2, book.getTitle()); pstmt.setBoolean(4, book.isRented()); pstmt.setString(3, book.getDescription()); java.sql.Date sqlPackageDate = new java.sql.Date(book.getAdded_to_library().getTime()); System.out.println(sqlPackageDate); pstmt.setDate(5, sqlPackageDate); System.out.println(book); // at least one row added if (pstmt.executeUpdate() > 0) { return true; } } catch (SQLException e) { e.printStackTrace(); } return false; } @Override public boolean deleteBook(String isbn) { try (PreparedStatement pstmt = conn.prepareStatement(DELETE_BOOK)) { pstmt.setString(1, isbn); // at least one row deleted if (pstmt.executeUpdate() > 0) { return true; } } catch (SQLException e) { e.printStackTrace(); } return false; } @Override public boolean updateBook(Book book) { try (PreparedStatement pstmt = conn.prepareStatement(UPDATE_BOOK)) { pstmt.setString(1, book.getTitle()); pstmt.setBoolean(2, book.isRented()); pstmt.setString(3, book.getDescription()); pstmt.setString(4, book.getIsbn()); System.out.println("book"); // at least one row updated if (pstmt.executeUpdate() > 0) { return true; } } catch (SQLException e) { e.printStackTrace(); } return false; } @Override public boolean updateBookAvailability(Book book) { try (PreparedStatement pstmt = conn.prepareStatement(UPDATE_BOOK_AVAILABILITY)) { pstmt.setBoolean(1, book.isRented()); pstmt.setString(2, book.getIsbn()); // at least one row updated if (pstmt.executeUpdate() > 0) { return true; } } catch (SQLException e) { e.printStackTrace(); } return false; } @Override public boolean updateUsername(Librarian librarian) { try (PreparedStatement pstmt = conn.prepareStatement(UPDATE_USERNAME)) { pstmt.setString(1, librarian.getUsername()); // at least one row updated if (pstmt.executeUpdate() > 0) { return true; } } catch (SQLException e) { e.printStackTrace(); } return false; } @Override public boolean updatePassword(Librarian librarian) { try (PreparedStatement pstmt = conn.prepareStatement(UPDATE_PASSWORD)) { pstmt.setString(1, librarian.getPassword()); // at least one row updated if (pstmt.executeUpdate() > 0) { return true; } } catch (SQLException e) { e.printStackTrace(); } return false; } @Override public Librarian getLibrarian(String username, String password) { Librarian librarian = null; try(PreparedStatement pstmt = conn.prepareStatement(GET_LIBRARIAN)) { pstmt.setString(1, username); pstmt.setString(2, password); ResultSet rs = pstmt.executeQuery(); if(!rs.isBeforeFirst()) { return librarian; } if(rs.next()) { int librarian_id = rs.getInt("librarian_id"); String userName = rs.getString("username"); String passWord = rs.getString("password"); librarian = new Librarian(librarian_id, userName, passWord); return librarian; } }catch (SQLException e) { e.printStackTrace(); } return librarian; } }
package com.lkl.algorithm.mazeGeneralization.RandomMazeB.MoreAboutRandomMazeGenWithMazeSolver; import java.util.LinkedList; public class RandomQueue<E> { private LinkedList<E> queue; public RandomQueue() { queue = new LinkedList<E>(); } public void add(E e) { if (Math.random() < 0.5) queue.addFirst(e); else queue.addLast(e); } public E remove() { if (queue.size() == 0) throw new IllegalArgumentException("There's no element to remove in Random Qeuue"); if (Math.random() < 0.5) return queue.removeFirst(); else return queue.removeLast(); } public int size() { return queue.size(); } public boolean empty() { return size() == 0; } }
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.monitor; import java.util.Arrays; import java.util.Comparator; import java.util.concurrent.CopyOnWriteArrayList; import java.io.File; import java.io.FileFilter; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOCase; import java.util.List; import org.apache.commons.io.comparator.NameFileComparator; import java.io.Serializable; /** * FileAlterationObserver represents the state of files below a root directory, * checking the filesystem and notifying listeners of create, change or * delete events. * <p> * To use this implementation: * <ul> * <li>Create {@link FileAlterationListener} implementation(s) that process * the file/directory create, change and delete events</li> * <li>Register the listener(s) with a {@link FileAlterationObserver} for * the appropriate directory.</li> * <li>Either register the observer(s) with a {@link FileAlterationMonitor} or * run manually.</li> * </ul> * * <h2>Basic Usage</h2> * Create a {@link FileAlterationObserver} for the directory and register the listeners: * <pre> * File directory = new File(new File("."), "src"); * FileAlterationObserver observer = new FileAlterationObserver(directory); * observer.addListener(...); * observer.addListener(...); * </pre> * To manually observe a directory, initialize the observer and invoked the * {@link #checkAndNotify()} method as required: * <pre> * // intialize * observer.init(); * ... * // invoke as required * observer.checkAndNotify(); * ... * observer.checkAndNotify(); * ... * // finished * observer.finish(); * </pre> * Alternatively, register the oberver(s) with a {@link FileAlterationMonitor}, * which creates a new thread, invoking the observer at the specified interval: * <pre> * long interval = ... * FileAlterationMonitor monitor = new FileAlterationMonitor(interval); * monitor.addObserver(observer); * monitor.start(); * ... * monitor.stop(); * </pre> * * <h2>File Filters</h2> * This implementation can monitor portions of the file system * by using {@link FileFilter}s to observe only the files and/or directories * that are of interest. This makes it more efficient and reduces the * noise from <i>unwanted</i> file system events. * <p> * <a href="http://commons.apache.org/io/">Commons IO</a> has a good range of * useful, ready made * <a href="../filefilter/package-summary.html">File Filter</a> * implementations for this purpose. * <p> * For example, to only observe 1) visible directories and 2) files with a ".java" suffix * in a root directory called "src" you could set up a {@link FileAlterationObserver} in the following * way: * <pre> * // Create a FileFilter * IOFileFilter directories = FileFilterUtils.and( * FileFilterUtils.directoryFileFilter(), * HiddenFileFilter.VISIBLE); * IOFileFilter files = FileFilterUtils.and( * FileFilterUtils.fileFileFilter(), * FileFilterUtils.suffixFileFilter(".java")); * IOFileFilter filter = FileFilterUtils.or(directories, files); * * // Create the File system observer and register File Listeners * FileAlterationObserver observer = new FileAlterationObserver(new File("src"), filter); * observer.addListener(...); * observer.addListener(...); * </pre> * * <h2>FileEntry</h2> * {@link FileEntry} represents the state of a file or directory, capturing * {@link File} attributes at a point in time. Custom implementations of * {@link FileEntry} can be used to capture additional properties that the * basic implementation does not support. The {@link FileEntry#refresh(File)} * method is used to determine if a file or directory has changed since the last * check and stores the current state of the {@link File}'s properties. * * @see FileAlterationListener * @see FileAlterationMonitor * @version $Id: FileAlterationObserver.java 1686747 2015-06-21 18:44:49Z krosenvold $ * @since 2.0 */ public class FileAlterationObserver implements Serializable { private static final long serialVersionUID = 1185122225658782848L; private final List<FileAlterationListener> listeners = new CopyOnWriteArrayList<FileAlterationListener>(); private final FileEntry rootEntry; private final FileFilter fileFilter; private final Comparator<File> comparator; /** * Construct an observer for the specified directory. * * @param directoryName the name of the directory to observe */ public FileAlterationObserver(final String directoryName) { this(new File(directoryName)); } /** * Construct an observer for the specified directory and file filter. * * @param directoryName the name of the directory to observe * @param fileFilter The file filter or null if none */ public FileAlterationObserver(final String directoryName, final FileFilter fileFilter) { this(new File(directoryName), fileFilter); } /** * Construct an observer for the specified directory, file filter and * file comparator. * * @param directoryName the name of the directory to observe * @param fileFilter The file filter or null if none * @param caseSensitivity what case sensitivity to use comparing file names, null means system sensitive */ public FileAlterationObserver(final String directoryName, final FileFilter fileFilter, final IOCase caseSensitivity) { this(new File(directoryName), fileFilter, caseSensitivity); } /** * Construct an observer for the specified directory. * * @param directory the directory to observe */ public FileAlterationObserver(final File directory) { this(directory, null); } /** * Construct an observer for the specified directory and file filter. * * @param directory the directory to observe * @param fileFilter The file filter or null if none */ public FileAlterationObserver(final File directory, final FileFilter fileFilter) { this(directory, fileFilter, null); } /** * Construct an observer for the specified directory, file filter and * file comparator. * * @param directory the directory to observe * @param fileFilter The file filter or null if none * @param caseSensitivity what case sensitivity to use comparing file names, null means system sensitive */ public FileAlterationObserver(final File directory, final FileFilter fileFilter, final IOCase caseSensitivity) { this(new FileEntry(directory), fileFilter, caseSensitivity); } /** * Construct an observer for the specified directory, file filter and * file comparator. * * @param rootEntry the root directory to observe * @param fileFilter The file filter or null if none * @param caseSensitivity what case sensitivity to use comparing file names, null means system sensitive */ protected FileAlterationObserver(final FileEntry rootEntry, final FileFilter fileFilter, final IOCase caseSensitivity) { if (rootEntry == null) { throw new IllegalArgumentException("Root entry is missing"); } if ((rootEntry.getFile()) == null) { throw new IllegalArgumentException("Root directory is missing"); } this.rootEntry = rootEntry; this.fileFilter = fileFilter; if ((caseSensitivity == null) || (caseSensitivity.equals(IOCase.SYSTEM))) { this.comparator = NameFileComparator.NAME_SYSTEM_COMPARATOR; } else if (caseSensitivity.equals(IOCase.INSENSITIVE)) { this.comparator = NameFileComparator.NAME_INSENSITIVE_COMPARATOR; } else { this.comparator = NameFileComparator.NAME_COMPARATOR; } } /** * Return the directory being observed. * * @return the directory being observed */ public File getDirectory() { return rootEntry.getFile(); } /** * Return the fileFilter. * * @return the fileFilter * @since 2.1 */ public FileFilter getFileFilter() { return fileFilter; } /** * Add a file system listener. * * @param listener The file system listener */ public void addListener(final FileAlterationListener listener) { if (listener != null) { listeners.add(listener); } } /** * Remove a file system listener. * * @param listener The file system listener */ public void removeListener(final FileAlterationListener listener) { if (listener != null) { while (listeners.remove(listener)) { } } } /** * Returns the set of registered file system listeners. * * @return The file system listeners */ public Iterable<FileAlterationListener> getListeners() { return listeners; } /** * Initialize the observer. * * @throws Exception if an error occurs */ public void initialize() throws Exception { rootEntry.refresh(rootEntry.getFile()); final FileEntry[] children = doListFiles(rootEntry.getFile(), rootEntry); rootEntry.setChildren(children); } /** * Final processing. * * @throws Exception if an error occurs */ public void destroy() throws Exception { } /** * Check whether the file and its chlidren have been created, modified or deleted. */ public void checkAndNotify() { /* fire onStart() */ for (final FileAlterationListener listener : listeners) { listener.onStart(FileAlterationObserver.this); } /* fire directory/file events */ final File rootFile = rootEntry.getFile(); if (rootFile.exists()) { checkAndNotify(rootEntry, rootEntry.getChildren(), listFiles(rootFile)); } else if (rootEntry.isExists()) { checkAndNotify(rootEntry, rootEntry.getChildren(), FileUtils.EMPTY_FILE_ARRAY); } else { // Didn't exist and still doesn't } /* fire onStop() */ for (final FileAlterationListener listener : listeners) { listener.onStop(FileAlterationObserver.this); } } /** * Compare two file lists for files which have been created, modified or deleted. * * @param parent The parent entry * @param previous The original list of files * @param files The current list of files */ private void checkAndNotify(final FileEntry parent, final FileEntry[] previous, final File[] files) { int c = 0; final FileEntry[] current = (files.length) > 0 ? new FileEntry[files.length] : FileEntry.EMPTY_ENTRIES; for (final FileEntry entry : previous) { while ((c < (files.length)) && ((comparator.compare(entry.getFile(), files[c])) > 0)) { current[c] = createFileEntry(parent, files[c]); doCreate(current[c]); c++; } if ((c < (files.length)) && ((comparator.compare(entry.getFile(), files[c])) == 0)) { doMatch(entry, files[c]); checkAndNotify(entry, entry.getChildren(), listFiles(files[c])); current[c] = entry; c++; } else { checkAndNotify(entry, entry.getChildren(), FileUtils.EMPTY_FILE_ARRAY); doDelete(entry); } } for (; c < (files.length); c++) { current[c] = createFileEntry(parent, files[c]); doCreate(current[c]); } parent.setChildren(current); } /** * Create a new file entry for the specified file. * * @param parent The parent file entry * @param file The file to create an entry for * @return A new file entry */ private FileEntry createFileEntry(final FileEntry parent, final File file) { final FileEntry entry = parent.newChildInstance(file); entry.refresh(file); final FileEntry[] children = doListFiles(file, entry); entry.setChildren(children); return entry; } /** * List the files * @param file The file to list files for * @param entry the parent entry * @return The child files */ private FileEntry[] doListFiles(File file, FileEntry entry) { final File[] files = listFiles(file); final FileEntry[] children = (files.length) > 0 ? new FileEntry[files.length] : FileEntry.EMPTY_ENTRIES; for (int i = 0; i < (files.length); i++) { children[i] = createFileEntry(entry, files[i]); } return children; } /** * Fire directory/file created events to the registered listeners. * * @param entry The file entry */ private void doCreate(final FileEntry entry) { for (final FileAlterationListener listener : listeners) { if (entry.isDirectory()) { listener.onDirectoryCreate(entry.getFile()); } else { listener.onFileCreate(entry.getFile()); } } final FileEntry[] children = entry.getChildren(); for (final FileEntry aChildren : children) { doCreate(aChildren); } } /** * Fire directory/file change events to the registered listeners. * * @param entry The previous file system entry * @param file The current file */ private void doMatch(final FileEntry entry, final File file) { if (entry.refresh(file)) { for (final FileAlterationListener listener : listeners) { if (entry.isDirectory()) { listener.onDirectoryChange(file); } else { listener.onFileChange(file); } } } } /** * Fire directory/file delete events to the registered listeners. * * @param entry The file entry */ private void doDelete(final FileEntry entry) { for (final FileAlterationListener listener : listeners) { if (entry.isDirectory()) { listener.onDirectoryDelete(entry.getFile()); } else { listener.onFileDelete(entry.getFile()); } } } /** * List the contents of a directory * * @param file The file to list the contents of * @return the directory contents or a zero length array if * the empty or the file is not a directory */ private File[] listFiles(final File file) { File[] children = null; if (file.isDirectory()) { children = ((fileFilter) == null) ? file.listFiles() : file.listFiles(fileFilter); } if (children == null) { children = FileUtils.EMPTY_FILE_ARRAY; } if (((comparator) != null) && ((children.length) > 1)) { Arrays.sort(children, comparator); } return children; } /** * Provide a String representation of this observer. * * @return a String representation of this observer */ @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append(getClass().getSimpleName()); builder.append("[file='"); builder.append(getDirectory().getPath()); builder.append('\''); if ((fileFilter) != null) { builder.append(", "); builder.append(fileFilter.toString()); } builder.append(", listeners="); builder.append(listeners.size()); builder.append("]"); return builder.toString(); } }
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot; import java.util.HashMap; import java.util.Map; import edu.wpi.first.math.trajectory.Trajectory; import edu.wpi.first.util.sendable.Sendable; import edu.wpi.first.util.sendable.SendableRegistry; import edu.wpi.first.wpilibj.GenericHID; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.XboxController; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.InstantCommand; import edu.wpi.first.wpilibj2.command.button.JoystickButton; import edu.wpi.first.wpilibj2.command.button.Trigger; import frc.robot.commands.intake.Deploy; import frc.robot.commands.intake.Intake; import frc.robot.commands.intake.Retract; import frc.robot.commands.intake.ReverseIntake; import frc.robot.commands.auto.DriveFunctions; import frc.robot.commands.auto.DriveToCargo; import frc.robot.commands.auto.DriveToHub; import frc.robot.commands.auto.ShootThreeStart; import frc.robot.commands.climb.ClimbStageTwoBackward; import frc.robot.commands.climb.ClimbStageTwoForward; import frc.robot.commands.drive.DriveWithJoystick; import frc.robot.commands.outtake.OuttakeHigh; import frc.robot.commands.outtake.OuttakeLow; import frc.robot.subsystems.ClimbSubsystem; import frc.robot.subsystems.DriveSystem; import frc.robot.subsystems.IntakeSubsystem; import frc.robot.subsystems.OuttakeSubsystem; import frc.robot.vision.Limelight; import frc.robot.vision.PhotonVision; import static frc.robot.Constants.ControllerConstants.*; /** * This class is where the bulk of the robot should be declared. Since Command-based is a * "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot} * periodic methods (other than the scheduler calls). Instead, the structure of the robot (including * subsystems, commands, and button mappings) should be declared here. */ public class RobotContainer { // The robot's subsystems and commands are defined here... private DriveSystem driveSystem; private IntakeSubsystem intake; private OuttakeSubsystem outtake; private ClimbSubsystem climb; private PhotonVision photon; private Limelight limelight; private InstantCommand toggleFieldOriented; private InstantCommand toggleSlowMode; private InstantCommand toggleTurboMode; private InstantCommand zeroRotatingArm; private Command deploy; private Command retract; private Command intakeCmd; private Command reverseIntake; private Command stage2Backwards; private Command stage2Forwards; private DriveWithJoystick driveWithJoystick; private OuttakeHigh outtakeHigh; private OuttakeLow outtakeLow; private Joystick driver; private JoystickButton toggleFieldOrientedBtn; private JoystickButton toggleSlowModeBtn; private XboxController operator; private JoystickButton deployBtn; private JoystickButton intakeBtn; private JoystickButton reverseIntakeBtn; private JoystickButton outtakeHighBtn; private JoystickButton stage2ForwardBtn; private JoystickButton stage2BackwardBtn; private JoystickButton zeroRotatingArmBtn; private Trigger outtakeLowBtn; private SendableChooser<Command> autoChooser; private Command driveToCargo; private Command driveToHub; private Command shootThreeStart; private Command exitTarmac; /** The container for the robot. Contains subsystems, OI devices, and commands. */ public RobotContainer() { // Subsystems driveSystem = new DriveSystem(); outtake = new OuttakeSubsystem(); intake = new IntakeSubsystem(); climb = new ClimbSubsystem(); photon = new PhotonVision("camera"); limelight = new Limelight(); // Joystick driver = new Joystick(DRIVER_PORT); operator = new XboxController(OPERATOR_PORT); // Driver buttons toggleFieldOrientedBtn = new JoystickButton(driver, DRIVER_FIELD_ORIENTED_BTN); // Button 5 toggleSlowModeBtn = new JoystickButton(driver, DRIVER_SLOW_MODE_BTN); // Button 7 // Operator buttons //deployBtn = new JoystickButton(operator, OP_DEPLOY_INTAKE_BTN); // Right bumper outtakeHighBtn = new JoystickButton(operator, OP_OUTTAKE_HIGH_BTN); // Left bumper outtakeLowBtn = new Trigger(() -> { return (operator.getRightTriggerAxis() >= 0.8); }); // Right trigger intakeBtn = new JoystickButton(operator, OP_DEPLOY_INTAKE_BTN); // Right Bumper reverseIntakeBtn = new JoystickButton(operator, OP_REVERSE_INTAKE_BTN); // B Button stage2ForwardBtn = new JoystickButton(operator, OP_CLIMB_STAGE2_FORWARD_BTN); // X button stage2BackwardBtn = new JoystickButton(operator, OP_CLIMB_STAGE2_REVERSE_BTN); // Y button zeroRotatingArmBtn = new JoystickButton(driver, OP_ZERO_ROTATING_ARM_BTN); toggleSlowModeBtn = new JoystickButton(operator, OP_TOGGLE_SLOW_BTN); // Back/Select Button // Toggle Commands toggleFieldOriented = new InstantCommand(driveSystem::toggleFieldOriented, driveSystem); toggleSlowMode = new InstantCommand(driveSystem::toggleSlowMode, driveSystem); toggleTurboMode = new InstantCommand(driveSystem::toggleTurboMode, driveSystem); // Drive With Joystick driveWithJoystick = new DriveWithJoystick(driveSystem, driver); driveSystem.setDefaultCommand(driveWithJoystick); // Outtake Commands outtakeHigh = new OuttakeHigh(outtake); outtakeLow = new OuttakeLow(outtake); // Intake Commands /*retract = new Retract(intake); deploy = new Deploy(intake).andThen(new Retract(intake));*/ intakeCmd = new Intake(intake); /*reverseIntake = new ReverseIntake(intake).andThen(new Retract(intake)); intake.setDefaultCommand(retract);*/ // Drive With Joystick driveWithJoystick = new DriveWithJoystick(driveSystem, driver); driveSystem.setDefaultCommand(driveWithJoystick); // Second stage climb commands /*stage2Backwards = new ClimbStageTwoBackward(climb); stage2Forwards = new ClimbStageTwoForward(climb); zeroRotatingArm = new InstantCommand(climb::zeroRotatingArm, climb);*/ // Configure the button bindings configureButtonBindings(); //Documentation for sendables: https://docs.wpilib.org/en/latest/docs/software/telemetry/robot-telemetry-with-sendable.html SmartDashboard.putData(driveSystem); SmartDashboard.putData(outtake); SmartDashboard.putData(limelight); SmartDashboard.putData(photon); SmartDashboard.putData(climb); // Makes the autonomous chooser and associated commands autoChooser = new SendableChooser<>(); driveToCargo = new DriveToCargo(driveSystem, photon); driveToHub = new DriveToHub(driveSystem, limelight); shootThreeStart = new ShootThreeStart(outtake, driveSystem, photon, intake, limelight); exitTarmac = new DriveFunctions(driveSystem, outtake); // Add options to the smart dashboard autoChooser.setDefaultOption("Shoot 1 Cargo", driveToHub); autoChooser.addOption("Shoot 2 Cargo", driveToCargo); autoChooser.addOption("Shoot 3 Cargo", shootThreeStart); autoChooser.setDefaultOption("Shoot 1 and leave the tarmac", exitTarmac); // Sets chooser name and sends to dashboard SendableRegistry.setName(autoChooser, "Autonomous Chooser"); SmartDashboard.putData(autoChooser); } /** * Use this method to define your button->command mappings. Buttons can be created by * instantiating a {@link GenericHID} or one of its subclasses ({@link * edu.wpi.first.wpilibj.Joystick} or {@link XboxController}), and then passing it to a {@link * edu.wpi.first.wpilibj2.command.button.JoystickButton}. */ private void configureButtonBindings() { // Driver toggleFieldOrientedBtn.whenPressed(toggleFieldOriented); // Button 5 toggleSlowModeBtn.whenPressed(toggleSlowMode); // Button 7 // Operator /*deployBtn.whileHeld(deploy); // Right bumper reverseIntakeBtn.whileHeld(reverseIntake); // B button*/ intakeBtn.whileHeld(intakeCmd); outtakeHighBtn.whileHeld(outtakeHigh); // Left bumper outtakeLowBtn.whileActiveContinuous(outtakeLow); /*stage2ForwardBtn.whileHeld(stage2Forwards); // X button stage2BackwardBtn.whileHeld(stage2Backwards); // Y button zeroRotatingArmBtn.whenPressed(zeroRotatingArm);*/ } /** * Use this to pass the autonomous command to the main {@link Robot} class. * * @return the command to run in autonomous */ public Command getAutonomousCommand() { // trajectory to follow during auto var trajectory = new Trajectory(); // command to follow that trajectory return driveSystem.trajectoryCommand(trajectory); } /** * Test each subsystem with a test method and display the results on the dashboard */ public void sendTestResults() { // individual subsystem test results Map<String, Boolean> driveResults = driveSystem.test(); Map<String, Boolean> outtakeResults = outtake.test(); Map<String, Boolean> intakeResults = intake.test(); Map<String, Boolean> climbResults = climb.test(); Map<String, Boolean> photonResults = photon.test(); Map<String, Boolean> limelightResults = limelight.test(); Map<String, Boolean> results = new HashMap<>(); results.putAll(driveResults); results.putAll(outtakeResults); results.putAll(intakeResults); results.putAll(climbResults); results.putAll(photonResults); results.putAll(limelightResults); // name of every test failure String failures = ""; // iterate over all results for(Map.Entry<String, Boolean> entry: results.entrySet()) { // test mode failures will be false if (entry.getValue().booleanValue() == false) { failures += entry.getKey() + ", "; } } // send results to dashboard SmartDashboard.putString("Test Mode Failures", failures); } }
package io.github.hotspacode.neeza.agent.adapter; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.commons.AdviceAdapter; public class VoidMethodAdapter extends AdviceAdapter { private int argumentTypeSize; public VoidMethodAdapter(MethodVisitor mv, int access, String name, String desc,int argumentTypeSize) { super(ASM7, mv, access, name, desc); this.argumentTypeSize = argumentTypeSize; } /** * 方法前置 */ @Override protected void onMethodEnter() { Label l0 = new Label(); mv.visitLabel(l0); mv.visitLineNumber(10, l0); mv.visitMethodInsn(INVOKESTATIC, "java/lang/Thread", "currentThread", "()Ljava/lang/Thread;", false); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Thread", "getStackTrace", "()[Ljava/lang/StackTraceElement;", false); mv.visitInsn(ICONST_1); mv.visitInsn(AALOAD); mv.visitMethodInsn(INVOKESTATIC, "top/moxingwang/simplemock/core/api/MockApi", "getMockData", "(Ljava/lang/StackTraceElement;)Ltop/moxingwang/simplemock/core/dto/MethodSpiResponseDTO;", false); mv.visitVarInsn(ASTORE, argumentTypeSize); Label l1 = new Label(); mv.visitLabel(l1); mv.visitLineNumber(11, l1); mv.visitVarInsn(ALOAD, argumentTypeSize); mv.visitMethodInsn(INVOKEVIRTUAL, "top/moxingwang/simplemock/core/dto/MethodSpiResponseDTO", "isMocked", "()Z", false); Label l2 = new Label(); mv.visitJumpInsn(IFEQ, l2); Label l3 = new Label(); mv.visitLabel(l3); mv.visitLineNumber(12, l3); mv.visitVarInsn(ALOAD, argumentTypeSize); mv.visitMethodInsn(INVOKEVIRTUAL, "top/moxingwang/simplemock/core/dto/MethodSpiResponseDTO", "isReturnVoid", "()Z", false); mv.visitJumpInsn(IFEQ, l2); Label l4 = new Label(); mv.visitLabel(l4); mv.visitLineNumber(13, l4); mv.visitInsn(RETURN); mv.visitLabel(l2); mv.visitLineNumber(18, l2); mv.visitFrame(F_APPEND, 1, new Object[]{"top/moxingwang/simplemock/core/dto/MethodSpiResponseDTO"}, 0, null); } }
/* * 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.geode.internal; import static org.apache.geode.distributed.ConfigurationProperties.LOG_LEVEL; import static org.apache.geode.distributed.ConfigurationProperties.START_LOCATOR; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.io.RandomAccessFile; import java.io.StringWriter; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.URL; import java.net.URLDecoder; import java.net.UnknownHostException; import java.nio.file.Paths; import java.text.DateFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.zip.GZIPInputStream; import org.apache.commons.lang3.StringUtils; import org.apache.geode.GemFireException; import org.apache.geode.GemFireIOException; import org.apache.geode.InternalGemFireException; import org.apache.geode.NoSystemException; import org.apache.geode.SystemFailure; import org.apache.geode.UncreatedSystemException; import org.apache.geode.UnstartedSystemException; import org.apache.geode.admin.AdminException; import org.apache.geode.admin.internal.AdminDistributedSystemImpl; import org.apache.geode.annotations.Immutable; import org.apache.geode.annotations.internal.MakeNotStatic; import org.apache.geode.cache.persistence.PersistentID; import org.apache.geode.distributed.DistributedMember; import org.apache.geode.distributed.internal.DistributionConfig; import org.apache.geode.distributed.internal.DistributionConfigImpl; import org.apache.geode.distributed.internal.HighPriorityAckedMessage; import org.apache.geode.distributed.internal.InternalDistributedSystem; import org.apache.geode.distributed.internal.membership.InternalDistributedMember; import org.apache.geode.distributed.internal.tcpserver.TcpClient; import org.apache.geode.internal.admin.remote.TailLogResponse; import org.apache.geode.internal.cache.DiskStoreImpl; import org.apache.geode.internal.cache.backup.BackupOperation; import org.apache.geode.internal.logging.DateFormatter; import org.apache.geode.internal.logging.MergeLogFiles; import org.apache.geode.internal.net.SocketCreator; import org.apache.geode.internal.statistics.StatArchiveReader; import org.apache.geode.internal.statistics.StatArchiveReader.ResourceInst; import org.apache.geode.internal.statistics.StatArchiveReader.StatValue; import org.apache.geode.internal.util.JavaCommandBuilder; import org.apache.geode.internal.util.PluckStacks; import org.apache.geode.internal.util.PluckStacks.ThreadStack; import org.apache.geode.management.BackupStatus; /** * Provides static methods for various system administation tasks. */ public class SystemAdmin { /** * Finds the gemfire jar path element in the given classpath and returns the directory that jar is * in. */ public static File findGemFireLibDir() { URL jarURL = GemFireVersion.getJarURL(); if (jarURL == null) return null; String path = jarURL.getPath(); // Decode URL to get rid of escaped characters. See bug 32465. path = URLDecoder.decode(path); File f = new File(path); if (f.isDirectory()) { return f; } return f.getParentFile(); } // ------------------- begin: Locator methods ------------------------------ public void locatorStart(File directory, String portOption, String addressOption, String gemfirePropertiesFileOption, boolean peerOption, boolean serverOption, String hostnameForClientsOption) throws InterruptedException { // if (Thread.interrupted()) throw new InterruptedException(); not necessary checked in // locatorStart locatorStart(directory, portOption, addressOption, gemfirePropertiesFileOption, null, null, peerOption, serverOption, hostnameForClientsOption); } public void locatorStart(File directory, String portOption, String addressOption, String gemfirePropertiesFileOption, Properties propertyOptionArg, List xoptions, boolean peerOption, boolean serverOption, String hostnameForClientsOption) throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); int port = DistributionLocator.parsePort(portOption); if (addressOption == null) addressOption = ""; if (!addressOption.equals("")) { // make sure its a valid ip address if (!validLocalAddress(addressOption)) { throw new IllegalArgumentException( String.format("' %s ' is not a valid IP address for this machine", addressOption)); } } // check to see if locator is already running File logFile = new File(directory, DistributionLocator.DEFAULT_STARTUP_LOG_FILE); try { // make sure file can be opened for writing (new FileOutputStream(logFile.getPath(), true)).close(); } catch (IOException ex) { throw new GemFireIOException( String.format( "Logfile %s could not be opened for writing. Verify file permissions are correct and that another locator is not already running in the same directory.", logFile.getPath()), ex); } if (gemfirePropertiesFileOption != null) { Properties newPropOptions = new Properties();// see #43731 newPropOptions.putAll(propertyOptionArg); newPropOptions.setProperty("gemfirePropertyFile", gemfirePropertiesFileOption); propertyOptionArg = newPropOptions; } // read ssl properties Map<String, String> env = new HashMap<String, String>(); SocketCreator.readSSLProperties(env); List cmdVec = JavaCommandBuilder.buildCommand(getDistributionLocatorPath(), null, propertyOptionArg, xoptions); cmdVec.add(String.valueOf(port)); cmdVec.add(addressOption); cmdVec.add(Boolean.toString(peerOption)); cmdVec.add(Boolean.toString(serverOption)); if (hostnameForClientsOption == null) { hostnameForClientsOption = ""; } cmdVec.add(hostnameForClientsOption); String[] cmd = (String[]) cmdVec.toArray(new String[cmdVec.size()]); // start with a fresh log each time if (!logFile.delete() && logFile.exists()) { throw new GemFireIOException("Unable to delete " + logFile.getAbsolutePath()); } boolean treatAsPure = true; /** * A counter used by PureJava to determine when its waited too long to start the locator * process. countDown * 250 = how many seconds to wait before giving up. **/ int countDown = 60; // NYI: wait around until we can attach while (!ManagerInfo.isLocatorStarted(directory)) { countDown--; Thread.sleep(250); if (countDown < 0) { try { String msg = tailFile(logFile, false); throw new GemFireIOException( String.format("Start of locator failed. The end of %s contained this message: %s.", logFile, msg), null); } catch (IOException ignore) { throw new GemFireIOException( String.format("Start of locator failed. Check end of %s for reason.", logFile), null); } } Thread.sleep(500); } } /** get the path to the distribution locator class */ protected String getDistributionLocatorPath() { return "org.apache.geode.internal.DistributionLocator"; } /** * enumerates all available local network addresses to find a match with the given address. * Returns false if the address is not usable on the current machine */ public static boolean validLocalAddress(String bindAddress) { InetAddress addr = null; try { addr = InetAddress.getByName(bindAddress); } catch (UnknownHostException ex) { return false; } try { Enumeration en = NetworkInterface.getNetworkInterfaces(); while (en.hasMoreElements()) { NetworkInterface ni = (NetworkInterface) en.nextElement(); Enumeration en2 = ni.getInetAddresses(); while (en2.hasMoreElements()) { InetAddress check = (InetAddress) en2.nextElement(); if (check.equals(addr)) { return true; } } } } catch (SocketException sex) { return true; // can't query the interfaces - punt } return false; } @SuppressWarnings("hiding") public void locatorStop(File directory, String portOption, String addressOption, Properties propertyOption) throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); InetAddress addr = null; // fix for bug 30810 if (addressOption == null) addressOption = ""; if (!addressOption.equals("")) { // make sure its a valid ip address try { addr = InetAddress.getByName(addressOption); } catch (UnknownHostException ex) { throw new IllegalArgumentException( String.format("-address value was not a known IP address: %s", ex)); } } if (propertyOption != null) { Iterator iter = propertyOption.keySet().iterator(); while (iter.hasNext()) { String key = (String) iter.next(); System.setProperty(key, propertyOption.getProperty(key)); } } int port = DistributionLocator.parsePort(portOption); int pid = 0; try { ManagerInfo info = ManagerInfo.loadLocatorInfo(directory); pid = info.getManagerProcessId(); if (portOption == null || portOption.trim().length() == 0) { port = info.getManagerPort(); } if (addressOption.trim().length() == 0) { addr = info.getManagerAddress(); } try { new TcpClient().stop(addr, port); } catch (java.net.ConnectException ce) { System.out.println( "Unable to connect to Locator process. Possible causes are that an incorrect bind address/port combination was specified to the stop-locator command or the process is unresponsive."); return; } // wait for the locator process to go away // format and change message if (!quiet) { System.out.println( "Waiting 5 seconds for locator process to terminate..."); } Thread.sleep(5000); } catch (UnstartedSystemException ex) { // fix for bug 28133 throw new UnstartedSystemException( String.format("Locator in directory %s is not running.", directory)); } catch (NoSystemException ex) { // before returning see if a stale lock file/shared memory can be cleaned up cleanupAfterKilledLocator(directory); throw ex; } } /** * Gets the status of a locator. * * @param directory the locator's directory * @return the status string. Will be one of the following: "running", "killed", "stopped", * "stopping", or "starting". * @throws UncreatedSystemException if the locator <code>directory</code> does not exist or is not * a directory. * @throws GemFireIOException if the manager info exists but could not be read. This probably * means that the info file is corrupt. */ public String locatorStatus(File directory) { return ManagerInfo.getLocatorStatusCodeString(directory); } /** * Gets information on the locator. * * @param directory the locator's directory * @return information string. * @throws UncreatedSystemException if the locator <code>directory</code> does not exist or is not * a directory. * @throws GemFireIOException if the manager info exists but could not be read. This probably * means that the info file is corrupt. */ public String locatorInfo(File directory) { int statusCode = ManagerInfo.getLocatorStatusCode(directory); String statusString = ManagerInfo.statusToString(statusCode); try { ManagerInfo mi = ManagerInfo.loadLocatorInfo(directory); if (statusCode == ManagerInfo.KILLED_STATUS_CODE) { return String.format("Locator in %s was killed while it was %s. Locator process id was %s.", directory, ManagerInfo.statusToString(mi.getManagerStatus()), Integer.valueOf(mi.getManagerProcessId())); } else { return String.format("Locator in %s is %s. Locator process id is %s.", directory, statusString, Integer.valueOf(mi.getManagerProcessId())); } } catch (UnstartedSystemException ex) { return String.format("Locator in %s is stopped.", directory); } catch (GemFireIOException ex) { return String.format("Locator in %s is starting.", directory); } } /** * Cleans up any artifacts left by a killed locator. Namely the info file is deleted. */ private static void cleanupAfterKilledLocator(File directory) { try { if (ManagerInfo.getLocatorStatusCode(directory) == ManagerInfo.KILLED_STATUS_CODE) { File infoFile = ManagerInfo.getLocatorInfoFile(directory); if (infoFile.exists()) { if (!infoFile.delete() && infoFile.exists()) { System.out.println("WARNING: unable to delete " + infoFile.getAbsolutePath()); } if (!quiet) { System.out.println( "Cleaned up artifacts left by the previous killed locator."); } } } } catch (GemFireException ignore) { } } /** * Tails the end of the locator's log file * * @since GemFire 4.0 */ public String locatorTailLog(File directory) { File logFile = new File(directory, DistributionLocator.DEFAULT_LOG_FILE); if (!logFile.exists()) { return String.format("Log file %s does not exist.", logFile); } try { return TailLogResponse.tailSystemLog(logFile); } catch (IOException ex) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); sw.write(String.format("An IOException was thrown while tailing %s", logFile)); ex.printStackTrace(pw); pw.flush(); return sw.toString(); } } // -------------------- end: Locator methods ------------------------------- public static void compactDiskStore(String... args) { compactDiskStore(Arrays.asList(args)); } public static void compactDiskStore(List args) { String diskStoreName = (String) args.get(0); List dirList = args.subList(1, args.size()); File[] dirs = new File[dirList.size()]; Iterator it = dirList.iterator(); int idx = 0; while (it.hasNext()) { dirs[idx] = new File((String) it.next()); idx++; } try { DiskStoreImpl.offlineCompact(diskStoreName, dirs, false, maxOplogSize); } catch (Exception ex) { throw new GemFireIOException(" disk-store=" + diskStoreName + ": " + ex, ex); } } public static void upgradeDiskStore(List args) { String diskStoreName = (String) args.get(0); List dirList = args.subList(1, args.size()); File[] dirs = new File[dirList.size()]; Iterator it = dirList.iterator(); int idx = 0; while (it.hasNext()) { dirs[idx] = new File((String) it.next()); idx++; } try { DiskStoreImpl.offlineCompact(diskStoreName, dirs, true, maxOplogSize); } catch (Exception ex) { throw new GemFireIOException(" disk-store=" + diskStoreName + ": " + ex, ex); } } public static void compactAllDiskStores(List args) throws AdminException { InternalDistributedSystem ads = getAdminCnx(); Map<DistributedMember, Set<PersistentID>> status = AdminDistributedSystemImpl.compactAllDiskStores(ads.getDistributionManager()); System.out.println("Compaction complete."); System.out.println("The following disk stores compacted some files:"); for (Set<PersistentID> memberStores : status.values()) { for (PersistentID store : memberStores) { System.out.println("\t" + store); } } } public static void validateDiskStore(String... args) { validateDiskStore(Arrays.asList(args)); } public static void validateDiskStore(List args) { String diskStoreName = (String) args.get(0); List dirList = args.subList(1, args.size()); File[] dirs = new File[dirList.size()]; Iterator it = dirList.iterator(); int idx = 0; while (it.hasNext()) { dirs[idx] = new File((String) it.next()); idx++; } try { DiskStoreImpl.validate(diskStoreName, dirs); } catch (Exception ex) { throw new GemFireIOException(" disk-store=" + diskStoreName + ": " + ex, ex); } } private static InternalDistributedSystem getAdminCnx() { InternalDistributedSystem.setCommandLineAdmin(true); Properties props = propertyOption; props.setProperty(LOG_LEVEL, "warning"); DistributionConfigImpl dsc = new DistributionConfigImpl(props); System.out.print("Connecting to distributed system:"); if (!"".equals(dsc.getLocators())) { System.out.println(" locators=" + dsc.getLocators()); } else { System.out.println(" mcast=" + dsc.getMcastAddress() + ":" + dsc.getMcastPort()); } InternalDistributedSystem ds = (InternalDistributedSystem) InternalDistributedSystem.connectForAdmin(props); Set existingMembers = ds.getDistributionManager().getDistributionManagerIds(); if (existingMembers.isEmpty()) { throw new RuntimeException("There are no members in the distributed system"); } return ds; } public static void shutDownAll(ArrayList<String> cmdLine) { try { long timeout = 0; if (cmdLine.size() > 0) { timeout = Long.parseLong(cmdLine.get(0)); } InternalDistributedSystem ads = getAdminCnx(); Set members = AdminDistributedSystemImpl.shutDownAllMembers(ads.getDistributionManager(), timeout); int count = members == null ? 0 : members.size(); if (members == null) { System.err .println("Unable to shut down the distributed system in the specified amount of time."); } else if (count == 0) { System.err.println("The distributed system had no members to shut down."); } else if (count == 1) { System.out.println("Successfully shut down one member"); } else { System.out.println("Successfully shut down " + count + " members"); } } catch (Exception ex) { throw new GemFireIOException(ex.toString(), ex); } } /** * this is a test hook to allow us to drive SystemAdmin functions without invoking main(), which * can call System.exit(). * */ public static void setDistributedSystemProperties(Properties props) { propertyOption = props; } public static void printStacks(List<String> cmdLine, boolean allStacks) { try { InternalDistributedSystem ads = getAdminCnx(); HighPriorityAckedMessage msg = new HighPriorityAckedMessage(); OutputStream os; PrintWriter ps; File outputFile = null; if (cmdLine.size() > 0) { outputFile = new File(cmdLine.get(0)); os = new FileOutputStream(outputFile); ps = new PrintWriter(os); } else { os = System.out; ps = new PrintWriter(System.out); } Map<InternalDistributedMember, byte[]> dumps = msg.dumpStacks(ads.getDistributionManager().getAllOtherMembers(), false, true); for (Map.Entry<InternalDistributedMember, byte[]> entry : dumps.entrySet()) { ps.append("--- dump of stack for member " + entry.getKey() + " ------------------------------------------------------------------------------\n"); ps.flush(); GZIPInputStream zipIn = new GZIPInputStream(new ByteArrayInputStream(entry.getValue())); if (allStacks) { BufferedInputStream bin = new BufferedInputStream(zipIn); byte[] buffer = new byte[10000]; int count; while ((count = bin.read(buffer)) != -1) { os.write(buffer, 0, count); } ps.append('\n'); } else { BufferedReader reader = new BufferedReader(new InputStreamReader(zipIn)); List<ThreadStack> stacks = (new PluckStacks()).getStacks(reader); for (ThreadStack s : stacks) { s.writeTo(ps); ps.append('\n'); } ps.append('\n'); } } ps.flush(); os.close(); if (outputFile != null) { System.out.println(dumps.size() + " stack dumps written to " + outputFile.getName()); } } catch (Exception ex) { throw new GemFireIOException(ex.toString(), ex); } } public static void backup(String targetDir) throws AdminException { InternalDistributedSystem ads = getAdminCnx(); // Baseline directory should be null if it was not provided on the command line BackupStatus status = new BackupOperation(ads.getDistributionManager(), ads.getCache()).backupAllMembers( targetDir, SystemAdmin.baselineDir); boolean incomplete = !status.getOfflineDiskStores().isEmpty(); System.out.println("The following disk stores were backed up:"); for (Set<PersistentID> memberStores : status.getBackedUpDiskStores().values()) { for (PersistentID store : memberStores) { System.out.println("\t" + store); } } if (incomplete) { System.err.println("The backup may be incomplete. The following disk stores are not online:"); for (PersistentID store : status.getOfflineDiskStores()) { System.err.println("\t" + store); } } else { System.out.println("Backup successful."); } } public static void listMissingDiskStores() throws AdminException { InternalDistributedSystem ads = getAdminCnx(); Set s = AdminDistributedSystemImpl.getMissingPersistentMembers(ads.getDistributionManager()); if (s.isEmpty()) { System.out.println("The distributed system did not have any missing disk stores"); } else { for (Object o : s) { System.out.println(o); } } } private static File[] argsToFile(Collection<String> args) { File[] dirs = new File[args.size()]; int i = 0; for (String dir : args) { dirs[i++] = new File(dir); } return dirs; } public static void showDiskStoreMetadata(ArrayList<String> args) { String dsName = args.get(0); File[] dirs = argsToFile(args.subList(1, args.size())); try { DiskStoreImpl.dumpMetadata(dsName, dirs, showBuckets); } catch (Exception ex) { throw new GemFireIOException(" disk-store=" + dsName + ": " + ex, ex); } } public static void exportDiskStore(ArrayList<String> args, String outputDir) { File out = outputDir == null ? new File(".") : new File(outputDir); if (!out.exists()) { out.mkdirs(); } String dsName = args.get(0); File[] dirs = argsToFile(args.subList(1, args.size())); try { DiskStoreImpl.exportOfflineSnapshot(dsName, dirs, out); } catch (Exception ex) { throw new GemFireIOException(" disk-store=" + dsName + ": " + ex, ex); } } public static void revokeMissingDiskStores(ArrayList<String> cmdLine) throws UnknownHostException, AdminException { String uuidString = cmdLine.get(0); UUID uuid = UUID.fromString(uuidString); InternalDistributedSystem ads = getAdminCnx(); AdminDistributedSystemImpl.revokePersistentMember(ads.getDistributionManager(), uuid); Set<PersistentID> s = AdminDistributedSystemImpl.getMissingPersistentMembers(ads.getDistributionManager()); // Fix for 42607 - wait to see if the revoked member goes way if it is still in the set of // missing members. It may take a moment to clear the missing member set after the revoke. long start = System.currentTimeMillis(); while (containsRevokedMember(s, uuid)) { try { Thread.sleep(1000); } catch (InterruptedException ignore) { } s = AdminDistributedSystemImpl.getMissingPersistentMembers(ads.getDistributionManager()); if (start + 30000 < System.currentTimeMillis()) { break; } } if (s.isEmpty()) { System.out.println("revocation was successful and no disk stores are now missing"); } else { System.out.println("The following disk stores are still missing:"); for (Object o : s) { System.out.println(o); } } } private static boolean containsRevokedMember(Set<PersistentID> missing, UUID revokedUUID) { for (PersistentID id : missing) { if (id.getUUID().equals(revokedUUID)) { return true; } } return false; } public static void modifyDiskStore(String... args) { modifyDiskStore(Arrays.asList(args)); } public static void modifyDiskStore(List args) { String diskStoreName = (String) args.get(0); List dirList = args.subList(1, args.size()); File[] dirs = new File[dirList.size()]; Iterator it = dirList.iterator(); int idx = 0; while (it.hasNext()) { dirs[idx] = new File((String) it.next()); idx++; } try { if (lruOption != null || lruActionOption != null || lruLimitOption != null || concurrencyLevelOption != null || initialCapacityOption != null || loadFactorOption != null || compressorClassNameOption != null || statisticsEnabledOption != null) { if (regionOption == null) { throw new IllegalArgumentException("modify-disk-store requires -region=<regionName>"); } if (remove) { throw new IllegalArgumentException( "the -remove option can not be used with the other modify options."); } DiskStoreImpl.modifyRegion(diskStoreName, dirs, regionOption, lruOption, lruActionOption, lruLimitOption, concurrencyLevelOption, initialCapacityOption, loadFactorOption, compressorClassNameOption, statisticsEnabledOption, null/* offHeap */, true); System.out.println("The region " + regionOption + " was successfully modified in the disk store " + diskStoreName); } else if (remove) { if (regionOption == null) { throw new IllegalArgumentException("modify-disk-store requires -region=<regionName>"); } DiskStoreImpl.destroyRegion(diskStoreName, dirs, regionOption); System.out.println("The region " + regionOption + " was successfully removed from the disk store " + diskStoreName); } else { DiskStoreImpl.dumpInfo(System.out, diskStoreName, dirs, regionOption, null); if (regionOption == null) { System.out.println("Please specify -region=<regionName> and a modify option."); } else { System.out.println("Please specify a modify option."); } } } catch (Exception ex) { throw new GemFireIOException(" disk-store=" + diskStoreName + ": " + ex, ex); } } public void mergeLogs(String outOption, List<String> args) { Map<String, InputStream> inputs = new HashMap<>(); PrintStream ps; if (outOption != null) { try { ps = new PrintStream(new FileOutputStream(outOption)); } catch (FileNotFoundException ex) { throw new GemFireIOException( String.format("Could not create file %s for output because %s", outOption, getExceptionMessage(ex))); } } else { ps = System.out; } PrintWriter mergedFile = new PrintWriter(ps, true); List<String> normalizedFiles = args.stream().map(f -> Paths.get(f).toAbsolutePath().toString()).collect( Collectors.toList()); int prefixLength = StringUtils.getCommonPrefix(normalizedFiles.toArray(new String[] {})).length(); if (!quiet) { ps.println("Merging the following log files:"); } for (String fileName : normalizedFiles) { try { String shortName = fileName.substring(prefixLength); inputs.put(shortName, new FileInputStream(fileName)); } catch (FileNotFoundException ex) { throw new GemFireIOException( String.format("Could not open to %s for reading because %s", fileName, getExceptionMessage(ex))); } if (!quiet) { ps.println(" " + fileName); } } if (MergeLogFiles.mergeLogFiles(inputs, mergedFile)) { throw new GemFireIOException( "trouble merging log files."); } mergedFile.flush(); if (outOption != null) { mergedFile.close(); } if (!quiet) { System.out .println(String.format("Completed merge of %s logs to %s.", args.size(), ((outOption != null) ? outOption : "stdout"))); } } /** * Returns the contents located at the end of the file as a string. * * @throws IOException if the file can not be opened or read */ public String tailFile(File file, boolean problemsOnly) throws IOException { byte buffer[] = new byte[128000]; int readSize = buffer.length; RandomAccessFile f = new RandomAccessFile(file, "r"); long length = f.length(); if (length < readSize) { readSize = (int) length; } long seekOffset = length - readSize; f.seek(seekOffset); if (readSize != f.read(buffer, 0, readSize)) { throw new EOFException( "Failed to read " + readSize + " bytes from " + file.getAbsolutePath()); } f.close(); // Now look for the last message header int msgStart = -1; int msgEnd = readSize; for (int i = readSize - 1; i >= 0; i--) { if (buffer[i] == '[' && (buffer[i + 1] == 's' || buffer[i + 1] == 'e' || buffer[i + 1] == 'w' /* ignore all messages except severe, error, and warning to fix bug 28968 */) && i > 0 && (buffer[i - 1] == '\n' || buffer[i - 1] == '\r')) { msgStart = i; break; } } if (msgStart == -1) { if (problemsOnly) { return null; } // Could not find message start. Show last line instead. for (int i = readSize - 3; i >= 0; i--) { if (buffer[i] == '\n' || buffer[i] == '\r') { msgStart = (buffer[i] == '\n') ? (i + 1) : (i + 2); break; } } if (msgStart == -1) { // Could not find line so show entire buffer msgStart = 0; } } else { // try to find the start of the next message and get rid of it for (int i = msgStart + 1; i < readSize; i++) { if (buffer[i] == '[' && (buffer[i - 1] == '\n' || buffer[i - 1] == '\r')) { msgEnd = i; break; } } } for (int i = msgStart; i < msgEnd; i++) { if (buffer[i] == '\n' || buffer[i] == '\r') { buffer[i] = ' '; } } return new String(buffer, msgStart, msgEnd - msgStart); } protected void format(PrintWriter pw, String msg, String linePrefix, int initialLength) { final int maxWidth = 79; boolean firstLine = true; int lineLength = 0; final int prefixLength = linePrefix.length(); int idx = 0; while (idx < msg.length()) { if (lineLength == 0) { if (isBreakChar(msg, idx)) { // skip over only lead break characters idx++; continue; } pw.print(linePrefix); lineLength += prefixLength; if (firstLine) { firstLine = false; lineLength += initialLength; } } if (msg.charAt(idx) == '\n' || msg.charAt(idx) == '\r') { pw.println(); lineLength = 0; if (msg.charAt(idx) == '\r') { idx += 2; } else { idx++; } } else if (msg.charAt(idx) == ' ' && idx > 0 && msg.charAt(idx - 1) == '.' && idx < (msg.length() - 1) && msg.charAt(idx + 1) == ' ') { // treat ". " as a hardbreak pw.println(); lineLength = 0; idx += 2; } else { String word = msg.substring(idx, findWordBreak(msg, idx)); if (lineLength == prefixLength || (word.length() + lineLength) <= maxWidth) { pw.print(word); lineLength += word.length(); idx += word.length(); } else { // no room on current line. So start a new line. pw.println(); lineLength = 0; } } } if (lineLength != 0) { pw.println(); } } private static final char breakChars[] = new char[] {' ', '\t', '\n', '\r'}; private static boolean isBreakChar(String str, int idx) { char c = str.charAt(idx); for (int i = 0; i < breakChars.length; i++) { if (c == breakChars[i]) { return true; } } return false; } private static int findWordBreak(String str, int fromIdx) { int result = str.length(); for (int i = 0; i < breakChars.length; i++) { int tmp = str.indexOf(breakChars[i], fromIdx + 1); if (tmp > fromIdx && tmp < result) { result = tmp; } } return result; } public static class StatSpec implements StatArchiveReader.StatSpec { public final String cmdLineSpec; public final String typeId; public final String instanceId; public final String statId; private final Pattern tp; private final Pattern sp; private final Pattern ip; private final int combineType; public StatSpec(String cmdLineSpec) { this.cmdLineSpec = cmdLineSpec; if (cmdLineSpec.charAt(0) == '+') { cmdLineSpec = cmdLineSpec.substring(1); if (cmdLineSpec.charAt(0) == '+') { cmdLineSpec = cmdLineSpec.substring(1); this.combineType = GLOBAL; } else { this.combineType = FILE; } } else { this.combineType = NONE; } int dotIdx = cmdLineSpec.lastIndexOf('.'); String typeId = null; String instanceId = null; String statId = null; if (dotIdx != -1) { statId = cmdLineSpec.substring(dotIdx + 1); cmdLineSpec = cmdLineSpec.substring(0, dotIdx); } int commaIdx = cmdLineSpec.indexOf(':'); if (commaIdx != -1) { instanceId = cmdLineSpec.substring(0, commaIdx); typeId = cmdLineSpec.substring(commaIdx + 1); } else { instanceId = cmdLineSpec; } if (statId == null || statId.length() == 0) { this.statId = ""; this.sp = null; } else { this.statId = statId; this.sp = Pattern.compile(statId, Pattern.CASE_INSENSITIVE); } if (typeId == null || typeId.length() == 0) { this.typeId = ""; this.tp = null; } else { this.typeId = typeId; this.tp = Pattern.compile(".*" + typeId, Pattern.CASE_INSENSITIVE); } if (instanceId == null || instanceId.length() == 0) { this.instanceId = ""; this.ip = null; } else { this.instanceId = instanceId; this.ip = Pattern.compile(instanceId, Pattern.CASE_INSENSITIVE); } } @Override public String toString() { return "StatSpec instanceId=" + this.instanceId + " typeId=" + this.typeId + " statId=" + this.statId; } @Override public int getCombineType() { return this.combineType; } @Override public boolean archiveMatches(File archive) { return true; } @Override public boolean statMatches(String statName) { if (this.sp == null) { return true; } else { Matcher m = this.sp.matcher(statName); return m.matches(); } } @Override public boolean typeMatches(String typeName) { if (this.tp == null) { return true; } else { Matcher m = this.tp.matcher(typeName); return m.matches(); } } @Override public boolean instanceMatches(String textId, long numericId) { if (this.ip == null) { return true; } else { Matcher m = this.ip.matcher(textId); if (m.matches()) { return true; } m = this.ip.matcher(String.valueOf(numericId)); return m.matches(); } } } private static StatSpec[] createSpecs(List cmdLineSpecs) { StatSpec[] result = new StatSpec[cmdLineSpecs.size()]; Iterator it = cmdLineSpecs.iterator(); int idx = 0; while (it.hasNext()) { result[idx] = new StatSpec((String) it.next()); idx++; } return result; } private static void printStatValue(StatArchiveReader.StatValue v, long startTime, long endTime, boolean nofilter, boolean persec, boolean persample, boolean prunezeros, boolean details) { v = v.createTrimmed(startTime, endTime); if (nofilter) { v.setFilter(StatArchiveReader.StatValue.FILTER_NONE); } else if (persec) { v.setFilter(StatArchiveReader.StatValue.FILTER_PERSEC); } else if (persample) { v.setFilter(StatArchiveReader.StatValue.FILTER_PERSAMPLE); } if (prunezeros) { if (v.getSnapshotsMinimum() == 0.0 && v.getSnapshotsMaximum() == 0.0) { return; } } System.out.println(" " + v.toString()); if (details) { System.out.print(" values="); double[] snapshots = v.getSnapshots(); for (int i = 0; i < snapshots.length; i++) { System.out.print(' '); System.out.print(snapshots[i]); } System.out.println(); String desc = v.getDescriptor().getDescription(); if (desc != null && desc.length() > 0) { System.out.println(" " + desc); } } } /** * List the statistics of a running system. * * @param directory the system directory of the system to list. * @param archiveNames the archive file(s) to read. * @param details if true the statistic descriptions will also be listed. * @param nofilter if true then printed stat values will all be raw unfiltered. * @param persec if true then printed stat values will all be the rate of change, per second, of * the raw values. * @param persample if true then printed stat values will all be the rate of change, per sample, * of the raw values. * @param prunezeros if true then stat values whose samples are all zero will not be printed. * * @throws UncreatedSystemException if the system <code>sysDir</code> does not exist, is not a * directory, or does not contain a configuration file. * @throws NoSystemException if the system is not running or could not be connected to. * @throws IllegalArgumentException if a statSpec does not match a resource and/or statistic. * @throws GemFireIOException if the archive could not be read */ public void statistics(File directory, List archiveNames, boolean details, boolean nofilter, boolean persec, boolean persample, boolean prunezeros, boolean monitor, long startTime, long endTime, List cmdLineSpecs) { if (persec && nofilter) { throw new IllegalArgumentException( "The -nofilter and -persec options are mutually exclusive."); } if (persec && persample) { throw new IllegalArgumentException( "The -persample and -persec options are mutually exclusive."); } if (nofilter && persample) { throw new IllegalArgumentException( "The -persample and -nofilter options are mutually exclusive."); } StatSpec[] specs = createSpecs(cmdLineSpecs); if (archiveOption != null) { if (directory != null) { throw new IllegalArgumentException( "The -archive= and -dir= options are mutually exclusive."); } StatArchiveReader reader = null; boolean interrupted = false; try { reader = new StatArchiveReader((File[]) archiveNames.toArray(new File[archiveNames.size()]), specs, !monitor); // Runtime.getRuntime().gc(); System.out.println("DEBUG: heap size=" + // (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())); if (specs.length == 0) { if (details) { StatArchiveReader.StatArchiveFile[] archives = reader.getArchives(); for (int i = 0; i < archives.length; i++) { System.out.println(archives[i].getArchiveInfo().toString()); } } } do { if (specs.length == 0) { Iterator it = reader.getResourceInstList().iterator(); while (it.hasNext()) { ResourceInst inst = (ResourceInst) it.next(); StatValue values[] = inst.getStatValues(); boolean firstTime = true; for (int i = 0; i < values.length; i++) { if (values[i] != null && values[i].hasValueChanged()) { if (firstTime) { firstTime = false; System.out.println(inst.toString()); } printStatValue(values[i], startTime, endTime, nofilter, persec, persample, prunezeros, details); } } } } else { Map<CombinedResources, List<StatValue>> allSpecsMap = new HashMap<CombinedResources, List<StatValue>>(); for (int i = 0; i < specs.length; i++) { StatValue[] values = reader.matchSpec(specs[i]); if (values.length == 0) { if (!quiet) { System.err.println(String.format("[warning] No stats matched %s.", specs[i].cmdLineSpec)); } } else { Map<CombinedResources, List<StatValue>> specMap = new HashMap<CombinedResources, List<StatValue>>(); for (StatValue v : values) { CombinedResources key = new CombinedResources(v); List<StatArchiveReader.StatValue> list = specMap.get(key); if (list != null) { list.add(v); } else { specMap.put(key, new ArrayList<StatValue>(Collections.singletonList(v))); } } if (!quiet) { System.out.println( String.format("[info] Found %s instances matching %s:", new Object[] {Integer.valueOf(specMap.size()), specs[i].cmdLineSpec})); } for (Map.Entry<CombinedResources, List<StatValue>> me : specMap.entrySet()) { List<StatArchiveReader.StatValue> list = allSpecsMap.get(me.getKey()); if (list != null) { list.addAll(me.getValue()); } else { allSpecsMap.put(me.getKey(), me.getValue()); } } } } for (Map.Entry<CombinedResources, List<StatValue>> me : allSpecsMap.entrySet()) { System.out.println(me.getKey()); for (StatValue v : me.getValue()) { printStatValue(v, startTime, endTime, nofilter, persec, persample, prunezeros, details); } } } if (monitor) { while (!reader.update()) { try { Thread.sleep(1000); } catch (InterruptedException ignore) { interrupted = true; } } } } while (monitor && !interrupted); } catch (IOException ex) { throw new GemFireIOException( String.format("Failed reading %s", archiveOption), ex); } finally { if (reader != null) { try { reader.close(); } catch (IOException ignore) { } } if (interrupted) { Thread.currentThread().interrupt(); } } } } /** * Represents a list of ResourceInst that have been combined together. Note the most common case * is for this class to only own a single ResourceInst. * */ @SuppressWarnings("serial") private static class CombinedResources extends ArrayList<ResourceInst> { public CombinedResources(StatValue v) { super(Arrays.asList(v.getResources())); } @Override public String toString() { StringBuffer sb = new StringBuffer(); boolean first = true; for (ResourceInst inst : this) { if (first) { first = false; } else { sb.append(" + "); } sb.append(inst); } return sb.toString(); } } public SystemAdmin() { // register DSFID types first; invoked explicitly so that all message type // initializations do not happen in first deserialization on a possibly // "precious" thread DSFIDFactory.registerTypes(); } private static final String[] helpTopics = new String[] {"all", "overview", "commands", "options", "usage", "configuration"}; protected void printHelpTopic(String topic, PrintWriter pw) { if (topic.equalsIgnoreCase("all")) { for (int i = 0; i < helpTopics.length; i++) { if (!helpTopics[i].equals("all")) { pw.println("-------- " + helpTopics[i] + " --------"); printHelpTopic(helpTopics[i], pw); } } } else if (topic.equalsIgnoreCase("overview")) { pw.println( String.format( "This program allows GemFire to be managed from the command line. It expects a command to execute.See the help topic %s. For a summary of supported options see the help topic %s.For a concise description of command line syntax see the help topic %s.For a description of system configuration see the help topic %s.For help on a specific command use the %s option with the command name.", new Object[] {"commands", "options", "usage", "configuration", "-h"})); } else if (topic.equalsIgnoreCase("commands")) { pw.println(usageMap.get("gemfire") + " <command> ..."); format(pw, (String) helpMap.get("gemfire"), " ", 0); for (int i = 0; i < validCommands.length; i++) { pw.println((String) usageMap.get(validCommands[i])); if (helpMap.get(validCommands[i]) == null) { pw.println(" (help message missing for " + validCommands[i] + ")"); } else { format(pw, (String) helpMap.get(validCommands[i]), " ", 0); } } } else if (topic.equalsIgnoreCase("options")) { pw.println( "All command line options start with a - and are not required.Each option has a default that will be used when its not specified.Options that take an argument always use a single = character, with no spaces, to delimit where the option name ends and the argument begins.Options that precede the command word can be used with any command and are also permitted to follow the command word."); for (int i = 0; i < validOptions.length; i++) { pw.print(validOptions[i] + ":"); try { format(pw, (String) helpMap.get(validOptions[i]), " ", validOptions[i].length() + 1); } catch (RuntimeException ex) { System.err.println( String.format("no help for option %s]", validOptions[i])); throw ex; } } } else if (topic.equalsIgnoreCase("usage")) { pw.println( "The following synax is used in the usage strings:[] designate an optional item() are used to group items<> designate non-literal text. Used to designate logical items* suffix means zero or more of the previous item| means the item to the left or right is required"); for (int i = 0; i < validCommands.length; i++) { pw.println(getUsageString(validCommands[i])); } } } protected void help(List args) { String topic = "overview"; if (args.size() > 0) { topic = (String) args.get(0); if (!Arrays.asList(helpTopics).contains(topic.toLowerCase())) { System.err.println( String.format("ERROR: Invalid help topic %s.", topic)); usage(); } } PrintWriter pw = new PrintWriter(System.out); printHelpTopic(topic, pw); pw.flush(); if (args.size() == 0) { usage("help"); } } protected void usage() { usage(null); } protected String getUsageString(String cmd) { StringBuffer result = new StringBuffer(80); result.append(usageMap.get("gemfire")).append(' '); if (cmd == null || cmd.equalsIgnoreCase("gemfire")) { result.append(join(Arrays.asList(validCommands), "|")).append(" ..."); } else { result.append(usageMap.get(cmd.toLowerCase())); } return result.toString(); } protected void usage(String cmd) { System.err.println( "Usage " + getUsageString(cmd)); ExitCode.FATAL.doSystemExit(); } private static final String[] validCommands = new String[] {"version", "stats", START_LOCATOR, "stop-locator", "status-locator", "info-locator", "tail-locator-log", "merge-logs", "revoke-missing-disk-store", "list-missing-disk-stores", "validate-disk-store", "upgrade-disk-store", "compact-disk-store", "compact-all-disk-stores", "modify-disk-store", "show-disk-store-metadata", "export-disk-store", "shut-down-all", "backup", "print-stacks", "help"}; protected static String[] getValidCommands() { return validCommands.clone(); } private static final String[] aliasCommands = new String[] {"locator-start", "locator-stop", "locator-status", "locator-info", "locator-tail-log", "logs-merge", "shutdown-all", "shutdownall", "compact", "modify", "validate"}; private static final String[] validOptions = new String[] {"-address=", "-archive=", "-concurrencyLevel=", "-debug", "-remove", "-details", "-dir=", "-endtime=", "-h", "-help", "-initialCapacity=", "-loadFactor=", "-lru=", "-lruAction=", "-lruLimit=", "-maxOplogSize=", "-properties=", "-monitor", "-nofilter", "-persample", "-persec", "-out=", "-port=", "-prunezeros", "-region=", "-starttime=", "-statisticsEnabled=", "-peer=", "-server=", "-q", "-D", "-X", "-outputDir="}; protected String checkCmd(String theCmd) { String cmd = theCmd; if (!Arrays.asList(validCommands).contains(cmd.toLowerCase())) { if (!Arrays.asList(aliasCommands).contains(cmd.toLowerCase())) { System.err .println(String.format("ERROR: Invalid command %s.", cmd)); usage(); } else { if (cmd.equalsIgnoreCase("locator-start")) { cmd = START_LOCATOR; } else if (cmd.equalsIgnoreCase("locator-stop")) { cmd = "stop-locator"; } else if (cmd.equalsIgnoreCase("locator-info")) { cmd = "info-locator"; } else if (cmd.equalsIgnoreCase("locator-status")) { cmd = "status-locator"; } else if (cmd.equalsIgnoreCase("locator-tail-log")) { cmd = "tail-locator-log"; } else if (cmd.equalsIgnoreCase("logs-merge")) { cmd = "merge-logs"; } else if (cmd.equalsIgnoreCase("shutdownall")) { cmd = "shut-down-all"; } else if (cmd.equalsIgnoreCase("shutdown-all")) { cmd = "shut-down-all"; } else if (cmd.equalsIgnoreCase("upgrade")) { cmd = "upgrade-disk-store"; } else if (cmd.equalsIgnoreCase("compact")) { cmd = "compact-disk-store"; } else if (cmd.equalsIgnoreCase("modify")) { cmd = "modify-disk-store"; } else if (cmd.equalsIgnoreCase("validate")) { cmd = "validate-disk-store"; } else { throw new InternalGemFireException( String.format("Unhandled alias %s", cmd)); } } } return cmd; } public static String join(Object[] a) { return join(a, " "); } public static String join(Object[] a, String joinString) { return join(Arrays.asList(a), joinString); } public static String join(List l) { return join(l, " "); } public static String join(List l, String joinString) { StringBuffer result = new StringBuffer(80); boolean firstTime = true; Iterator it = l.iterator(); while (it.hasNext()) { if (firstTime) { firstTime = false; } else { result.append(joinString); } result.append(it.next()); } return result.toString(); } protected final Map helpMap = new HashMap(); protected void initHelpMap() { helpMap.put("gemfire", "GemFire requires one of the following command strings: " + join(validCommands) + ". For additional help on a command specify it along with the '-h' option. " + "The '-debug' option causes gemfire to print out extra information when it fails. " + "The '-h' and '-help' are synonyms that cause gemfire to print out help information instead of performing a task. " + "The '-q' option quiets GemFire down by suppressing extra messages. The '-J<vmOpt>' option passes <vmOpt> to the Java VM's command line."); helpMap.put("version", "Prints GemFire product version information."); helpMap.put("help", "Prints information on how to use this executable. If an optional help topic is specified then more detailed help is printed."); helpMap.put("stats", "Prints statistic values from a statistic archive. By default all statistics are printed.\n" + "The 'statSpec' arguments can be used to print individual resources or a specific statistic.\n" + "The format of a 'statSpec' is: an optional combine operator, followed by an optional instanceId, followed by an optional typeId, followed by an optional statId.\n" + "The '+' operator combines all matches in the same file. The '++' operator combines all matches across all files.\n" + "An instanceId must be the name or id of a resource. A typeId is a ':' followed by the name of a resource type.\n" + "A statId is a '.' followed by the name of a statistic. A typeId or instanceId with no statId prints out all the matching resources and all their statistics.\n" + "A typeId or instanceId with a statId prints out just the named statistic on the matching resources. A statId with no typeId or instanceId matches all statistics with that name.\n" + "The '-details' option causes statistic descriptions to also be printed.\n" + "The '-nofilter' option, in conjunction with '-archive=', causes the printed statistics to all be raw, unfiltered, values.\n" + "The '-persec' option, in conjunction with '-archive=', causes the printed statistics to be the rate of change, per second, of the raw values.\n" + "The '-persample' option, in conjunction with '-archive=', causes the printed statistics to be the rate of change, per sample, of the raw values.\n" + "The '-prunezeros' option', in conjunction with '-archive=', causes statistics whose values are all zero to not be printed.\n" + "The '-starttime=' option, in conjunction with '-archive=', causes statistics samples taken before this time to be ignored. The argument format must match " + DateFormatter.FORMAT_STRING + ".\n" + "The '-endtime' option, in conjunction with '-archive=', causes statistics samples taken after this time to be ignored. The argument format must match " + DateFormatter.FORMAT_STRING + ".\n" + "The '-archive=' option causes the data to come from an archive file."); helpMap.put(START_LOCATOR, "Starts a locator.\n" + "The 'port=' option specifies the port the locator will listen on. It defaults to " + DistributionLocator.DEFAULT_LOCATOR_PORT + "\n." + "The '-address=' option specifies the address the locator will listen on. It defaults to listening on all local addresses.\n" + "The '-dir=' option can be used to specify the directory the locator will run in.\n" + "The '-properties=' option can be used to specify the gemfire.properties file for configuring the locator's distributed system. The file's path should be absolute, or relative to the locator's directory ('-dir=').\n" + "The '-peer=' option can be used to specify whether peer locator service should be enabled. True (the default) will enable the service.\n" + "The '-server=' option can be used to specify whether server locator service should be enabled. True (the default) will enable the service.\n" + "The '-hostname-for-clients=' option can be used to specify a host name or ip address that will be sent to clients so they can connect to this locator. The default is to use the address the locator is listening on.\n" + "The '-D' option can be used to set system properties for the locator VM. " + "The '-X' option can be used to set vendor-specific VM options and is usually used to increase the size of the locator VM when using multicast."); helpMap.put("stop-locator", "Stops a locator.\n" + "The '-port=' option specifies the port the locator is listening on. It defaults to " + DistributionLocator.DEFAULT_LOCATOR_PORT + ".\n" + "The '-address=' option specifies the address the locator is listening on. It defaults to the local host's address.\n" + "The '-dir=' option can be used to specify the directory the locator is running in."); helpMap.put("status-locator", "Prints the status of a locator. The status string will one of the following: " + join(ManagerInfo.statusNames) + ".\n" + "The '-dir=' option can be used to specify the directory of the locator whose status is desired."); helpMap.put("info-locator", "Prints information on a locator. The information includes the process id of the locator, if the product is not running in PureJava mode. " + "The '-dir=' option can be used to specify the directory of the locator whose information is desired."); helpMap.put("tail-locator-log", "Prints the last 64K bytes of the locator's log file. The '-dir=' option can be used to specify the directory of the locator whose information is desired."); helpMap.put("merge-logs", "Merges multiple logs files into a single log.The -out option can be used to specify the file to write the merged log to. The default is stdout."); helpMap.put("validate-disk-store", "Checks to make sure files of a disk store are valid. The name of the disk store and the directories its files are stored in are required arguments."); helpMap.put("upgrade-disk-store", "Upgrade an offline disk store with new version format.\n" + "'-maxOplogSize=<long> causes the oplogs created by compaction to be no larger than the specified size in megabytes."); helpMap.put("compact-disk-store", "Compacts an offline disk store. Compaction removes all unneeded records from the persistent files.\n" + "-maxOplogSize=<long> causes the oplogs created by compaction to be no larger than the specified size in megabytes."); helpMap.put("compact-all-disk-stores", "Connects to a running system and tells its members to compact their disk stores. " + "This command uses the compaction threshold that each member has " + "configured for its disk stores. The disk store must have allow-force-compaction " + "set to true in order for this command to work.\n" + "This command will use the gemfire.properties file to determine what distributed system to connect to."); helpMap.put("modify-disk-store", "Modifies the contents stored in a disk store. Note that this operation writes to the disk store files so use it with care. Requires that a region name by specified using -region=<regionName> Options: -remove will remove the region from the disk store causing any data stored in the disk store for this region to no longer exist. Subregions of the removed region will not be removed. -lru=<type> Sets region's lru algorithm. Valid types are: none, lru-entry-count, lru-heap-percentage, or lru-memory-size -lruAction=<action> Sets the region's lru action. Valid actions are: none, overflow-to-disk, local-destroy -lruLimit=<int> Sets the region's lru limit. Valid values are >= 0 -concurrencyLevel=<int> Sets the region's concurrency level. Valid values are >= 0 -initialCapacity=<int> Sets the region's initial capacity. Valid values are >= 0. -loadFactor=<float> Sets the region's load factory. Valid values are >= 0.0 -statisticsEnabled=<boolean> Sets the region's statistics enabled. Value values are true or false. The name of the disk store and the directories its files are stored in and the region to target are all required arguments."); helpMap.put("revoke-missing-disk-store", "Connects to a running system and tells its members to stop waiting for the " + "specified disk store to be available. Only revoke a disk store if its files " + "are lost. Once a disk store is revoked its files can no longer be loaded so be " + "careful. Use the list-missing-disk-stores command to get descriptions of the" + "missing disk stores.\n" + "You must pass the in the unique id for the disk store to revoke. The unique id is listed in the output " + "of the list-missing-disk-stores command, for example a63d7d99-f8f8-4907-9eb7-cca965083dbb.\n" + "This command will use the gemfire.properties file to determine what distributed system to connect to."); helpMap.put("list-missing-disk-stores", "Prints out a description of the disk stores that are currently missing from a distributed system\n\\n." + "This command will use the gemfire.properties file to determine what distributed system to connect to."); helpMap.put("export-disk-store", "Exports an offline disk store. The persistent data is written to a binary format.\n" + " -outputDir=<directory> specifies the location of the exported snapshot files."); helpMap.put("shut-down-all", "Connects to a running system and asks all its members that have a cache to close the cache and disconnect from system." + "The timeout parameter allows you to specify that the system should be shutdown forcibly after the time has exceeded.\n" + "This command will use the gemfire.properties file to determine what distributed system to connect to."); helpMap.put("backup", "Connects to a running system and asks all its members that have persistent data " + "to backup their data to the specified directory. The directory specified must exist " + "on all members, but it can be a local directory on each machine. This command " + "takes care to ensure that the backup files will not be corrupted by concurrent " + "operations. Backing up a running system with filesystem copy is not recommended.\n" + "This command will use the gemfire.properties file to determine what distributed system to connect to."); helpMap.put("print-stacks", "fetches stack dumps of all processes. By default an attempt" + " is made to remove idle GemFire threads from the dump. " + "Use -all-threads to include these threads in the dump. " + "An optional filename may be given for storing the dumps."); helpMap.put("-out=", "Causes gemfire to write output to the specified file. The file is overwritten if it already exists."); helpMap.put("-debug", "Causes gemfire to print out extra information when it fails. This option is supported by all commands."); helpMap.put("-details", "Causes gemfire to print detailed information. With the 'stats' command it means statistic descriptions."); helpMap.put("-nofilter", "Causes gemfire 'stats' command to print unfiltered, raw, statistic values. This is the default for non-counter statistics."); helpMap.put("-persec", "Causes gemfire 'stats' command to print the rate of change, per second, for statistic values. This is the default for counter statistics."); helpMap.put("-persample", "Causes gemfire 'stats' command to print the rate of change, per sample, for statistic values."); helpMap.put("-prunezeros", "Causes gemfire 'stats' command to not print statistics whose values are all zero."); helpMap.put("-port=", "Used to specify a non-default port when starting or stopping a locator."); helpMap.put("-address=", "Used to specify a specific IP address to listen on when starting or stopping a locator."); helpMap.put("-hostname-for-clients=", "Used to specify a host name or IP address to give to clients so they can connect to a locator."); helpMap.put("-properties=", "Used to specify the " + DistributionConfig.GEMFIRE_PREFIX + "properties file to be used in configuring the locator's DistributedSystem."); helpMap.put("-archive=", "The argument is the statistic archive file the 'stats' command should read."); helpMap.put("-h", "Causes GemFire to print out information instead of performing the command. This option is supported by all commands."); helpMap.put("-help", helpMap.get("-h")); helpMap.put("-q", "Turns on quiet mode. This option is supported by all commands."); helpMap.put("-starttime=", "Causes the 'stats' command to ignore statistics samples taken before this time. The argument format must match " + DateFormatter.FORMAT_STRING + "."); helpMap.put("-endtime=", "Causes the 'stats' command to ignore statistics samples taken after this time. The argument format must match " + DateFormatter.FORMAT_STRING + "."); helpMap.put("-dir=", "The argument is the system directory the command should operate on. If the argument is empty then a default system directory will be search for.\n" + "However the search will not include the " + DistributionConfig.GEMFIRE_PREFIX + "properties file. By default if a command needs a system directory, and one is not specified, then a search is done.\n" + "If a " + DistributionConfig.GEMFIRE_PREFIX + "properties file can be located then " + DistributionConfig.GEMFIRE_PREFIX + "systemDirectory property from that file is used.\n" + "Otherwise if the GEMFIRE environment variable is set to a directory that contains a subdirectory named defaultSystem then that directory is used.\n" + "The property file is searched for in the following locations:\n" + "1. The current working directory.\n" + "2. The user's home directory.\n" + "3. The class path. All commands except 'version' use the system directory."); helpMap.put("-D", "Sets a Java system property in the locator VM. Used most often for configuring SSL communication."); helpMap.put("-X", "Sets a Java VM X setting in the locator VM. Used most often for increasing the size of the virtual machine."); helpMap.put("-remove", "Causes the region specified by the -region=<regionName> to be removed from a disk store. Any records in the disk store for this region become garbage and will be deleted from the disk store files if compact-disk-store is called. Note that this option writes to the disk store files so use it with care."); helpMap.put("-maxOplogSize=", "Limits the size of any oplogs that are created to the specified size in megabytes."); helpMap.put("-lru=", "-lru=<type> Sets region's lru algorithm. Valid types are: none, lru-entry-count, lru-heap-percentage, or lru-memory-size"); helpMap.put("-lruAction=", "-lruAction=<action> Sets the region's lru action. Valid actions are: none, overflow-to-disk, local-destroy"); helpMap.put("-lruLimit=", "-lruLimit=<int> Sets the region's lru limit. Valid values are >= 0"); helpMap.put("-concurrencyLevel=", "-concurrencyLevel=<int> Sets the region's concurrency level. Valid values are >= 0"); helpMap.put("-initialCapacity=", "-initialCapacity=<int> Sets the region's initial capacity. Valid values are >= 0"); helpMap.put("-loadFactor=", "-loadFactor=<float> Sets the region's load factory. Valid values are >= 0.0"); helpMap.put("-statisticsEnabled=", "-statisticsEnabled=<boolean> Sets the region's statistics enabled. Value values are true or false"); helpMap.put("-region=", "Used to specify what region an operation is to be done on."); helpMap.put("-monitor", "-monitor Causes the stats command to keep periodically checking its statistic archives for updates."); helpMap.put("-peer=", "-peer=<true|false> True, the default, causes the locator to find peers for other peers. False will cause the locator to not locate peers."); helpMap.put("-server=", "-server=<true|false> True, the default, causes the locator to find servers for clients. False will cause the locator to not locate servers for clients."); helpMap.put("-outputDir=", "The directory where the disk store should be exported."); } protected final Map usageMap = new HashMap(); protected void initUsageMap() { usageMap.put("gemfire", "gemfire [-debug] [-h[elp]] [-q] [-J<vmOpt>]*"); usageMap.put("version", "version"); usageMap.put("help", "help [" + join(helpTopics, "|") + "]"); usageMap.put("stats", "stats ([<instanceId>][:<typeId>][.<statId>])* [-details] [-nofilter|-persec|-persample] [-prunezeros] [-starttime=<time>] [-endtime=<time>] -archive=<statFile>"); usageMap.put(START_LOCATOR, "start-locator [-port=<port>] [-address=<ipAddr>] [-dir=<locatorDir>] [-properties=<gemfire.properties>] [-peer=<true|false>] [-server=<true|false>] [-hostname-for-clients=<ipAddr>] [-D<system.property>=<value>] [-X<vm-setting>]"); usageMap.put("stop-locator", "stop-locator [-port=<port>] [-address=<ipAddr>] [-dir=<locatorDir>]"); usageMap.put("status-locator", "status-locator [-dir=<locatorDir>]"); usageMap.put("info-locator", "info-locator [-dir=<locatorDir>]"); usageMap.put("tail-locator-log", "tail-locator-log [-dir=<locatorDir>]"); usageMap.put("merge-logs", "merge-logs <logFile>+ [-out=<outFile>]"); usageMap.put("validate-disk-store", "validate-disk-store <diskStoreName> <directory>+"); usageMap.put("upgrade-disk-store", "upgrade-disk-store <diskStoreName> <directory>+ [-maxOplogSize=<int>]"); usageMap.put("compact-disk-store", "compact-disk-store <diskStoreName> <directory>+ [-maxOplogSize=<int>]"); usageMap.put("compact-all-disk-stores", "compact-all-disk-stores"); usageMap.put("modify-disk-store", "modify-disk-store <diskStoreName> <directory>+ [-region=<regionName> [-remove|(-lru=<none|lru-entry-count|lru-heap-percentage|lru-memory-size>|-lruAction=<none|overflow-to-disk|local-destroy>|-lruLimit=<int>|-concurrencyLevel=<int>|-initialCapacity=<int>|-loadFactor=<float>|-statisticsEnabled=<boolean>)*]]"); usageMap.put("list-missing-disk-stores", "list-missing-disk-stores"); usageMap.put("export-disk-store", "export-disk-store <diskStoreName> <directory>+ [-outputDir=<directory>]"); usageMap.put("shut-down-all", "shut-down-all [timeout_in_ms]"); usageMap.put("backup", "backup [-baseline=<baseline directory>] <target directory>"); usageMap.put("revoke-missing-disk-store", "revoke-missing-disk-store <disk-store-id>"); usageMap.put("print-stacks", "print-stacks [-all-threads] [<filename>]"); } // option statics @MakeNotStatic private static boolean debug = false; @MakeNotStatic private static boolean details = false; @MakeNotStatic private static boolean nofilter = false; @MakeNotStatic private static boolean persec = false; @MakeNotStatic private static boolean persample = false; @MakeNotStatic private static boolean prunezeros = false; @MakeNotStatic private static boolean quiet = false; @MakeNotStatic private static boolean help = false; @MakeNotStatic private static boolean monitor = false; @MakeNotStatic private static boolean showBuckets = false; @MakeNotStatic private static long startTime = -1; @MakeNotStatic private static long endTime = -1; @MakeNotStatic private static String portOption = null; @MakeNotStatic private static String addressOption = ""; @MakeNotStatic private static String regionOption = null; @MakeNotStatic private static long maxOplogSize = -1L; @MakeNotStatic private static String lruOption = null; @MakeNotStatic private static String lruActionOption = null; @MakeNotStatic private static String lruLimitOption = null; @MakeNotStatic private static String concurrencyLevelOption = null; @MakeNotStatic private static String initialCapacityOption = null; @MakeNotStatic private static String loadFactorOption = null; @MakeNotStatic private static String compressorClassNameOption = null; @MakeNotStatic private static String statisticsEnabledOption = null; @MakeNotStatic private static boolean remove = false; @MakeNotStatic private static String sysDirName = null; @MakeNotStatic private static final ArrayList archiveOption = new ArrayList(); @MakeNotStatic private static String printStacksOption = null; @MakeNotStatic private static String outOption = null; @MakeNotStatic private static Properties propertyOption = new Properties(); @MakeNotStatic private static boolean serverOption = true; @MakeNotStatic private static boolean peerOption = true; @MakeNotStatic private static String gemfirePropertiesFileOption = null; @MakeNotStatic private static final ArrayList xoptions = new ArrayList(); @MakeNotStatic private static String hostnameForClientsOption = null; @MakeNotStatic private static String baselineDir = null; // Baseline directory option value for backup command @MakeNotStatic private static String outputDir = null; @Immutable private static final Map<String, String[]> cmdOptionsMap; static { Map<String, String[]> optionsMap = new HashMap<>(); optionsMap.put("gemfire", new String[] {"--help", "-h", "-help", "-debug", "-q"}); optionsMap.put("version", new String[] {}); optionsMap.put("help", new String[] {}); optionsMap.put("merge-logs", new String[] {"-out="}); optionsMap.put("stats", new String[] {"-details", "-monitor", "-nofilter", "-persec", "-persample", "-prunezeros", "-archive=", "-starttime=", "-endtime="}); optionsMap.put(START_LOCATOR, new String[] {"-port=", "-dir=", "-address=", "-properties=", "-D", "-X", "-peer=", "-server=", "-hostname-for-clients="}); optionsMap.put("stop-locator", new String[] {"-port=", "-dir=", "-address=", "-D"}); optionsMap.put("status-locator", new String[] {"-dir=", "-D"}); optionsMap.put("info-locator", new String[] {"-dir=", "-D"}); optionsMap.put("tail-locator-log", new String[] {"-dir=", "-D"}); optionsMap.put("validate-disk-store", new String[] {}); optionsMap.put("upgrade-disk-store", new String[] {"-maxOplogSize="}); optionsMap.put("compact-disk-store", new String[] {"-maxOplogSize="}); optionsMap.put("modify-disk-store", new String[] {"-region=", "-remove", "-lru=", "-lruAction=", "-lruLimit=", "-concurrencyLevel=", "-initialCapacity=", "-loadFactor=", "-statisticsEnabled="}); optionsMap.put("list-missing-disk-stores", new String[] {}); optionsMap.put("compact-all-disk-stores", new String[] {}); optionsMap.put("revoke-missing-disk-store", new String[] {}); optionsMap.put("show-disk-store-metadata", new String[] {"-buckets"}); optionsMap.put("export-disk-store", new String[] {"-outputDir="}); optionsMap.put("shut-down-all", new String[] {}); optionsMap.put("backup", new String[] {"-baseline="}); optionsMap.put("print-stacks", new String[] {"-all-threads"}); cmdOptionsMap = Collections.unmodifiableMap(optionsMap); } private static long parseLong(String arg) { try { return Long.parseLong(arg); } catch (NumberFormatException ex) { throw new IllegalArgumentException( "Could not parse -maxOplogSize=" + arg + " because: " + ex.getMessage()); } } private static long parseTime(String arg) { DateFormat fmt = DateFormatter.createDateFormat(); try { Date d = fmt.parse(arg); return d.getTime(); } catch (ParseException ex) { throw new IllegalArgumentException( String.format("Time was not in this format %s. %s", new Object[] {DateFormatter.FORMAT_STRING, ex})); } } protected boolean matchCmdArg(String cmd, String arg) { String[] validArgs = (String[]) cmdOptionsMap.get(cmd.toLowerCase()); for (int i = 0; i < validArgs.length; i++) { if (validArgs[i].endsWith("=") || validArgs[i].equals("-D") || validArgs[i].equals("-X")) { if (arg.toLowerCase().startsWith(validArgs[i]) || arg.startsWith(validArgs[i])) { String argValue = arg.substring(validArgs[i].length()); if (validArgs[i].equals("-dir=")) { sysDirName = argValue; } else if (validArgs[i].equals("-archive=")) { archiveOption.add(new File(argValue)); } else if (validArgs[i].equals("-port=")) { portOption = argValue; } else if (validArgs[i].equals("-address=")) { addressOption = argValue; } else if (validArgs[i].equals("-region=")) { regionOption = argValue; } else if (validArgs[i].equals("-maxOplogSize=")) { maxOplogSize = parseLong(argValue); } else if (validArgs[i].equals("-lru=")) { lruOption = argValue; } else if (validArgs[i].equals("-lruAction=")) { lruActionOption = argValue; } else if (validArgs[i].equals("-lruLimit=")) { lruLimitOption = argValue; } else if (validArgs[i].equals("-concurrencyLevel=")) { concurrencyLevelOption = argValue; } else if (validArgs[i].equals("-initialCapacity=")) { initialCapacityOption = argValue; } else if (validArgs[i].equals("-loadFactor=")) { loadFactorOption = argValue; } else if (validArgs[i].equals("-compressor=")) { compressorClassNameOption = argValue; } else if (validArgs[i].equals("-statisticsEnabled=")) { statisticsEnabledOption = argValue; } else if (validArgs[i].equals("-properties=")) { gemfirePropertiesFileOption = argValue; } else if (validArgs[i].equals("-out=")) { outOption = argValue; } else if (validArgs[i].equals("-starttime=")) { startTime = parseTime(argValue); } else if (validArgs[i].equals("-endtime=")) { endTime = parseTime(argValue); } else if (validArgs[i].equals("-peer=")) { peerOption = "true".equalsIgnoreCase(argValue); } else if (validArgs[i].equals("-server=")) { serverOption = "true".equalsIgnoreCase(argValue); } else if (validArgs[i].equals("-hostname-for-clients=")) { hostnameForClientsOption = argValue; } else if (validArgs[i].equals("-D")) { int idx = argValue.indexOf('='); String key = argValue.substring(0, idx); String value = argValue.substring(idx + 1); propertyOption.setProperty(key, value); } else if (validArgs[i].equals("-X")) { xoptions.add(arg); } else if (validArgs[i].equals("-baseline=")) { baselineDir = argValue; } else if (validArgs[i].equals("-outputDir=")) { outputDir = argValue; } else { throw new InternalGemFireException( String.format("unexpected valid option %s", validArgs[i])); } return true; } } else if (validArgs[i].equalsIgnoreCase(arg)) { if (validArgs[i].equals("-h") || validArgs[i].toLowerCase().matches("-{0,2}help")) { help = true; } else if (validArgs[i].equals("-debug")) { debug = true; } else if (validArgs[i].equals("-remove")) { remove = true; } else if (validArgs[i].equals("-q")) { quiet = true; } else if (validArgs[i].equals("-details")) { details = true; } else if (validArgs[i].equals("-nofilter")) { nofilter = true; } else if (validArgs[i].equals("-persec")) { persec = true; } else if (validArgs[i].equals("-persample")) { persample = true; } else if (validArgs[i].equals("-prunezeros")) { prunezeros = true; } else if (validArgs[i].equals("-monitor")) { monitor = true; } else if (validArgs[i].equalsIgnoreCase("-buckets")) { showBuckets = true; } else if (validArgs[i].equals("-all-threads")) { printStacksOption = arg; } else { throw new InternalGemFireException(String.format("unexpected valid option %s", validArgs[i])); } return true; } } return false; } protected void printHelp(String cmd) { List<String> lines = format((String) helpMap.get(cmd.toLowerCase()), 80); for (String line : lines) { System.err.println(line); } usage(cmd); } public static List<String> format(String string, int width) { List<String> results = new ArrayList<String>(); String[] realLines = string.split("\n"); for (String line : realLines) { results.addAll(lineWrapOut(line, width)); results.add(""); } return results; } public static List<String> lineWrapOut(String string, int width) { Pattern pattern = Pattern.compile("(.{0," + (width - 1) + "}\\S|\\S{" + (width) + ",})(\n|\\s+|$)"); Matcher matcher = pattern.matcher(string); List<String> lines = new ArrayList<String>(); while (matcher.find()) { lines.add(matcher.group(1)); } return lines; } private static String getExceptionMessage(Throwable ex) { String result = ex.getMessage(); if (result == null || result.length() == 0) { result = ex.toString(); } return result; } private static boolean needsSysDir(String cmd) { return !(cmd.equalsIgnoreCase("stats") || cmd.equalsIgnoreCase("merge-logs") || cmd.equalsIgnoreCase("version") || cmd.equalsIgnoreCase("help")); } public static File getProductDir() { File libdir = findGemFireLibDir(); if (libdir == null) { return new File("").getAbsoluteFile(); // default to current directory } else { return libdir.getParentFile(); } } public static File getHiddenDir() throws IOException { File prodDir = getProductDir(); if (prodDir == null) { return null; } File hiddenDir = new File(prodDir.getParentFile(), "hidden"); if (!hiddenDir.exists()) { hiddenDir = new File(prodDir.getCanonicalFile().getParentFile(), "hidden"); } if (!hiddenDir.exists()) { // If we don't have a jar file (eg, when running in eclipse), look for a hidden // directory in same same directory as our classes. File libDir = findGemFireLibDir(); File oldHiddenDir = hiddenDir; if (libDir != null && libDir.exists()) { hiddenDir = new File(libDir, "hidden"); } if (!hiddenDir.exists()) { hiddenDir = oldHiddenDir; } } return hiddenDir; } public static void main(String[] args) { try { final SystemAdmin admin = new SystemAdmin(); admin.initHelpMap(); admin.initUsageMap(); admin.invoke(args); } finally { InternalDistributedSystem sys = InternalDistributedSystem.getConnectedInstance(); if (sys != null) { sys.disconnect(); } } } public void invoke(String[] args) { String cmd = null; ArrayList cmdLine = new ArrayList(Arrays.asList(args)); try { Iterator it = cmdLine.iterator(); while (it.hasNext()) { String arg = (String) it.next(); if (arg.startsWith("-")) { if (matchCmdArg("gemfire", arg)) { it.remove(); } else { System.err.println( String.format("ERROR: Unknown option %s.", arg)); usage(); } } else { break; } } } catch (IllegalArgumentException ex) { System.err.println( "ERROR: " + getExceptionMessage(ex)); if (debug) { ex.printStackTrace(System.err); } ExitCode.FATAL.doSystemExit(); // fix for bug 28351 } if (cmdLine.size() == 0) { if (help) { printHelp("gemfire"); } else { System.err.println("ERROR: Wrong number of command line args."); usage(); } } cmd = (String) cmdLine.remove(0); cmd = checkCmd(cmd); File sysDir = null; // File configFile = null; try { Iterator it = cmdLine.iterator(); while (it.hasNext()) { String arg = (String) it.next(); if (arg.startsWith("-")) { if (matchCmdArg(cmd, arg) || matchCmdArg("gemfire", arg)) { it.remove(); } else { System.err.println( String.format("ERROR: Unknown option %s.", arg)); usage(cmd); } } } } catch (IllegalArgumentException ex) { System.err.println( "ERROR: " + getExceptionMessage(ex)); if (debug) { ex.printStackTrace(System.err); } ExitCode.FATAL.doSystemExit(); // fix for bug 28351 } if (needsSysDir(cmd) && !help) { if (sysDirName != null && sysDirName.length() > 0) { sysDir = new File(sysDirName).getAbsoluteFile(); } else { sysDir = new File(System.getProperty("user.dir")).getAbsoluteFile(); } } SystemFailure.loadEmergencyClasses(); if (help) { printHelp(cmd); } try { if (cmd.equalsIgnoreCase("stats")) { statistics(sysDir, archiveOption, details, nofilter, persec, persample, prunezeros, monitor, startTime, endTime, cmdLine); } else if (cmd.equalsIgnoreCase("version")) { boolean optionOK = (cmdLine.size() == 0); if (cmdLine.size() == 1) { optionOK = false; String option = (String) cmdLine.get(0); if ("CREATE".equals(option) || "FULL".equalsIgnoreCase(option)) { // CREATE and FULL are secret for internal use only optionOK = true; } } if (!optionOK) { System.err.println(String.format("ERROR: unexpected command line arguments: %s.", join(cmdLine))); usage(cmd); } System.out.println(String.format("GemFire product directory: %s", getProductDir())); GemFireVersion.print(System.out); } else if (cmd.equalsIgnoreCase("help")) { if (cmdLine.size() > 1) { System.err.println(String.format("ERROR: unexpected command line arguments: %s.", join(cmdLine))); usage(cmd); } help(cmdLine); } else if (cmd.equalsIgnoreCase(START_LOCATOR)) { if (cmdLine.size() != 0) { System.err.println(String.format("ERROR: unexpected command line arguments: %s.", join(cmdLine))); usage(cmd); } locatorStart(sysDir, portOption, addressOption, gemfirePropertiesFileOption, propertyOption, xoptions, peerOption, serverOption, hostnameForClientsOption); if (!quiet) { System.out .println("Locator start complete."); } } else if (cmd.equalsIgnoreCase("stop-locator")) { if (cmdLine.size() != 0) { System.err.println(String.format("ERROR: unexpected command line arguments: %s.", join(cmdLine))); usage(cmd); } locatorStop(sysDir, portOption, addressOption, propertyOption); if (!quiet) { System.out .println("Locator stop complete."); } } else if (cmd.equalsIgnoreCase("status-locator")) { if (cmdLine.size() != 0) { System.err.println(String.format("ERROR: unexpected command line arguments: %s.", join(cmdLine))); usage(cmd); } if (!quiet) { System.out.println(locatorStatus(sysDir)); } } else if (cmd.equalsIgnoreCase("info-locator")) { if (cmdLine.size() != 0) { System.err.println(String.format("ERROR: unexpected command line arguments: %s.", join(cmdLine))); usage(cmd); } System.out.println(locatorInfo(sysDir)); } else if (cmd.equalsIgnoreCase("tail-locator-log")) { if (cmdLine.size() != 0) { System.err.println(String.format("ERROR: unexpected command line arguments: %s.", join(cmdLine))); usage(cmd); } System.out.println(locatorTailLog(sysDir)); } else if (cmd.equalsIgnoreCase("merge-logs")) { if (cmdLine.size() == 0) { System.err .println("ERROR: expected at least one log file to merge."); usage(cmd); } mergeLogs(outOption, cmdLine); } else if (cmd.equalsIgnoreCase("validate-disk-store")) { if (cmdLine.size() == 0) { System.err.println("Expected disk store name and at least one directory"); usage(cmd); } else if (cmdLine.size() == 1) { System.err.println("Expected at least one directory"); usage(cmd); } validateDiskStore(cmdLine); } else if (cmd.equalsIgnoreCase("upgrade-disk-store")) { if (cmdLine.size() == 0) { System.err.println("Expected disk store name and at least one directory"); usage(cmd); } else if (cmdLine.size() == 1) { System.err.println("Expected at least one directory"); usage(cmd); } upgradeDiskStore(cmdLine); } else if (cmd.equalsIgnoreCase("compact-disk-store")) { if (cmdLine.size() == 0) { System.err.println("Expected disk store name and at least one directory"); usage(cmd); } else if (cmdLine.size() == 1) { System.err.println("Expected at least one directory"); usage(cmd); } compactDiskStore(cmdLine); } else if (cmd.equalsIgnoreCase("compact-all-disk-stores")) { if (cmdLine.size() != 0) { System.err.println("Did not expect any command line arguments"); usage(cmd); } compactAllDiskStores(cmdLine); } else if (cmd.equalsIgnoreCase("modify-disk-store")) { if (cmdLine.size() == 0) { System.err.println("Expected disk store name and at least one directory"); usage(cmd); } else if (cmdLine.size() == 1) { System.err.println("Expected at least one directory"); usage(cmd); } modifyDiskStore(cmdLine); } else if (cmd.equalsIgnoreCase("list-missing-disk-stores")) { if (cmdLine.size() != 0) { System.err.println("Did not expect any command line arguments"); usage(cmd); } listMissingDiskStores(); } else if (cmd.equalsIgnoreCase("revoke-missing-disk-store")) { if (cmdLine.size() != 1) { System.err.println("Expected a disk store id"); usage(cmd); } revokeMissingDiskStores(cmdLine); } else if (cmd.equalsIgnoreCase("show-disk-store-metadata")) { if (cmdLine.size() == 0) { System.err.println("Expected disk store name and at least one directory"); usage(cmd); } else if (cmdLine.size() == 1) { System.err.println("Expected at least one directory"); usage(cmd); } showDiskStoreMetadata(cmdLine); } else if (cmd.equalsIgnoreCase("export-disk-store")) { if (cmdLine.size() == 0) { System.err.println("Expected disk store name and at least one directory"); usage(cmd); } else if (cmdLine.size() == 1) { System.err.println("Expected at least one directory"); usage(cmd); } exportDiskStore(cmdLine, outputDir); } else if (cmd.equalsIgnoreCase("shut-down-all")) { if (cmdLine.size() > 1) { System.err.println("Expected an optional timeout (ms)"); usage(cmd); } shutDownAll(cmdLine); } else if (cmd.equalsIgnoreCase("backup")) { if (cmdLine.size() != 1) { usage(cmd); } backup((String) cmdLine.get(0)); } else if (cmd.equalsIgnoreCase("print-stacks")) { printStacks(cmdLine, printStacksOption != null); } else { System.err .println(String.format("ERROR: Unknown command %s.", cmd)); usage(); } } catch (InterruptedException ex) { System.err.println(String.format("ERROR: Operation %s failed because: %s.", new Object[] {cmd, getExceptionMessage(ex)})); if (debug) { ex.printStackTrace(System.err); } ExitCode.FATAL.doSystemExit(); // fix for bug 28351 } catch (IllegalArgumentException ex) { System.err.println(String.format("ERROR: Operation %s failed because: %s.", new Object[] {cmd, getExceptionMessage(ex)})); if (debug) { ex.printStackTrace(System.err); } ExitCode.FATAL.doSystemExit(); // fix for bug 28351 } catch (Exception ex) { System.err.println(String.format("ERROR: Operation %s failed because: %s.", new Object[] {cmd, getExceptionMessage(ex)})); if (debug) { ex.printStackTrace(System.err); } ExitCode.FATAL.doSystemExit(); // fix for bug 28351 } } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.sql.planner; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import io.airlift.log.Logger; import io.trino.Session; import io.trino.cost.CachingCostProvider; import io.trino.cost.CachingStatsProvider; import io.trino.cost.CostCalculator; import io.trino.cost.CostProvider; import io.trino.cost.StatsAndCosts; import io.trino.cost.StatsCalculator; import io.trino.cost.StatsProvider; import io.trino.execution.warnings.WarningCollector; import io.trino.metadata.Metadata; import io.trino.metadata.QualifiedObjectName; import io.trino.metadata.ResolvedFunction; import io.trino.metadata.TableExecuteHandle; import io.trino.metadata.TableHandle; import io.trino.metadata.TableLayout; import io.trino.metadata.TableMetadata; import io.trino.spi.StandardErrorCode; import io.trino.spi.TrinoException; import io.trino.spi.connector.ColumnHandle; import io.trino.spi.connector.ColumnMetadata; import io.trino.spi.connector.ConnectorTableMetadata; import io.trino.spi.security.AccessDeniedException; import io.trino.spi.statistics.TableStatisticsMetadata; import io.trino.spi.type.CharType; import io.trino.spi.type.Type; import io.trino.spi.type.VarcharType; import io.trino.sql.PlannerContext; import io.trino.sql.analyzer.Analysis; import io.trino.sql.analyzer.Field; import io.trino.sql.analyzer.RelationId; import io.trino.sql.analyzer.RelationType; import io.trino.sql.analyzer.Scope; import io.trino.sql.planner.StatisticsAggregationPlanner.TableStatisticAggregation; import io.trino.sql.planner.optimizations.PlanOptimizer; import io.trino.sql.planner.plan.AggregationNode; import io.trino.sql.planner.plan.Assignments; import io.trino.sql.planner.plan.DeleteNode; import io.trino.sql.planner.plan.ExplainAnalyzeNode; import io.trino.sql.planner.plan.FilterNode; import io.trino.sql.planner.plan.LimitNode; import io.trino.sql.planner.plan.OutputNode; import io.trino.sql.planner.plan.PlanNode; import io.trino.sql.planner.plan.ProjectNode; import io.trino.sql.planner.plan.RefreshMaterializedViewNode; import io.trino.sql.planner.plan.StatisticAggregations; import io.trino.sql.planner.plan.StatisticsWriterNode; import io.trino.sql.planner.plan.TableExecuteNode; import io.trino.sql.planner.plan.TableFinishNode; import io.trino.sql.planner.plan.TableScanNode; import io.trino.sql.planner.plan.TableWriterNode; import io.trino.sql.planner.plan.UpdateNode; import io.trino.sql.planner.plan.ValuesNode; import io.trino.sql.planner.planprinter.PlanPrinter; import io.trino.sql.planner.sanity.PlanSanityChecker; import io.trino.sql.tree.Analyze; import io.trino.sql.tree.Cast; import io.trino.sql.tree.CoalesceExpression; import io.trino.sql.tree.ComparisonExpression; import io.trino.sql.tree.CreateTableAsSelect; import io.trino.sql.tree.Delete; import io.trino.sql.tree.ExplainAnalyze; import io.trino.sql.tree.Expression; import io.trino.sql.tree.FunctionCall; import io.trino.sql.tree.GenericLiteral; import io.trino.sql.tree.IfExpression; import io.trino.sql.tree.Insert; import io.trino.sql.tree.LambdaArgumentDeclaration; import io.trino.sql.tree.LongLiteral; import io.trino.sql.tree.NodeRef; import io.trino.sql.tree.NullLiteral; import io.trino.sql.tree.QualifiedName; import io.trino.sql.tree.Query; import io.trino.sql.tree.RefreshMaterializedView; import io.trino.sql.tree.Row; import io.trino.sql.tree.Statement; import io.trino.sql.tree.StringLiteral; import io.trino.sql.tree.Table; import io.trino.sql.tree.TableExecute; import io.trino.sql.tree.Update; import io.trino.type.TypeCoercion; import io.trino.type.UnknownType; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Function; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Verify.verify; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableMap.toImmutableMap; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Streams.zip; import static io.trino.SystemSessionProperties.isCollectPlanStatisticsForAllQueries; import static io.trino.metadata.MetadataUtil.createQualifiedObjectName; import static io.trino.spi.StandardErrorCode.NOT_SUPPORTED; import static io.trino.spi.StandardErrorCode.PERMISSION_DENIED; import static io.trino.spi.statistics.TableStatisticType.ROW_COUNT; import static io.trino.spi.type.BigintType.BIGINT; import static io.trino.spi.type.BooleanType.BOOLEAN; import static io.trino.spi.type.IntegerType.INTEGER; import static io.trino.spi.type.VarbinaryType.VARBINARY; import static io.trino.spi.type.VarcharType.VARCHAR; import static io.trino.sql.analyzer.TypeSignatureProvider.fromTypes; import static io.trino.sql.analyzer.TypeSignatureTranslator.toSqlType; import static io.trino.sql.planner.LogicalPlanner.Stage.OPTIMIZED; import static io.trino.sql.planner.LogicalPlanner.Stage.OPTIMIZED_AND_VALIDATED; import static io.trino.sql.planner.PlanBuilder.newPlanBuilder; import static io.trino.sql.planner.QueryPlanner.visibleFields; import static io.trino.sql.planner.SystemPartitioningHandle.FIXED_HASH_DISTRIBUTION; import static io.trino.sql.planner.plan.AggregationNode.singleGroupingSet; import static io.trino.sql.planner.plan.TableWriterNode.CreateReference; import static io.trino.sql.planner.plan.TableWriterNode.InsertReference; import static io.trino.sql.planner.plan.TableWriterNode.WriterTarget; import static io.trino.sql.planner.sanity.PlanSanityChecker.DISTRIBUTED_PLAN_SANITY_CHECKER; import static io.trino.sql.tree.BooleanLiteral.TRUE_LITERAL; import static io.trino.sql.tree.ComparisonExpression.Operator.GREATER_THAN_OR_EQUAL; import static java.lang.String.format; import static java.util.Objects.requireNonNull; public class LogicalPlanner { private static final Logger LOG = Logger.get(LogicalPlanner.class); public enum Stage { CREATED, OPTIMIZED, OPTIMIZED_AND_VALIDATED } private final PlanNodeIdAllocator idAllocator; private final Session session; private final List<PlanOptimizer> planOptimizers; private final PlanSanityChecker planSanityChecker; private final SymbolAllocator symbolAllocator = new SymbolAllocator(); private final Metadata metadata; private final PlannerContext plannerContext; private final TypeCoercion typeCoercion; private final TypeAnalyzer typeAnalyzer; private final StatisticsAggregationPlanner statisticsAggregationPlanner; private final StatsCalculator statsCalculator; private final CostCalculator costCalculator; private final WarningCollector warningCollector; public LogicalPlanner( Session session, List<PlanOptimizer> planOptimizers, PlanNodeIdAllocator idAllocator, PlannerContext plannerContext, TypeAnalyzer typeAnalyzer, StatsCalculator statsCalculator, CostCalculator costCalculator, WarningCollector warningCollector) { this(session, planOptimizers, DISTRIBUTED_PLAN_SANITY_CHECKER, idAllocator, plannerContext, typeAnalyzer, statsCalculator, costCalculator, warningCollector); } public LogicalPlanner( Session session, List<PlanOptimizer> planOptimizers, PlanSanityChecker planSanityChecker, PlanNodeIdAllocator idAllocator, PlannerContext plannerContext, TypeAnalyzer typeAnalyzer, StatsCalculator statsCalculator, CostCalculator costCalculator, WarningCollector warningCollector) { this.session = requireNonNull(session, "session is null"); this.planOptimizers = requireNonNull(planOptimizers, "planOptimizers is null"); this.planSanityChecker = requireNonNull(planSanityChecker, "planSanityChecker is null"); this.idAllocator = requireNonNull(idAllocator, "idAllocator is null"); this.plannerContext = requireNonNull(plannerContext, "plannerContext is null"); this.metadata = plannerContext.getMetadata(); this.typeCoercion = new TypeCoercion(plannerContext.getTypeManager()::getType); this.typeAnalyzer = requireNonNull(typeAnalyzer, "typeAnalyzer is null"); this.statisticsAggregationPlanner = new StatisticsAggregationPlanner(symbolAllocator, metadata, session); this.statsCalculator = requireNonNull(statsCalculator, "statsCalculator is null"); this.costCalculator = requireNonNull(costCalculator, "costCalculator is null"); this.warningCollector = requireNonNull(warningCollector, "warningCollector is null"); } public Plan plan(Analysis analysis) { return plan(analysis, OPTIMIZED_AND_VALIDATED); } public Plan plan(Analysis analysis, Stage stage) { return plan(analysis, stage, analysis.getStatement() instanceof ExplainAnalyze || isCollectPlanStatisticsForAllQueries(session)); } public Plan plan(Analysis analysis, Stage stage, boolean collectPlanStatistics) { PlanNode root = planStatement(analysis, analysis.getStatement()); if (LOG.isDebugEnabled()) { LOG.debug("Initial plan:\n%s", PlanPrinter.textLogicalPlan( root, symbolAllocator.getTypes(), metadata, plannerContext.getFunctionManager(), StatsAndCosts.empty(), session, 0, false)); } planSanityChecker.validateIntermediatePlan(root, session, plannerContext, typeAnalyzer, symbolAllocator.getTypes(), warningCollector); if (stage.ordinal() >= OPTIMIZED.ordinal()) { for (PlanOptimizer optimizer : planOptimizers) { root = optimizer.optimize(root, session, symbolAllocator.getTypes(), symbolAllocator, idAllocator, warningCollector); requireNonNull(root, format("%s returned a null plan", optimizer.getClass().getName())); if (LOG.isDebugEnabled()) { LOG.debug("%s:\n%s", optimizer.getClass().getName(), PlanPrinter.textLogicalPlan( root, symbolAllocator.getTypes(), metadata, plannerContext.getFunctionManager(), StatsAndCosts.empty(), session, 0, false)); } } } if (stage.ordinal() >= OPTIMIZED_AND_VALIDATED.ordinal()) { // make sure we produce a valid plan after optimizations run. This is mainly to catch programming errors planSanityChecker.validateFinalPlan(root, session, plannerContext, typeAnalyzer, symbolAllocator.getTypes(), warningCollector); } TypeProvider types = symbolAllocator.getTypes(); StatsAndCosts statsAndCosts = StatsAndCosts.empty(); if (collectPlanStatistics) { StatsProvider statsProvider = new CachingStatsProvider(statsCalculator, session, types); CostProvider costProvider = new CachingCostProvider(costCalculator, statsProvider, Optional.empty(), session, types); statsAndCosts = StatsAndCosts.create(root, statsProvider, costProvider); } return new Plan(root, types, statsAndCosts); } public PlanNode planStatement(Analysis analysis, Statement statement) { if ((statement instanceof CreateTableAsSelect && analysis.getCreate().orElseThrow().isCreateTableAsSelectNoOp()) || statement instanceof RefreshMaterializedView && analysis.isSkipMaterializedViewRefresh()) { Symbol symbol = symbolAllocator.newSymbol("rows", BIGINT); PlanNode source = new ValuesNode(idAllocator.getNextId(), ImmutableList.of(symbol), ImmutableList.of(new Row(ImmutableList.of(new GenericLiteral("BIGINT", "0"))))); return new OutputNode(idAllocator.getNextId(), source, ImmutableList.of("rows"), ImmutableList.of(symbol)); } return createOutputPlan(planStatementWithoutOutput(analysis, statement), analysis); } private RelationPlan planStatementWithoutOutput(Analysis analysis, Statement statement) { if (statement instanceof CreateTableAsSelect) { if (analysis.getCreate().orElseThrow().isCreateTableAsSelectNoOp()) { throw new TrinoException(NOT_SUPPORTED, "CREATE TABLE IF NOT EXISTS is not supported in this context " + statement.getClass().getSimpleName()); } return createTableCreationPlan(analysis, ((CreateTableAsSelect) statement).getQuery()); } if (statement instanceof Analyze) { return createAnalyzePlan(analysis, (Analyze) statement); } if (statement instanceof Insert) { checkState(analysis.getInsert().isPresent(), "Insert handle is missing"); return createInsertPlan(analysis, (Insert) statement); } if (statement instanceof RefreshMaterializedView) { return createRefreshMaterializedViewPlan(analysis); } if (statement instanceof Delete) { return createDeletePlan(analysis, (Delete) statement); } if (statement instanceof Update) { return createUpdatePlan(analysis, (Update) statement); } if (statement instanceof Query) { return createRelationPlan(analysis, (Query) statement); } if (statement instanceof ExplainAnalyze) { return createExplainAnalyzePlan(analysis, (ExplainAnalyze) statement); } if (statement instanceof TableExecute) { return createTableExecutePlan(analysis, (TableExecute) statement); } throw new TrinoException(NOT_SUPPORTED, "Unsupported statement type " + statement.getClass().getSimpleName()); } private RelationPlan createExplainAnalyzePlan(Analysis analysis, ExplainAnalyze statement) { RelationPlan underlyingPlan = planStatementWithoutOutput(analysis, statement.getStatement()); PlanNode root = underlyingPlan.getRoot(); Scope scope = analysis.getScope(statement); Symbol outputSymbol = symbolAllocator.newSymbol(scope.getRelationType().getFieldByIndex(0)); ImmutableList.Builder<Symbol> actualOutputs = ImmutableList.builder(); RelationType outputDescriptor = analysis.getOutputDescriptor(statement.getStatement()); for (Field field : outputDescriptor.getVisibleFields()) { int fieldIndex = outputDescriptor.indexOf(field); Symbol symbol = underlyingPlan.getSymbol(fieldIndex); actualOutputs.add(symbol); } root = new ExplainAnalyzeNode(idAllocator.getNextId(), root, outputSymbol, actualOutputs.build(), statement.isVerbose()); return new RelationPlan(root, scope, ImmutableList.of(outputSymbol), Optional.empty()); } private RelationPlan createAnalyzePlan(Analysis analysis, Analyze analyzeStatement) { TableHandle targetTable = analysis.getAnalyzeTarget().orElseThrow(); // Plan table scan Map<String, ColumnHandle> columnHandles = metadata.getColumnHandles(session, targetTable); ImmutableList.Builder<Symbol> tableScanOutputs = ImmutableList.builder(); ImmutableMap.Builder<Symbol, ColumnHandle> symbolToColumnHandle = ImmutableMap.builder(); ImmutableMap.Builder<String, Symbol> columnNameToSymbol = ImmutableMap.builder(); TableMetadata tableMetadata = metadata.getTableMetadata(session, targetTable); for (ColumnMetadata column : tableMetadata.getColumns()) { Symbol symbol = symbolAllocator.newSymbol(column.getName(), column.getType()); tableScanOutputs.add(symbol); symbolToColumnHandle.put(symbol, columnHandles.get(column.getName())); columnNameToSymbol.put(column.getName(), symbol); } TableStatisticsMetadata tableStatisticsMetadata = metadata.getStatisticsCollectionMetadata( session, targetTable.getCatalogName().getCatalogName(), tableMetadata.getMetadata()); TableStatisticAggregation tableStatisticAggregation = statisticsAggregationPlanner.createStatisticsAggregation(tableStatisticsMetadata, columnNameToSymbol.buildOrThrow()); StatisticAggregations statisticAggregations = tableStatisticAggregation.getAggregations(); List<Symbol> groupingSymbols = statisticAggregations.getGroupingSymbols(); PlanNode planNode = new StatisticsWriterNode( idAllocator.getNextId(), new AggregationNode( idAllocator.getNextId(), TableScanNode.newInstance(idAllocator.getNextId(), targetTable, tableScanOutputs.build(), symbolToColumnHandle.buildOrThrow(), false, Optional.empty()), statisticAggregations.getAggregations(), singleGroupingSet(groupingSymbols), ImmutableList.of(), AggregationNode.Step.SINGLE, Optional.empty(), Optional.empty()), new StatisticsWriterNode.WriteStatisticsReference(targetTable), symbolAllocator.newSymbol("rows", BIGINT), tableStatisticsMetadata.getTableStatistics().contains(ROW_COUNT), tableStatisticAggregation.getDescriptor()); return new RelationPlan(planNode, analysis.getScope(analyzeStatement), planNode.getOutputSymbols(), Optional.empty()); } private RelationPlan createTableCreationPlan(Analysis analysis, Query query) { Analysis.Create create = analysis.getCreate().orElseThrow(); QualifiedObjectName destination = create.getDestination().orElseThrow(); RelationPlan plan = createRelationPlan(analysis, query); if (!create.isCreateTableAsSelectWithData()) { PlanNode root = new LimitNode(idAllocator.getNextId(), plan.getRoot(), 0L, false); plan = new RelationPlan(root, plan.getScope(), plan.getFieldMappings(), Optional.empty()); } ConnectorTableMetadata tableMetadata = create.getMetadata().orElseThrow(); Optional<TableLayout> newTableLayout = create.getLayout(); List<String> columnNames = tableMetadata.getColumns().stream() .filter(column -> !column.isHidden()) // todo this filter is redundant .map(ColumnMetadata::getName) .collect(toImmutableList()); TableStatisticsMetadata statisticsMetadata = metadata.getStatisticsCollectionMetadataForWrite(session, destination.getCatalogName(), tableMetadata); return createTableWriterPlan( analysis, plan.getRoot(), visibleFields(plan), new CreateReference(destination.getCatalogName(), tableMetadata, newTableLayout), columnNames, tableMetadata.getColumns(), newTableLayout, statisticsMetadata); } private RelationPlan getInsertPlan( Analysis analysis, Table table, Query query, TableHandle tableHandle, List<ColumnHandle> insertColumns, Optional<TableLayout> newTableLayout, Optional<WriterTarget> materializedViewRefreshWriterTarget) { TableMetadata tableMetadata = metadata.getTableMetadata(session, tableHandle); Map<NodeRef<LambdaArgumentDeclaration>, Symbol> lambdaDeclarationToSymbolMap = buildLambdaDeclarationToSymbolMap(analysis, symbolAllocator); RelationPlanner planner = new RelationPlanner(analysis, symbolAllocator, idAllocator, lambdaDeclarationToSymbolMap, plannerContext, Optional.empty(), session, ImmutableMap.of()); RelationPlan plan = planner.process(query, null); ImmutableList.Builder<Symbol> builder = ImmutableList.builder(); for (int i = 0; i < plan.getFieldMappings().size(); i++) { if (!plan.getDescriptor().getFieldByIndex(i).isHidden()) { builder.add(plan.getFieldMappings().get(i)); } } List<Symbol> visibleFieldMappings = builder.build(); Map<String, ColumnHandle> columns = metadata.getColumnHandles(session, tableHandle); Assignments.Builder assignments = Assignments.builder(); boolean supportsMissingColumnsOnInsert = metadata.supportsMissingColumnsOnInsert(session, tableHandle); ImmutableList.Builder<ColumnMetadata> insertedColumnsBuilder = ImmutableList.builder(); for (ColumnMetadata column : tableMetadata.getColumns()) { if (column.isHidden()) { continue; } Symbol output = symbolAllocator.newSymbol(column.getName(), column.getType()); int index = insertColumns.indexOf(columns.get(column.getName())); if (index < 0) { if (supportsMissingColumnsOnInsert) { continue; } Expression cast = new Cast(new NullLiteral(), toSqlType(column.getType())); assignments.put(output, cast); insertedColumnsBuilder.add(column); } else { Symbol input = visibleFieldMappings.get(index); Type tableType = column.getType(); Type queryType = symbolAllocator.getTypes().get(input); if (queryType.equals(tableType) || typeCoercion.isTypeOnlyCoercion(queryType, tableType)) { assignments.put(output, input.toSymbolReference()); } else { Expression cast = noTruncationCast(input.toSymbolReference(), queryType, tableType); assignments.put(output, cast); } insertedColumnsBuilder.add(column); } } ProjectNode projectNode = new ProjectNode(idAllocator.getNextId(), plan.getRoot(), assignments.build()); List<ColumnMetadata> insertedColumns = insertedColumnsBuilder.build(); List<Field> fields = insertedColumns.stream() .map(column -> Field.newUnqualified(column.getName(), column.getType())) .collect(toImmutableList()); Scope scope = Scope.builder().withRelationType(RelationId.anonymous(), new RelationType(fields)).build(); plan = new RelationPlan(projectNode, scope, projectNode.getOutputSymbols(), Optional.empty()); plan = planner.addRowFilters( table, plan, failIfPredicateIsNotMeet(metadata, session, PERMISSION_DENIED, AccessDeniedException.PREFIX + "Cannot insert row that does not match to a row filter"), node -> { Scope accessControlScope = analysis.getAccessControlScope(table); // hidden fields are not accessible in insert return Scope.builder() .like(accessControlScope) .withRelationType(accessControlScope.getRelationId(), accessControlScope.getRelationType().withOnlyVisibleFields()) .build(); }); List<String> insertedTableColumnNames = insertedColumns.stream() .map(ColumnMetadata::getName) .collect(toImmutableList()); String catalogName = tableHandle.getCatalogName().getCatalogName(); TableStatisticsMetadata statisticsMetadata = metadata.getStatisticsCollectionMetadataForWrite(session, catalogName, tableMetadata.getMetadata()); if (materializedViewRefreshWriterTarget.isPresent()) { return createTableWriterPlan( analysis, plan.getRoot(), plan.getFieldMappings(), materializedViewRefreshWriterTarget.get(), insertedTableColumnNames, insertedColumns, newTableLayout, statisticsMetadata); } InsertReference insertTarget = new InsertReference( tableHandle, insertedTableColumnNames.stream() .map(columns::get) .collect(toImmutableList())); return createTableWriterPlan( analysis, plan.getRoot(), plan.getFieldMappings(), insertTarget, insertedTableColumnNames, insertedColumns, newTableLayout, statisticsMetadata); } private static Function<Expression, Expression> failIfPredicateIsNotMeet(Metadata metadata, Session session, StandardErrorCode errorCode, String errorMessage) { ResolvedFunction fail = metadata.resolveFunction(session, QualifiedName.of("fail"), fromTypes(INTEGER, VARCHAR)); return predicate -> new IfExpression( predicate, TRUE_LITERAL, new Cast( new FunctionCall( fail.toQualifiedName(), ImmutableList.of( new Cast(new LongLiteral(Long.toString(errorCode.toErrorCode().getCode())), toSqlType(INTEGER)), new Cast(new StringLiteral(errorMessage), toSqlType(VARCHAR)))), toSqlType(BOOLEAN))); } private RelationPlan createInsertPlan(Analysis analysis, Insert insertStatement) { Analysis.Insert insert = analysis.getInsert().orElseThrow(); TableHandle tableHandle = insert.getTarget(); Query query = insertStatement.getQuery(); Optional<TableLayout> newTableLayout = insert.getNewTableLayout(); return getInsertPlan(analysis, insert.getTable(), query, tableHandle, insert.getColumns(), newTableLayout, Optional.empty()); } private RelationPlan createRefreshMaterializedViewPlan(Analysis analysis) { Optional<QualifiedObjectName> delegatedRefreshMaterializedView = analysis.getDelegatedRefreshMaterializedView(); if (delegatedRefreshMaterializedView.isPresent()) { return new RelationPlan( new RefreshMaterializedViewNode(idAllocator.getNextId(), delegatedRefreshMaterializedView.get()), analysis.getRootScope(), ImmutableList.of(), Optional.empty()); } checkState(analysis.getRefreshMaterializedView().isPresent(), "RefreshMaterializedViewAnalysis handle is missing"); Analysis.RefreshMaterializedViewAnalysis viewAnalysis = analysis.getRefreshMaterializedView().get(); TableHandle tableHandle = viewAnalysis.getTarget(); Query query = viewAnalysis.getQuery(); Optional<TableLayout> newTableLayout = metadata.getInsertLayout(session, viewAnalysis.getTarget()); TableWriterNode.RefreshMaterializedViewReference writerTarget = new TableWriterNode.RefreshMaterializedViewReference( viewAnalysis.getTable(), tableHandle, new ArrayList<>(analysis.getTables())); return getInsertPlan(analysis, viewAnalysis.getTable(), query, tableHandle, viewAnalysis.getColumns(), newTableLayout, Optional.of(writerTarget)); } private RelationPlan createTableWriterPlan( Analysis analysis, PlanNode source, List<Symbol> symbols, WriterTarget target, List<String> columnNames, List<ColumnMetadata> columnMetadataList, Optional<TableLayout> writeTableLayout, TableStatisticsMetadata statisticsMetadata) { Optional<PartitioningScheme> partitioningScheme = Optional.empty(); Optional<PartitioningScheme> preferredPartitioningScheme = Optional.empty(); if (writeTableLayout.isPresent()) { List<Symbol> partitionFunctionArguments = new ArrayList<>(); writeTableLayout.get().getPartitionColumns().stream() .mapToInt(columnNames::indexOf) .mapToObj(symbols::get) .forEach(partitionFunctionArguments::add); List<Symbol> outputLayout = new ArrayList<>(symbols); Optional<PartitioningHandle> partitioningHandle = writeTableLayout.get().getPartitioning(); if (partitioningHandle.isPresent()) { partitioningScheme = Optional.of(new PartitioningScheme( Partitioning.create(partitioningHandle.get(), partitionFunctionArguments), outputLayout)); } else { // empty connector partitioning handle means evenly partitioning on partitioning columns preferredPartitioningScheme = Optional.of(new PartitioningScheme( Partitioning.create(FIXED_HASH_DISTRIBUTION, partitionFunctionArguments), outputLayout)); } } verify(columnNames.size() == symbols.size(), "columnNames.size() != symbols.size(): %s and %s", columnNames, symbols); Map<String, Symbol> columnToSymbolMap = zip(columnNames.stream(), symbols.stream(), SimpleImmutableEntry::new) .collect(toImmutableMap(Entry::getKey, Entry::getValue)); Set<Symbol> notNullColumnSymbols = columnMetadataList.stream() .filter(column -> !column.isNullable()) .map(ColumnMetadata::getName) .map(columnToSymbolMap::get) .collect(toImmutableSet()); if (!statisticsMetadata.isEmpty()) { TableStatisticAggregation result = statisticsAggregationPlanner.createStatisticsAggregation(statisticsMetadata, columnToSymbolMap); StatisticAggregations.Parts aggregations = result.getAggregations().createPartialAggregations(symbolAllocator, plannerContext); // partial aggregation is run within the TableWriteOperator to calculate the statistics for // the data consumed by the TableWriteOperator // final aggregation is run within the TableFinishOperator to summarize collected statistics // by the partial aggregation from all of the writer nodes StatisticAggregations partialAggregation = aggregations.getPartialAggregation(); TableFinishNode commitNode = new TableFinishNode( idAllocator.getNextId(), new TableWriterNode( idAllocator.getNextId(), source, target, symbolAllocator.newSymbol("partialrows", BIGINT), symbolAllocator.newSymbol("fragment", VARBINARY), symbols, columnNames, notNullColumnSymbols, partitioningScheme, preferredPartitioningScheme, Optional.of(partialAggregation), Optional.of(result.getDescriptor().map(aggregations.getMappings()::get))), target, symbolAllocator.newSymbol("rows", BIGINT), Optional.of(aggregations.getFinalAggregation()), Optional.of(result.getDescriptor())); return new RelationPlan(commitNode, analysis.getRootScope(), commitNode.getOutputSymbols(), Optional.empty()); } TableFinishNode commitNode = new TableFinishNode( idAllocator.getNextId(), new TableWriterNode( idAllocator.getNextId(), source, target, symbolAllocator.newSymbol("partialrows", BIGINT), symbolAllocator.newSymbol("fragment", VARBINARY), symbols, columnNames, notNullColumnSymbols, partitioningScheme, preferredPartitioningScheme, Optional.empty(), Optional.empty()), target, symbolAllocator.newSymbol("rows", BIGINT), Optional.empty(), Optional.empty()); return new RelationPlan(commitNode, analysis.getRootScope(), commitNode.getOutputSymbols(), Optional.empty()); } /* According to the standard, for the purpose of store assignment (INSERT), no non-space characters of a character string, and no non-zero octets of a binary string must be lost when the inserted value is truncated to fit in the target column type. The following method returns a cast from source type to target type with a guarantee of no illegal truncation. TODO Once BINARY and parametric VARBINARY types are supported, they should be handled here. TODO This workaround is insufficient to handle structural types */ private Expression noTruncationCast(Expression expression, Type fromType, Type toType) { if (fromType instanceof UnknownType || (!(toType instanceof VarcharType) && !(toType instanceof CharType))) { return new Cast(expression, toSqlType(toType)); } int targetLength; if (toType instanceof VarcharType) { if (((VarcharType) toType).isUnbounded()) { return new Cast(expression, toSqlType(toType)); } targetLength = ((VarcharType) toType).getBoundedLength(); } else { targetLength = ((CharType) toType).getLength(); } checkState(fromType instanceof VarcharType || fromType instanceof CharType, "inserting non-character value to column of character type"); ResolvedFunction spaceTrimmedLength = metadata.resolveFunction(session, QualifiedName.of("$space_trimmed_length"), fromTypes(VARCHAR)); ResolvedFunction fail = metadata.resolveFunction(session, QualifiedName.of("fail"), fromTypes(VARCHAR)); return new IfExpression( // check if the trimmed value fits in the target type new ComparisonExpression( GREATER_THAN_OR_EQUAL, new GenericLiteral("BIGINT", Integer.toString(targetLength)), new CoalesceExpression( new FunctionCall( spaceTrimmedLength.toQualifiedName(), ImmutableList.of(new Cast(expression, toSqlType(VARCHAR)))), new GenericLiteral("BIGINT", "0"))), new Cast(expression, toSqlType(toType)), new Cast( new FunctionCall( fail.toQualifiedName(), ImmutableList.of(new Cast( new StringLiteral(format( "Cannot truncate non-space characters when casting from %s to %s on INSERT", fromType.getDisplayName(), toType.getDisplayName())), toSqlType(VARCHAR)))), toSqlType(toType))); } private RelationPlan createDeletePlan(Analysis analysis, Delete node) { DeleteNode deleteNode = new QueryPlanner(analysis, symbolAllocator, idAllocator, buildLambdaDeclarationToSymbolMap(analysis, symbolAllocator), plannerContext, Optional.empty(), session, ImmutableMap.of()) .plan(node); TableFinishNode commitNode = new TableFinishNode( idAllocator.getNextId(), deleteNode, deleteNode.getTarget(), symbolAllocator.newSymbol("rows", BIGINT), Optional.empty(), Optional.empty()); return new RelationPlan(commitNode, analysis.getScope(node), commitNode.getOutputSymbols(), Optional.empty()); } private RelationPlan createUpdatePlan(Analysis analysis, Update node) { UpdateNode updateNode = new QueryPlanner(analysis, symbolAllocator, idAllocator, buildLambdaDeclarationToSymbolMap(analysis, symbolAllocator), plannerContext, Optional.empty(), session, ImmutableMap.of()) .plan(node); TableFinishNode commitNode = new TableFinishNode( idAllocator.getNextId(), updateNode, updateNode.getTarget(), symbolAllocator.newSymbol("rows", BIGINT), Optional.empty(), Optional.empty()); return new RelationPlan(commitNode, analysis.getScope(node), commitNode.getOutputSymbols(), Optional.empty()); } private PlanNode createOutputPlan(RelationPlan plan, Analysis analysis) { ImmutableList.Builder<Symbol> outputs = ImmutableList.builder(); ImmutableList.Builder<String> names = ImmutableList.builder(); int columnNumber = 0; RelationType outputDescriptor = analysis.getOutputDescriptor(); for (Field field : outputDescriptor.getVisibleFields()) { String name = field.getName().orElse("_col" + columnNumber); names.add(name); int fieldIndex = outputDescriptor.indexOf(field); Symbol symbol = plan.getSymbol(fieldIndex); outputs.add(symbol); columnNumber++; } return new OutputNode(idAllocator.getNextId(), plan.getRoot(), names.build(), outputs.build()); } private RelationPlan createRelationPlan(Analysis analysis, Query query) { return getRelationPlanner(analysis).process(query, null); } private RelationPlan createRelationPlan(Analysis analysis, Table table) { return getRelationPlanner(analysis).process(table, null); } private RelationPlanner getRelationPlanner(Analysis analysis) { return new RelationPlanner(analysis, symbolAllocator, idAllocator, buildLambdaDeclarationToSymbolMap(analysis, symbolAllocator), plannerContext, Optional.empty(), session, ImmutableMap.of()); } private static Map<NodeRef<LambdaArgumentDeclaration>, Symbol> buildLambdaDeclarationToSymbolMap(Analysis analysis, SymbolAllocator symbolAllocator) { Map<Key, Symbol> allocations = new HashMap<>(); Map<NodeRef<LambdaArgumentDeclaration>, Symbol> result = new LinkedHashMap<>(); for (Entry<NodeRef<Expression>, Type> entry : analysis.getTypes().entrySet()) { if (!(entry.getKey().getNode() instanceof LambdaArgumentDeclaration)) { continue; } LambdaArgumentDeclaration argument = (LambdaArgumentDeclaration) entry.getKey().getNode(); Key key = new Key(argument, entry.getValue()); // Allocate the same symbol for all lambda argument names with a given type. This is needed to be able to // properly identify multiple instances of syntactically equal lambda expressions during planning as expressions // get rewritten via TranslationMap Symbol symbol = allocations.get(key); if (symbol == null) { symbol = symbolAllocator.newSymbol(argument, entry.getValue()); allocations.put(key, symbol); } result.put(NodeRef.of(argument), symbol); } return result; } private RelationPlan createTableExecutePlan(Analysis analysis, TableExecute statement) { Table table = statement.getTable(); TableHandle tableHandle = analysis.getTableHandle(table); QualifiedObjectName tableName = createQualifiedObjectName(session, statement, table.getName()); TableExecuteHandle executeHandle = analysis.getTableExecuteHandle().orElseThrow(); RelationPlan tableScanPlan = createRelationPlan(analysis, table); PlanBuilder sourcePlanBuilder = newPlanBuilder(tableScanPlan, analysis, ImmutableMap.of(), ImmutableMap.of()); if (statement.getWhere().isPresent()) { SubqueryPlanner subqueryPlanner = new SubqueryPlanner(analysis, symbolAllocator, idAllocator, buildLambdaDeclarationToSymbolMap(analysis, symbolAllocator), plannerContext, typeCoercion, Optional.empty(), session, ImmutableMap.of()); Expression whereExpression = statement.getWhere().get(); sourcePlanBuilder = subqueryPlanner.handleSubqueries(sourcePlanBuilder, whereExpression, analysis.getSubqueries(statement)); sourcePlanBuilder = sourcePlanBuilder.withNewRoot(new FilterNode(idAllocator.getNextId(), sourcePlanBuilder.getRoot(), sourcePlanBuilder.rewrite(whereExpression))); } PlanNode sourcePlanRoot = sourcePlanBuilder.getRoot(); TableMetadata tableMetadata = metadata.getTableMetadata(session, tableHandle); List<String> columnNames = tableMetadata.getColumns().stream() .filter(column -> !column.isHidden()) // todo this filter is redundant .map(ColumnMetadata::getName) .collect(toImmutableList()); TableWriterNode.TableExecuteTarget tableExecuteTarget = new TableWriterNode.TableExecuteTarget(executeHandle, Optional.empty(), tableName.asSchemaTableName()); Optional<TableLayout> layout = metadata.getLayoutForTableExecute(session, executeHandle); List<Symbol> symbols = visibleFields(tableScanPlan); // todo extract common method to be used here and in createTableWriterPlan() Optional<PartitioningScheme> partitioningScheme = Optional.empty(); Optional<PartitioningScheme> preferredPartitioningScheme = Optional.empty(); if (layout.isPresent()) { List<Symbol> partitionFunctionArguments = new ArrayList<>(); layout.get().getPartitionColumns().stream() .mapToInt(columnNames::indexOf) .mapToObj(symbols::get) .forEach(partitionFunctionArguments::add); List<Symbol> outputLayout = new ArrayList<>(symbols); Optional<PartitioningHandle> partitioningHandle = layout.get().getPartitioning(); if (partitioningHandle.isPresent()) { partitioningScheme = Optional.of(new PartitioningScheme( Partitioning.create(partitioningHandle.get(), partitionFunctionArguments), outputLayout)); } else { // empty connector partitioning handle means evenly partitioning on partitioning columns preferredPartitioningScheme = Optional.of(new PartitioningScheme( Partitioning.create(FIXED_HASH_DISTRIBUTION, partitionFunctionArguments), outputLayout)); } } verify(columnNames.size() == symbols.size(), "columnNames.size() != symbols.size(): %s and %s", columnNames, symbols); TableFinishNode commitNode = new TableFinishNode( idAllocator.getNextId(), new TableExecuteNode( idAllocator.getNextId(), sourcePlanRoot, tableExecuteTarget, symbolAllocator.newSymbol("partialrows", BIGINT), symbolAllocator.newSymbol("fragment", VARBINARY), symbols, columnNames, partitioningScheme, preferredPartitioningScheme), tableExecuteTarget, symbolAllocator.newSymbol("rows", BIGINT), Optional.empty(), Optional.empty()); return new RelationPlan(commitNode, analysis.getRootScope(), commitNode.getOutputSymbols(), Optional.empty()); } private static class Key { private final LambdaArgumentDeclaration argument; private final Type type; public Key(LambdaArgumentDeclaration argument, Type type) { this.argument = requireNonNull(argument, "argument is null"); this.type = requireNonNull(type, "type is null"); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Key key = (Key) o; return Objects.equals(argument, key.argument) && Objects.equals(type, key.type); } @Override public int hashCode() { return Objects.hash(argument, type); } } }
package com.bunq.sdk.model.generated.endpoint; import com.bunq.sdk.http.ApiClient; import com.bunq.sdk.http.BunqResponse; import com.bunq.sdk.http.BunqResponseRaw; import com.bunq.sdk.model.core.BunqModel; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Create a batch of tab items. */ public class TabItemShopBatch extends BunqModel { /** * Field constants. */ public static final String FIELD_TAB_ITEMS = "tab_items"; /** * Endpoint constants. */ protected static final String ENDPOINT_URL_CREATE = "user/%s/monetary-account/%s/cash-register/%s/tab/%s/tab-item-batch"; /** * The list of tab items in the batch. */ @Expose @SerializedName("tab_items") private List<TabItemShop> tabItems; /** * The list of tab items we want to create in a single batch. Limited to 50 items per batch. */ @Expose @SerializedName("tab_items_field_for_request") private List<TabItemShop> tabItemsFieldForRequest; public TabItemShopBatch() { this(null); } public TabItemShopBatch(List<TabItemShop> tabItems) { this.tabItemsFieldForRequest = tabItems; } /** * Create tab items as a batch. * * @param tabItems The list of tab items we want to create in a single batch. Limited to 50 * items per batch. */ public static BunqResponse<Integer> create(Integer cashRegisterId, String tabUuid, List<TabItemShop> tabItems, Integer monetaryAccountId, Map<String, String> customHeaders) { ApiClient apiClient = new ApiClient(getApiContext()); if (customHeaders == null) { customHeaders = new HashMap<>(); } HashMap<String, Object> requestMap = new HashMap<>(); requestMap.put(FIELD_TAB_ITEMS, tabItems); byte[] requestBytes = determineAllRequestByte(requestMap); BunqResponseRaw responseRaw = apiClient.post(String.format(ENDPOINT_URL_CREATE, determineUserId(), determineMonetaryAccountId(monetaryAccountId), cashRegisterId, tabUuid), requestBytes, customHeaders); return processForId(responseRaw); } public static BunqResponse<Integer> create() { return create(null, null, null, null, null); } public static BunqResponse<Integer> create(Integer cashRegisterId) { return create(cashRegisterId, null, null, null, null); } public static BunqResponse<Integer> create(Integer cashRegisterId, String tabUuid) { return create(cashRegisterId, tabUuid, null, null, null); } public static BunqResponse<Integer> create(Integer cashRegisterId, String tabUuid, List<TabItemShop> tabItems) { return create(cashRegisterId, tabUuid, tabItems, null, null); } public static BunqResponse<Integer> create(Integer cashRegisterId, String tabUuid, List<TabItemShop> tabItems, Integer monetaryAccountId) { return create(cashRegisterId, tabUuid, tabItems, monetaryAccountId, null); } /** * */ public static TabItemShopBatch fromJsonReader(JsonReader reader) { return fromJsonReader(TabItemShopBatch.class, reader); } /** * The list of tab items in the batch. */ public List<TabItemShop> getTabItems() { return this.tabItems; } public void setTabItems(List<TabItemShop> tabItems) { this.tabItems = tabItems; } /** * */ public boolean isAllFieldNull() { if (this.tabItems != null) { return false; } return true; } }
/* * 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.test.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation used to mark WebDriver tests for perf regression testing */ @Retention(RetentionPolicy.RUNTIME) @Inherited @Target({ ElementType.TYPE, ElementType.METHOD }) public @interface PerfTest { }
package com.idugalic.common.command; import com.idugalic.common.model.AuditEntry; public class AuditableAbstractCommand { private AuditEntry auditEntry; public AuditableAbstractCommand(AuditEntry auditEntry) { this.setAuditEntry(auditEntry); } public AuditableAbstractCommand() { } public AuditEntry getAuditEntry() { return auditEntry; } public void setAuditEntry(AuditEntry auditEntry) { this.auditEntry = auditEntry; } }
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.videointelligence.v1p1beta1.model; /** * Annotation progress for a single video. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Cloud Video Intelligence API. For a detailed * explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class GoogleCloudVideointelligenceV1p3beta1VideoAnnotationProgress extends com.google.api.client.json.GenericJson { /** * Specifies which feature is being tracked if the request contains more than one feature. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String feature; /** * Video file location in [Cloud Storage](https://cloud.google.com/storage/). * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String inputUri; /** * Approximate percentage processed thus far. Guaranteed to be 100 when fully processed. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer progressPercent; /** * Specifies which segment is being tracked if the request contains more than one segment. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudVideointelligenceV1p3beta1VideoSegment segment; /** * Time when the request was received. * The value may be {@code null}. */ @com.google.api.client.util.Key private String startTime; /** * Time of the most recent update. * The value may be {@code null}. */ @com.google.api.client.util.Key private String updateTime; /** * Specifies which feature is being tracked if the request contains more than one feature. * @return value or {@code null} for none */ public java.lang.String getFeature() { return feature; } /** * Specifies which feature is being tracked if the request contains more than one feature. * @param feature feature or {@code null} for none */ public GoogleCloudVideointelligenceV1p3beta1VideoAnnotationProgress setFeature(java.lang.String feature) { this.feature = feature; return this; } /** * Video file location in [Cloud Storage](https://cloud.google.com/storage/). * @return value or {@code null} for none */ public java.lang.String getInputUri() { return inputUri; } /** * Video file location in [Cloud Storage](https://cloud.google.com/storage/). * @param inputUri inputUri or {@code null} for none */ public GoogleCloudVideointelligenceV1p3beta1VideoAnnotationProgress setInputUri(java.lang.String inputUri) { this.inputUri = inputUri; return this; } /** * Approximate percentage processed thus far. Guaranteed to be 100 when fully processed. * @return value or {@code null} for none */ public java.lang.Integer getProgressPercent() { return progressPercent; } /** * Approximate percentage processed thus far. Guaranteed to be 100 when fully processed. * @param progressPercent progressPercent or {@code null} for none */ public GoogleCloudVideointelligenceV1p3beta1VideoAnnotationProgress setProgressPercent(java.lang.Integer progressPercent) { this.progressPercent = progressPercent; return this; } /** * Specifies which segment is being tracked if the request contains more than one segment. * @return value or {@code null} for none */ public GoogleCloudVideointelligenceV1p3beta1VideoSegment getSegment() { return segment; } /** * Specifies which segment is being tracked if the request contains more than one segment. * @param segment segment or {@code null} for none */ public GoogleCloudVideointelligenceV1p3beta1VideoAnnotationProgress setSegment(GoogleCloudVideointelligenceV1p3beta1VideoSegment segment) { this.segment = segment; return this; } /** * Time when the request was received. * @return value or {@code null} for none */ public String getStartTime() { return startTime; } /** * Time when the request was received. * @param startTime startTime or {@code null} for none */ public GoogleCloudVideointelligenceV1p3beta1VideoAnnotationProgress setStartTime(String startTime) { this.startTime = startTime; return this; } /** * Time of the most recent update. * @return value or {@code null} for none */ public String getUpdateTime() { return updateTime; } /** * Time of the most recent update. * @param updateTime updateTime or {@code null} for none */ public GoogleCloudVideointelligenceV1p3beta1VideoAnnotationProgress setUpdateTime(String updateTime) { this.updateTime = updateTime; return this; } @Override public GoogleCloudVideointelligenceV1p3beta1VideoAnnotationProgress set(String fieldName, Object value) { return (GoogleCloudVideointelligenceV1p3beta1VideoAnnotationProgress) super.set(fieldName, value); } @Override public GoogleCloudVideointelligenceV1p3beta1VideoAnnotationProgress clone() { return (GoogleCloudVideointelligenceV1p3beta1VideoAnnotationProgress) super.clone(); } }
/** * */ package com.vip.saturn.job.console.domain; import java.io.Serializable; /** * @author chembo.huang * */ public class ZkStatistics implements Serializable { private static final long serialVersionUID = 1L; private int count; private int error; public ZkStatistics() { } public ZkStatistics(int count, int error) { this.count = count; this.error = error; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public int getError() { return error; } public void setError(int error) { this.error = error; } }
/* * Copyright 2010-2013 Ning, Inc. * Copyright 2014-2016 Groupon, Inc * Copyright 2014-2016 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.billing.jaxrs; import java.util.UUID; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.LocalDate; import org.mockito.Mockito; import org.testng.Assert; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import org.killbill.billing.account.api.Account; import org.killbill.billing.account.api.AccountApiException; import org.killbill.billing.account.api.AccountUserApi; import org.killbill.clock.ClockMock; import org.killbill.billing.jaxrs.resources.JaxRsResourceBase; import org.killbill.billing.util.UUIDs; public class TestDateConversion extends JaxRsResourceBase { public TestDateConversion() throws AccountApiException { super(null, null, null, null, Mockito.mock(AccountUserApi.class), null, null, new ClockMock(), null); } public UUID setupAccount(DateTimeZone accountTimeZone) throws AccountApiException { final UUID accountId = UUIDs.randomUUID(); final Account account = Mockito.mock(Account.class); Mockito.when(account.getTimeZone()).thenReturn(accountTimeZone); Mockito.when(accountUserApi.getAccountById(accountId, null)).thenReturn(account); return accountId; } @BeforeTest(groups = "fast") public void beforeTest() { ((ClockMock) clock).resetDeltaFromReality(); } // // BASIC Tests to understand how toLocalDate converts different inputs (null, LocalDate, DateTime) // @Test(groups = "fast") public void testNullConversion() throws AccountApiException { final String input = null; final LocalDate result = toLocalDate(input); Assert.assertNull(result); final UUID accountId = setupAccount(DateTimeZone.forOffsetHours(-8)); ((ClockMock) clock).setTime(new DateTime("2013-08-26T06:50:20Z")); final LocalDate result2 = toLocalDateDefaultToday(accountId, input, null); Assert.assertTrue(result2.compareTo(new LocalDate(2013, 8, 25)) == 0); ((ClockMock) clock).resetDeltaFromReality(); } @Test(groups = "fast") public void testLocalDateConversion() throws AccountApiException { final UUID accountId = setupAccount(DateTimeZone.forOffsetHours(-8)); final String input = "2013-08-25"; final LocalDate result = toLocalDate(input); Assert.assertTrue(result.compareTo(new LocalDate(2013, 8, 25)) == 0); } // // MOSTLY FOR OUR UNDERSTANDING ON HOW LocalDate and DateTime behave with respect to DateTimeZone // // Illustrate that specifying a DateTimeZone in a LocalDate when the input 'instant' is a LocalDate has NO effect. @Test(groups = "fast") public void testTwoLocalDatesWithDifferentTimeZonesAreEquals() throws AccountApiException { final String inputDate = "2013-08-25"; final LocalDate localDate = LocalDate.parse(inputDate, LOCAL_DATE_FORMATTER); final LocalDate localDateInUTC = new LocalDate(localDate, DateTimeZone.UTC); final LocalDate localDateInAccountTimeZone = new LocalDate(localDate, DateTimeZone.forOffsetHours(-8)); Assert.assertEquals(localDateInUTC, localDateInAccountTimeZone); } // Illustrate that specifying a DateTimeZone in a LocalDate when the input 'instant' is a DateTime DOES HAVE an effect. @Test(groups = "fast") public void testTwoDateTimesConstructedFromDateTimesWithDifferentTimeZonesAreDifferent() throws AccountApiException { final DateTime nowUTC = DATE_TIME_FORMATTER.parseDateTime("2015-04-05T05:27:17.547Z"); final LocalDate localDateInUTC = new LocalDate(nowUTC, DateTimeZone.UTC); final LocalDate localDateInAccountTimeZone = new LocalDate(nowUTC, DateTimeZone.forOffsetHours(-8)); Assert.assertNotEquals(localDateInUTC, localDateInAccountTimeZone); } }
package com.jemmy.services.user.model.dto.user; import com.jemmy.apis.user.vo.MenuVo; import com.jemmy.common.base.dto.LoginAuthDto; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.io.Serializable; import java.util.List; /** * The class Login resp dto. * * @author paascloud.net@gmail.com */ @Data @ApiModel(value = "发送短信参数Dto") public class LoginRespDto implements Serializable { private static final long serialVersionUID = -8992761897550131632L; @ApiModelProperty(value = "登陆信息") private LoginAuthDto loginAuthDto; @ApiModelProperty(value = "菜单集合") private List<MenuVo> menuList; }
/* * Copyright (c) Huawei Technologies Co., Ltd. 2021-2022. All rights reserved. */ package com.huawei.recordconsole; import com.huawei.recordconsole.consumer.RecordConsoleConsumer; import com.huawei.recordconsole.elasticsearch.ElasticSearchIndexCreator; import org.elasticsearch.client.RestHighLevelClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import java.io.IOException; /** * Springboot主入口 * * @author lihongjiang * @version 0.1 * @since 2021-02-19 */ @SpringBootApplication public class RecordConsoleApplication implements ApplicationRunner { /** * 自动注入自定义的kafka消费者consumer对象 */ @Autowired RecordConsoleConsumer consumer; @Autowired private ElasticSearchIndexCreator elasticSearchimpl; @Autowired private RestHighLevelClient restHighLevelClient; public static void main(String[] args) { SpringApplication.run(RecordConsoleApplication.class, args); } @Override public void run(ApplicationArguments args) throws InterruptedException, IOException { startSubscribeKafka(); } /** * 启动kafka consumer */ public void startSubscribeKafka() { consumer.start(); } }
package io.gomint.inventory.item; import io.gomint.GoMint; /** * @author geNAZt * @version 1.0 * @stability 3 */ public interface ItemWoodenShovel extends ItemShovel<ItemWoodenShovel>, ItemBurnable { /** * Create a new item stack with given class and amount * * @param amount which is used for the creation * @return freshly generated item */ static ItemWoodenShovel create( int amount ) { return GoMint.instance().createItemStack( ItemWoodenShovel.class, amount ); } }
package com.onlyu.thesis.service.layer.data.remng.repositories; import com.onlyu.thesis.service.domain.remng.embeddables.Floor; import com.onlyu.thesis.service.domain.remng.models.*; import com.onlyu.thesis.service.layer.data.remng.configs.EntityManagerFactoryConfiguration; import lombok.extern.slf4j.Slf4j; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaDelete; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import javax.persistence.metamodel.EntityType; import javax.persistence.metamodel.Metamodel; import java.util.List; import java.util.Optional; @Slf4j @SuppressWarnings({"unused"}) public class PropertyDAONoSessImpl implements PropertyDAO { private final EntityManager entityManager; private final CriteriaBuilder criteriaBuilder; private final Metamodel metamodel; private final EntityTransaction transaction; private final PropertyDAO propertyDAO; public PropertyDAONoSessImpl() { this.entityManager = new EntityManagerFactoryConfiguration(new Class[]{ Property.class, PropertyDetails.class, Floor.class, ProjectDetails.class, Address.class }).getEntityManager(); this.criteriaBuilder = entityManager.getCriteriaBuilder(); this.metamodel = entityManager.getMetamodel(); this.transaction = entityManager.getTransaction(); this.propertyDAO = new PropertyDAOImpl(); } @Override public Property create(Property property) { try { transaction.begin(); entityManager.persist(property); transaction.commit(); return property; } catch (Exception e) { log.error(e.getMessage()); transaction.rollback(); return propertyDAO.create(property); } } @Override public Iterable<Property> createAll(Iterable<Property> propertys) { try { transaction.begin(); propertys.forEach(property -> entityManager.persist(property)); transaction.commit(); return propertys; } catch (Exception e) { log.error(e.getMessage()); transaction.rollback(); return propertyDAO.createAll(propertys); } } @Override public long count() { try { entityManager.clear(); CriteriaQuery<Long> query = criteriaBuilder.createQuery(Long.class); EntityType<Property> property_ = metamodel.entity(Property.class); query.select(criteriaBuilder.count(query.from(property_))); return entityManager.createQuery(query).getSingleResult(); } catch (Exception e) { log.error(e.getMessage()); return propertyDAO.count(); } } @Override public boolean existsById(String id) { try { entityManager.clear(); CriteriaQuery<Long> query = criteriaBuilder.createQuery(Long.class); EntityType<Property> property_ = metamodel.entity(Property.class); Root<Property> from = query.from(property_); query .select(criteriaBuilder.count(from)) .where(criteriaBuilder.equal(from.get(Property_.id), id)); Long count = entityManager.createQuery(query).getSingleResult(); return count != 0 ? true : false; } catch (Exception e) { log.error(e.getMessage()); return propertyDAO.existsById(id); } } @Override public Optional<Property> getById(String id) { try { entityManager.clear(); CriteriaQuery<Property> query = criteriaBuilder.createQuery(Property.class); EntityType<Property> property_ = metamodel.entity(Property.class); Root<Property> fromProperty = query.from(property_); query .select(fromProperty) .where(criteriaBuilder.equal(fromProperty.get(Property_.id), id)); return Optional.of(entityManager.createQuery(query).getSingleResult()); } catch (Exception e) { log.error(e.getMessage()); return propertyDAO.getById(id); } } @Override public List<Property> getById(Iterable<String> ids) { try { entityManager.clear(); CriteriaQuery<Property> query = criteriaBuilder.createQuery(Property.class); EntityType<Property> property_ = metamodel.entity(Property.class); Root<Property> fromProperty = query.from(property_); query .select(fromProperty) .where(fromProperty.get(Property_.id).in(ids)); return entityManager.createQuery(query).getResultList(); } catch (Exception e) { log.error(e.getMessage()); return propertyDAO.getById(ids); } } @Override public Property update(Property property) { try { transaction.begin(); entityManager.merge(property); transaction.commit(); return property; } catch (Exception e) { log.error(e.getMessage()); transaction.rollback(); return propertyDAO.update(property); } } @Override public boolean deleteById(String id) { try { transaction.begin(); CriteriaDelete<Property> delete = criteriaBuilder.createCriteriaDelete(Property.class); EntityType<Property> property_ = metamodel.entity(Property.class); Root<Property> from = delete.from(property_); delete .where(criteriaBuilder.equal(from.get(Property_.id), id)); entityManager.createQuery(delete).executeUpdate(); transaction.commit(); return true; } catch (Exception e) { log.error(e.getMessage()); transaction.rollback(); return propertyDAO.deleteById(id); } } }
// 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.cloudstack.api.command.admin.volume; import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.ResponseObject.ResponseView; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.command.user.volume.AttachVolumeCmd; import org.apache.cloudstack.api.response.VolumeResponse; import org.apache.cloudstack.context.CallContext; import com.cloud.storage.Volume; import com.cloud.vm.VirtualMachine; @APICommand(name = "attachVolume", description = "Attaches a disk volume to a virtual machine.", responseObject = VolumeResponse.class, responseView = ResponseView.Full, entityType = {VirtualMachine.class}, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class AttachVolumeCmdByAdmin extends AttachVolumeCmd { public static final Logger s_logger = Logger.getLogger(AttachVolumeCmdByAdmin.class.getName()); @Override public void execute(){ CallContext.current().setEventDetails("Volume Id: "+this._uuidMgr.getUuid(Volume.class, getId())+" VmId: "+this._uuidMgr.getUuid(VirtualMachine.class, getVirtualMachineId())); Volume result = _volumeService.attachVolumeToVM(this); if (result != null) { VolumeResponse response = _responseGenerator.createVolumeResponse(ResponseView.Full, result); response.setResponseName(getCommandName()); setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to attach volume"); } } }
package org.springframework.cloud.deployer.spi.util; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Utility class for dealing with parseable byte sizes, such as memory and disk limits. * * @author Eric Bottard */ public class ByteSizeUtils { private ByteSizeUtils() { } private static final Pattern SIZE_PATTERN = Pattern.compile("(?<amount>\\d+)(?<unit>(m|g)?)", Pattern.CASE_INSENSITIVE); /** * Return the number of mebibytes (1024*1024) denoted by the given text, where an optional case-insensitive unit of * 'm' or 'g' can be used to mean mebi- or gebi- bytes, respectively. Lack of unit assumes mebibytes. */ public static long parseToMebibytes(String text) { Matcher matcher = SIZE_PATTERN.matcher(text); if (!matcher.matches()) { throw new IllegalArgumentException(String.format("Could not parse '%s' as a byte size." + " Expected a number with optional 'm' or 'g' suffix", text)); } long size = Long.parseLong(matcher.group("amount")); if (matcher.group("unit").equalsIgnoreCase("g")) { size *= 1024L; } return size; } }
/** * Copyright © 2020 SUNCORPORATION All rights reserved. * * Creation Date : July 14th, 2020 */ package com.sun.m2m.okudakelinkdemoapp.view; /** * ListViewに表示するセンサー名とセンサー値を格納 */ public class SensorValue { /** ListViewに表示するセンサー名) */ public String title; /** ListViewに表示するセンサー値 */ public String value; /** * コンストラクタ * @param title センサー名 * @param value センサー値 */ public SensorValue(String title, String value) { this.title = title; this.value = value; } }
package com.smt.web.controller.system; import java.awt.image.BufferedImage; import java.io.IOException; import javax.annotation.Resource; import javax.imageio.ImageIO; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.google.code.kaptcha.Constants; import com.google.code.kaptcha.Producer; import com.smt.framework.web.base.BaseController; /** * 图片验证码(支持算术形式) * * @author smt */ @Controller @RequestMapping("/captcha") public class SysCaptchaController extends BaseController { @Resource(name = "captchaProducer") private Producer captchaProducer; @Resource(name = "captchaProducerMath") private Producer captchaProducerMath; /** * 验证码生成 */ @GetMapping(value = "/captchaImage") public ModelAndView getKaptchaImage(HttpServletRequest request, HttpServletResponse response) { ServletOutputStream out = null; try { HttpSession session = request.getSession(); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); response.addHeader("Cache-Control", "post-check=0, pre-check=0"); response.setHeader("Pragma", "no-cache"); response.setContentType("image/jpeg"); String type = request.getParameter("type"); String capStr = null; String code = null; BufferedImage bi = null; if ("math".equals(type)) { String capText = captchaProducerMath.createText(); capStr = capText.substring(0, capText.lastIndexOf("@")); code = capText.substring(capText.lastIndexOf("@") + 1); bi = captchaProducerMath.createImage(capStr); } else if ("char".equals(type)) { capStr = code = captchaProducer.createText(); bi = captchaProducer.createImage(capStr); } session.setAttribute(Constants.KAPTCHA_SESSION_KEY, code); out = response.getOutputStream(); ImageIO.write(bi, "jpg", out); out.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; } }
package uk.gov.pay.api.service; import org.apache.http.HttpStatus; import uk.gov.pay.api.exception.ConnectorResponseErrorException; import uk.gov.pay.api.model.links.directdebit.DirectDebitEvent; import uk.gov.pay.api.model.links.directdebit.DirectDebitEventsResponse; import javax.inject.Inject; import javax.ws.rs.client.Client; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; public class DirectDebitEventService { private final PublicApiUriGenerator publicApiUriGenerator; private final Client client; @Inject public DirectDebitEventService(PublicApiUriGenerator publicApiUriGenerator, Client client) { this.publicApiUriGenerator = publicApiUriGenerator; this.client = client; } public DirectDebitEventsResponse getResponse(String searchUri) { Response ddConnectorResponse = client.target(searchUri) .request() .accept(MediaType.APPLICATION_JSON) .get(); if (ddConnectorResponse.getStatus() == HttpStatus.SC_OK) { DirectDebitEventsResponse eventsResponse = ddConnectorResponse.readEntity(DirectDebitEventsResponse.class); updatePaginationLinks(eventsResponse); addAgreementAndPaymentLinks(eventsResponse); return eventsResponse; } throw new ConnectorResponseErrorException(ddConnectorResponse); } private void addAgreementAndPaymentLinks(DirectDebitEventsResponse response) { for (DirectDebitEvent event : response.getResults()) { String agreementLink = null; String paymentLink = null; if (event.getMandateExternalId() != null) { agreementLink = publicApiUriGenerator.getMandateURI(event.getMandateExternalId()).toString(); } if (event.getPaymentExternalId() != null) { paymentLink = publicApiUriGenerator.getPaymentURI(event.getPaymentExternalId()).toString(); } event.setLinks(new DirectDebitEvent.Links(agreementLink, paymentLink)); } } private void updatePaginationLinks(DirectDebitEventsResponse response) { DirectDebitEventsResponse.DirectDebitEventsPagination links = response.getPaginationLinks(); if (links.getSelfLink() != null) { response.getPaginationLinks().getFirstLink().setHref(updateHost(response.getPaginationLinks().getFirstLink().getHref())); } if (links.getPrevLink() != null) { response.getPaginationLinks().getPrevLink().setHref(updateHost(response.getPaginationLinks().getPrevLink().getHref())); } if (links.getNextLink() != null) { response.getPaginationLinks().getNextLink().setHref(updateHost(response.getPaginationLinks().getNextLink().getHref())); } if (links.getLastLink() != null) { response.getPaginationLinks().getLastLink().setHref(updateHost(response.getPaginationLinks().getLastLink().getHref())); } if (links.getFirstLink() != null) { response.getPaginationLinks().getSelfLink().setHref(updateHost(response.getPaginationLinks().getSelfLink().getHref())); } } private String updateHost(String url) { if (url != null) { return publicApiUriGenerator.convertHostToPublicAPI(url); } return null; } }
package com.cmclinnovations.ontochem.model.parser.ctml.phase; import org.xml.sax.Attributes; public interface IStateParser { public void parse(String qName, Attributes attributes); }
package com.stormphoenix.ogit.mvp.ui.activities; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.design.widget.TextInputEditText; import android.support.v7.widget.AppCompatButton; import android.util.Log; import android.view.View; import com.stormphoenix.ogit.R; import com.stormphoenix.ogit.dagger2.component.DaggerActivityComponent; import com.stormphoenix.ogit.dagger2.module.ContextModule; import com.stormphoenix.ogit.mvp.presenter.user.LoginPresenter; import com.stormphoenix.ogit.mvp.ui.activities.base.BaseActivity; import com.stormphoenix.ogit.mvp.ui.dialog.ProgressDialogGenerator; import com.stormphoenix.ogit.mvp.view.LoginView; import com.stormphoenix.ogit.utils.ActivityUtils; import javax.inject.Inject; import butterknife.BindView; import butterknife.OnClick; /** * Created by wanlei on 18-2-26. */ public class LoginActivity extends BaseActivity implements LoginView { private static final String TAG = LoginActivity.class.getSimpleName(); @Inject public LoginPresenter mPresenter = null; @BindView(R.id.edit_username) TextInputEditText mEditUsername; @BindView(R.id.edit_password) TextInputEditText mEditPassword; @BindView(R.id.btn_login) AppCompatButton mBtnLogin; private ProgressDialogGenerator generator; public static Intent newIntent(Context context) { return new Intent(context, LoginActivity.class); } @Override protected int getLayoutId() { return R.layout.activity_login; } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); buildProgressDialog(); mPresenter.onAttachView(this); mPresenter.onCreate(savedInstanceState); } @Override public void initializeInjector() { DaggerActivityComponent.builder() .contextModule(new ContextModule(this)) .build() .inject(this); } @Override public void showMessage(String string) { Snackbar.make(mBtnLogin, string, Snackbar.LENGTH_SHORT).show(); } public String getUsernameText() { return mEditUsername.getText().toString().trim(); } public String getPasswordText() { return mEditPassword.getText().toString().trim(); } @Override public void onLoginSuccess() { generator.cancel(); finishView(); startMainActivity(); } @Override protected void onStart() { SplashActivity.finishSplash(); super.onStart(); } @Override public void finishView() { finish(); } @Override public void startMainActivity() { ActivityUtils.startActivity(this, MainActivity.newIntent(this)); } @Override public void showProgress() { generator.show(); } @Override public void hideProgress() { generator.cancel(); } private void buildProgressDialog() { generator = new ProgressDialogGenerator(this); generator.cancelable(false); generator.circularProgress(); generator.content(getResources().getString(R.string.logining)); generator.title(getResources().getString(R.string.login)); } @OnClick(R.id.btn_login) public void onClick(View view) { switch (view.getId()) { case R.id.btn_login: mPresenter.login(getUsernameText(), getPasswordText()); break; default: Log.e(TAG, "onClick: unknown click"); break; } } }
@RestrictTo(LIBRARY) package com.airbnb.android.react.lottie.animation.content; import android.support.annotation.RestrictTo; import static android.support.annotation.RestrictTo.Scope.LIBRARY;
package org.javainaction.sort; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * Implement Raddix sort * * Idea is that if we know some key information about our input array such as maximum number then we can improve sort * time complexity better than O(nlog(n)) * * We perform counting sort meaning identify occurances of number to the base 10 then to 100 and then to 1000 * While we are performing counting sort we make sure we do running some so that have space for numbers whose base * count is colliding with each other say 62 and 12 for base 10 as 2. * * We do this sort until all base are computed with counting sort * */ public class RaddixSort { //O(d * (n + b)) time | O(n + b) space where n is length and d is max number of //digits, and b is base of numbering systems public List<Integer> radixSort(List<Integer> array) { if (array == null || array.size() == 0) return array; int max = Collections.max(array); int digit = 0; while ((max / Math.pow(10, digit)) > 0) { countingSort(array, digit); digit++; } return array; } public void countingSort(List<Integer> array, int digit) { int[] sortedArray = new int[array.size()]; int[] countArray = new int[10]; int digitCol = (int) Math.pow(10, digit); //count array for each elements base for (int num : array) { int countIndex = (num / digitCol) % 10; countArray[countIndex]++; } //do running sum for (int i = 1; i < 10; i++) { //this ensures we have space for elements match with same digitcol countArray[i] += countArray[i - 1]; } //place each element from right to left at position defined by count array //if there are move than one element keep track of total elements by removing occurence for (int i = array.size() - 1; i >= 0; i--) { int countIndex = (array.get(i) / digitCol) % 10; countArray[countIndex]--; int sortedIndex = countArray[countIndex]; sortedArray[sortedIndex] = array.get(i); } for (int i = 0; i < array.size(); i++) { array.set(i, sortedArray[i]); } } public static void main(String[] arg) { var input = new ArrayList<Integer>(Arrays.asList(8762, 654, 3008, 345, 87, 65, 234, 12, 2)); var expected = new ArrayList<Integer>(Arrays.asList(2, 12, 65, 87, 234, 345, 654, 3008, 8762)); var actual = new RaddixSort().radixSort(input); System.out.println(actual); } }
package org.gradle.test.performance.mediummonolithicjavaproject.p104; import org.junit.Test; import static org.junit.Assert.*; public class Test2094 { Production2094 objectUnderTest = new Production2094(); @Test public void testProperty0() { String value = "value"; objectUnderTest.setProperty0(value); assertEquals(value, objectUnderTest.getProperty0()); } @Test public void testProperty1() { String value = "value"; objectUnderTest.setProperty1(value); assertEquals(value, objectUnderTest.getProperty1()); } @Test public void testProperty2() { String value = "value"; objectUnderTest.setProperty2(value); assertEquals(value, objectUnderTest.getProperty2()); } @Test public void testProperty3() { String value = "value"; objectUnderTest.setProperty3(value); assertEquals(value, objectUnderTest.getProperty3()); } @Test public void testProperty4() { String value = "value"; objectUnderTest.setProperty4(value); assertEquals(value, objectUnderTest.getProperty4()); } @Test public void testProperty5() { String value = "value"; objectUnderTest.setProperty5(value); assertEquals(value, objectUnderTest.getProperty5()); } @Test public void testProperty6() { String value = "value"; objectUnderTest.setProperty6(value); assertEquals(value, objectUnderTest.getProperty6()); } @Test public void testProperty7() { String value = "value"; objectUnderTest.setProperty7(value); assertEquals(value, objectUnderTest.getProperty7()); } @Test public void testProperty8() { String value = "value"; objectUnderTest.setProperty8(value); assertEquals(value, objectUnderTest.getProperty8()); } @Test public void testProperty9() { String value = "value"; objectUnderTest.setProperty9(value); assertEquals(value, objectUnderTest.getProperty9()); } }
/******************************************************************************* * SAT4J: a SATisfiability library for Java Copyright (C) 2004, 2013 Artois University and CNRS * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Alternatively, the contents of this file may be used under the terms of * either the GNU Lesser General Public License Version 2.1 or later (the * "LGPL"), in which case the provisions of the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of the LGPL, and not to allow others to use your version of * this file under the terms of the EPL, indicate your decision by deleting * the provisions above and replace them with the notice and other provisions * required by the LGPL. If you do not delete the provisions above, a recipient * may use your version of this file under the terms of the EPL or the LGPL. * * Based on the original MiniSat specification from: * * An extensible SAT solver. Niklas Een and Niklas Sorensson. Proceedings of the * Sixth International Conference on Theory and Applications of Satisfiability * Testing, LNCS 2919, pp 502-518, 2003. * * See www.minisat.se for the original solver in C++. * * Contributors: * CRIL - initial API and implementation *******************************************************************************/ package org.sat4j.pb.multiobjective; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.sat4j.core.VecInt; import org.sat4j.pb.IIntegerPBSolver; import org.sat4j.pb.ObjectiveFunction; import org.sat4j.pb.PseudoOptDecorator; import org.sat4j.specs.IVecInt; import org.sat4j.specs.TimeoutException; /** * A partial implementation of the IMUltiObjectivePBSolver interface designed to * handle optimization functions which are a linear aggregation of other * objective functions. * * The two abstract methods, setInitConstraints() and setGlobalObj(), are called * before the solver is called. setInitConstraints() is designed to add * linearization constraints, while setGlobalObj() is intended to set the global * linear function to the decorated PB solver. * * @author lonca */ public abstract class AbstractLinMultiObjOptimizer extends PseudoOptDecorator implements IMultiObjOptimizationProblem { private static final long serialVersionUID = 1L; protected final List<ObjectiveFunction> objs = new ArrayList<ObjectiveFunction>(); protected boolean initConstraintsSet = false; protected final IIntegerPBSolver integerSolver; public AbstractLinMultiObjOptimizer(IIntegerPBSolver solver) { super(solver); this.integerSolver = solver; } public void addObjectiveFunction(ObjectiveFunction obj) { this.objs.add(obj); } @Override public void setObjectiveFunction(ObjectiveFunction objf) { addObjectiveFunction(objf); } /** * Return the objective functions values through the last model found. The * values are ordered from the lowest to the highest. */ public BigInteger[] getObjectiveValues() { BigInteger[] objValues = new BigInteger[this.objs.size()]; for (int i = 0; i < this.objs.size(); ++i) { objValues[i] = this.objs.get(i).calculateDegree(this); } Arrays.sort(objValues); return objValues; } @Override public boolean admitABetterSolution() throws TimeoutException { return admitABetterSolution(VecInt.EMPTY); } @Override public boolean admitABetterSolution(IVecInt assumps) throws TimeoutException { if (!this.initConstraintsSet) { setInitConstraints(); setGlobalObj(); this.initConstraintsSet = true; } boolean res = super.admitABetterSolution(assumps); if (res && isVerbose()) { System.out.println(getLogPrefix() + "Current objective functions values: " + Arrays.toString(getObjectiveValues())); } return res; } @Override public boolean hasNoObjectiveFunction() { return false; } /** * Implement this method to add some constraints before the first call to * the solver. */ protected abstract void setInitConstraints(); /** * Implement this method to set a global linear objective function, which * depends on the added objective functions and the initialization-added * constraints. */ protected abstract void setGlobalObj(); }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: addressbookv3.proto package com.example.tutorial; public final class AddressBookProtos { private AddressBookProtos() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } public interface PersonOrBuilder extends // @@protoc_insertion_point(interface_extends:tutorial.Person) com.google.protobuf.MessageOrBuilder { /** * <code>string name = 1;</code> */ java.lang.String getName(); /** * <code>string name = 1;</code> */ com.google.protobuf.ByteString getNameBytes(); /** * <pre> * Unique ID number for this person. * </pre> * * <code>int32 id = 2;</code> */ int getId(); /** * <code>string email = 3;</code> */ java.lang.String getEmail(); /** * <code>string email = 3;</code> */ com.google.protobuf.ByteString getEmailBytes(); /** * <code>repeated .tutorial.Person.PhoneNumber phones = 4;</code> */ java.util.List<com.example.tutorial.AddressBookProtos.Person.PhoneNumber> getPhonesList(); /** * <code>repeated .tutorial.Person.PhoneNumber phones = 4;</code> */ com.example.tutorial.AddressBookProtos.Person.PhoneNumber getPhones(int index); /** * <code>repeated .tutorial.Person.PhoneNumber phones = 4;</code> */ int getPhonesCount(); /** * <code>repeated .tutorial.Person.PhoneNumber phones = 4;</code> */ java.util.List<? extends com.example.tutorial.AddressBookProtos.Person.PhoneNumberOrBuilder> getPhonesOrBuilderList(); /** * <code>repeated .tutorial.Person.PhoneNumber phones = 4;</code> */ com.example.tutorial.AddressBookProtos.Person.PhoneNumberOrBuilder getPhonesOrBuilder( int index); /** * <code>.google.protobuf.Timestamp last_updated = 5;</code> */ boolean hasLastUpdated(); /** * <code>.google.protobuf.Timestamp last_updated = 5;</code> */ com.google.protobuf.Timestamp getLastUpdated(); /** * <code>.google.protobuf.Timestamp last_updated = 5;</code> */ com.google.protobuf.TimestampOrBuilder getLastUpdatedOrBuilder(); } /** * <pre> * [START messages] * </pre> * * Protobuf type {@code tutorial.Person} */ public static final class Person extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:tutorial.Person) PersonOrBuilder { private static final long serialVersionUID = 0L; // Use Person.newBuilder() to construct. private Person(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private Person() { name_ = ""; id_ = 0; email_ = ""; phones_ = java.util.Collections.emptyList(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private Person( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); name_ = s; break; } case 16: { id_ = input.readInt32(); break; } case 26: { java.lang.String s = input.readStringRequireUtf8(); email_ = s; break; } case 34: { if (!((mutable_bitField0_ & 0x00000008) == 0x00000008)) { phones_ = new java.util.ArrayList<com.example.tutorial.AddressBookProtos.Person.PhoneNumber>(); mutable_bitField0_ |= 0x00000008; } phones_.add( input.readMessage(com.example.tutorial.AddressBookProtos.Person.PhoneNumber.parser(), extensionRegistry)); break; } case 42: { com.google.protobuf.Timestamp.Builder subBuilder = null; if (lastUpdated_ != null) { subBuilder = lastUpdated_.toBuilder(); } lastUpdated_ = input.readMessage(com.google.protobuf.Timestamp.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(lastUpdated_); lastUpdated_ = subBuilder.buildPartial(); } break; } default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000008) == 0x00000008)) { phones_ = java.util.Collections.unmodifiableList(phones_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.example.tutorial.AddressBookProtos.internal_static_tutorial_Person_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.example.tutorial.AddressBookProtos.internal_static_tutorial_Person_fieldAccessorTable .ensureFieldAccessorsInitialized( com.example.tutorial.AddressBookProtos.Person.class, com.example.tutorial.AddressBookProtos.Person.Builder.class); } /** * Protobuf enum {@code tutorial.Person.PhoneType} */ public enum PhoneType implements com.google.protobuf.ProtocolMessageEnum { /** * <code>MOBILE = 0;</code> */ MOBILE(0), /** * <code>HOME = 1;</code> */ HOME(1), /** * <code>WORK = 2;</code> */ WORK(2), UNRECOGNIZED(-1), ; /** * <code>MOBILE = 0;</code> */ public static final int MOBILE_VALUE = 0; /** * <code>HOME = 1;</code> */ public static final int HOME_VALUE = 1; /** * <code>WORK = 2;</code> */ public static final int WORK_VALUE = 2; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static PhoneType valueOf(int value) { return forNumber(value); } public static PhoneType forNumber(int value) { switch (value) { case 0: return MOBILE; case 1: return HOME; case 2: return WORK; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<PhoneType> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< PhoneType> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<PhoneType>() { public PhoneType findValueByNumber(int number) { return PhoneType.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return com.example.tutorial.AddressBookProtos.Person.getDescriptor().getEnumTypes().get(0); } private static final PhoneType[] VALUES = values(); public static PhoneType valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private PhoneType(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:tutorial.Person.PhoneType) } public interface PhoneNumberOrBuilder extends // @@protoc_insertion_point(interface_extends:tutorial.Person.PhoneNumber) com.google.protobuf.MessageOrBuilder { /** * <code>string number = 1;</code> */ java.lang.String getNumber(); /** * <code>string number = 1;</code> */ com.google.protobuf.ByteString getNumberBytes(); /** * <code>.tutorial.Person.PhoneType type = 2;</code> */ int getTypeValue(); /** * <code>.tutorial.Person.PhoneType type = 2;</code> */ com.example.tutorial.AddressBookProtos.Person.PhoneType getType(); } /** * Protobuf type {@code tutorial.Person.PhoneNumber} */ public static final class PhoneNumber extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:tutorial.Person.PhoneNumber) PhoneNumberOrBuilder { private static final long serialVersionUID = 0L; // Use PhoneNumber.newBuilder() to construct. private PhoneNumber(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private PhoneNumber() { number_ = ""; type_ = 0; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private PhoneNumber( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); number_ = s; break; } case 16: { int rawValue = input.readEnum(); type_ = rawValue; break; } default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.example.tutorial.AddressBookProtos.internal_static_tutorial_Person_PhoneNumber_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.example.tutorial.AddressBookProtos.internal_static_tutorial_Person_PhoneNumber_fieldAccessorTable .ensureFieldAccessorsInitialized( com.example.tutorial.AddressBookProtos.Person.PhoneNumber.class, com.example.tutorial.AddressBookProtos.Person.PhoneNumber.Builder.class); } public static final int NUMBER_FIELD_NUMBER = 1; private volatile java.lang.Object number_; /** * <code>string number = 1;</code> */ public java.lang.String getNumber() { java.lang.Object ref = number_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); number_ = s; return s; } } /** * <code>string number = 1;</code> */ public com.google.protobuf.ByteString getNumberBytes() { java.lang.Object ref = number_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); number_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int TYPE_FIELD_NUMBER = 2; private int type_; /** * <code>.tutorial.Person.PhoneType type = 2;</code> */ public int getTypeValue() { return type_; } /** * <code>.tutorial.Person.PhoneType type = 2;</code> */ public com.example.tutorial.AddressBookProtos.Person.PhoneType getType() { @SuppressWarnings("deprecation") com.example.tutorial.AddressBookProtos.Person.PhoneType result = com.example.tutorial.AddressBookProtos.Person.PhoneType.valueOf(type_); return result == null ? com.example.tutorial.AddressBookProtos.Person.PhoneType.UNRECOGNIZED : result; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getNumberBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, number_); } if (type_ != com.example.tutorial.AddressBookProtos.Person.PhoneType.MOBILE.getNumber()) { output.writeEnum(2, type_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getNumberBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, number_); } if (type_ != com.example.tutorial.AddressBookProtos.Person.PhoneType.MOBILE.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(2, type_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.example.tutorial.AddressBookProtos.Person.PhoneNumber)) { return super.equals(obj); } com.example.tutorial.AddressBookProtos.Person.PhoneNumber other = (com.example.tutorial.AddressBookProtos.Person.PhoneNumber) obj; boolean result = true; result = result && getNumber() .equals(other.getNumber()); result = result && type_ == other.type_; result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + NUMBER_FIELD_NUMBER; hash = (53 * hash) + getNumber().hashCode(); hash = (37 * hash) + TYPE_FIELD_NUMBER; hash = (53 * hash) + type_; hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.example.tutorial.AddressBookProtos.Person.PhoneNumber parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.example.tutorial.AddressBookProtos.Person.PhoneNumber parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.example.tutorial.AddressBookProtos.Person.PhoneNumber parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.example.tutorial.AddressBookProtos.Person.PhoneNumber parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.example.tutorial.AddressBookProtos.Person.PhoneNumber parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.example.tutorial.AddressBookProtos.Person.PhoneNumber parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.example.tutorial.AddressBookProtos.Person.PhoneNumber parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.example.tutorial.AddressBookProtos.Person.PhoneNumber parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.example.tutorial.AddressBookProtos.Person.PhoneNumber parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.example.tutorial.AddressBookProtos.Person.PhoneNumber parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.example.tutorial.AddressBookProtos.Person.PhoneNumber parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.example.tutorial.AddressBookProtos.Person.PhoneNumber parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.example.tutorial.AddressBookProtos.Person.PhoneNumber prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code tutorial.Person.PhoneNumber} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:tutorial.Person.PhoneNumber) com.example.tutorial.AddressBookProtos.Person.PhoneNumberOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.example.tutorial.AddressBookProtos.internal_static_tutorial_Person_PhoneNumber_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.example.tutorial.AddressBookProtos.internal_static_tutorial_Person_PhoneNumber_fieldAccessorTable .ensureFieldAccessorsInitialized( com.example.tutorial.AddressBookProtos.Person.PhoneNumber.class, com.example.tutorial.AddressBookProtos.Person.PhoneNumber.Builder.class); } // Construct using com.example.tutorial.AddressBookProtos.Person.PhoneNumber.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); number_ = ""; type_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.example.tutorial.AddressBookProtos.internal_static_tutorial_Person_PhoneNumber_descriptor; } @java.lang.Override public com.example.tutorial.AddressBookProtos.Person.PhoneNumber getDefaultInstanceForType() { return com.example.tutorial.AddressBookProtos.Person.PhoneNumber.getDefaultInstance(); } @java.lang.Override public com.example.tutorial.AddressBookProtos.Person.PhoneNumber build() { com.example.tutorial.AddressBookProtos.Person.PhoneNumber result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.example.tutorial.AddressBookProtos.Person.PhoneNumber buildPartial() { com.example.tutorial.AddressBookProtos.Person.PhoneNumber result = new com.example.tutorial.AddressBookProtos.Person.PhoneNumber(this); result.number_ = number_; result.type_ = type_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return (Builder) super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.example.tutorial.AddressBookProtos.Person.PhoneNumber) { return mergeFrom((com.example.tutorial.AddressBookProtos.Person.PhoneNumber)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.example.tutorial.AddressBookProtos.Person.PhoneNumber other) { if (other == com.example.tutorial.AddressBookProtos.Person.PhoneNumber.getDefaultInstance()) return this; if (!other.getNumber().isEmpty()) { number_ = other.number_; onChanged(); } if (other.type_ != 0) { setTypeValue(other.getTypeValue()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.example.tutorial.AddressBookProtos.Person.PhoneNumber parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.example.tutorial.AddressBookProtos.Person.PhoneNumber) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object number_ = ""; /** * <code>string number = 1;</code> */ public java.lang.String getNumber() { java.lang.Object ref = number_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); number_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string number = 1;</code> */ public com.google.protobuf.ByteString getNumberBytes() { java.lang.Object ref = number_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); number_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>string number = 1;</code> */ public Builder setNumber( java.lang.String value) { if (value == null) { throw new NullPointerException(); } number_ = value; onChanged(); return this; } /** * <code>string number = 1;</code> */ public Builder clearNumber() { number_ = getDefaultInstance().getNumber(); onChanged(); return this; } /** * <code>string number = 1;</code> */ public Builder setNumberBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); number_ = value; onChanged(); return this; } private int type_ = 0; /** * <code>.tutorial.Person.PhoneType type = 2;</code> */ public int getTypeValue() { return type_; } /** * <code>.tutorial.Person.PhoneType type = 2;</code> */ public Builder setTypeValue(int value) { type_ = value; onChanged(); return this; } /** * <code>.tutorial.Person.PhoneType type = 2;</code> */ public com.example.tutorial.AddressBookProtos.Person.PhoneType getType() { @SuppressWarnings("deprecation") com.example.tutorial.AddressBookProtos.Person.PhoneType result = com.example.tutorial.AddressBookProtos.Person.PhoneType.valueOf(type_); return result == null ? com.example.tutorial.AddressBookProtos.Person.PhoneType.UNRECOGNIZED : result; } /** * <code>.tutorial.Person.PhoneType type = 2;</code> */ public Builder setType(com.example.tutorial.AddressBookProtos.Person.PhoneType value) { if (value == null) { throw new NullPointerException(); } type_ = value.getNumber(); onChanged(); return this; } /** * <code>.tutorial.Person.PhoneType type = 2;</code> */ public Builder clearType() { type_ = 0; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:tutorial.Person.PhoneNumber) } // @@protoc_insertion_point(class_scope:tutorial.Person.PhoneNumber) private static final com.example.tutorial.AddressBookProtos.Person.PhoneNumber DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.example.tutorial.AddressBookProtos.Person.PhoneNumber(); } public static com.example.tutorial.AddressBookProtos.Person.PhoneNumber getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<PhoneNumber> PARSER = new com.google.protobuf.AbstractParser<PhoneNumber>() { @java.lang.Override public PhoneNumber parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new PhoneNumber(input, extensionRegistry); } }; public static com.google.protobuf.Parser<PhoneNumber> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<PhoneNumber> getParserForType() { return PARSER; } @java.lang.Override public com.example.tutorial.AddressBookProtos.Person.PhoneNumber getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } private int bitField0_; public static final int NAME_FIELD_NUMBER = 1; private volatile java.lang.Object name_; /** * <code>string name = 1;</code> */ public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } } /** * <code>string name = 1;</code> */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ID_FIELD_NUMBER = 2; private int id_; /** * <pre> * Unique ID number for this person. * </pre> * * <code>int32 id = 2;</code> */ public int getId() { return id_; } public static final int EMAIL_FIELD_NUMBER = 3; private volatile java.lang.Object email_; /** * <code>string email = 3;</code> */ public java.lang.String getEmail() { java.lang.Object ref = email_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); email_ = s; return s; } } /** * <code>string email = 3;</code> */ public com.google.protobuf.ByteString getEmailBytes() { java.lang.Object ref = email_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); email_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PHONES_FIELD_NUMBER = 4; private java.util.List<com.example.tutorial.AddressBookProtos.Person.PhoneNumber> phones_; /** * <code>repeated .tutorial.Person.PhoneNumber phones = 4;</code> */ public java.util.List<com.example.tutorial.AddressBookProtos.Person.PhoneNumber> getPhonesList() { return phones_; } /** * <code>repeated .tutorial.Person.PhoneNumber phones = 4;</code> */ public java.util.List<? extends com.example.tutorial.AddressBookProtos.Person.PhoneNumberOrBuilder> getPhonesOrBuilderList() { return phones_; } /** * <code>repeated .tutorial.Person.PhoneNumber phones = 4;</code> */ public int getPhonesCount() { return phones_.size(); } /** * <code>repeated .tutorial.Person.PhoneNumber phones = 4;</code> */ public com.example.tutorial.AddressBookProtos.Person.PhoneNumber getPhones(int index) { return phones_.get(index); } /** * <code>repeated .tutorial.Person.PhoneNumber phones = 4;</code> */ public com.example.tutorial.AddressBookProtos.Person.PhoneNumberOrBuilder getPhonesOrBuilder( int index) { return phones_.get(index); } public static final int LAST_UPDATED_FIELD_NUMBER = 5; private com.google.protobuf.Timestamp lastUpdated_; /** * <code>.google.protobuf.Timestamp last_updated = 5;</code> */ public boolean hasLastUpdated() { return lastUpdated_ != null; } /** * <code>.google.protobuf.Timestamp last_updated = 5;</code> */ public com.google.protobuf.Timestamp getLastUpdated() { return lastUpdated_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : lastUpdated_; } /** * <code>.google.protobuf.Timestamp last_updated = 5;</code> */ public com.google.protobuf.TimestampOrBuilder getLastUpdatedOrBuilder() { return getLastUpdated(); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getNameBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_); } if (id_ != 0) { output.writeInt32(2, id_); } if (!getEmailBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, email_); } for (int i = 0; i < phones_.size(); i++) { output.writeMessage(4, phones_.get(i)); } if (lastUpdated_ != null) { output.writeMessage(5, getLastUpdated()); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getNameBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_); } if (id_ != 0) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(2, id_); } if (!getEmailBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, email_); } for (int i = 0; i < phones_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(4, phones_.get(i)); } if (lastUpdated_ != null) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(5, getLastUpdated()); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.example.tutorial.AddressBookProtos.Person)) { return super.equals(obj); } com.example.tutorial.AddressBookProtos.Person other = (com.example.tutorial.AddressBookProtos.Person) obj; boolean result = true; result = result && getName() .equals(other.getName()); result = result && (getId() == other.getId()); result = result && getEmail() .equals(other.getEmail()); result = result && getPhonesList() .equals(other.getPhonesList()); result = result && (hasLastUpdated() == other.hasLastUpdated()); if (hasLastUpdated()) { result = result && getLastUpdated() .equals(other.getLastUpdated()); } result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + NAME_FIELD_NUMBER; hash = (53 * hash) + getName().hashCode(); hash = (37 * hash) + ID_FIELD_NUMBER; hash = (53 * hash) + getId(); hash = (37 * hash) + EMAIL_FIELD_NUMBER; hash = (53 * hash) + getEmail().hashCode(); if (getPhonesCount() > 0) { hash = (37 * hash) + PHONES_FIELD_NUMBER; hash = (53 * hash) + getPhonesList().hashCode(); } if (hasLastUpdated()) { hash = (37 * hash) + LAST_UPDATED_FIELD_NUMBER; hash = (53 * hash) + getLastUpdated().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.example.tutorial.AddressBookProtos.Person parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.example.tutorial.AddressBookProtos.Person parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.example.tutorial.AddressBookProtos.Person parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.example.tutorial.AddressBookProtos.Person parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.example.tutorial.AddressBookProtos.Person parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.example.tutorial.AddressBookProtos.Person parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.example.tutorial.AddressBookProtos.Person parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.example.tutorial.AddressBookProtos.Person parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.example.tutorial.AddressBookProtos.Person parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.example.tutorial.AddressBookProtos.Person parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.example.tutorial.AddressBookProtos.Person parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.example.tutorial.AddressBookProtos.Person parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.example.tutorial.AddressBookProtos.Person prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * [START messages] * </pre> * * Protobuf type {@code tutorial.Person} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:tutorial.Person) com.example.tutorial.AddressBookProtos.PersonOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.example.tutorial.AddressBookProtos.internal_static_tutorial_Person_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.example.tutorial.AddressBookProtos.internal_static_tutorial_Person_fieldAccessorTable .ensureFieldAccessorsInitialized( com.example.tutorial.AddressBookProtos.Person.class, com.example.tutorial.AddressBookProtos.Person.Builder.class); } // Construct using com.example.tutorial.AddressBookProtos.Person.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { getPhonesFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); name_ = ""; id_ = 0; email_ = ""; if (phonesBuilder_ == null) { phones_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000008); } else { phonesBuilder_.clear(); } if (lastUpdatedBuilder_ == null) { lastUpdated_ = null; } else { lastUpdated_ = null; lastUpdatedBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.example.tutorial.AddressBookProtos.internal_static_tutorial_Person_descriptor; } @java.lang.Override public com.example.tutorial.AddressBookProtos.Person getDefaultInstanceForType() { return com.example.tutorial.AddressBookProtos.Person.getDefaultInstance(); } @java.lang.Override public com.example.tutorial.AddressBookProtos.Person build() { com.example.tutorial.AddressBookProtos.Person result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.example.tutorial.AddressBookProtos.Person buildPartial() { com.example.tutorial.AddressBookProtos.Person result = new com.example.tutorial.AddressBookProtos.Person(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; result.name_ = name_; result.id_ = id_; result.email_ = email_; if (phonesBuilder_ == null) { if (((bitField0_ & 0x00000008) == 0x00000008)) { phones_ = java.util.Collections.unmodifiableList(phones_); bitField0_ = (bitField0_ & ~0x00000008); } result.phones_ = phones_; } else { result.phones_ = phonesBuilder_.build(); } if (lastUpdatedBuilder_ == null) { result.lastUpdated_ = lastUpdated_; } else { result.lastUpdated_ = lastUpdatedBuilder_.build(); } result.bitField0_ = to_bitField0_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return (Builder) super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.example.tutorial.AddressBookProtos.Person) { return mergeFrom((com.example.tutorial.AddressBookProtos.Person)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.example.tutorial.AddressBookProtos.Person other) { if (other == com.example.tutorial.AddressBookProtos.Person.getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; onChanged(); } if (other.getId() != 0) { setId(other.getId()); } if (!other.getEmail().isEmpty()) { email_ = other.email_; onChanged(); } if (phonesBuilder_ == null) { if (!other.phones_.isEmpty()) { if (phones_.isEmpty()) { phones_ = other.phones_; bitField0_ = (bitField0_ & ~0x00000008); } else { ensurePhonesIsMutable(); phones_.addAll(other.phones_); } onChanged(); } } else { if (!other.phones_.isEmpty()) { if (phonesBuilder_.isEmpty()) { phonesBuilder_.dispose(); phonesBuilder_ = null; phones_ = other.phones_; bitField0_ = (bitField0_ & ~0x00000008); phonesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getPhonesFieldBuilder() : null; } else { phonesBuilder_.addAllMessages(other.phones_); } } } if (other.hasLastUpdated()) { mergeLastUpdated(other.getLastUpdated()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.example.tutorial.AddressBookProtos.Person parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.example.tutorial.AddressBookProtos.Person) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.lang.Object name_ = ""; /** * <code>string name = 1;</code> */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string name = 1;</code> */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>string name = 1;</code> */ public Builder setName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; onChanged(); return this; } /** * <code>string name = 1;</code> */ public Builder clearName() { name_ = getDefaultInstance().getName(); onChanged(); return this; } /** * <code>string name = 1;</code> */ public Builder setNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; onChanged(); return this; } private int id_ ; /** * <pre> * Unique ID number for this person. * </pre> * * <code>int32 id = 2;</code> */ public int getId() { return id_; } /** * <pre> * Unique ID number for this person. * </pre> * * <code>int32 id = 2;</code> */ public Builder setId(int value) { id_ = value; onChanged(); return this; } /** * <pre> * Unique ID number for this person. * </pre> * * <code>int32 id = 2;</code> */ public Builder clearId() { id_ = 0; onChanged(); return this; } private java.lang.Object email_ = ""; /** * <code>string email = 3;</code> */ public java.lang.String getEmail() { java.lang.Object ref = email_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); email_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string email = 3;</code> */ public com.google.protobuf.ByteString getEmailBytes() { java.lang.Object ref = email_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); email_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>string email = 3;</code> */ public Builder setEmail( java.lang.String value) { if (value == null) { throw new NullPointerException(); } email_ = value; onChanged(); return this; } /** * <code>string email = 3;</code> */ public Builder clearEmail() { email_ = getDefaultInstance().getEmail(); onChanged(); return this; } /** * <code>string email = 3;</code> */ public Builder setEmailBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); email_ = value; onChanged(); return this; } private java.util.List<com.example.tutorial.AddressBookProtos.Person.PhoneNumber> phones_ = java.util.Collections.emptyList(); private void ensurePhonesIsMutable() { if (!((bitField0_ & 0x00000008) == 0x00000008)) { phones_ = new java.util.ArrayList<com.example.tutorial.AddressBookProtos.Person.PhoneNumber>(phones_); bitField0_ |= 0x00000008; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.example.tutorial.AddressBookProtos.Person.PhoneNumber, com.example.tutorial.AddressBookProtos.Person.PhoneNumber.Builder, com.example.tutorial.AddressBookProtos.Person.PhoneNumberOrBuilder> phonesBuilder_; /** * <code>repeated .tutorial.Person.PhoneNumber phones = 4;</code> */ public java.util.List<com.example.tutorial.AddressBookProtos.Person.PhoneNumber> getPhonesList() { if (phonesBuilder_ == null) { return java.util.Collections.unmodifiableList(phones_); } else { return phonesBuilder_.getMessageList(); } } /** * <code>repeated .tutorial.Person.PhoneNumber phones = 4;</code> */ public int getPhonesCount() { if (phonesBuilder_ == null) { return phones_.size(); } else { return phonesBuilder_.getCount(); } } /** * <code>repeated .tutorial.Person.PhoneNumber phones = 4;</code> */ public com.example.tutorial.AddressBookProtos.Person.PhoneNumber getPhones(int index) { if (phonesBuilder_ == null) { return phones_.get(index); } else { return phonesBuilder_.getMessage(index); } } /** * <code>repeated .tutorial.Person.PhoneNumber phones = 4;</code> */ public Builder setPhones( int index, com.example.tutorial.AddressBookProtos.Person.PhoneNumber value) { if (phonesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePhonesIsMutable(); phones_.set(index, value); onChanged(); } else { phonesBuilder_.setMessage(index, value); } return this; } /** * <code>repeated .tutorial.Person.PhoneNumber phones = 4;</code> */ public Builder setPhones( int index, com.example.tutorial.AddressBookProtos.Person.PhoneNumber.Builder builderForValue) { if (phonesBuilder_ == null) { ensurePhonesIsMutable(); phones_.set(index, builderForValue.build()); onChanged(); } else { phonesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .tutorial.Person.PhoneNumber phones = 4;</code> */ public Builder addPhones(com.example.tutorial.AddressBookProtos.Person.PhoneNumber value) { if (phonesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePhonesIsMutable(); phones_.add(value); onChanged(); } else { phonesBuilder_.addMessage(value); } return this; } /** * <code>repeated .tutorial.Person.PhoneNumber phones = 4;</code> */ public Builder addPhones( int index, com.example.tutorial.AddressBookProtos.Person.PhoneNumber value) { if (phonesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePhonesIsMutable(); phones_.add(index, value); onChanged(); } else { phonesBuilder_.addMessage(index, value); } return this; } /** * <code>repeated .tutorial.Person.PhoneNumber phones = 4;</code> */ public Builder addPhones( com.example.tutorial.AddressBookProtos.Person.PhoneNumber.Builder builderForValue) { if (phonesBuilder_ == null) { ensurePhonesIsMutable(); phones_.add(builderForValue.build()); onChanged(); } else { phonesBuilder_.addMessage(builderForValue.build()); } return this; } /** * <code>repeated .tutorial.Person.PhoneNumber phones = 4;</code> */ public Builder addPhones( int index, com.example.tutorial.AddressBookProtos.Person.PhoneNumber.Builder builderForValue) { if (phonesBuilder_ == null) { ensurePhonesIsMutable(); phones_.add(index, builderForValue.build()); onChanged(); } else { phonesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .tutorial.Person.PhoneNumber phones = 4;</code> */ public Builder addAllPhones( java.lang.Iterable<? extends com.example.tutorial.AddressBookProtos.Person.PhoneNumber> values) { if (phonesBuilder_ == null) { ensurePhonesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, phones_); onChanged(); } else { phonesBuilder_.addAllMessages(values); } return this; } /** * <code>repeated .tutorial.Person.PhoneNumber phones = 4;</code> */ public Builder clearPhones() { if (phonesBuilder_ == null) { phones_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); } else { phonesBuilder_.clear(); } return this; } /** * <code>repeated .tutorial.Person.PhoneNumber phones = 4;</code> */ public Builder removePhones(int index) { if (phonesBuilder_ == null) { ensurePhonesIsMutable(); phones_.remove(index); onChanged(); } else { phonesBuilder_.remove(index); } return this; } /** * <code>repeated .tutorial.Person.PhoneNumber phones = 4;</code> */ public com.example.tutorial.AddressBookProtos.Person.PhoneNumber.Builder getPhonesBuilder( int index) { return getPhonesFieldBuilder().getBuilder(index); } /** * <code>repeated .tutorial.Person.PhoneNumber phones = 4;</code> */ public com.example.tutorial.AddressBookProtos.Person.PhoneNumberOrBuilder getPhonesOrBuilder( int index) { if (phonesBuilder_ == null) { return phones_.get(index); } else { return phonesBuilder_.getMessageOrBuilder(index); } } /** * <code>repeated .tutorial.Person.PhoneNumber phones = 4;</code> */ public java.util.List<? extends com.example.tutorial.AddressBookProtos.Person.PhoneNumberOrBuilder> getPhonesOrBuilderList() { if (phonesBuilder_ != null) { return phonesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(phones_); } } /** * <code>repeated .tutorial.Person.PhoneNumber phones = 4;</code> */ public com.example.tutorial.AddressBookProtos.Person.PhoneNumber.Builder addPhonesBuilder() { return getPhonesFieldBuilder().addBuilder( com.example.tutorial.AddressBookProtos.Person.PhoneNumber.getDefaultInstance()); } /** * <code>repeated .tutorial.Person.PhoneNumber phones = 4;</code> */ public com.example.tutorial.AddressBookProtos.Person.PhoneNumber.Builder addPhonesBuilder( int index) { return getPhonesFieldBuilder().addBuilder( index, com.example.tutorial.AddressBookProtos.Person.PhoneNumber.getDefaultInstance()); } /** * <code>repeated .tutorial.Person.PhoneNumber phones = 4;</code> */ public java.util.List<com.example.tutorial.AddressBookProtos.Person.PhoneNumber.Builder> getPhonesBuilderList() { return getPhonesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.example.tutorial.AddressBookProtos.Person.PhoneNumber, com.example.tutorial.AddressBookProtos.Person.PhoneNumber.Builder, com.example.tutorial.AddressBookProtos.Person.PhoneNumberOrBuilder> getPhonesFieldBuilder() { if (phonesBuilder_ == null) { phonesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.example.tutorial.AddressBookProtos.Person.PhoneNumber, com.example.tutorial.AddressBookProtos.Person.PhoneNumber.Builder, com.example.tutorial.AddressBookProtos.Person.PhoneNumberOrBuilder>( phones_, ((bitField0_ & 0x00000008) == 0x00000008), getParentForChildren(), isClean()); phones_ = null; } return phonesBuilder_; } private com.google.protobuf.Timestamp lastUpdated_ = null; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> lastUpdatedBuilder_; /** * <code>.google.protobuf.Timestamp last_updated = 5;</code> */ public boolean hasLastUpdated() { return lastUpdatedBuilder_ != null || lastUpdated_ != null; } /** * <code>.google.protobuf.Timestamp last_updated = 5;</code> */ public com.google.protobuf.Timestamp getLastUpdated() { if (lastUpdatedBuilder_ == null) { return lastUpdated_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : lastUpdated_; } else { return lastUpdatedBuilder_.getMessage(); } } /** * <code>.google.protobuf.Timestamp last_updated = 5;</code> */ public Builder setLastUpdated(com.google.protobuf.Timestamp value) { if (lastUpdatedBuilder_ == null) { if (value == null) { throw new NullPointerException(); } lastUpdated_ = value; onChanged(); } else { lastUpdatedBuilder_.setMessage(value); } return this; } /** * <code>.google.protobuf.Timestamp last_updated = 5;</code> */ public Builder setLastUpdated( com.google.protobuf.Timestamp.Builder builderForValue) { if (lastUpdatedBuilder_ == null) { lastUpdated_ = builderForValue.build(); onChanged(); } else { lastUpdatedBuilder_.setMessage(builderForValue.build()); } return this; } /** * <code>.google.protobuf.Timestamp last_updated = 5;</code> */ public Builder mergeLastUpdated(com.google.protobuf.Timestamp value) { if (lastUpdatedBuilder_ == null) { if (lastUpdated_ != null) { lastUpdated_ = com.google.protobuf.Timestamp.newBuilder(lastUpdated_).mergeFrom(value).buildPartial(); } else { lastUpdated_ = value; } onChanged(); } else { lastUpdatedBuilder_.mergeFrom(value); } return this; } /** * <code>.google.protobuf.Timestamp last_updated = 5;</code> */ public Builder clearLastUpdated() { if (lastUpdatedBuilder_ == null) { lastUpdated_ = null; onChanged(); } else { lastUpdated_ = null; lastUpdatedBuilder_ = null; } return this; } /** * <code>.google.protobuf.Timestamp last_updated = 5;</code> */ public com.google.protobuf.Timestamp.Builder getLastUpdatedBuilder() { onChanged(); return getLastUpdatedFieldBuilder().getBuilder(); } /** * <code>.google.protobuf.Timestamp last_updated = 5;</code> */ public com.google.protobuf.TimestampOrBuilder getLastUpdatedOrBuilder() { if (lastUpdatedBuilder_ != null) { return lastUpdatedBuilder_.getMessageOrBuilder(); } else { return lastUpdated_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : lastUpdated_; } } /** * <code>.google.protobuf.Timestamp last_updated = 5;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> getLastUpdatedFieldBuilder() { if (lastUpdatedBuilder_ == null) { lastUpdatedBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>( getLastUpdated(), getParentForChildren(), isClean()); lastUpdated_ = null; } return lastUpdatedBuilder_; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:tutorial.Person) } // @@protoc_insertion_point(class_scope:tutorial.Person) private static final com.example.tutorial.AddressBookProtos.Person DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.example.tutorial.AddressBookProtos.Person(); } public static com.example.tutorial.AddressBookProtos.Person getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<Person> PARSER = new com.google.protobuf.AbstractParser<Person>() { @java.lang.Override public Person parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new Person(input, extensionRegistry); } }; public static com.google.protobuf.Parser<Person> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<Person> getParserForType() { return PARSER; } @java.lang.Override public com.example.tutorial.AddressBookProtos.Person getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface AddressBookOrBuilder extends // @@protoc_insertion_point(interface_extends:tutorial.AddressBook) com.google.protobuf.MessageOrBuilder { /** * <code>repeated .tutorial.Person people = 1;</code> */ java.util.List<com.example.tutorial.AddressBookProtos.Person> getPeopleList(); /** * <code>repeated .tutorial.Person people = 1;</code> */ com.example.tutorial.AddressBookProtos.Person getPeople(int index); /** * <code>repeated .tutorial.Person people = 1;</code> */ int getPeopleCount(); /** * <code>repeated .tutorial.Person people = 1;</code> */ java.util.List<? extends com.example.tutorial.AddressBookProtos.PersonOrBuilder> getPeopleOrBuilderList(); /** * <code>repeated .tutorial.Person people = 1;</code> */ com.example.tutorial.AddressBookProtos.PersonOrBuilder getPeopleOrBuilder( int index); } /** * <pre> * Our address book file is just one of these. * </pre> * * Protobuf type {@code tutorial.AddressBook} */ public static final class AddressBook extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:tutorial.AddressBook) AddressBookOrBuilder { private static final long serialVersionUID = 0L; // Use AddressBook.newBuilder() to construct. private AddressBook(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private AddressBook() { people_ = java.util.Collections.emptyList(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private AddressBook( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { people_ = new java.util.ArrayList<com.example.tutorial.AddressBookProtos.Person>(); mutable_bitField0_ |= 0x00000001; } people_.add( input.readMessage(com.example.tutorial.AddressBookProtos.Person.parser(), extensionRegistry)); break; } default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) { people_ = java.util.Collections.unmodifiableList(people_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.example.tutorial.AddressBookProtos.internal_static_tutorial_AddressBook_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.example.tutorial.AddressBookProtos.internal_static_tutorial_AddressBook_fieldAccessorTable .ensureFieldAccessorsInitialized( com.example.tutorial.AddressBookProtos.AddressBook.class, com.example.tutorial.AddressBookProtos.AddressBook.Builder.class); } public static final int PEOPLE_FIELD_NUMBER = 1; private java.util.List<com.example.tutorial.AddressBookProtos.Person> people_; /** * <code>repeated .tutorial.Person people = 1;</code> */ public java.util.List<com.example.tutorial.AddressBookProtos.Person> getPeopleList() { return people_; } /** * <code>repeated .tutorial.Person people = 1;</code> */ public java.util.List<? extends com.example.tutorial.AddressBookProtos.PersonOrBuilder> getPeopleOrBuilderList() { return people_; } /** * <code>repeated .tutorial.Person people = 1;</code> */ public int getPeopleCount() { return people_.size(); } /** * <code>repeated .tutorial.Person people = 1;</code> */ public com.example.tutorial.AddressBookProtos.Person getPeople(int index) { return people_.get(index); } /** * <code>repeated .tutorial.Person people = 1;</code> */ public com.example.tutorial.AddressBookProtos.PersonOrBuilder getPeopleOrBuilder( int index) { return people_.get(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < people_.size(); i++) { output.writeMessage(1, people_.get(i)); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < people_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, people_.get(i)); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.example.tutorial.AddressBookProtos.AddressBook)) { return super.equals(obj); } com.example.tutorial.AddressBookProtos.AddressBook other = (com.example.tutorial.AddressBookProtos.AddressBook) obj; boolean result = true; result = result && getPeopleList() .equals(other.getPeopleList()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getPeopleCount() > 0) { hash = (37 * hash) + PEOPLE_FIELD_NUMBER; hash = (53 * hash) + getPeopleList().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.example.tutorial.AddressBookProtos.AddressBook parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.example.tutorial.AddressBookProtos.AddressBook parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.example.tutorial.AddressBookProtos.AddressBook parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.example.tutorial.AddressBookProtos.AddressBook parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.example.tutorial.AddressBookProtos.AddressBook parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.example.tutorial.AddressBookProtos.AddressBook parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.example.tutorial.AddressBookProtos.AddressBook parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.example.tutorial.AddressBookProtos.AddressBook parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.example.tutorial.AddressBookProtos.AddressBook parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.example.tutorial.AddressBookProtos.AddressBook parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.example.tutorial.AddressBookProtos.AddressBook parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.example.tutorial.AddressBookProtos.AddressBook parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.example.tutorial.AddressBookProtos.AddressBook prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * Our address book file is just one of these. * </pre> * * Protobuf type {@code tutorial.AddressBook} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:tutorial.AddressBook) com.example.tutorial.AddressBookProtos.AddressBookOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.example.tutorial.AddressBookProtos.internal_static_tutorial_AddressBook_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.example.tutorial.AddressBookProtos.internal_static_tutorial_AddressBook_fieldAccessorTable .ensureFieldAccessorsInitialized( com.example.tutorial.AddressBookProtos.AddressBook.class, com.example.tutorial.AddressBookProtos.AddressBook.Builder.class); } // Construct using com.example.tutorial.AddressBookProtos.AddressBook.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { getPeopleFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); if (peopleBuilder_ == null) { people_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); } else { peopleBuilder_.clear(); } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.example.tutorial.AddressBookProtos.internal_static_tutorial_AddressBook_descriptor; } @java.lang.Override public com.example.tutorial.AddressBookProtos.AddressBook getDefaultInstanceForType() { return com.example.tutorial.AddressBookProtos.AddressBook.getDefaultInstance(); } @java.lang.Override public com.example.tutorial.AddressBookProtos.AddressBook build() { com.example.tutorial.AddressBookProtos.AddressBook result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.example.tutorial.AddressBookProtos.AddressBook buildPartial() { com.example.tutorial.AddressBookProtos.AddressBook result = new com.example.tutorial.AddressBookProtos.AddressBook(this); int from_bitField0_ = bitField0_; if (peopleBuilder_ == null) { if (((bitField0_ & 0x00000001) == 0x00000001)) { people_ = java.util.Collections.unmodifiableList(people_); bitField0_ = (bitField0_ & ~0x00000001); } result.people_ = people_; } else { result.people_ = peopleBuilder_.build(); } onBuilt(); return result; } @java.lang.Override public Builder clone() { return (Builder) super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.example.tutorial.AddressBookProtos.AddressBook) { return mergeFrom((com.example.tutorial.AddressBookProtos.AddressBook)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.example.tutorial.AddressBookProtos.AddressBook other) { if (other == com.example.tutorial.AddressBookProtos.AddressBook.getDefaultInstance()) return this; if (peopleBuilder_ == null) { if (!other.people_.isEmpty()) { if (people_.isEmpty()) { people_ = other.people_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensurePeopleIsMutable(); people_.addAll(other.people_); } onChanged(); } } else { if (!other.people_.isEmpty()) { if (peopleBuilder_.isEmpty()) { peopleBuilder_.dispose(); peopleBuilder_ = null; people_ = other.people_; bitField0_ = (bitField0_ & ~0x00000001); peopleBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getPeopleFieldBuilder() : null; } else { peopleBuilder_.addAllMessages(other.people_); } } } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.example.tutorial.AddressBookProtos.AddressBook parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.example.tutorial.AddressBookProtos.AddressBook) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.util.List<com.example.tutorial.AddressBookProtos.Person> people_ = java.util.Collections.emptyList(); private void ensurePeopleIsMutable() { if (!((bitField0_ & 0x00000001) == 0x00000001)) { people_ = new java.util.ArrayList<com.example.tutorial.AddressBookProtos.Person>(people_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.example.tutorial.AddressBookProtos.Person, com.example.tutorial.AddressBookProtos.Person.Builder, com.example.tutorial.AddressBookProtos.PersonOrBuilder> peopleBuilder_; /** * <code>repeated .tutorial.Person people = 1;</code> */ public java.util.List<com.example.tutorial.AddressBookProtos.Person> getPeopleList() { if (peopleBuilder_ == null) { return java.util.Collections.unmodifiableList(people_); } else { return peopleBuilder_.getMessageList(); } } /** * <code>repeated .tutorial.Person people = 1;</code> */ public int getPeopleCount() { if (peopleBuilder_ == null) { return people_.size(); } else { return peopleBuilder_.getCount(); } } /** * <code>repeated .tutorial.Person people = 1;</code> */ public com.example.tutorial.AddressBookProtos.Person getPeople(int index) { if (peopleBuilder_ == null) { return people_.get(index); } else { return peopleBuilder_.getMessage(index); } } /** * <code>repeated .tutorial.Person people = 1;</code> */ public Builder setPeople( int index, com.example.tutorial.AddressBookProtos.Person value) { if (peopleBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePeopleIsMutable(); people_.set(index, value); onChanged(); } else { peopleBuilder_.setMessage(index, value); } return this; } /** * <code>repeated .tutorial.Person people = 1;</code> */ public Builder setPeople( int index, com.example.tutorial.AddressBookProtos.Person.Builder builderForValue) { if (peopleBuilder_ == null) { ensurePeopleIsMutable(); people_.set(index, builderForValue.build()); onChanged(); } else { peopleBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .tutorial.Person people = 1;</code> */ public Builder addPeople(com.example.tutorial.AddressBookProtos.Person value) { if (peopleBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePeopleIsMutable(); people_.add(value); onChanged(); } else { peopleBuilder_.addMessage(value); } return this; } /** * <code>repeated .tutorial.Person people = 1;</code> */ public Builder addPeople( int index, com.example.tutorial.AddressBookProtos.Person value) { if (peopleBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePeopleIsMutable(); people_.add(index, value); onChanged(); } else { peopleBuilder_.addMessage(index, value); } return this; } /** * <code>repeated .tutorial.Person people = 1;</code> */ public Builder addPeople( com.example.tutorial.AddressBookProtos.Person.Builder builderForValue) { if (peopleBuilder_ == null) { ensurePeopleIsMutable(); people_.add(builderForValue.build()); onChanged(); } else { peopleBuilder_.addMessage(builderForValue.build()); } return this; } /** * <code>repeated .tutorial.Person people = 1;</code> */ public Builder addPeople( int index, com.example.tutorial.AddressBookProtos.Person.Builder builderForValue) { if (peopleBuilder_ == null) { ensurePeopleIsMutable(); people_.add(index, builderForValue.build()); onChanged(); } else { peopleBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .tutorial.Person people = 1;</code> */ public Builder addAllPeople( java.lang.Iterable<? extends com.example.tutorial.AddressBookProtos.Person> values) { if (peopleBuilder_ == null) { ensurePeopleIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, people_); onChanged(); } else { peopleBuilder_.addAllMessages(values); } return this; } /** * <code>repeated .tutorial.Person people = 1;</code> */ public Builder clearPeople() { if (peopleBuilder_ == null) { people_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { peopleBuilder_.clear(); } return this; } /** * <code>repeated .tutorial.Person people = 1;</code> */ public Builder removePeople(int index) { if (peopleBuilder_ == null) { ensurePeopleIsMutable(); people_.remove(index); onChanged(); } else { peopleBuilder_.remove(index); } return this; } /** * <code>repeated .tutorial.Person people = 1;</code> */ public com.example.tutorial.AddressBookProtos.Person.Builder getPeopleBuilder( int index) { return getPeopleFieldBuilder().getBuilder(index); } /** * <code>repeated .tutorial.Person people = 1;</code> */ public com.example.tutorial.AddressBookProtos.PersonOrBuilder getPeopleOrBuilder( int index) { if (peopleBuilder_ == null) { return people_.get(index); } else { return peopleBuilder_.getMessageOrBuilder(index); } } /** * <code>repeated .tutorial.Person people = 1;</code> */ public java.util.List<? extends com.example.tutorial.AddressBookProtos.PersonOrBuilder> getPeopleOrBuilderList() { if (peopleBuilder_ != null) { return peopleBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(people_); } } /** * <code>repeated .tutorial.Person people = 1;</code> */ public com.example.tutorial.AddressBookProtos.Person.Builder addPeopleBuilder() { return getPeopleFieldBuilder().addBuilder( com.example.tutorial.AddressBookProtos.Person.getDefaultInstance()); } /** * <code>repeated .tutorial.Person people = 1;</code> */ public com.example.tutorial.AddressBookProtos.Person.Builder addPeopleBuilder( int index) { return getPeopleFieldBuilder().addBuilder( index, com.example.tutorial.AddressBookProtos.Person.getDefaultInstance()); } /** * <code>repeated .tutorial.Person people = 1;</code> */ public java.util.List<com.example.tutorial.AddressBookProtos.Person.Builder> getPeopleBuilderList() { return getPeopleFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.example.tutorial.AddressBookProtos.Person, com.example.tutorial.AddressBookProtos.Person.Builder, com.example.tutorial.AddressBookProtos.PersonOrBuilder> getPeopleFieldBuilder() { if (peopleBuilder_ == null) { peopleBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.example.tutorial.AddressBookProtos.Person, com.example.tutorial.AddressBookProtos.Person.Builder, com.example.tutorial.AddressBookProtos.PersonOrBuilder>( people_, ((bitField0_ & 0x00000001) == 0x00000001), getParentForChildren(), isClean()); people_ = null; } return peopleBuilder_; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:tutorial.AddressBook) } // @@protoc_insertion_point(class_scope:tutorial.AddressBook) private static final com.example.tutorial.AddressBookProtos.AddressBook DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.example.tutorial.AddressBookProtos.AddressBook(); } public static com.example.tutorial.AddressBookProtos.AddressBook getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<AddressBook> PARSER = new com.google.protobuf.AbstractParser<AddressBook>() { @java.lang.Override public AddressBook parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new AddressBook(input, extensionRegistry); } }; public static com.google.protobuf.Parser<AddressBook> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<AddressBook> getParserForType() { return PARSER; } @java.lang.Override public com.example.tutorial.AddressBookProtos.AddressBook getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } private static final com.google.protobuf.Descriptors.Descriptor internal_static_tutorial_Person_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_tutorial_Person_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_tutorial_Person_PhoneNumber_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_tutorial_Person_PhoneNumber_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_tutorial_AddressBook_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_tutorial_AddressBook_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\023addressbookv3.proto\022\010tutorial\032\037google/" + "protobuf/timestamp.proto\"\207\002\n\006Person\022\014\n\004n" + "ame\030\001 \001(\t\022\n\n\002id\030\002 \001(\005\022\r\n\005email\030\003 \001(\t\022,\n\006" + "phones\030\004 \003(\0132\034.tutorial.Person.PhoneNumb" + "er\0220\n\014last_updated\030\005 \001(\0132\032.google.protob" + "uf.Timestamp\032G\n\013PhoneNumber\022\016\n\006number\030\001 " + "\001(\t\022(\n\004type\030\002 \001(\0162\032.tutorial.Person.Phon" + "eType\"+\n\tPhoneType\022\n\n\006MOBILE\020\000\022\010\n\004HOME\020\001" + "\022\010\n\004WORK\020\002\"/\n\013AddressBook\022 \n\006people\030\001 \003(" + "\0132\020.tutorial.PersonBP\n\024com.example.tutor" + "ialB\021AddressBookProtos\252\002$Google.Protobuf" + ".Examples.AddressBookb\006proto3" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { com.google.protobuf.TimestampProto.getDescriptor(), }, assigner); internal_static_tutorial_Person_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_tutorial_Person_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_tutorial_Person_descriptor, new java.lang.String[] { "Name", "Id", "Email", "Phones", "LastUpdated", }); internal_static_tutorial_Person_PhoneNumber_descriptor = internal_static_tutorial_Person_descriptor.getNestedTypes().get(0); internal_static_tutorial_Person_PhoneNumber_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_tutorial_Person_PhoneNumber_descriptor, new java.lang.String[] { "Number", "Type", }); internal_static_tutorial_AddressBook_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_tutorial_AddressBook_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_tutorial_AddressBook_descriptor, new java.lang.String[] { "People", }); com.google.protobuf.TimestampProto.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.completion; import com.intellij.codeInsight.CodeInsightBundle; import com.intellij.codeInsight.CodeInsightSettings; import com.intellij.codeInsight.completion.CompletionAssertions.WatchingInsertionContext; import com.intellij.codeInsight.completion.actions.BaseCodeCompletionAction; import com.intellij.codeInsight.completion.impl.CompletionServiceImpl; import com.intellij.codeInsight.editorActions.smartEnter.SmartEnterProcessor; import com.intellij.codeInsight.editorActions.smartEnter.SmartEnterProcessors; import com.intellij.codeInsight.lookup.*; import com.intellij.codeInsight.lookup.impl.LookupImpl; import com.intellij.featureStatistics.FeatureUsageTracker; import com.intellij.ide.DataManager; import com.intellij.lang.Language; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.actionSystem.OverridingAction; import com.intellij.openapi.actionSystem.impl.ActionManagerImpl; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.application.impl.ApplicationInfoImpl; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Caret; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorModificationUtil; import com.intellij.openapi.editor.actionSystem.EditorActionManager; import com.intellij.openapi.editor.actionSystem.TypedAction; import com.intellij.openapi.editor.ex.DocumentEx; import com.intellij.openapi.editor.ex.util.EditorUtil; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.progress.util.ProgressIndicatorUtils; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.IndexNotReadyException; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.registry.Registry; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.psi.impl.source.PostprocessReformattingAspect; import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil; import com.intellij.psi.stubs.StubTextInconsistencyException; import com.intellij.psi.util.PsiUtilBase; import com.intellij.util.concurrency.AppExecutorUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import java.util.List; import java.util.concurrent.Future; @SuppressWarnings("deprecation") public class CodeCompletionHandlerBase { private static final Logger LOG = Logger.getInstance(CodeCompletionHandlerBase.class); private static final Key<Boolean> CARET_PROCESSED = Key.create("CodeCompletionHandlerBase.caretProcessed"); /** * If this key is set for a lookup element, the framework will only call handleInsert() on the lookup element when it is selected, * and will not perform any additional processing such as multi-caret handling or insertion of completion character. */ public static final Key<Boolean> DIRECT_INSERTION = Key.create("CodeCompletionHandlerBase.directInsertion"); @NotNull final CompletionType completionType; final boolean invokedExplicitly; final boolean synchronous; final boolean autopopup; private static int ourAutoInsertItemTimeout = 2000; public static CodeCompletionHandlerBase createHandler(@NotNull CompletionType completionType) { return createHandler(completionType, true, false, true); } public static CodeCompletionHandlerBase createHandler(@NotNull CompletionType completionType, boolean invokedExplicitly, boolean autopopup, boolean synchronous) { AnAction codeCompletionAction = ActionManager.getInstance().getAction("CodeCompletion"); if (codeCompletionAction instanceof OverridingAction) { codeCompletionAction = ((ActionManagerImpl) ActionManager.getInstance()).getBaseAction((OverridingAction) codeCompletionAction); } assert (codeCompletionAction instanceof BaseCodeCompletionAction); BaseCodeCompletionAction baseCodeCompletionAction = (BaseCodeCompletionAction) codeCompletionAction; return baseCodeCompletionAction.createHandler(completionType, invokedExplicitly, autopopup, synchronous); } public CodeCompletionHandlerBase(@NotNull CompletionType completionType) { this(completionType, true, false, true); } public CodeCompletionHandlerBase(@NotNull CompletionType completionType, boolean invokedExplicitly, boolean autopopup, boolean synchronous) { this.completionType = completionType; this.invokedExplicitly = invokedExplicitly; this.autopopup = autopopup; this.synchronous = synchronous; if (invokedExplicitly) { assert synchronous; } if (autopopup) { assert !invokedExplicitly; } } public final void invokeCompletion(final Project project, final Editor editor) { invokeCompletion(project, editor, 1); } public final void invokeCompletion(@NotNull final Project project, @NotNull final Editor editor, int time) { invokeCompletion(project, editor, time, false); } public final void invokeCompletion(@NotNull Project project, @NotNull Editor editor, int time, boolean hasModifiers) { clearCaretMarkers(editor); invokeCompletion(project, editor, time, hasModifiers, editor.getCaretModel().getPrimaryCaret()); } private void invokeCompletion(@NotNull Project project, @NotNull Editor editor, int time, boolean hasModifiers, @NotNull Caret caret) { markCaretAsProcessed(caret); if (invokedExplicitly) { StatisticsUpdate.applyLastCompletionStatisticsUpdate(); } checkNoWriteAccess(); CompletionAssertions.checkEditorValid(editor); int offset = editor.getCaretModel().getOffset(); if (editor.isViewer() || editor.getDocument().getRangeGuard(offset, offset) != null) { editor.getDocument().fireReadOnlyModificationAttempt(); EditorModificationUtil.checkModificationAllowed(editor); return; } if (!FileDocumentManager.getInstance().requestWriting(editor.getDocument(), project)) { return; } CompletionPhase phase = CompletionServiceImpl.getCompletionPhase(); boolean repeated = phase.indicator != null && phase.indicator.isRepeatedInvocation(completionType, editor); final int newTime = phase.newCompletionStarted(time, repeated); if (invokedExplicitly) { time = newTime; } final int invocationCount = time; if (CompletionServiceImpl.isPhase(CompletionPhase.InsertedSingleItem.class)) { CompletionServiceImpl.setCompletionPhase(CompletionPhase.NoCompletion); } CompletionServiceImpl.assertPhase(CompletionPhase.NoCompletion.getClass(), CompletionPhase.CommittingDocuments.class); if (invocationCount > 1 && completionType == CompletionType.BASIC) { FeatureUsageTracker.getInstance().triggerFeatureUsed(CodeCompletionFeatures.SECOND_BASIC_COMPLETION); } long startingTime = System.currentTimeMillis(); Runnable initCmd = () -> { WriteAction.run(() -> EditorUtil.fillVirtualSpaceUntilCaret(editor)); CompletionInitializationContextImpl context = withTimeout(calcSyncTimeOut(startingTime), () -> CompletionInitializationUtil.createCompletionInitializationContext(project, editor, caret, invocationCount, completionType)); boolean hasValidContext = context != null; if (!hasValidContext) { final PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(caret, project); context = new CompletionInitializationContextImpl(editor, caret, psiFile, completionType, invocationCount); } doComplete(context, hasModifiers, hasValidContext, startingTime); }; try { if (autopopup) { CommandProcessor.getInstance().runUndoTransparentAction(initCmd); } else { CommandProcessor.getInstance().executeCommand(project, initCmd, null, null, editor.getDocument()); } } catch (IndexNotReadyException e) { if (invokedExplicitly) { DumbService.getInstance(project).showDumbModeNotification(CodeInsightBundle.message("completion.not.available.during.indexing")); } } } private static void checkNoWriteAccess() { if (!ApplicationManager.getApplication().isUnitTestMode()) { if (ApplicationManager.getApplication().isWriteAccessAllowed()) { throw new AssertionError("Completion should not be invoked inside write action"); } } } @NotNull private LookupImpl obtainLookup(Editor editor, Project project) { CompletionAssertions.checkEditorValid(editor); LookupImpl existing = (LookupImpl)LookupManager.getActiveLookup(editor); if (existing != null && existing.isCompletion()) { existing.markReused(); if (!autopopup) { existing.setLookupFocusDegree(LookupFocusDegree.FOCUSED); } return existing; } LookupImpl lookup = (LookupImpl)LookupManager.getInstance(project).createLookup(editor, LookupElement.EMPTY_ARRAY, "", new LookupArranger.DefaultArranger()); if (editor.isOneLineMode()) { lookup.setCancelOnClickOutside(true); lookup.setCancelOnOtherWindowOpen(true); } lookup.setLookupFocusDegree(autopopup ? LookupFocusDegree.UNFOCUSED : LookupFocusDegree.FOCUSED); return lookup; } private void doComplete(CompletionInitializationContextImpl initContext, boolean hasModifiers, boolean isValidContext, long startingTime) { final Editor editor = initContext.getEditor(); CompletionAssertions.checkEditorValid(editor); LookupImpl lookup = obtainLookup(editor, initContext.getProject()); CompletionPhase phase = CompletionServiceImpl.getCompletionPhase(); if (phase instanceof CompletionPhase.CommittingDocuments) { if (phase.indicator != null) { phase.indicator.closeAndFinish(false); } ((CompletionPhase.CommittingDocuments)phase).replaced = true; } else { CompletionServiceImpl.assertPhase(CompletionPhase.NoCompletion.getClass()); } CompletionProgressIndicator indicator = new CompletionProgressIndicator(editor, initContext.getCaret(), initContext.getInvocationCount(), this, initContext.getOffsetMap(), initContext.getHostOffsets(), hasModifiers, lookup); if (synchronous && isValidContext) { OffsetsInFile hostCopyOffsets = withTimeout(calcSyncTimeOut(startingTime), () -> { PsiDocumentManager.getInstance(initContext.getProject()).commitAllDocuments(); return CompletionInitializationUtil.insertDummyIdentifier(initContext, indicator).get(); }); if (hostCopyOffsets != null) { trySynchronousCompletion(initContext, hasModifiers, startingTime, indicator, hostCopyOffsets); return; } } scheduleContributorsAfterAsyncCommit(initContext, indicator, hasModifiers); } private void scheduleContributorsAfterAsyncCommit(CompletionInitializationContextImpl initContext, CompletionProgressIndicator indicator, boolean hasModifiers) { CompletionPhase phase; if (synchronous) { phase = new CompletionPhase.BgCalculation(indicator); indicator.makeSureLookupIsShown(0); } else { phase = new CompletionPhase.CommittingDocuments(indicator, InjectedLanguageUtil.getTopLevelEditor(indicator.getEditor())); } CompletionServiceImpl.setCompletionPhase(phase); ReadAction .nonBlocking(() -> CompletionInitializationUtil.insertDummyIdentifier(initContext, indicator)) .expireWith(phase) .withDocumentsCommitted(indicator.getProject()) .finishOnUiThread(ModalityState.defaultModalityState(), applyPsiChanges -> { OffsetsInFile hostCopyOffsets = applyPsiChanges.get(); if (phase instanceof CompletionPhase.CommittingDocuments) { ((CompletionPhase.CommittingDocuments)phase).replaced = true; } CompletionServiceImpl.setCompletionPhase(new CompletionPhase.BgCalculation(indicator)); startContributorThread(initContext, indicator, hostCopyOffsets, hasModifiers); }) .submit(AppExecutorUtil.getAppExecutorService()); } private void trySynchronousCompletion(CompletionInitializationContextImpl initContext, boolean hasModifiers, long startingTime, CompletionProgressIndicator indicator, OffsetsInFile hostCopyOffsets) { CompletionServiceImpl.setCompletionPhase(new CompletionPhase.Synchronous(indicator)); Future<?> future = startContributorThread(initContext, indicator, hostCopyOffsets, hasModifiers); if (future == null) { return; } int timeout = calcSyncTimeOut(startingTime); indicator.makeSureLookupIsShown(timeout); if (indicator.blockingWaitForFinish(timeout)) { checkForExceptions(future); try { indicator.getLookup().refreshUi(true, false); completionFinished(indicator, hasModifiers); } catch (Throwable e) { indicator.closeAndFinish(true); CompletionServiceImpl.setCompletionPhase(CompletionPhase.NoCompletion); LOG.error(e); } return; } CompletionServiceImpl.setCompletionPhase(new CompletionPhase.BgCalculation(indicator)); indicator.showLookup(); } @Nullable private Future<?> startContributorThread(CompletionInitializationContextImpl initContext, CompletionProgressIndicator indicator, OffsetsInFile hostCopyOffsets, boolean hasModifiers) { if (!hostCopyOffsets.getFile().isValid()) { completionFinished(indicator, hasModifiers); return null; } return indicator.getCompletionThreading().startThread(indicator, () -> AsyncCompletion.tryReadOrCancel(indicator, () -> { OffsetsInFile finalOffsets = CompletionInitializationUtil.toInjectedIfAny(initContext.getFile(), hostCopyOffsets); indicator.registerChildDisposable(finalOffsets::getOffsets); CompletionParameters parameters = CompletionInitializationUtil.createCompletionParameters(initContext, indicator, finalOffsets); parameters.setIsTestingMode(isTestingMode()); indicator.setParameters(parameters); indicator.runContributors(initContext); })); } private static void checkForExceptions(Future<?> future) { if (ApplicationManager.getApplication().isUnitTestMode()) { try { future.get(); } catch (Exception e) { LOG.error(e); } } } private static void checkNotSync(CompletionProgressIndicator indicator, List<LookupElement> allItems) { if (CompletionServiceImpl.isPhase(CompletionPhase.Synchronous.class)) { LOG.error("sync phase survived: " + allItems + "; indicator=" + CompletionServiceImpl.getCompletionPhase().indicator + "; myIndicator=" + indicator); CompletionServiceImpl.setCompletionPhase(CompletionPhase.NoCompletion); } } private AutoCompletionDecision shouldAutoComplete(@NotNull CompletionProgressIndicator indicator, @NotNull List<LookupElement> items, @NotNull CompletionParameters parameters) { if (!invokedExplicitly) { return AutoCompletionDecision.SHOW_LOOKUP; } final LookupElement item = items.get(0); if (items.size() == 1) { final AutoCompletionPolicy policy = getAutocompletionPolicy(item); if (policy == AutoCompletionPolicy.NEVER_AUTOCOMPLETE) return AutoCompletionDecision.SHOW_LOOKUP; if (policy == AutoCompletionPolicy.ALWAYS_AUTOCOMPLETE) return AutoCompletionDecision.insertItem(item); if (!indicator.getLookup().itemMatcher(item).isStartMatch(item)) return AutoCompletionDecision.SHOW_LOOKUP; } if (!isAutocompleteOnInvocation(parameters.getCompletionType())) { return AutoCompletionDecision.SHOW_LOOKUP; } if (isInsideIdentifier(indicator.getOffsetMap())) { return AutoCompletionDecision.SHOW_LOOKUP; } if (items.size() == 1 && getAutocompletionPolicy(item) == AutoCompletionPolicy.GIVE_CHANCE_TO_OVERWRITE) { return AutoCompletionDecision.insertItem(item); } AutoCompletionContext context = new AutoCompletionContext(parameters, items.toArray(LookupElement.EMPTY_ARRAY), indicator.getOffsetMap(), indicator.getLookup()); for (final CompletionContributor contributor : CompletionContributor.forParameters(parameters)) { final AutoCompletionDecision decision = contributor.handleAutoCompletionPossibility(context); if (decision != null) { return decision; } } return AutoCompletionDecision.SHOW_LOOKUP; } @Nullable private static AutoCompletionPolicy getAutocompletionPolicy(LookupElement element) { return element.getAutoCompletionPolicy(); } private static boolean isInsideIdentifier(final OffsetMap offsetMap) { return offsetMap.getOffset(CompletionInitializationContext.IDENTIFIER_END_OFFSET) != offsetMap.getOffset(CompletionInitializationContext.SELECTION_END_OFFSET); } protected void completionFinished(final CompletionProgressIndicator indicator, boolean hasModifiers) { List<LookupElement> items = indicator.getLookup().getItems(); if (items.isEmpty()) { LookupManager.hideActiveLookup(indicator.getProject()); Caret nextCaret = getNextCaretToProcess(indicator.getEditor()); if (nextCaret != null) { invokeCompletion(indicator.getProject(), indicator.getEditor(), indicator.getInvocationCount(), hasModifiers, nextCaret); } else { indicator.handleEmptyLookup(true); checkNotSync(indicator, items); } return; } LOG.assertTrue(!indicator.isRunning(), "running"); LOG.assertTrue(!indicator.isCanceled(), "canceled"); try { CompletionParameters parameters = indicator.getParameters(); AutoCompletionDecision decision = parameters == null ? AutoCompletionDecision.CLOSE_LOOKUP : shouldAutoComplete(indicator, items, parameters); if (decision == AutoCompletionDecision.SHOW_LOOKUP) { indicator.getLookup().setCalculating(false); indicator.showLookup(); CompletionServiceImpl.setCompletionPhase(new CompletionPhase.ItemsCalculated(indicator)); } else if (decision instanceof AutoCompletionDecision.InsertItem) { final Runnable restorePrefix = rememberDocumentState(indicator.getEditor()); final LookupElement item = ((AutoCompletionDecision.InsertItem)decision).getElement(); CommandProcessor.getInstance().executeCommand(indicator.getProject(), () -> { indicator.setMergeCommand(); indicator.getLookup().finishLookup(Lookup.AUTO_INSERT_SELECT_CHAR, item); }, CodeInsightBundle.message("completion.automatic.command.name"), null); // the insert handler may have started a live template with completion if (CompletionService.getCompletionService().getCurrentCompletion() == null && // ...or scheduled another autopopup !CompletionServiceImpl.isPhase(CompletionPhase.CommittingDocuments.class)) { CompletionServiceImpl.setCompletionPhase(hasModifiers? new CompletionPhase.InsertedSingleItem(indicator, restorePrefix) : CompletionPhase.NoCompletion); } } else if (decision == AutoCompletionDecision.CLOSE_LOOKUP) { LookupManager.hideActiveLookup(indicator.getProject()); } } catch (Throwable e) { CompletionServiceImpl.setCompletionPhase(CompletionPhase.NoCompletion); LOG.error(e); } finally { checkNotSync(indicator, items); } } protected void lookupItemSelected(final CompletionProgressIndicator indicator, @NotNull final LookupElement item, final char completionChar, final List<LookupElement> items) { if (indicator.isAutopopupCompletion()) { FeatureUsageTracker.getInstance().triggerFeatureUsed(CodeCompletionFeatures.EDITING_COMPLETION_BASIC); } WatchingInsertionContext context = null; try { StatisticsUpdate update = StatisticsUpdate.collectStatisticChanges(item); if (item.getUserData(DIRECT_INSERTION) != null) { context = callHandleInsert(indicator, item, completionChar); } else { context = insertItemHonorBlockSelection(indicator, item, completionChar, update); } update.trackStatistics(context); } finally { afterItemInsertion(indicator, context == null ? null : context.getLaterRunnable()); } } private static WatchingInsertionContext insertItemHonorBlockSelection(CompletionProcessEx indicator, LookupElement item, char completionChar, StatisticsUpdate update) { final Editor editor = indicator.getEditor(); final int caretOffset = indicator.getCaret().getOffset(); final int idEndOffset = CompletionUtil.calcIdEndOffset(indicator); final int idEndOffsetDelta = idEndOffset - caretOffset; WatchingInsertionContext context; if (editor.getCaretModel().supportsMultipleCarets()) { Ref<WatchingInsertionContext> lastContext = Ref.create(); Editor hostEditor = InjectedLanguageUtil.getTopLevelEditor(editor); boolean wasInjected = hostEditor != editor; OffsetsInFile topLevelOffsets = indicator.getHostOffsets(); hostEditor.getCaretModel().runForEachCaret(caret -> { OffsetsInFile targetOffsets = findInjectedOffsetsIfAny(caret, wasInjected, topLevelOffsets, hostEditor); PsiFile targetFile = targetOffsets.getFile(); Editor targetEditor = InjectedLanguageUtil.getInjectedEditorForInjectedFile(hostEditor, targetFile); int targetCaretOffset = targetEditor.getCaretModel().getOffset(); int idEnd = targetCaretOffset + idEndOffsetDelta; if (idEnd > targetEditor.getDocument().getTextLength()) { idEnd = targetCaretOffset; // no replacement by Tab when offsets gone wrong for some reason } WatchingInsertionContext currentContext = insertItem(indicator.getLookup(), item, completionChar, update, targetEditor, targetFile, targetCaretOffset, idEnd, targetOffsets.getOffsets()); lastContext.set(currentContext); }); context = lastContext.get(); } else { PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, indicator.getProject()); context = insertItem(indicator.getLookup(), item, completionChar, update, editor, psiFile, caretOffset, idEndOffset, indicator.getOffsetMap()); } if (context.shouldAddCompletionChar()) { WriteAction.run(() -> addCompletionChar(context, item)); } checkPsiTextConsistency(indicator); return context; } private static OffsetsInFile findInjectedOffsetsIfAny(@NotNull Caret caret, boolean wasInjected, @NotNull OffsetsInFile topLevelOffsets, @NotNull Editor hostEditor) { if (!wasInjected) return topLevelOffsets; PsiDocumentManager.getInstance(topLevelOffsets.getFile().getProject()).commitDocument(hostEditor.getDocument()); return topLevelOffsets.toInjectedIfAny(caret.getOffset()); } private static void checkPsiTextConsistency(CompletionProcessEx indicator) { PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(InjectedLanguageUtil.getTopLevelEditor(indicator.getEditor()), indicator.getProject()); if (psiFile != null) { if (Registry.is("ide.check.stub.text.consistency") || ApplicationManager.getApplication().isUnitTestMode() && !ApplicationInfoImpl.isInStressTest()) { StubTextInconsistencyException.checkStubTextConsistency(psiFile); if (PsiDocumentManager.getInstance(psiFile.getProject()).hasUncommitedDocuments()) { PsiDocumentManager.getInstance(psiFile.getProject()).commitAllDocuments(); StubTextInconsistencyException.checkStubTextConsistency(psiFile); } } } } public void afterItemInsertion(final CompletionProgressIndicator indicator, final Runnable laterRunnable) { if (laterRunnable != null) { ActionTracker tracker = new ActionTracker(indicator.getEditor(), indicator); Runnable wrapper = () -> { if (!Disposer.isDisposed(indicator) && !indicator.getProject().isDisposed() && !tracker.hasAnythingHappened()) { laterRunnable.run(); } indicator.disposeIndicator(); }; if (isTestingMode()) { wrapper.run(); } else { ApplicationManager.getApplication().invokeLater(wrapper); } } else { indicator.disposeIndicator(); } } private static WatchingInsertionContext insertItem(@Nullable final Lookup lookup, final LookupElement item, final char completionChar, final StatisticsUpdate update, final Editor editor, final PsiFile psiFile, final int caretOffset, final int idEndOffset, final OffsetMap offsetMap) { editor.getCaretModel().moveToOffset(caretOffset); WatchingInsertionContext context = CompletionUtil.createInsertionContext(lookup, item, completionChar, editor, psiFile, caretOffset, idEndOffset, offsetMap); int initialStartOffset = Math.max(0, caretOffset - item.getLookupString().length()); ApplicationManager.getApplication().runWriteAction(() -> { try { if (caretOffset < idEndOffset && completionChar == Lookup.REPLACE_SELECT_CHAR) { Document document = editor.getDocument(); if (document.getRangeGuard(caretOffset, idEndOffset) == null) { document.deleteString(caretOffset, idEndOffset); } } assert context.getStartOffset() >= 0 : "stale startOffset: was " + initialStartOffset + "; selEnd=" + caretOffset + "; idEnd=" + idEndOffset + "; file=" + psiFile; assert context.getTailOffset() >= 0 : "stale tail: was " + initialStartOffset + "; selEnd=" + caretOffset + "; idEnd=" + idEndOffset + "; file=" + psiFile; Project project = psiFile.getProject(); if (item.requiresCommittedDocuments()) { PsiDocumentManager.getInstance(project).commitAllDocuments(); } item.handleInsert(context); PostprocessReformattingAspect.getInstance(project).doPostponedFormatting(); } finally { context.stopWatching(); } EditorModificationUtil.scrollToCaret(editor); }); if (lookup != null) { update.addSparedChars(lookup, item, context); } return context; } private static WatchingInsertionContext callHandleInsert(CompletionProgressIndicator indicator, LookupElement item, char completionChar) { final Editor editor = indicator.getEditor(); final int caretOffset = indicator.getCaret().getOffset(); final int idEndOffset = CompletionUtil.calcIdEndOffset(indicator); PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, indicator.getProject()); WatchingInsertionContext context = CompletionUtil.createInsertionContext(indicator.getLookup(), item, completionChar, editor, psiFile, caretOffset, idEndOffset, indicator.getOffsetMap()); try { item.handleInsert(context); } finally { context.stopWatching(); } return context; } public static void addCompletionChar(InsertionContext context, LookupElement item) { if (!context.getOffsetMap().containsOffset(InsertionContext.TAIL_OFFSET)) { @NonNls String message = "tailOffset<0 after inserting " + item + " of " + item.getClass(); if (context instanceof WatchingInsertionContext) { message += "; invalidated at: " + ((WatchingInsertionContext)context).invalidateTrace + "\n--------"; } LOG.info(message); } else if (!CompletionAssertions.isEditorValid(context.getEditor())) { LOG.info("Injected editor invalidated " + context.getEditor()); } else { context.getEditor().getCaretModel().moveToOffset(context.getTailOffset()); } if (context.getCompletionChar() == Lookup.COMPLETE_STATEMENT_SELECT_CHAR) { Language language = PsiUtilBase.getLanguageInEditor(context.getEditor(), context.getFile().getProject()); if (language != null) { for (SmartEnterProcessor processor : SmartEnterProcessors.INSTANCE.allForLanguage(language)) { if (processor.processAfterCompletion(context.getEditor(), context.getFile())) break; } } } else { DataContext dataContext = DataManager.getInstance().getDataContext(context.getEditor().getContentComponent()); EditorActionManager.getInstance(); TypedAction.getInstance().getHandler().execute(context.getEditor(), context.getCompletionChar(), dataContext); } } private static boolean isAutocompleteOnInvocation(final CompletionType type) { final CodeInsightSettings settings = CodeInsightSettings.getInstance(); if (type == CompletionType.SMART) { return settings.AUTOCOMPLETE_ON_SMART_TYPE_COMPLETION; } return settings.AUTOCOMPLETE_ON_CODE_COMPLETION; } private static Runnable rememberDocumentState(final Editor _editor) { final Editor editor = InjectedLanguageUtil.getTopLevelEditor(_editor); final String documentText = editor.getDocument().getText(); final int caret = editor.getCaretModel().getOffset(); final int selStart = editor.getSelectionModel().getSelectionStart(); final int selEnd = editor.getSelectionModel().getSelectionEnd(); final int vOffset = editor.getScrollingModel().getVerticalScrollOffset(); final int hOffset = editor.getScrollingModel().getHorizontalScrollOffset(); return () -> { DocumentEx document = (DocumentEx) editor.getDocument(); document.replaceString(0, document.getTextLength(), documentText); editor.getCaretModel().moveToOffset(caret); editor.getSelectionModel().setSelection(selStart, selEnd); editor.getScrollingModel().scrollHorizontally(hOffset); editor.getScrollingModel().scrollVertically(vOffset); }; } private static void clearCaretMarkers(@NotNull Editor editor) { for (Caret caret : editor.getCaretModel().getAllCarets()) { caret.putUserData(CARET_PROCESSED, null); } } private static void markCaretAsProcessed(@NotNull Caret caret) { caret.putUserData(CARET_PROCESSED, Boolean.TRUE); } private static Caret getNextCaretToProcess(@NotNull Editor editor) { for (Caret caret : editor.getCaretModel().getAllCarets()) { if (caret.getUserData(CARET_PROCESSED) == null) { return caret; } } return null; } @Nullable private <T> T withTimeout(long maxDurationMillis, @NotNull Computable<T> task) { if (isTestingMode()) { return task.compute(); } return ProgressIndicatorUtils.withTimeout(maxDurationMillis, task); } private static int calcSyncTimeOut(long startTime) { return (int)Math.max(300, ourAutoInsertItemTimeout - (System.currentTimeMillis() - startTime)); } @SuppressWarnings("unused") // for Rider @TestOnly public static void setAutoInsertTimeout(int timeout) { ourAutoInsertItemTimeout = timeout; } protected boolean isTestingCompletionQualityMode() { return false; } protected boolean isTestingMode() { return ApplicationManager.getApplication().isUnitTestMode() || isTestingCompletionQualityMode(); } }
/** * Wrapper to put together all the cli commands used by the application. * * @author donlaiq */ package com.donlaiq.command; import java.util.ArrayList; import java.util.List; import java.util.Properties; import com.donlaiq.command.factory.ReturnSingleOutputProcessHandler; import com.donlaiq.command.factory.ReturnValueOfInteresProcessHandler; import com.donlaiq.command.factory.ProcessHandler; import com.donlaiq.command.factory.ReturnNothingProcessHandler; import com.donlaiq.command.factory.TAddressBalanceProcessHandler; import com.donlaiq.command.factory.TAddressFinderProcessHandler; import com.donlaiq.command.factory.TotalBalanceProcessHandler; import com.donlaiq.command.factory.TransactionListProcessHandler; import com.donlaiq.command.factory.ZAddressFinderProcessHandler; import com.donlaiq.controller.model.Address; import com.donlaiq.controller.model.Transaction; public class ProcessHandlerWrapper { private Properties properties; public ProcessHandlerWrapper() { try { properties = new Properties(); properties.load(TransactionListProcessHandler.class.getClassLoader().getResourceAsStream("resources/setup.properties")); } catch(Exception e) {} } /* * Get a list with the last 100 transactions, where some address of the wallet is associated with them. */ public List<Transaction> getTransactionList() { ProcessHandler processHandler = new TransactionListProcessHandler(" " + properties.getProperty("list.transactions")); return (List<Transaction>)processHandler.executeProcess(); } /* * Get the balances of the wallet. Two balances and the final sum of them, if there are more than one kind of address. */ public String[] getBalances() { ProcessHandler processHandler = new TotalBalanceProcessHandler(" " + properties.getProperty("get.total.balance")); return (String[])processHandler.executeProcess(); } /* * Get the list of transparent addresses. */ public List<Address> getTAddressesList() { ProcessHandler processHandler = new TAddressFinderProcessHandler(" " + properties.getProperty("get.addresses.by.account")); TAddressBalanceProcessHandler tAddressBalanceProcessHandler = new TAddressBalanceProcessHandler(" " + properties.getProperty("t.address.balance")); tAddressBalanceProcessHandler.setAllAddresses((List<String>)processHandler.executeProcess()); return (List<Address>)tAddressBalanceProcessHandler.executeProcess(); } /* * Get the list of private addresses. */ public List<Address> getZAddressesList() { List<Address> zAddressList = new ArrayList<Address>(); ProcessHandler processHandler = new ZAddressFinderProcessHandler(" " + properties.getProperty("z.list.addresses")); List<String> zAddresses = (List<String>)processHandler.executeProcess(); for(String address : zAddresses) { ProcessHandler zAddressBalanceProcessHandler = new ReturnSingleOutputProcessHandler(" " + properties.getProperty("z.get.balance") + " " + address); zAddressList.add(new Address(address, (String)zAddressBalanceProcessHandler.executeProcess())); } return zAddressList; } /* * Get the private key of a transparent address. */ public String getTPrivateKey(String publicKey) { ProcessHandler processHandler = new ReturnSingleOutputProcessHandler(" " + properties.getProperty("dump.priv.key") + " \"" + publicKey + "\""); return (String) processHandler.executeProcess(); } /* * Get the private key of a private address. */ public String getZPrivateKey(String publicKey) { ProcessHandler processHandler = new ReturnSingleOutputProcessHandler(" " + properties.getProperty("z.export.key") + " \"" + publicKey + "\""); return (String) processHandler.executeProcess(); } /* * Import a transparent address to the wallet given its private key. */ public void importTPrivateKey(String privateKey, String rescan) { ProcessHandler processHandler = new ReturnNothingProcessHandler(" " + properties.getProperty("import.priv.key") + " \"" + privateKey + "\" \"\" " + rescan); processHandler.executeProcess(); } /* * Import a private address to the wallet given its private key. */ public void importZPrivateKey(String privateKey, String rescan) { ProcessHandler processHandler = new ReturnNothingProcessHandler(" " + properties.getProperty("z.import.key") + " \"" + privateKey + "\" " + rescan); processHandler.executeProcess(); } /* * Generate a new transparent address. */ public String newTAddress() { ProcessHandler processHandler = new ReturnSingleOutputProcessHandler(" " + properties.getProperty("get.new.address")); return (String)processHandler.executeProcess(); } /* * Generate a new private address. */ public String newZAddress() { ProcessHandler processHandler = new ReturnSingleOutputProcessHandler(" " + properties.getProperty("z.get.new.address")); return (String)processHandler.executeProcess(); } /* * Returns the percentage of synchronization of the local node. */ public String getBlockchainPercentage() { ProcessHandler processHandler = new ReturnValueOfInteresProcessHandler(" " + properties.getProperty("get.blockchain.info"), "verificationprogress"); return (String)processHandler.executeProcess(); } /* * It allows to send coins to another address. */ public void sendMoney(String addressFrom, String addressTo, String amount) { ProcessHandler processHandler = new ReturnNothingProcessHandler(" " + properties.getProperty("send.many") + " \"" + addressFrom + "\" \"[{\\\"address\\\":\\\"" + addressTo + "\\\", \\\"amount\\\":" + amount + "}]\""); processHandler.executeProcess(); } }
package org.hotuganda.collect.android.location.client; import android.content.Context; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; import com.google.android.gms.location.FusedLocationProviderApi; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import timber.log.Timber; /** * An implementation of {@link LocationClient} that uses Google Play * Services to retrieve the User's location. * <p> * Should be used whenever there Google Play Services is present. * <p> * Package-private, use {@link LocationClients} to retrieve the correct * {@link LocationClient}. */ class GoogleLocationClient extends BaseLocationClient implements LocationClient, ConnectionCallbacks, OnConnectionFailedListener, LocationListener { /** * The default requested time between location updates, in milliseconds. */ private static final long DEFAULT_UPDATE_INTERVAL = 5000; /** * The default maximum rate at which location updates can arrive (other updates will be throttled), * in milliseconds. */ private static final long DEFAULT_FASTEST_UPDATE_INTERVAL = 2500; @NonNull private final FusedLocationProviderApi fusedLocationProviderApi; @NonNull private final GoogleApiClient googleApiClient; @Nullable private LocationClientListener locationClientListener; @Nullable private LocationListener locationListener = null; private long updateInterval = DEFAULT_UPDATE_INTERVAL; private long fastestUpdateInterval = DEFAULT_FASTEST_UPDATE_INTERVAL; /** * Constructs a new GoogleLocationClient with the provided Context. * <p> * This Constructor should be used normally. * * @param context The Context where the GoogleLocationClient will be running. */ GoogleLocationClient(@NonNull Context context) { this(locationServicesClientForContext(context), LocationServices.FusedLocationApi, (LocationManager) context.getSystemService(Context.LOCATION_SERVICE)); } /** * Constructs a new AndroidLocationClient with the provided GoogleApiClient * and FusedLocationProviderApi. * <p> * This Constructor should only be used for testing. * * @param googleApiClient The GoogleApiClient for managing the LocationClient's connection * to Play Services. * @param fusedLocationProviderApi The FusedLocationProviderApi for fetching the User's * location. */ GoogleLocationClient(@NonNull GoogleApiClient googleApiClient, @NonNull FusedLocationProviderApi fusedLocationProviderApi, @NonNull LocationManager locationManager) { super(locationManager); this.googleApiClient = googleApiClient; this.fusedLocationProviderApi = fusedLocationProviderApi; } // LocationClient: public void start() { googleApiClient.registerConnectionCallbacks(this); googleApiClient.registerConnectionFailedListener(this); googleApiClient.connect(); } public void stop() { stopLocationUpdates(); googleApiClient.unregisterConnectionCallbacks(this); googleApiClient.unregisterConnectionFailedListener(this); if (googleApiClient.isConnected()) { googleApiClient.disconnect(); } else { onConnectionSuspended(0); } } public void requestLocationUpdates(@NonNull LocationListener locationListener) { if (!isMonitoringLocation()) { fusedLocationProviderApi.requestLocationUpdates(googleApiClient, createLocationRequest(), this); } this.locationListener = locationListener; } public void stopLocationUpdates() { if (!isMonitoringLocation()) { return; } locationListener = null; fusedLocationProviderApi.removeLocationUpdates(googleApiClient, this); } @Override public void setListener(@Nullable LocationClientListener locationClientListener) { this.locationClientListener = locationClientListener; } @Override public Location getLastLocation() { // We need to block if the Client isn't already connected: if (!googleApiClient.isConnected()) { googleApiClient.blockingConnect(); } return fusedLocationProviderApi.getLastLocation(googleApiClient); } @Override public boolean isMonitoringLocation() { return locationListener != null; } @Override public boolean canSetUpdateIntervals() { return true; } @Override public void setUpdateIntervals(long updateInterval, long fastestUpdateInterval) { Timber.i("GoogleLocationClient setting update intervals: %d, %d", updateInterval, fastestUpdateInterval); this.updateInterval = updateInterval; this.fastestUpdateInterval = fastestUpdateInterval; } @Override public void resetUpdateIntervals() { Timber.i("GoogleLocationClient resetting update intervals."); this.updateInterval = DEFAULT_UPDATE_INTERVAL; this.fastestUpdateInterval = DEFAULT_FASTEST_UPDATE_INTERVAL; } // GoogleLocationClient: private LocationRequest createLocationRequest() { LocationRequest locationRequest = new LocationRequest(); locationRequest.setPriority(getPriority().getValue()); locationRequest.setInterval(updateInterval); locationRequest.setInterval(fastestUpdateInterval); return locationRequest; } // ConnectionCallbacks: @Override public void onConnected(@Nullable Bundle bundle) { if (locationClientListener != null) { locationClientListener.onClientStart(); } } @Override public void onConnectionSuspended(int cause) { if (locationClientListener != null) { locationClientListener.onClientStop(); } } // OnConnectionFailedListener: @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { if (locationClientListener != null) { locationClientListener.onClientStartFailure(); } } // LocationListener: @Override public void onLocationChanged(Location location) { Timber.i("Location changed: %s", location.toString()); if (locationListener != null) { locationListener.onLocationChanged(location); } } /** * Helper method for building a GoogleApiClient with the LocationServices API. * * @param context The Context for building the GoogleApiClient. * @return A GoogleApiClient with the LocationServices API. */ private static GoogleApiClient locationServicesClientForContext(@NonNull Context context) { return new GoogleApiClient.Builder(context) .addApi(LocationServices.API) .build(); } }
import java.net.Socket; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.XMLConstants; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamSource; import org.xml.sax.InputSource; class DocumentBuilderTests { public void unconfiguredParse(Socket sock) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.parse(sock.getInputStream()); //unsafe } public void disableDTD(Socket sock) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); DocumentBuilder builder = factory.newDocumentBuilder(); builder.parse(sock.getInputStream()); //safe } public void enableSecurityFeature(Socket sock) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilder builder = factory.newDocumentBuilder(); builder.parse(sock.getInputStream()); //safe } public void enableSecurityFeature2(Socket sock) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://javax.xml.XMLConstants/feature/secure-processing", true); DocumentBuilder builder = factory.newDocumentBuilder(); builder.parse(sock.getInputStream()); //safe } public void enableDTD(Socket sock) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", false); DocumentBuilder builder = factory.newDocumentBuilder(); builder.parse(sock.getInputStream()); //unsafe } public void disableSecurityFeature(Socket sock) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://javax.xml.XMLConstants/feature/secure-processing", false); DocumentBuilder builder = factory.newDocumentBuilder(); builder.parse(sock.getInputStream()); //unsafe } public void disableExternalEntities(Socket sock) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); DocumentBuilder builder = factory.newDocumentBuilder(); builder.parse(sock.getInputStream()); //safe } public void partialDisableExternalEntities(Socket sock) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); DocumentBuilder builder = factory.newDocumentBuilder(); builder.parse(sock.getInputStream()); //unsafe } public void partialDisableExternalEntities2(Socket sock) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); DocumentBuilder builder = factory.newDocumentBuilder(); builder.parse(sock.getInputStream()); //unsafe } public void misConfigureExternalEntities1(Socket sock) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", true); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); DocumentBuilder builder = factory.newDocumentBuilder(); builder.parse(sock.getInputStream()); //unsafe } public void misConfigureExternalEntities2(Socket sock) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); factory.setFeature("http://xml.org/sax/features/external-general-entities", true); DocumentBuilder builder = factory.newDocumentBuilder(); builder.parse(sock.getInputStream()); //unsafe } public void taintedSAXInputSource1(Socket sock) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); SAXSource source = new SAXSource(new InputSource(sock.getInputStream())); builder.parse(source.getInputSource()); //unsafe } public void taintedSAXInputSource2(Socket sock) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); StreamSource source = new StreamSource(sock.getInputStream()); builder.parse(SAXSource.sourceToInputSource(source)); //unsafe builder.parse(source.getInputStream()); //unsafe } private static DocumentBuilderFactory getDocumentBuilderFactory() { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); String feature = ""; feature = "http://xml.org/sax/features/external-parameter-entities"; factory.setFeature(feature, false); feature = "http://xml.org/sax/features/external-general-entities"; factory.setFeature(feature, false); return factory; } private static final ThreadLocal<DocumentBuilder> XML_DOCUMENT_BUILDER = new ThreadLocal<DocumentBuilder>() { @Override protected DocumentBuilder initialValue() { DocumentBuilderFactory factory = getDocumentBuilderFactory(); try { return factory.newDocumentBuilder(); } catch (Exception ex) { throw new RuntimeException(ex); } } }; public void disableExternalEntities2(Socket sock) throws Exception { DocumentBuilder builder = XML_DOCUMENT_BUILDER.get(); builder.parse(sock.getInputStream()); //safe } }
package com.alphawallet.app.ui; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.lifecycle.ViewModelProvider; import com.alphawallet.app.C; import com.alphawallet.app.R; import com.alphawallet.app.entity.CryptoFunctions; import com.alphawallet.app.entity.EIP681Type; import com.alphawallet.app.entity.NetworkInfo; import com.alphawallet.app.entity.Operation; import com.alphawallet.app.entity.QRResult; import com.alphawallet.app.entity.SignAuthenticationCallback; import com.alphawallet.app.entity.StandardFunctionInterface; import com.alphawallet.app.entity.TransactionData; import com.alphawallet.app.entity.Wallet; import com.alphawallet.app.entity.tokens.Token; import com.alphawallet.app.repository.EthereumNetworkBase; import com.alphawallet.app.repository.EthereumNetworkRepository; import com.alphawallet.app.service.GasService; import com.alphawallet.app.ui.QRScanning.QRScanner; import com.alphawallet.app.ui.widget.entity.ActionSheetCallback; import com.alphawallet.app.ui.widget.entity.AddressReadyCallback; import com.alphawallet.app.ui.widget.entity.AmountReadyCallback; import com.alphawallet.app.util.KeyboardUtils; import com.alphawallet.app.util.QRParser; import com.alphawallet.app.util.Utils; import com.alphawallet.app.viewmodel.SendViewModel; import com.alphawallet.app.viewmodel.SendViewModelFactory; import com.alphawallet.app.web3.entity.Address; import com.alphawallet.app.web3.entity.Web3Transaction; import com.alphawallet.app.widget.AWalletAlertDialog; import com.alphawallet.app.widget.ActionSheetDialog; import com.alphawallet.app.widget.FunctionButtonBar; import com.alphawallet.app.widget.InputAddress; import com.alphawallet.app.widget.InputAmount; import com.alphawallet.app.widget.SignTransactionDialog; import com.alphawallet.token.entity.SalesOrderMalformed; import com.alphawallet.token.tools.Convert; import com.alphawallet.token.tools.Numeric; import com.alphawallet.token.tools.ParseMagicLink; import org.web3j.protocol.core.methods.response.EthEstimateGas; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.inject.Inject; import dagger.android.AndroidInjection; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; import static com.alphawallet.app.C.GAS_LIMIT_MIN; import static com.alphawallet.app.C.Key.WALLET; import static com.alphawallet.app.repository.EthereumNetworkBase.hasGasOverride; import static com.alphawallet.app.widget.AWalletAlertDialog.ERROR; import static com.alphawallet.app.widget.AWalletAlertDialog.WARNING; import static com.alphawallet.ethereum.EthereumNetworkBase.MAINNET_ID; public class SendActivity extends BaseActivity implements AmountReadyCallback, StandardFunctionInterface, AddressReadyCallback, ActionSheetCallback { private static final BigDecimal NEGATIVE = BigDecimal.ZERO.subtract(BigDecimal.ONE); @Inject SendViewModelFactory sendViewModelFactory; SendViewModel viewModel; private Wallet wallet; private Token token; private final Handler handler = new Handler(); private AWalletAlertDialog dialog; private QRResult currentResult; private InputAmount amountInput; private InputAddress addressInput; private String sendAddress; private String ensAddress; private BigDecimal sendAmount; private BigDecimal sendGasPrice; private ActionSheetDialog confirmationDialog; @Nullable private Disposable calcGasCost; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { AndroidInjection.inject(this); super.onCreate(savedInstanceState); setContentView(R.layout.activity_send); toolbar(); viewModel = new ViewModelProvider(this, sendViewModelFactory) .get(SendViewModel.class); String contractAddress = getIntent().getStringExtra(C.EXTRA_CONTRACT_ADDRESS); int currentChain = getIntent().getIntExtra(C.EXTRA_NETWORKID, MAINNET_ID); wallet = getIntent().getParcelableExtra(WALLET); token = viewModel.getToken(currentChain, getIntent().getStringExtra(C.EXTRA_ADDRESS)); QRResult result = getIntent().getParcelableExtra(C.EXTRA_AMOUNT); viewModel.transactionFinalised().observe(this, this::txWritten); viewModel.transactionError().observe(this, this::txError); sendAddress = null; sendGasPrice = BigDecimal.ZERO; sendAmount = NEGATIVE; if (!checkTokenValidity(currentChain, contractAddress)) { return; } setTitle(getString(R.string.action_send_tkn, token.getShortName())); setupTokenContent(); if (result != null) { //restore payment request validateEIP681Request(result, true); } } @Override protected void onResume() { super.onResume(); QRResult result = getIntent().getParcelableExtra(C.EXTRA_AMOUNT); if (result != null && (result.type == EIP681Type.PAYMENT || result.type == EIP681Type.TRANSFER)) { handleClick("", R.string.action_next); } } private boolean checkTokenValidity(int currentChain, String contractAddress) { if (token == null || token.tokenInfo == null) { //bad token - try to load from service token = viewModel.getToken(currentChain, contractAddress); if (token == null) { //TODO: possibly invoke token finder in tokensService finish(); } } return (token != null); } private void onBack() { finish(); } @Override public boolean onCreateOptionsMenu(Menu menu) { return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { onBack(); } else if (item.getItemId() == R.id.action_qr) { viewModel.showContractInfo(this, wallet, token); } return false; } @Override public void onBackPressed() { onBack(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Operation taskCode = null; if (requestCode >= SignTransactionDialog.REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS && requestCode <= SignTransactionDialog.REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS + 10) { taskCode = Operation.values()[requestCode - SignTransactionDialog.REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS]; requestCode = SignTransactionDialog.REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS; } if (requestCode == C.SET_GAS_SETTINGS) { //will either be an index, or if using custom then it will contain a price and limit if (data != null && confirmationDialog != null) { int gasSelectionIndex = data.getIntExtra(C.EXTRA_SINGLE_ITEM, -1); long customNonce = data.getLongExtra(C.EXTRA_NONCE, -1); BigDecimal customGasPrice = data.hasExtra(C.EXTRA_GAS_PRICE) ? new BigDecimal(data.getStringExtra(C.EXTRA_GAS_PRICE)) : BigDecimal.ZERO; //may not have set a custom gas price BigDecimal customGasLimit = new BigDecimal(data.getStringExtra(C.EXTRA_GAS_LIMIT)); long expectedTxTime = data.getLongExtra(C.EXTRA_AMOUNT, 0); confirmationDialog.setCurrentGasIndex(gasSelectionIndex, customGasPrice, customGasLimit, expectedTxTime, customNonce); } } else if (requestCode >= SignTransactionDialog.REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS && requestCode <= SignTransactionDialog.REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS + 10) { if (confirmationDialog != null && confirmationDialog.isShowing()) confirmationDialog.completeSignRequest(resultCode == RESULT_OK); } else if (requestCode == C.BARCODE_READER_REQUEST_CODE) { switch (resultCode) { case Activity.RESULT_OK: if (data != null) { String qrCode = data.getStringExtra(C.EXTRA_QR_CODE); //if barcode is still null, ensure we don't GPF if (qrCode == null) { //Toast.makeText(this, R.string.toast_qr_code_no_address, Toast.LENGTH_SHORT).show(); displayScanError(); return; } else if (qrCode.startsWith("wc:")) { startWalletConnect(qrCode); } else { QRParser parser = QRParser.getInstance(EthereumNetworkBase.extraChains()); QRResult result = parser.parse(qrCode); String extracted_address = null; if (result != null) { extracted_address = result.getAddress(); switch (result.getProtocol()) { case "address": addressInput.setAddress(extracted_address); break; case "ethereum": //EIP681 protocol validateEIP681Request(result, false); break; default: break; } } else //try magiclink { ParseMagicLink magicParser = new ParseMagicLink(new CryptoFunctions(), EthereumNetworkRepository.extraChains()); try { if (magicParser.parseUniversalLink(qrCode).chainId > 0) //see if it's a valid link { //let's try to import the link viewModel.showImportLink(this, qrCode); finish(); return; } } catch (SalesOrderMalformed e) { e.printStackTrace(); } } if (extracted_address == null) { displayScanError(); } } } break; case QRScanner.DENY_PERMISSION: showCameraDenied(); break; default: Log.e("SEND", String.format(getString(R.string.barcode_error_format), "Code: " + String.valueOf(resultCode) )); break; } } else { super.onActivityResult(requestCode, resultCode, data); } } private void startWalletConnect(String qrCode) { Intent intent = new Intent(this, WalletConnectActivity.class); intent.putExtra("qrCode", qrCode); intent.putExtra(C.EXTRA_CHAIN_ID, token.tokenInfo.chainId); startActivity(intent); setResult(RESULT_OK); finish(); } private void showCameraDenied() { if (dialog != null && dialog.isShowing()) dialog.dismiss(); dialog = new AWalletAlertDialog(this); dialog.setTitle(R.string.title_dialog_error); dialog.setMessage(R.string.error_camera_permission_denied); dialog.setIcon(ERROR); dialog.setButtonText(R.string.button_ok); dialog.setButtonListener(v -> { dialog.dismiss(); }); dialog.show(); } private void showTokenFetch() { if (dialog != null && dialog.isShowing()) dialog.dismiss(); dialog = new AWalletAlertDialog(this); dialog.setTitle(R.string.searching_for_token); dialog.setIcon(AWalletAlertDialog.NONE); dialog.setProgressMode(); dialog.setCancelable(false); dialog.show(); } private void calculateEstimateDialog() { if (dialog != null && dialog.isShowing()) dialog.dismiss(); dialog = new AWalletAlertDialog(this); dialog.setTitle(getString(R.string.calc_gas_limit)); dialog.setIcon(AWalletAlertDialog.NONE); dialog.setProgressMode(); dialog.setCancelable(false); dialog.show(); } private void validateEIP681Request(QRResult result, boolean overrideNetwork) { if (dialog != null) dialog.dismiss(); //check chain if (result == null) { displayScanError(); return; } NetworkInfo info = viewModel.getNetworkInfo(result.chainId); if (info == null) { displayScanError(); return; } else if (result.type != EIP681Type.ADDRESS && result.chainId != token.tokenInfo.chainId && token.isEthereum()) { //Display chain change warning currentResult = result; showChainChangeDialog(result.chainId); return; } TextView sendText = findViewById(R.id.text_payment_request); switch (result.type) { case ADDRESS: addressInput.setAddress(result.getAddress()); break; case PAYMENT: //correct chain and asset type String ethAmount = Convert.getConvertedValue(new BigDecimal(result.weiValue), Convert.Unit.ETHER.getFactor()); sendText.setVisibility(View.VISIBLE); sendText.setText(R.string.transfer_request); token = viewModel.getToken(result.chainId, wallet.address); addressInput.setAddress(result.getAddress()); amountInput.setupToken(token, viewModel.getAssetDefinitionService(), viewModel.getTokenService(), this); amountInput.setAmount(ethAmount); setupTokenContent(); break; case TRANSFER: Token resultToken = viewModel.getToken(result.chainId, result.getAddress()); if (resultToken == null) { currentResult = result; showTokenFetch(); viewModel.fetchToken(result.chainId, result.getAddress(), wallet.address); } else if (resultToken.isERC20()) { //ERC20 send request token = resultToken; setupTokenContent(); amountInput.setupToken(token, viewModel.getAssetDefinitionService(), viewModel.getTokenService(), this); //convert token amount into scaled value String convertedAmount = Convert.getConvertedValue(result.tokenAmount, token.tokenInfo.decimals); amountInput.setAmount(convertedAmount); addressInput.setAddress(result.functionToAddress); sendText.setVisibility(View.VISIBLE); sendText.setText(getString(R.string.token_transfer_request, resultToken.getFullName())); } //TODO: Handle NFT eg ERC721 break; case FUNCTION_CALL: //Generic function call, not handled yet displayScanError(R.string.toast_qr_code_no_address, getString(R.string.no_tokens)); if (result.functionToAddress != null) addressInput.setAddress(result.functionToAddress); break; default: displayScanError(); } } private void showChainChangeDialog(int chainId) { if (dialog != null && dialog.isShowing()) dialog.dismiss(); dialog = new AWalletAlertDialog(this); dialog.setIcon(AWalletAlertDialog.WARNING); dialog.setTitle(R.string.change_chain_request); dialog.setMessage(R.string.change_chain_message); dialog.setButtonText(R.string.dialog_ok); dialog.setButtonListener(v -> { //we should change the chain. token = viewModel.getToken(chainId, token.getAddress()); amountInput.setupToken(token, viewModel.getAssetDefinitionService(), viewModel.getTokenService(), this); dialog.dismiss(); validateEIP681Request(currentResult, false); }); dialog.setSecondaryButtonText(R.string.action_cancel); dialog.setSecondaryButtonListener(v -> { dialog.dismiss(); //proceed without changing the chain currentResult.chainId = token.tokenInfo.chainId; validateEIP681Request(currentResult, false); }); dialog.show(); } private void displayScanError() { if (dialog != null && dialog.isShowing()) dialog.dismiss(); dialog = new AWalletAlertDialog(this); dialog.setIcon(AWalletAlertDialog.ERROR); dialog.setTitle(R.string.toast_qr_code_no_address); dialog.setButtonText(R.string.dialog_ok); dialog.setButtonListener(v -> dialog.dismiss()); dialog.show(); } private void displayScanError(int titleId, String message) { if (dialog != null && dialog.isShowing()) dialog.dismiss(); dialog = new AWalletAlertDialog(this); dialog.setIcon(AWalletAlertDialog.ERROR); dialog.setTitle(titleId); dialog.setMessage(message); dialog.setButtonText(R.string.dialog_ok); dialog.setButtonListener(v -> dialog.dismiss()); dialog.show(); } @Override protected void onDestroy() { if (dialog != null && dialog.isShowing()) { dialog.dismiss(); } super.onDestroy(); if (viewModel != null) viewModel.onDestroy(); if (handler != null) handler.removeCallbacksAndMessages(null); if (amountInput != null) amountInput.onDestroy(); if (confirmationDialog != null) confirmationDialog.onDestroy(); } private void setupTokenContent() { amountInput = findViewById(R.id.input_amount); amountInput.setupToken(token, viewModel.getAssetDefinitionService(), viewModel.getTokenService(), this); addressInput = findViewById(R.id.input_address); addressInput.setAddressCallback(this); addressInput.setChainOverrideForWalletConnect(token.tokenInfo.chainId); FunctionButtonBar functionBar = findViewById(R.id.layoutButtons); functionBar.revealButtons(); List<Integer> functions = new ArrayList<>(Collections.singletonList(R.string.action_next)); functionBar.setupFunctions(this, functions); viewModel.startGasCycle(token.tokenInfo.chainId); } @Override public void amountReady(BigDecimal value, BigDecimal gasPrice) { Token base = viewModel.getToken(token.tokenInfo.chainId, wallet.address); //validate that we have sufficient balance if ((token.isEthereum() && token.balance.subtract(value).compareTo(BigDecimal.ZERO) > 0) // if sending base ethereum then check we have more than just the value || (hasGasOverride(token.tokenInfo.chainId) && token.getBalanceRaw().subtract(value).compareTo(BigDecimal.ZERO) >= 0) //allow for chains with no gas requirement || (base.balance.compareTo(BigDecimal.ZERO) > 0 && token.getBalanceRaw().subtract(value).compareTo(BigDecimal.ZERO) >= 0)) // contract token, check gas and sufficient token balance { sendAmount = value; sendGasPrice = gasPrice; calculateTransactionCost(); } else { sendAmount = NEGATIVE; //insufficient balance amountInput.showError(true, 0); //if currently resolving ENS, stop addressInput.stopNameCheck(); } } @Override public void handleClick(String action, int actionId) { //clicked the next button if (actionId == R.string.action_next) { KeyboardUtils.hideKeyboard(getCurrentFocus()); amountInput.getInputAmount(); addressInput.getAddress(); } } @Override public void addressReady(String address, String ensName) { sendAddress = address; ensAddress = ensName; if (!Utils.isAddressValid(address)) { //show address error addressInput.setError(getString(R.string.error_invalid_address)); } else { calculateTransactionCost(); } } private void calculateTransactionCost() { if ((calcGasCost != null && !calcGasCost.isDisposed()) || (confirmationDialog != null && confirmationDialog.isShowing())) return; if (sendAmount.compareTo(NEGATIVE) > 0 && Utils.isAddressValid(sendAddress)) { final String txSendAddress = sendAddress; sendAddress = null; //either sending base chain or ERC20 tokens. final byte[] transactionBytes = viewModel.getTransactionBytes(token, txSendAddress, sendAmount); if (token.isEthereum()) { checkConfirm(BigInteger.valueOf(GAS_LIMIT_MIN), transactionBytes, txSendAddress, txSendAddress); } else { calculateEstimateDialog(); //form payload and calculate tx cost calcGasCost = viewModel.calculateGasEstimate(wallet, transactionBytes, token.tokenInfo.chainId, token.getAddress(), BigDecimal.ZERO) .map(this::convertToGasLimit) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(estimate -> checkConfirm(estimate, transactionBytes, token.getAddress(), txSendAddress), error -> handleError(error, transactionBytes, token.getAddress(), txSendAddress)); } } } private BigInteger convertToGasLimit(EthEstimateGas estimate) { if (estimate.hasError()) { return BigInteger.ZERO; } else { return estimate.getAmountUsed(); } } private void handleError(Throwable throwable, final byte[] transactionBytes, final String txSendAddress, final String resolvedAddress) { Log.w(this.getLocalClassName(), throwable.getMessage()); checkConfirm(BigInteger.ZERO, transactionBytes, txSendAddress, resolvedAddress); } /** * Called to check if we're ready to send user to confirm screen / activity sheet popup * */ private void checkConfirm(final BigInteger sendGasLimit, final byte[] transactionBytes, final String txSendAddress, final String resolvedAddress) { BigInteger ethValue = token.isEthereum() ? sendAmount.toBigInteger() : BigInteger.ZERO; Web3Transaction w3tx = new Web3Transaction( new Address(txSendAddress), new Address(token.getAddress()), ethValue, sendGasPrice.toBigInteger(), sendGasLimit, -1, Numeric.toHexString(transactionBytes), -1); if (sendGasLimit.equals(BigInteger.ZERO)) { estimateError(w3tx, transactionBytes, txSendAddress, resolvedAddress); } else { if (dialog != null && dialog.isShowing()) dialog.dismiss(); confirmationDialog = new ActionSheetDialog(this, w3tx, token, ensAddress, resolvedAddress, viewModel.getTokenService(), this); confirmationDialog.setCanceledOnTouchOutside(false); confirmationDialog.show(); sendAmount = NEGATIVE; } } /** * ActionSheetCallback, comms hooks for the ActionSheetDialog to trigger authentication & send transactions * * @param callback */ @Override public void getAuthorisation(SignAuthenticationCallback callback) { viewModel.getAuthentication(this, wallet, callback); } @Override public void sendTransaction(Web3Transaction finalTx) { viewModel.sendTransaction(finalTx, wallet, token.tokenInfo.chainId); } @Override public void dismissed(String txHash, long callbackId, boolean actionCompleted) { //ActionSheet was dismissed if (!TextUtils.isEmpty(txHash)) { Intent intent = new Intent(); intent.putExtra(C.EXTRA_TXHASH, txHash); setResult(RESULT_OK, intent); // successful transaction - try to show rate the app viewModel.tryToShowRateAppDialog(this); finish(); } } @Override public void notifyConfirm(String mode) { viewModel.actionSheetConfirm(mode); } private void txWritten(TransactionData transactionData) { confirmationDialog.transactionWritten(transactionData.txHash); } //Transaction failed to be sent private void txError(Throwable throwable) { if (dialog != null && dialog.isShowing()) dialog.dismiss(); dialog = new AWalletAlertDialog(this); dialog.setIcon(ERROR); dialog.setTitle(R.string.error_transaction_failed); dialog.setMessage(throwable.getMessage()); dialog.setButtonText(R.string.button_ok); dialog.setButtonListener(v -> { dialog.dismiss(); }); dialog.show(); confirmationDialog.dismiss(); } private void estimateError(final Web3Transaction w3tx, final byte[] transactionBytes, final String txSendAddress, final String resolvedAddress) { if (dialog != null && dialog.isShowing()) dialog.dismiss(); dialog = new AWalletAlertDialog(this); dialog.setIcon(WARNING); dialog.setTitle(R.string.confirm_transaction); dialog.setMessage(R.string.error_transaction_may_fail); dialog.setButtonText(R.string.button_ok); dialog.setSecondaryButtonText(R.string.action_cancel); dialog.setButtonListener(v -> { BigInteger gasEstimate = GasService.getDefaultGasLimit(token, w3tx); checkConfirm(gasEstimate, transactionBytes, txSendAddress, resolvedAddress); }); dialog.setSecondaryButtonListener(v -> { dialog.dismiss(); }); dialog.show(); } }
package octoteam.tahiti.performance; import octoteam.tahiti.performance.recorder.MeasurementRecorder; import octoteam.tahiti.performance.reporter.LogReporter; import java.util.LinkedList; import java.util.List; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * 性能检测 */ public class PerformanceMonitor { /** * 日志生成器 */ private LogReporter[] logReporters = null; /** * 定时调用服务 */ private ScheduledExecutorService executorService; /** * 指标记录器的集合 */ private List<MeasurementRecorder> recorders = new LinkedList<MeasurementRecorder>(); /** * 构造性能监控实例 * * @param reporter 输出器 */ public PerformanceMonitor(LogReporter... reporter) { logReporters = reporter; } /** * 开始定时生成报告 * * @param period 生成报告的时间间隔 * @param unit 时间单位 * @return 当前实例供链式调用 */ public PerformanceMonitor start(long period, TimeUnit unit) { if (executorService != null) { return this; } executorService = new ScheduledThreadPoolExecutor(1); executorService.scheduleAtFixedRate(new Runnable() { public void run() { PerformanceMonitor.this.report(); } }, period, period, unit); return this; } /** * 停止定时生成日志 * * @return 当前实例供链式调用 */ public PerformanceMonitor stop() { if (executorService == null) { return this; } executorService.shutdownNow(); executorService = null; return this; } /** * 添加指标记录器 * * @param recorder 指标记录器 * @return 当前实例供链式调用 */ public PerformanceMonitor addRecorder(MeasurementRecorder recorder) { recorders.add(recorder); return this; } /** * 是否已启动定时报告生成 * * @return 是否已经启动 */ public boolean isStarted() { return executorService != null; } /** * 生成一次报告 */ void report() { for (MeasurementRecorder recorder : recorders) { for (LogReporter reporter : logReporters) { reporter.getLogger().info(new RecordMarker(recorder), recorder.getReport()); recorder.reset(); } } } }
/* * Copyright 2002,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.jelly.tags.swing; /** * A default Factory implementation that creates new instances from a bean class * * @author <a href="mailto:jstrachan@apache.org">James Strachan</a> * @version $Revision: 155420 $ */ public class BeanFactory implements Factory { private Class beanClass; public BeanFactory(Class beanClass) { this.beanClass = beanClass; } /** * Create a new component instance */ public Object newInstance() throws InstantiationException { try { return beanClass.newInstance(); } catch (IllegalAccessException e) { throw new InstantiationException(e.toString()); } } }
package org.hisp.dhis.dxf2.dataset; /* * Copyright (c) 2004-2020, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableSet; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.hisp.dhis.category.CategoryCombo; import org.hisp.dhis.category.CategoryOptionCombo; import org.hisp.dhis.category.CategoryService; import org.hisp.dhis.common.DateRange; import org.hisp.dhis.common.IdScheme; import org.hisp.dhis.common.IdSchemes; import org.hisp.dhis.common.IdentifiableObjectManager; import org.hisp.dhis.common.IdentifiableProperty; import org.hisp.dhis.common.IllegalQueryException; import org.hisp.dhis.commons.collection.CachingMap; import org.hisp.dhis.commons.util.DebugUtils; import org.hisp.dhis.commons.util.StreamUtils; import org.hisp.dhis.dataelement.DataElementOperand; import org.hisp.dhis.dataset.CompleteDataSetRegistration; import org.hisp.dhis.dataset.CompleteDataSetRegistrationService; import org.hisp.dhis.dataset.DataSet; import org.hisp.dhis.dataset.notifications.DataSetNotificationEventPublisher; import org.hisp.dhis.datavalue.AggregateAccessManager; import org.hisp.dhis.dxf2.common.ImportOptions; import org.hisp.dhis.dxf2.dataset.streaming.StreamingXmlCompleteDataSetRegistrations; import org.hisp.dhis.dxf2.importsummary.ImportConflict; import org.hisp.dhis.dxf2.importsummary.ImportCount; import org.hisp.dhis.dxf2.importsummary.ImportStatus; import org.hisp.dhis.dxf2.importsummary.ImportSummary; import org.hisp.dhis.dxf2.util.InputUtils; import org.hisp.dhis.feedback.ErrorCode; import org.hisp.dhis.feedback.ErrorMessage; import org.hisp.dhis.i18n.I18n; import org.hisp.dhis.i18n.I18nManager; import org.hisp.dhis.importexport.ImportStrategy; import org.hisp.dhis.jdbc.batchhandler.CompleteDataSetRegistrationBatchHandler; import org.hisp.dhis.message.MessageService; import org.hisp.dhis.organisationunit.OrganisationUnit; import org.hisp.dhis.organisationunit.OrganisationUnitGroup; import org.hisp.dhis.organisationunit.OrganisationUnitService; import org.hisp.dhis.period.Period; import org.hisp.dhis.period.PeriodService; import org.hisp.dhis.period.PeriodType; import org.hisp.dhis.scheduling.JobConfiguration; import org.hisp.dhis.setting.SystemSettingManager; import org.hisp.dhis.system.notification.NotificationLevel; import org.hisp.dhis.system.notification.Notifier; import org.hisp.dhis.system.util.Clock; import org.hisp.dhis.system.util.ValidationUtils; import org.hisp.dhis.user.CurrentUserService; import org.hisp.dhis.user.User; import org.hisp.dhis.util.DateUtils; import org.hisp.quick.BatchHandler; import org.hisp.quick.BatchHandlerFactory; import org.hisp.staxwax.factory.XMLFactory; import org.springframework.stereotype.Service; import javax.annotation.Nonnull; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.checkNotNull; /** * @author Halvdan Hoem Grelland */ @Slf4j @Service( "org.hisp.dhis.dxf2.dataset.CompleteDataSetRegistrationExchangeService" ) public class DefaultCompleteDataSetRegistrationExchangeService implements CompleteDataSetRegistrationExchangeService { private static final int CACHE_MISS_THRESHOLD = 500; private static final Set<IdScheme> EXPORT_ID_SCHEMES = ImmutableSet.of( IdScheme.UID, IdScheme.NAME, IdScheme.CODE ); // ------------------------------------------------------------------------- // Dependencies // ------------------------------------------------------------------------- private final CompleteDataSetRegistrationExchangeStore cdsrStore; private final IdentifiableObjectManager idObjManager; private final OrganisationUnitService orgUnitService; private final Notifier notifier; private final I18nManager i18nManager; private final BatchHandlerFactory batchHandlerFactory; private final SystemSettingManager systemSettingManager; private final CategoryService categoryService; private final PeriodService periodService; private final CurrentUserService currentUserService; private final CompleteDataSetRegistrationService registrationService; private final InputUtils inputUtils; private final AggregateAccessManager accessManager; private final DataSetNotificationEventPublisher notificationPublisher; private final MessageService messageService; private final ObjectMapper jsonMapper; public DefaultCompleteDataSetRegistrationExchangeService( CompleteDataSetRegistrationExchangeStore cdsrStore, IdentifiableObjectManager idObjManager, OrganisationUnitService orgUnitService, Notifier notifier, I18nManager i18nManager, BatchHandlerFactory batchHandlerFactory, SystemSettingManager systemSettingManager, CategoryService categoryService, PeriodService periodService, CurrentUserService currentUserService, CompleteDataSetRegistrationService registrationService, InputUtils inputUtils, AggregateAccessManager accessManager, DataSetNotificationEventPublisher notificationPublisher, MessageService messageService, ObjectMapper jsonMapper ) { checkNotNull( cdsrStore ); checkNotNull( idObjManager ); checkNotNull( orgUnitService ); checkNotNull( notifier ); checkNotNull( i18nManager ); checkNotNull( batchHandlerFactory ); checkNotNull( systemSettingManager ); checkNotNull( systemSettingManager ); checkNotNull( categoryService ); checkNotNull( periodService ); checkNotNull( currentUserService ); checkNotNull( registrationService ); checkNotNull( inputUtils ); checkNotNull( accessManager ); checkNotNull( notificationPublisher ); checkNotNull( messageService ); checkNotNull( jsonMapper ); this.cdsrStore = cdsrStore; this.idObjManager = idObjManager; this.orgUnitService = orgUnitService; this.notifier = notifier; this.i18nManager = i18nManager; this.batchHandlerFactory = batchHandlerFactory; this.systemSettingManager = systemSettingManager; this.categoryService = categoryService; this.periodService = periodService; this.currentUserService = currentUserService; this.registrationService = registrationService; this.inputUtils = inputUtils; this.accessManager = accessManager; this.notificationPublisher = notificationPublisher; this.messageService = messageService; this.jsonMapper = jsonMapper; } // ------------------------------------------------------------------------- // CompleteDataSetRegistrationService implementation // ------------------------------------------------------------------------- @Override public ExportParams paramsFromUrl( Set<String> dataSets, Set<String> orgUnits, Set<String> orgUnitGroups, Set<String> periods, Date startDate, Date endDate, boolean includeChildren, Date created, String createdDuration, Integer limit, IdSchemes idSchemes ) { ExportParams params = new ExportParams(); if ( dataSets != null ) { params.getDataSets().addAll( idObjManager.getObjects( DataSet.class, IdentifiableProperty.UID, dataSets ) ); } if ( orgUnits != null ) { params.getOrganisationUnits() .addAll( idObjManager.getObjects( OrganisationUnit.class, IdentifiableProperty.UID, orgUnits ) ); } if ( orgUnitGroups != null ) { params.getOrganisationUnitGroups().addAll( idObjManager.getObjects( OrganisationUnitGroup.class, IdentifiableProperty.UID, orgUnitGroups ) ); } if ( periods != null && !periods.isEmpty() ) { params.getPeriods().addAll( periodService.reloadIsoPeriods( new ArrayList<>( periods ) ) ); } else if ( startDate != null && endDate != null ) { params.setStartDate( startDate ).setEndDate( endDate ); } params.setIncludeChildren( includeChildren ).setCreated( created ).setCreatedDuration( createdDuration ) .setLimit( limit ).setOutputIdSchemes( idSchemes ); return params; } @Override public void writeCompleteDataSetRegistrationsXml( ExportParams params, OutputStream out ) { decideAccess( params ); validate( params ); cdsrStore.writeCompleteDataSetRegistrationsXml( params, out ); } @Override public void writeCompleteDataSetRegistrationsJson( ExportParams params, OutputStream out ) { decideAccess( params ); validate( params ); cdsrStore.writeCompleteDataSetRegistrationsJson( params, out ); } @Override public void writeCompleteDataSetRegistrationsJson( Date lastUpdated, OutputStream outputStream, IdSchemes idSchemes ) { cdsrStore.writeCompleteDataSetRegistrationsJson( lastUpdated, outputStream, idSchemes ); } @Override public ImportSummary saveCompleteDataSetRegistrationsXml( InputStream in, ImportOptions importOptions ) { return saveCompleteDataSetRegistrationsXml( in, importOptions, null ); } @Override public ImportSummary saveCompleteDataSetRegistrationsXml( InputStream in, ImportOptions importOptions, JobConfiguration jobId ) { try { in = StreamUtils.wrapAndCheckCompressionFormat( in ); CompleteDataSetRegistrations completeDataSetRegistrations = new StreamingXmlCompleteDataSetRegistrations( XMLFactory.getXMLReader( in ) ); return saveCompleteDataSetRegistrations( importOptions, jobId, completeDataSetRegistrations ); } catch ( Exception ex ) { return handleImportError( jobId, ex ); } } @Override public ImportSummary saveCompleteDataSetRegistrationsJson( InputStream in, ImportOptions importOptions ) { return saveCompleteDataSetRegistrationsJson( in, ImportOptions.getDefaultImportOptions(), null ); } @Override public ImportSummary saveCompleteDataSetRegistrationsJson( InputStream in, ImportOptions importOptions, JobConfiguration jobId ) { try { in = StreamUtils.wrapAndCheckCompressionFormat( in ); CompleteDataSetRegistrations completeDataSetRegistrations = jsonMapper.readValue( in, CompleteDataSetRegistrations.class ); return saveCompleteDataSetRegistrations( importOptions, jobId, completeDataSetRegistrations ); } catch ( Exception ex ) { return handleImportError( jobId, ex ); } } public void validate( ExportParams params ) throws IllegalQueryException { ErrorMessage error = null; if ( params == null ) { throw new IllegalQueryException( ErrorCode.E2000 ); } if ( params.getDataSets().isEmpty() ) { error = new ErrorMessage( ErrorCode.E2013 ); } if ( !params.hasPeriods() && !params.hasStartEndDate() && !params.hasCreated() && !params.hasCreatedDuration() ) { error = new ErrorMessage( ErrorCode.E2002 ); } if ( params.hasPeriods() && params.hasStartEndDate() ) { error = new ErrorMessage( ErrorCode.E2003 ); } if ( params.hasStartEndDate() && params.getStartDate().after( params.getEndDate() ) ) { error = new ErrorMessage( ErrorCode.E2004 ); } if ( params.hasCreatedDuration() && DateUtils.getDuration( params.getCreatedDuration() ) == null ) { error = new ErrorMessage( ErrorCode.E2005 ); } if ( !params.hasOrganisationUnits() && !params.hasOrganisationUnitGroups() ) { error = new ErrorMessage( ErrorCode.E2006 ); } if ( params.isIncludeChildren() && params.hasOrganisationUnitGroups() ) { error = new ErrorMessage( ErrorCode.E2007 ); } if ( params.isIncludeChildren() && !params.hasOrganisationUnits() ) { error = new ErrorMessage( ErrorCode.E2008 ); } if ( params.hasLimit() && params.getLimit() < 0 ) { error = new ErrorMessage( ErrorCode.E2009 ); } if ( error != null ) { log.warn( String.format( "Complete data set registration validation failed, code: '%s', message: '%s'", error.getErrorCode(), error.getMessage() ) ); throw new IllegalQueryException( error ); } limitToValidIdSchemes( params ); } // ------------------------------------------------------------------------- // Supportive methods // ------------------------------------------------------------------------- /** * Limit valid IdSchemes for export to UID, CODE, NAME */ private static void limitToValidIdSchemes( ExportParams params ) { IdSchemes schemes = params.getOutputIdSchemes(); // If generic IdScheme is set to ID -> override to UID, for others: nullify field (inherits from generic scheme) if ( !EXPORT_ID_SCHEMES.contains( schemes.getIdScheme() ) ) { schemes.setIdScheme( IdScheme.UID.getIdentifiableString() ); } if ( !EXPORT_ID_SCHEMES.contains( schemes.getDataSetIdScheme() ) ) { schemes.setDataSetIdScheme( IdScheme.UID.getIdentifiableString() ); } if ( !EXPORT_ID_SCHEMES.contains( schemes.getOrgUnitIdScheme() ) ) { schemes.setOrgUnitIdScheme( IdScheme.UID.getIdentifiableString() ); } if ( !EXPORT_ID_SCHEMES.contains( schemes.getAttributeOptionComboIdScheme() ) ) { schemes.setAttributeOptionComboIdScheme( IdScheme.UID.getIdentifiableString() ); } params.setOutputIdSchemes( schemes ); } private void decideAccess( ExportParams params ) throws IllegalQueryException { for ( OrganisationUnit ou : params.getOrganisationUnits() ) { if ( !orgUnitService.isInUserHierarchy( ou ) ) { throw new IllegalQueryException( new ErrorMessage( ErrorCode.E2012, ou.getUid() ) ); } } } private ImportSummary handleImportError( JobConfiguration jobId, Throwable ex ) { log.error( DebugUtils.getStackTrace( ex ) ); notifier.notify( jobId, NotificationLevel.ERROR, "Process failed: " + ex.getMessage(), true ); return new ImportSummary( ImportStatus.ERROR, "The import process failed: " + ex.getMessage() ); } private ImportSummary saveCompleteDataSetRegistrations( ImportOptions importOptions, JobConfiguration id, CompleteDataSetRegistrations completeRegistrations ) { Clock clock = new Clock( log ).startClock() .logTime( "Starting complete data set registration import, options: " + importOptions ); notifier.clear( id ).notify( id, "Process started" ); // Start here so we can access any outer attributes for the // configuration completeRegistrations.open(); ImportSummary importSummary = new ImportSummary(); // --------------------------------------------------------------------- // Set up import configuration // --------------------------------------------------------------------- importOptions = importOptions != null ? importOptions : ImportOptions.getDefaultImportOptions(); log.info( "Import options: " + importOptions ); ImportConfig cfg = new ImportConfig( this.systemSettingManager, this.categoryService, completeRegistrations, importOptions ); // --------------------------------------------------------------------- // Set up meta-data // --------------------------------------------------------------------- MetadataCaches caches = new MetadataCaches(); MetadataCallables metaDataCallables = new MetadataCallables( cfg, this.idObjManager, this.periodService, this.categoryService ); if ( importOptions.isPreheatCacheDefaultFalse() ) { caches.preheat( idObjManager, cfg ); } // --------------------------------------------------------------------- // Perform import // --------------------------------------------------------------------- notifier.notify( id, "Importing complete data set registrations" ); int totalCount = batchImport( completeRegistrations, cfg, importSummary, metaDataCallables, caches ); notifier.notify( id, NotificationLevel.INFO, "Import done", true ).addJobSummary( id, importSummary, ImportSummary.class ); ImportCount count = importSummary.getImportCount(); clock.logTime( String.format( "Complete data set registration import done, total: %d, imported: %d, updated: %d, deleted: %d", totalCount, count.getImported(), count.getUpdated(), count.getDeleted() ) ); completeRegistrations.close(); return importSummary; } /** * @return total number of processed CompleteDataSetRegistration objects */ private int batchImport( CompleteDataSetRegistrations completeRegistrations, ImportConfig config, ImportSummary summary, MetadataCallables mdCallables, MetadataCaches mdCaches ) { final User currentUser = currentUserService.getCurrentUser(); final String currentUserName = currentUser.getUsername(); final Set<OrganisationUnit> userOrgUnits = currentUserService.getCurrentUserOrganisationUnits(); final I18n i18n = i18nManager.getI18n(); BatchHandler<CompleteDataSetRegistration> batchHandler = batchHandlerFactory .createBatchHandler( CompleteDataSetRegistrationBatchHandler.class ).init(); int importCount = 0, updateCount = 0, deleteCount = 0, totalCount = 0; Date now = new Date(); while ( completeRegistrations.hasNextCompleteDataSetRegistration() ) { org.hisp.dhis.dxf2.dataset.CompleteDataSetRegistration cdsr = completeRegistrations .getNextCompleteDataSetRegistration(); totalCount++; // --------------------------------------------------------------------- // Init meta-data properties against meta-data cache // --------------------------------------------------------------------- MetadataProperties mdProps = initMetaDataProperties( cdsr, mdCallables, mdCaches ); heatCaches( mdCaches, config ); // --------------------------------------------------------------------- // Meta-data validation // --------------------------------------------------------------------- String storedBy; String lastUpdatedBy; Boolean isCompleted; try { // Validate CDSR meta-data properties mdProps.validate( cdsr, config ); validateOrgUnitInUserHierarchy( mdCaches, mdProps, userOrgUnits, currentUserName ); // Constraints validation if ( config.isStrictAttrOptionCombos() ) { validateAocMatchesDataSetCc( mdProps ); } validateAttrOptCombo( mdProps, mdCaches, config ); if ( config.isStrictPeriods() ) { validateHasMatchingPeriodTypes( mdProps ); } if ( config.isStrictOrgUnits() ) { validateDataSetIsAssignedToOrgUnit( mdProps ); } storedBy = cdsr.getStoredBy(); validateStoredBy( storedBy, i18n ); storedBy = StringUtils.isBlank( storedBy ) ? currentUserName : storedBy; lastUpdatedBy = cdsr.getLastUpdatedBy(); validateStoredBy( lastUpdatedBy, i18n ); lastUpdatedBy = StringUtils.isBlank( lastUpdatedBy ) ? currentUserName : lastUpdatedBy; cdsr.setLastUpdatedBy( lastUpdatedBy ); boolean DEFAULT_COMPLETENESS_STATUS = true; isCompleted = cdsr.getCompleted(); isCompleted = (isCompleted == null) ? DEFAULT_COMPLETENESS_STATUS : isCompleted; cdsr.setCompleted( isCompleted ); // TODO Check if Period is within range of data set? } catch ( ImportConflictException ic ) { summary.getConflicts().add( ic.getImportConflict() ); continue; } // --------------------------------------------------------------------- // Compulsory fields validation // --------------------------------------------------------------------- List<DataElementOperand> missingDataElementOperands = registrationService.getMissingCompulsoryFields( mdProps.dataSet, mdProps.period, mdProps.orgUnit, mdProps.attrOptCombo ); if ( !missingDataElementOperands.isEmpty() ) { for ( DataElementOperand dataElementOperand : missingDataElementOperands ) { summary.getConflicts().add( new ImportConflict( "dataElementOperand", dataElementOperand.getDisplayName() + " needs to be filled. It is compulsory." ) ); } if ( mdProps.dataSet.isCompulsoryFieldsCompleteOnly() ) { continue; } } // --------------------------------------------------------------------- // Data Sharing check // --------------------------------------------------------------------- List<String> errors = validateDataAccess( currentUser, mdProps ); if ( !errors.isEmpty() ) { summary.getConflicts().addAll( errors.stream().map( s -> new ImportConflict( "dataSet", s ) ).collect( Collectors.toList() ) ); continue; } // ----------------------------------------------------------------- // Create complete data set registration // ----------------------------------------------------------------- CompleteDataSetRegistration internalCdsr = createCompleteDataSetRegistration( cdsr, mdProps, now, storedBy ); CompleteDataSetRegistration existingCdsr = config.isSkipExistingCheck() ? null : batchHandler.findObject( internalCdsr ); ImportStrategy strategy = config.getStrategy(); boolean isDryRun = config.isDryRun(); if ( !config.isSkipExistingCheck() && existingCdsr != null ) { // CDSR already exists if ( strategy.isCreateAndUpdate() || strategy.isUpdate() ) { // Update existing CDSR updateCount++; if ( !isDryRun ) { batchHandler.updateObject( internalCdsr ); } } else if ( strategy.isDelete() ) { // TODO Does 'delete' even make sense for CDSR? // Replace existing CDSR deleteCount++; if ( !isDryRun ) { batchHandler.deleteObject( internalCdsr ); } } } else { // CDSR does not already exist if ( strategy.isCreateAndUpdate() || strategy.isCreate() ) { if ( existingCdsr != null ) { // Already exists -> update importCount++; if ( !isDryRun ) { batchHandler.updateObject( internalCdsr ); } } else { // Does not exist -> add new CDSR boolean added = false; if ( !isDryRun ) { added = batchHandler.addObject( internalCdsr ); if ( added ) { sendNotifications( config, internalCdsr ); } } if ( isDryRun || added ) { importCount++; } } } } } batchHandler.flush(); finalizeSummary( summary, totalCount, importCount, updateCount, deleteCount ); return totalCount; } private static void finalizeSummary( ImportSummary summary, int totalCount, int importCount, int updateCount, int deleteCount ) { int ignores = totalCount - importCount - updateCount - deleteCount; summary.setImportCount( new ImportCount( importCount, updateCount, ignores, deleteCount ) ); summary.setStatus( totalCount == ignores ? ImportStatus.ERROR : ImportStatus.SUCCESS ); summary.setDescription( "Import process complete." ); } private static CompleteDataSetRegistration createCompleteDataSetRegistration( org.hisp.dhis.dxf2.dataset.CompleteDataSetRegistration cdsr, MetadataProperties mdProps, Date now, String storedBy ) { Date date = cdsr.hasDate() ? DateUtils.parseDate( cdsr.getDate() ) : now; return new CompleteDataSetRegistration( mdProps.dataSet, mdProps.period, mdProps.orgUnit, mdProps.attrOptCombo, date, storedBy, date, cdsr.getLastUpdatedBy(), cdsr.getCompleted() ); } /** * Check write permission for {@see DataSet} and {@see CategoryOptionCombo} * * @param user currently logged-in user * @param metaDataProperties {@see MetaDataProperties} containing the objects to check */ private List<String> validateDataAccess( User user, MetadataProperties metaDataProperties ) { List<String> errors = accessManager.canWrite( user, metaDataProperties.dataSet ); errors.addAll( accessManager.canWrite( user, metaDataProperties.attrOptCombo ) ); return errors; } private static void validateOrgUnitInUserHierarchy( MetadataCaches mdCaches, MetadataProperties mdProps, final Set<OrganisationUnit> userOrgUnits, String currentUsername ) throws ImportConflictException { boolean inUserHierarchy = mdCaches.getOrgUnitInHierarchyMap().get( mdProps.orgUnit.getUid(), () -> mdProps.orgUnit.isDescendant( userOrgUnits ) ); if ( !inUserHierarchy ) { throw new ImportConflictException( new ImportConflict( mdProps.orgUnit.getUid(), "Organisation unit is not in hierarchy of user: " + currentUsername ) ); } } private void sendNotifications( ImportConfig config, CompleteDataSetRegistration registration ) { if ( !config.isSkipNotifications() ) { if ( registration.getDataSet() != null && registration.getDataSet().isNotifyCompletingUser() ) { messageService.sendCompletenessMessage( registration ); } notificationPublisher.publishEvent( registration ); } } private void validateAttrOptCombo( MetadataProperties mdProps, MetadataCaches mdCaches, ImportConfig config ) throws ImportConflictException { final Period pe = mdProps.period; if ( mdProps.attrOptCombo == null ) { if ( config.isRequireAttrOptionCombos() ) { throw new ImportConflictException( new ImportConflict( "Attribute option combo", "Attribute option combo is required but is not specified" ) ); } else { mdProps.attrOptCombo = categoryService.getDefaultCategoryOptionCombo(); } } final CategoryOptionCombo aoc = mdProps.attrOptCombo; DateRange range = aoc.getDateRange( mdProps.dataSet ); if ( (range.getStartDate() != null && range.getStartDate().compareTo( pe.getStartDate() ) > 0) || (range.getEndDate() != null && range.getEndDate().compareTo( pe.getEndDate() ) < 0) ) { throw new ImportConflictException( new ImportConflict( mdProps.orgUnit.getUid(), String.format( "Period: %s is not within range of attribute option combo: %s", pe.getIsoDate(), aoc.getUid() ) ) ); } final String aocOrgUnitKey = aoc.getUid() + mdProps.orgUnit.getUid(); boolean isOrgUnitValidForAoc = mdCaches.getAttrOptComboOrgUnitMap().get( aocOrgUnitKey, () -> { Set<OrganisationUnit> aocOrgUnits = aoc.getOrganisationUnits(); return aocOrgUnits == null || mdProps.orgUnit.isDescendant( aocOrgUnits ); } ); if ( !isOrgUnitValidForAoc ) { throw new ImportConflictException( new ImportConflict( mdProps.orgUnit.getUid(), String.format( "Organisation unit: %s is not valid for attribute option combo %s", mdProps.orgUnit.getUid(), aoc.getUid() ) ) ); } } private static void validateStoredBy( String storedBy, I18n i18n ) throws ImportConflictException { String result = ValidationUtils.storedByIsValid( storedBy ); if ( result == null ) { return; } throw new ImportConflictException( new ImportConflict( storedBy, i18n.getString( result ) ) ); } private static void validateAocMatchesDataSetCc( MetadataProperties mdProps ) throws ImportConflictException { // TODO MdCache? CategoryCombo aocCC = mdProps.attrOptCombo.getCategoryCombo(); CategoryCombo dsCc = mdProps.dataSet.getCategoryCombo(); if ( !aocCC.equals( dsCc ) ) { throw new ImportConflictException( new ImportConflict( aocCC.getUid(), String .format( "Attribute option combo: %s must have category combo: %s", aocCC.getUid(), dsCc.getUid() ) ) ); } } private static void validateHasMatchingPeriodTypes( MetadataProperties props ) throws ImportConflictException { // TODO MdCache? PeriodType dsPeType = props.dataSet.getPeriodType(); PeriodType peType = props.period.getPeriodType(); if ( !dsPeType.equals( peType ) ) { throw new ImportConflictException( new ImportConflict( props.period.getUid(), String.format( "Period type of period: %s is not equal to the period type of data set: %s", props.period.getIsoDate(), props.dataSet.getPeriodType() ) ) ); } } private static void validateDataSetIsAssignedToOrgUnit( MetadataProperties props ) throws ImportConflictException { if ( !props.orgUnit.getDataSets().contains( props.dataSet ) ) { throw new ImportConflictException( new ImportConflict( props.dataSet.getUid(), String.format( "Data set %s is not assigned to organisation unit %s", props.dataSet.getUid(), props.orgUnit.getUid() ) ) ); } } private void heatCaches( MetadataCaches caches, ImportConfig config ) { if ( !caches.getDataSets().isCacheLoaded() && exceedsThreshold( caches.getDataSets() ) ) { caches.getDataSets().load( idObjManager.getAll( DataSet.class ), ds -> ds.getPropertyValue( config.getDsScheme() ) ); log.info( "Data set cache heated after cache miss threshold reached" ); } if ( !caches.getOrgUnits().isCacheLoaded() && exceedsThreshold( caches.getOrgUnits() ) ) { caches.getOrgUnits().load( idObjManager.getAll( OrganisationUnit.class ), ou -> ou.getPropertyValue( config.getOuScheme() ) ); log.info( "Org unit cache heated after cache miss threshold reached" ); } // TODO Consider need for checking/re-heating attrOptCombo and period caches if ( !caches.getAttrOptionCombos().isCacheLoaded() && exceedsThreshold( caches.getAttrOptionCombos() ) ) { caches.getAttrOptionCombos().load( idObjManager.getAll( CategoryOptionCombo.class ), aoc -> aoc.getPropertyValue( config.getAocScheme() ) ); log.info( "Attribute option combo cache heated after cache miss threshold reached" ); } if ( !caches.getPeriods().isCacheLoaded() && exceedsThreshold( caches.getPeriods() ) ) { caches.getPeriods().load( idObjManager.getAll( Period.class ), pe -> pe.getPropertyValue( null ) ); } } private MetadataProperties initMetaDataProperties( org.hisp.dhis.dxf2.dataset.CompleteDataSetRegistration cdsr, MetadataCallables callables, MetadataCaches cache ) { String ds = StringUtils.trimToNull( cdsr.getDataSet() ); String pe = StringUtils.trimToNull( cdsr.getPeriod() ); String ou = StringUtils.trimToNull( cdsr.getOrganisationUnit() ); String aoc = StringUtils.trimToNull( cdsr.getAttributeOptionCombo() ); if ( aoc == null ) { CategoryOptionCombo attributeOptionCombo = inputUtils.getAttributeOptionCombo( cdsr.getCc(), cdsr.getCp(), false ); aoc = attributeOptionCombo != null ? attributeOptionCombo.getUid() : aoc; } return new MetadataProperties( cache.getDataSets().get( ds, callables.getDataSetCallable().setId( ds ) ), cache.getPeriods().get( pe, callables.getPeriodCallable().setId( pe ) ), cache.getOrgUnits().get( ou, callables.getOrgUnitCallable().setId( ou ) ), cache.getAttrOptionCombos().get( aoc, callables.getOptionComboCallable().setId( aoc ) ) ); } private static boolean exceedsThreshold( CachingMap<?, ?> cachingMap ) { return cachingMap.getCacheMissCount() > CACHE_MISS_THRESHOLD; } // ----------------------------------------------------------------- // Internal classes // ----------------------------------------------------------------- private static class MetadataProperties { final DataSet dataSet; final Period period; final OrganisationUnit orgUnit; CategoryOptionCombo attrOptCombo; MetadataProperties( DataSet dataSet, Period period, OrganisationUnit orgUnit, CategoryOptionCombo attrOptCombo ) { this.dataSet = dataSet; this.period = period; this.orgUnit = orgUnit; this.attrOptCombo = attrOptCombo; } void validate( org.hisp.dhis.dxf2.dataset.CompleteDataSetRegistration cdsr, ImportConfig config ) throws ImportConflictException { if ( dataSet == null ) { throw new ImportConflictException( new ImportConflict( cdsr.getDataSet(), "Data set not found or not accessible" ) ); } if ( period == null ) { throw new ImportConflictException( new ImportConflict( cdsr.getPeriod(), "Period not valid" ) ); } if ( orgUnit == null ) { throw new ImportConflictException( new ImportConflict( cdsr.getOrganisationUnit(), "Organisation unit not found or not accessible" ) ); } // Ensure AOC is set is required, or is otherwise set to the default COC if ( attrOptCombo == null ) { if ( config.isRequireAttrOptionCombos() ) { throw new ImportConflictException( new ImportConflict( "Attribute option combo", "Attribute option combo is required but is not specified" ) ); } else { attrOptCombo = config.getFallbackCatOptCombo(); } } } } private static class ImportConflictException extends RuntimeException { private final ImportConflict importConflict; ImportConflictException( @Nonnull ImportConflict importConflict ) { this.importConflict = importConflict; } ImportConflict getImportConflict() { return importConflict; } } }
package com.infotrends.in.tictactoe.ui.home; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.CompoundButton; import android.widget.ToggleButton; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.navigation.NavController; import androidx.navigation.fragment.NavHostFragment; import com.in.tictactoe.R; public class GameModeSelFragment extends Fragment implements View.OnClickListener { View root; Context context; private NavController navController; private NavHostFragment navHostFragment; private String player1key="X"; private String player2key="O"; Button singleplayer, doubleplayer; ToggleButton gModeBtn; @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { root = inflater.inflate(R.layout.game_type_sel_fragment, container, false); context = getActivity(); singleplayer = root.findViewById(R.id.singleplayer); singleplayer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loadSingleGame(); } }); doubleplayer = root.findViewById(R.id.doubleplayer); doubleplayer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loadDoubleGame(); } }); gModeBtn = root.findViewById(R.id.selectgamemode); gModeBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked) { player1key = "O"; player2key = "X"; } else { player1key = "X"; player2key = "O"; } } }); navHostFragment = (NavHostFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment); navController = navHostFragment.getNavController(); return root; } @Override public void onClick(View v) { } private void loadSingleGame() { Bundle arguments = new Bundle(); arguments.putString("player1key",player1key); arguments.putString("player2key",player2key); navController.navigate(R.id.Main_Activity_to_Tic_Tac_Toe_Vs_Comp_View, arguments); } private void loadDoubleGame() { Bundle arguments = new Bundle(); navController.navigate(R.id.Main_Activity_to_Tic_Tac_Toe_View); } }
package com.acme; /** * Classe conta corrente com construcoes basicas em Java * @author Marco Mendes * @since 2017 * * Pontos para analise: * - Uso de enums * */ public class ContaCorrente { private double saldo; private double limiteCredito; private StatusConta status; public ContaCorrente(double saldo, double limiteCredito) { super(); this.saldo = saldo; this.limiteCredito = limiteCredito; this.status = StatusConta.ATIVA; } public double getSaldo() { return saldo; } public void setSaldo(double saldo) { this.saldo = saldo; } public double getLimiteCredito() { return limiteCredito; } public void setLimiteCredito(double limiteCredito) { this.limiteCredito = limiteCredito; } }
/* * L2jFrozen Project - www.l2jfrozen.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. * * http://www.gnu.org/copyleft/gpl.html */ package com.l2jfrozen.gameserver.network.serverpackets; import com.l2jfrozen.gameserver.model.actor.instance.L2PcInstance; import com.l2jfrozen.gameserver.model.quest.Quest; import com.l2jfrozen.gameserver.model.quest.QuestState; /** * Sh (dd) h (dddd) * @author Tempy */ public class GMViewQuestList extends L2GameServerPacket { private static final String _S__AC_GMVIEWQUESTLIST = "[S] ac GMViewQuestList"; private final L2PcInstance _activeChar; public GMViewQuestList(final L2PcInstance cha) { _activeChar = cha; } @Override protected final void writeImpl() { writeC(0x93); writeS(_activeChar.getName()); final Quest[] questList = _activeChar.getAllActiveQuests(); if (questList.length == 0) { writeC(0); writeH(0); writeH(0); return; } writeH(questList.length); // quest count for (final Quest q : questList) { writeD(q.getQuestIntId()); final QuestState qs = _activeChar.getQuestState(q.getName()); if (qs == null) { writeD(0); continue; } writeD(qs.getInt("cond")); // stage of quest progress } } /* * (non-Javadoc) * @see com.l2jfrozen.gameserver.serverpackets.ServerBasePacket#getType() */ @Override public String getType() { return _S__AC_GMVIEWQUESTLIST; } }
package net.hyper_pigeon.eldritch_mobs.mod_components.modifiers; import me.shedaniel.autoconfig.AutoConfig; import net.hyper_pigeon.eldritch_mobs.EldritchMobsMod; import net.hyper_pigeon.eldritch_mobs.config.EldritchMobsConfig; import net.hyper_pigeon.eldritch_mobs.mod_components.interfaces.ModifierInterface; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.ai.RangedAttackMob; import net.minecraft.entity.boss.WitherEntity; import net.minecraft.entity.boss.dragon.EnderDragonEntity; import net.minecraft.entity.damage.DamageSource; import net.minecraft.entity.mob.CreeperEntity; import net.minecraft.entity.mob.MobEntity; import net.minecraft.nbt.NbtCompound; import net.minecraft.util.math.MathHelper; import org.apache.commons.lang3.text.WordUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Random; public class ModifierComponent implements ModifierInterface { private boolean is_elite; private boolean is_ultra; private boolean is_eldritch; private boolean rank_decided; private int mod_number = 0; // private AlchemyComponent alchemy = new AlchemyComponent(); // private BeserkComponent beserk = new BeserkComponent(); // private BlindingComponent blinding = new BlindingComponent(); // private BurningComponent burning = sanew BurningComponent(); // private CloakedComponent cloaked = new CloakedComponent(); // private DrainingComponent draining = new DrainingComponent(); // private DrowningComponent drowning = new DrowningComponent(); // private GhastlyComponent ghastly = new GhastlyComponent(); // private GravityComponent gravity = new GravityComponent(); // private LethargicComponent lethargic = new LethargicComponent(); // private One_UpComponent one_up = new One_UpComponent(); // private RegeneratingComponent regen = new RegeneratingComponent(); // private ResistantComponent resistant = new ResistantComponent(); // private SnatcherComponent snatcher = new SnatcherComponent(); // private SpeedsterComponent speedster = new SpeedsterComponent(); // private SprintingComponent sprinting = new SprintingComponent(); // private StarvingComponent starving = new StarvingComponent(); // private StormyComponent stormy = new StormyComponent(); // private WeaknessComponent weakness = new WeaknessComponent(); // private WebslingingComponent webslinging = new WebslingingComponent(); public static ArrayList<String> all_mods = new ArrayList<>(Arrays.asList("alchemist", "berserk", "yeeter", "blinding", "burning", "cloaked","deflector","draining","drowning","ender","ghastly", "gravity","lethargic","lifesteal","one_up","regen", "resistant","rust","snatcher","speedster","sprinter","starving","stormy","thorny","toxic","weakness","webslinging", "withering", "sniper", "duplicator")); private ArrayList<String> mods = new ArrayList<>(Arrays.asList("alchemist", "berserk", "yeeter", "blinding", "burning", "cloaked","deflector","draining","drowning","ender","ghastly", "gravity","lethargic","lifesteal","one_up","regen", "resistant","rust","snatcher","speedster","sprinter","starving","stormy","thorny","toxic","weakness","webslinging", "withering","duplicator")); private ArrayList<String> ranged_mobs_mods = new ArrayList<>(Arrays.asList("alchemist", "blinding", "cloaked","deflector","draining","drowning","ender","ghastly", "gravity","lethargic","lifesteal","one_up","regen", "resistant", "snatcher","speedster","sprinter","starving","stormy","thorny","toxic","weakness","webslinging", "withering","sniper", "duplicator")); public ArrayList<String> creeper_mods = new ArrayList<>(Arrays.asList("alchemist", "blinding", "cloaked","deflector","draining","drowning","ender","ghastly", "gravity","lethargic","lifesteal","one_up","regen", "resistant", "snatcher","speedster","sprinter","starving","stormy","thorny","toxic","weakness","webslinging", "withering", "duplicator")); private ArrayList<String> alt_activated_mods = new ArrayList<>(Arrays.asList("yeeter", "deflector","rust","ender","lifesteal","one_up","thorny","toxic", "withering","sniper")); private HashMap<String, ModifierInterface> mods_hashmap = new HashMap<>(); { mods_hashmap.put("alchemist", new AlchemyComponent()); mods_hashmap.put("berserk", new BeserkComponent()); mods_hashmap.put("blinding", new BlindingComponent()); mods_hashmap.put("burning", new BurningComponent()); mods_hashmap.put("cloaked",new CloakedComponent()); mods_hashmap.put("draining",new DrainingComponent()); mods_hashmap.put("drowning",new DrowningComponent()); mods_hashmap.put("ghastly",new GhastlyComponent()); mods_hashmap.put("gravity",new GravityComponent()); mods_hashmap.put("lethargic",new LethargicComponent()); mods_hashmap.put("one_up",new One_UpComponent()); mods_hashmap.put("regen",new RegeneratingComponent()); mods_hashmap.put("resistant",new ResistantComponent()); mods_hashmap.put("snatcher",new SnatcherComponent()); mods_hashmap.put("speedster",new SpeedsterComponent()); mods_hashmap.put("sprinter",new SprintingComponent()); mods_hashmap.put("starving",new StarvingComponent()); mods_hashmap.put("stormy",new StormyComponent()); mods_hashmap.put("weakness",new WeaknessComponent()); mods_hashmap.put("webslinging",new WebslingingComponent()); mods_hashmap.put("duplicator", new DuplicatorComponent()); } public ArrayList<String> modifier_list = new ArrayList<>(); public LivingEntity mob; EldritchMobsConfig config = AutoConfig.getConfigHolder(EldritchMobsConfig.class).getConfig(); private final double EliteSpawnRate = config.EliteSpawnRates; private final double UltraSpawnRate = config.UltraSpawnRates; private final double EldritchSpawnRate = config.EldritchSpawnRates; public ModifierComponent(LivingEntity entity) { if((!config.ignoreNamed || !entity.hasCustomName()) && (entity.getType().isIn(EldritchMobsMod.ELDRITCH_ALLOWED)) && !(entity.getType().isIn(EldritchMobsMod.ELDRITCH_BLACKLIST))) { config.removeMods(); ranged_mobs_mods.retainAll(all_mods); creeper_mods.retainAll(all_mods); mods.retainAll(all_mods); mob = entity; if(entity instanceof EnderDragonEntity || entity instanceof WitherEntity) { if(config.toggleEldritchBossMobs) { this.setRank(); this.setMods(); } } else { this.setRank(); this.setMods(); } } } public void setRank_decided(boolean bool){ rank_decided = bool; } public void setIs_elite(boolean bool){ is_elite = bool; mod_number = config.EliteModTotal; } public void setIs_ultra(boolean bool){ is_ultra = bool; mod_number = config.UltraModTotal; } public void setIs_eldritch(boolean bool){ is_eldritch = bool; mod_number = config.EldritchModTotal; } public void setRank() { if(!rank_decided) { if(mob.getType().isIn(EldritchMobsMod.ALWAYS_ELITE)){ is_elite = true; mod_number = config.EliteModTotal; } else if(mob.getType().isIn(EldritchMobsMod.ALWAYS_ULTRA)){ is_elite = true; is_ultra = true; mod_number = config.UltraModTotal; } else if(mob.getType().isIn(EldritchMobsMod.ALWAYS_ELDRITCH)){ is_elite = true; is_ultra = true; is_eldritch = true; mod_number = config.EldritchModTotal; } else { Random random = new Random(); double random_int_one = random.nextDouble() * 100; if (random_int_one <= EliteSpawnRate) { is_elite = true; mod_number = config.EliteModTotal; double random_int_two = random.nextDouble() * 100; if (random_int_two <= UltraSpawnRate) { is_ultra = true; mod_number = config.UltraModTotal; double random_int_three = random.nextDouble() * 100; if (random_int_three <= EldritchSpawnRate) { is_eldritch = true; mod_number = config.EldritchModTotal; } } } } rank_decided = true; } } public String getEntityName(){ String type = mob.getType().toString(); String[] split_string = type.split("\\."); return split_string[2]; } public String get_mod_string(){ String ans = ""; if(modifier_list.toString().equals("[]")){ return ans; } else { for(String mod_name : modifier_list){ ans += WordUtils.capitalize(mod_name) + " "; } ans += WordUtils.capitalize(getEntityName().replaceAll("_"," ")); } return ans; } public void setMods() { if(is_elite) { modifier_list.clear(); if (mob instanceof RangedAttackMob) { //ranged_mobs_mods.retainAll(all_mods); if(mod_number > ranged_mobs_mods.size()){ mod_number = ranged_mobs_mods.size(); } for (int i = 0; i < MathHelper.clamp(mod_number,0,ranged_mobs_mods.size()); i++) { String random_mod = ranged_mobs_mods.get((int) (Math.random() * ranged_mobs_mods.size())); ranged_mobs_mods.remove(random_mod); modifier_list.add(random_mod); } } else if (mob instanceof CreeperEntity) { //creeper_mods.retainAll(all_mods); if(mod_number > creeper_mods.size()){ mod_number = creeper_mods.size(); } for (int i = 0; i < MathHelper.clamp(mod_number,0,creeper_mods.size()); i++) { String random_mod = creeper_mods.get((int) (Math.random() * creeper_mods.size())); creeper_mods.remove(random_mod); modifier_list.add(random_mod); } } else { //mods.retainAll(all_mods); if(mod_number > mods.size()){ mod_number = mods.size(); } for (int i = 0; i < MathHelper.clamp(mod_number,0,mods.size()); i++) { String random_mod = mods.get((int) (Math.random() * mods.size())); mods.remove(random_mod); modifier_list.add(random_mod); } } } } public boolean hasMod(String name) { return modifier_list.contains(name); } @Override public void damageActivatedMod(LivingEntity entity, DamageSource source, float amount) { if(modifier_list.contains("drowning")){ mods_hashmap.get("drowning").damageActivatedMod(entity,source,amount); } if(modifier_list.contains("one_up")){ mods_hashmap.get("one_up").damageActivatedMod(entity,source,amount); } } public void useAbility(MobEntity entity) { for(String mod_name : modifier_list){ if(!(alt_activated_mods.contains(mod_name))) { //System.out.println("Mob is trying to use " + mod_name + " ability!"); if(mods_hashmap.get(mod_name) != null) { mods_hashmap.get(mod_name).useAbility(entity); } } } } public boolean isEldritch(){ return is_eldritch; } public boolean isElite(){ return is_elite; } public boolean isUltra(){ return is_ultra; } @Override public void readFromNbt(NbtCompound tag) { this.setIs_elite(tag.getBoolean("elite")); this.setIs_ultra(tag.getBoolean("ultra")); this.setIs_eldritch(tag.getBoolean("eldritch")); this.setRank_decided(tag.getBoolean("rank")); NbtCompound saved_mods = tag.getCompound("saved_mods"); modifier_list.clear(); for (String mod : saved_mods.getKeys()) { modifier_list.add(mod); } } @Override public void writeToNbt(NbtCompound tag) { tag.putBoolean("elite", this.is_elite); tag.putBoolean("ultra", this.is_ultra); tag.putBoolean("eldritch", this.is_eldritch); tag.putBoolean("rank", this.rank_decided); NbtCompound saved_mods = new NbtCompound(); for(String mod_name : modifier_list){ saved_mods.putString(mod_name,mod_name); } tag.put("saved_mods", saved_mods); } public void spawnedInLampChunk(){ is_elite = false; is_ultra = false; is_eldritch = false; modifier_list.clear(); } }
// *************************************************************************************************************************** // * 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.juneau.dto.html5; import org.apache.juneau.annotation.*; /** * DTO for an HTML {@doc ExtHTML5.grouping-content#the-div-element <div>} * element. * * <ul class='seealso'> * <li class='link'>{@doc DtoHtml5} * </ul> */ @Bean(typeName="div") public class Div extends HtmlElementMixed { /** * Creates an empty {@link Div} element. */ public Div() {} /** * Creates a {@link Div} element with the specified child nodes. * * @param children The child nodes. */ public Div(Object...children) { children(children); } //----------------------------------------------------------------------------------------------------------------- // Overridden methods //----------------------------------------------------------------------------------------------------------------- @Override /* HtmlElement */ public final Div _class(String _class) { super._class(_class); return this; } @Override /* HtmlElement */ public final Div id(String id) { super.id(id); return this; } @Override /* HtmlElement */ public final Div style(String style) { super.style(style); return this; } @Override /* HtmlElementMixed */ public Div children(Object...children) { super.children(children); return this; } @Override /* HtmlElementMixed */ public Div child(Object child) { super.child(child); return this; } }
package com.linkedbear.architecture.h_decorator.utils; import java.util.Arrays; public class LogUtils { public static void printLog(String className, String methodName, Object... args) { System.out.println(className + " " + methodName + " ..."); System.out.println("参数列表: " + Arrays.toString(args)); } }
/* * The MIT License (MIT) * * Copyright (c) 2014 The Voxel Plugineering Team * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.voxelplugineering.voxelsniper.service.permission; import com.voxelplugineering.voxelsniper.entity.Player; import com.voxelplugineering.voxelsniper.service.AbstractService; import com.voxelplugineering.voxelsniper.util.Context; /** * A trivially implemented {@link PermissionProxy} which always returns true. */ public class TrivialPermissionProxy extends AbstractService implements PermissionProxy { /** * Creates a new {@link TrivialPermissionProxy}. * * @param context The context */ public TrivialPermissionProxy(Context context) { super(context); } @Override protected void _init() { } @Override protected void _shutdown() { } @Override public boolean hasPermission(Player sniper, String permission) { return true; } }
/* 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.wiki.pages; import org.apache.commons.lang3.ArrayUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.wiki.WikiBackgroundThread; import org.apache.wiki.api.core.Acl; import org.apache.wiki.api.core.AclEntry; import org.apache.wiki.api.core.Attachment; import org.apache.wiki.api.core.Context; import org.apache.wiki.api.core.Engine; import org.apache.wiki.api.core.Page; import org.apache.wiki.api.exceptions.NoRequiredPropertyException; import org.apache.wiki.api.exceptions.ProviderException; import org.apache.wiki.api.exceptions.WikiException; import org.apache.wiki.api.providers.PageProvider; import org.apache.wiki.api.providers.WikiProvider; import org.apache.wiki.api.spi.Wiki; import org.apache.wiki.attachment.AttachmentManager; import org.apache.wiki.auth.WikiPrincipal; import org.apache.wiki.auth.WikiSecurityException; import org.apache.wiki.auth.acl.AclManager; import org.apache.wiki.auth.user.UserProfile; import org.apache.wiki.diff.DifferenceManager; import org.apache.wiki.event.WikiEvent; import org.apache.wiki.event.WikiEventManager; import org.apache.wiki.event.WikiPageEvent; import org.apache.wiki.event.WikiSecurityEvent; import org.apache.wiki.providers.RepositoryModifiedException; import org.apache.wiki.references.ReferenceManager; import org.apache.wiki.tasks.TasksManager; import org.apache.wiki.ui.CommandResolver; import org.apache.wiki.util.ClassUtil; import org.apache.wiki.util.TextUtil; import org.apache.wiki.workflow.Decision; import org.apache.wiki.workflow.DecisionRequiredException; import org.apache.wiki.workflow.Fact; import org.apache.wiki.workflow.Step; import org.apache.wiki.workflow.Workflow; import org.apache.wiki.workflow.WorkflowBuilder; import org.apache.wiki.workflow.WorkflowManager; import java.io.IOException; import java.security.Permission; import java.security.Principal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Properties; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; /** * Manages the WikiPages. This class functions as an unified interface towards the page providers. It handles initialization * and management of the providers, and provides utility methods for accessing the contents. * <p/> * Saving a page is a two-stage Task; first the pre-save operations and then the actual save. See the descriptions of the tasks * for further information. * * @since 2.0 */ public class DefaultPageManager implements PageManager { private static final Logger LOG = LogManager.getLogger( DefaultPageManager.class ); private final PageProvider m_provider; private final Engine m_engine; protected final ConcurrentHashMap< String, PageLock > m_pageLocks = new ConcurrentHashMap<>(); private final int m_expiryTime; private LockReaper m_reaper; private final PageSorter pageSorter = new PageSorter(); /** * Creates a new PageManager. * * @param engine Engine instance * @param props Properties to use for initialization * @throws NoSuchElementException {@value #PROP_PAGEPROVIDER} property not found on Engine properties * @throws WikiException If anything goes wrong, you get this. */ public DefaultPageManager(final Engine engine, final Properties props) throws NoSuchElementException, WikiException { m_engine = engine; final String classname; final boolean useCache = "true".equals( props.getProperty( PROP_USECACHE ) ); m_expiryTime = TextUtil.parseIntParameter( props.getProperty( PROP_LOCKEXPIRY ), 60 ); // If user wants to use a cache, then we'll use the CachingProvider. if( useCache ) { classname = "org.apache.wiki.providers.CachingProvider"; } else { classname = TextUtil.getRequiredProperty( props, PROP_PAGEPROVIDER ); } pageSorter.initialize( props ); try { LOG.debug("Page provider class: '" + classname + "'"); final Class<?> providerclass = ClassUtil.findClass("org.apache.wiki.providers", classname); m_provider = ( PageProvider ) providerclass.newInstance(); LOG.debug("Initializing page provider class " + m_provider); m_provider.initialize(m_engine, props); } catch (final ClassNotFoundException e) { LOG.error("Unable to locate provider class '" + classname + "' (" + e.getMessage() + ")", e); throw new WikiException("No provider class. (" + e.getMessage() + ")", e); } catch (final InstantiationException e) { LOG.error("Unable to create provider class '" + classname + "' (" + e.getMessage() + ")", e); throw new WikiException("Faulty provider class. (" + e.getMessage() + ")", e); } catch (final IllegalAccessException e) { LOG.error("Illegal access to provider class '" + classname + "' (" + e.getMessage() + ")", e); throw new WikiException("Illegal provider class. (" + e.getMessage() + ")", e); } catch (final NoRequiredPropertyException e) { LOG.error("Provider did not found a property it was looking for: " + e.getMessage(), e); throw e; // Same exception works. } catch (final IOException e) { LOG.error("An I/O exception occurred while trying to create a new page provider: " + classname, e); throw new WikiException("Unable to start page provider: " + e.getMessage(), e); } } /** * {@inheritDoc} * @see org.apache.wiki.pages.PageManager#getProvider() */ @Override public PageProvider getProvider() { return m_provider; } /** * {@inheritDoc} * @see org.apache.wiki.pages.PageManager#getAllPages() */ @Override public Collection< Page > getAllPages() throws ProviderException { return m_provider.getAllPages(); } /** * {@inheritDoc} * @see org.apache.wiki.pages.PageManager#getPageText(java.lang.String, int) */ @Override public String getPageText( final String pageName, final int version ) throws ProviderException { if (pageName == null || pageName.isEmpty()) { throw new ProviderException( "Illegal page name" ); } String text; try { text = m_provider.getPageText( pageName, version ); } catch ( final RepositoryModifiedException e ) { // This only occurs with the latest version. LOG.info( "Repository has been modified externally while fetching page " + pageName ); // Empty the references and yay, it shall be recalculated final Page p = m_provider.getPageInfo( pageName, version ); m_engine.getManager( ReferenceManager.class ).updateReferences( p ); fireEvent( WikiPageEvent.PAGE_REINDEX, p.getName() ); text = m_provider.getPageText( pageName, version ); } return text; } /** * {@inheritDoc} * @see org.apache.wiki.pages.PageManager#getPureText(String, int) */ @Override public String getPureText( final String page, final int version ) { String result = null; try { result = getPageText( page, version ); } catch( final ProviderException e ) { LOG.error( "ProviderException getPureText for page " + page + " [version " + version + "]", e ); } finally { if( result == null ) { result = ""; } } return result; } /** * {@inheritDoc} * @see org.apache.wiki.pages.PageManager#getText(String, int) */ @Override public String getText( final String page, final int version ) { final String result = getPureText( page, version ); return TextUtil.replaceEntities( result ); } @Override public void saveText( final Context context, final String text ) throws WikiException { // Check if page data actually changed; bail if not final Page page = context.getPage(); final String oldText = getPureText( page ); final String proposedText = TextUtil.normalizePostData( text ); if ( oldText != null && oldText.equals( proposedText ) ) { return; } // Check if creation of empty pages is allowed; bail if not final boolean allowEmpty = TextUtil.getBooleanProperty( m_engine.getWikiProperties(), Engine.PROP_ALLOW_CREATION_OF_EMPTY_PAGES, false ); if ( !allowEmpty && !wikiPageExists( page ) && text.trim().equals( "" ) ) { return; } // Create approval workflow for page save; add the diffed, proposed and old text versions as // Facts for the approver (if approval is required). If submitter is authenticated, any reject // messages will appear in his/her workflow inbox. final WorkflowBuilder builder = WorkflowBuilder.getBuilder( m_engine ); final Principal submitter = context.getCurrentUser(); final Step prepTask = m_engine.getManager( TasksManager.class ).buildPreSaveWikiPageTask( proposedText ); final Step completionTask = m_engine.getManager( TasksManager.class ).buildSaveWikiPageTask(); final String diffText = m_engine.getManager( DifferenceManager.class ).makeDiff( context, oldText, proposedText ); final boolean isAuthenticated = context.getWikiSession().isAuthenticated(); final Fact[] facts = new Fact[ 5 ]; facts[ 0 ] = new Fact( WorkflowManager.WF_WP_SAVE_FACT_PAGE_NAME, page.getName() ); facts[ 1 ] = new Fact( WorkflowManager.WF_WP_SAVE_FACT_DIFF_TEXT, diffText ); facts[ 2 ] = new Fact( WorkflowManager.WF_WP_SAVE_FACT_PROPOSED_TEXT, proposedText ); facts[ 3 ] = new Fact( WorkflowManager.WF_WP_SAVE_FACT_CURRENT_TEXT, oldText); facts[ 4 ] = new Fact( WorkflowManager.WF_WP_SAVE_FACT_IS_AUTHENTICATED, isAuthenticated ); final String rejectKey = isAuthenticated ? WorkflowManager.WF_WP_SAVE_REJECT_MESSAGE_KEY : null; final Workflow workflow = builder.buildApprovalWorkflow( submitter, WorkflowManager.WF_WP_SAVE_APPROVER, prepTask, WorkflowManager.WF_WP_SAVE_DECISION_MESSAGE_KEY, facts, completionTask, rejectKey ); workflow.start( context ); // Let callers know if the page-save requires approval if ( workflow.getCurrentStep() instanceof Decision ) { throw new DecisionRequiredException( "The page contents must be approved before they become active." ); } } /** * Returns the Engine to which this PageManager belongs to. * * @return The Engine object. */ protected Engine getEngine() { return m_engine; } /** * {@inheritDoc} * @see org.apache.wiki.pages.PageManager#putPageText(org.apache.wiki.api.core.Page, java.lang.String) */ @Override public void putPageText( final Page page, final String content ) throws ProviderException { if (page == null || page.getName() == null || page.getName().isEmpty()) { throw new ProviderException("Illegal page name"); } m_provider.putPageText(page, content); } /** * {@inheritDoc} * @see org.apache.wiki.pages.PageManager#lockPage(org.apache.wiki.api.core.Page, java.lang.String) */ @Override public PageLock lockPage( final Page page, final String user ) { if( m_reaper == null ) { // Start the lock reaper lazily. We don't want to start it in the constructor, because starting threads in constructors // is a bad idea when it comes to inheritance. Besides, laziness is a virtue. m_reaper = new LockReaper( m_engine ); m_reaper.start(); } fireEvent( WikiPageEvent.PAGE_LOCK, page.getName() ); // prior to or after actual lock? PageLock lock = m_pageLocks.get( page.getName() ); if( lock == null ) { // // Lock is available, so make a lock. // final Date d = new Date(); lock = new PageLock( page, user, d, new Date( d.getTime() + m_expiryTime * 60 * 1000L ) ); m_pageLocks.put( page.getName(), lock ); LOG.debug( "Locked page " + page.getName() + " for " + user ); } else { LOG.debug( "Page " + page.getName() + " already locked by " + lock.getLocker() ); lock = null; // Nothing to return } return lock; } /** * {@inheritDoc} * @see org.apache.wiki.pages.PageManager#unlockPage(org.apache.wiki.pages.PageLock) */ @Override public void unlockPage( final PageLock lock ) { if (lock == null) { return; } m_pageLocks.remove( lock.getPage() ); LOG.debug( "Unlocked page " + lock.getPage() ); fireEvent( WikiPageEvent.PAGE_UNLOCK, lock.getPage() ); } /** * {@inheritDoc} * @see org.apache.wiki.pages.PageManager#getCurrentLock(org.apache.wiki.api.core.Page) */ @Override public PageLock getCurrentLock( final Page page ) { return m_pageLocks.get( page.getName() ); } /** * {@inheritDoc} * @see org.apache.wiki.pages.PageManager#getActiveLocks() */ @Override public List< PageLock > getActiveLocks() { return new ArrayList<>( m_pageLocks.values() ); } /** * {@inheritDoc} * @see org.apache.wiki.pages.PageManager#getPage(java.lang.String) */ @Override public Page getPage( final String pagereq ) { return getPage( pagereq, PageProvider.LATEST_VERSION ); } /** * {@inheritDoc} * @see org.apache.wiki.pages.PageManager#getPage(java.lang.String, int) */ @Override public Page getPage( final String pagereq, final int version ) { try { Page p = getPageInfo( pagereq, version ); if( p == null ) { p = m_engine.getManager( AttachmentManager.class ).getAttachmentInfo( null, pagereq ); } return p; } catch( final ProviderException e ) { LOG.error( "Unable to fetch page info for " + pagereq + " [version " + version + "]", e ); return null; } } /** * {@inheritDoc} * @see org.apache.wiki.pages.PageManager#getPageInfo(java.lang.String, int) */ @Override public Page getPageInfo( final String pageName, final int version) throws ProviderException { if( pageName == null || pageName.isEmpty() ) { throw new ProviderException( "Illegal page name '" + pageName + "'" ); } Page page; try { page = m_provider.getPageInfo( pageName, version ); } catch( final RepositoryModifiedException e ) { // This only occurs with the latest version. LOG.info( "Repository has been modified externally while fetching info for " + pageName ); page = m_provider.getPageInfo( pageName, version ); if( page != null ) { m_engine.getManager( ReferenceManager.class ).updateReferences( page ); } else { m_engine.getManager( ReferenceManager.class ).pageRemoved( Wiki.contents().page( m_engine, pageName ) ); } } return page; } /** * {@inheritDoc} * @see org.apache.wiki.pages.PageManager#getVersionHistory(java.lang.String) */ @Override @SuppressWarnings( "unchecked" ) public < T extends Page > List< T > getVersionHistory( final String pageName ) { List< T > c = null; try { if( pageExists( pageName ) ) { c = ( List< T > )m_provider.getVersionHistory( pageName ); } if( c == null ) { c = ( List< T > )m_engine.getManager( AttachmentManager.class ).getVersionHistory( pageName ); } } catch( final ProviderException e ) { LOG.error( "ProviderException requesting version history for " + pageName, e ); } return c; } /** * {@inheritDoc} * @see org.apache.wiki.pages.PageManager#getCurrentProvider() */ @Override public String getCurrentProvider() { return getProvider().getClass().getName(); } /** * {@inheritDoc} * * @see org.apache.wiki.pages.PageManager#getProviderDescription() */ @Override public String getProviderDescription() { return m_provider.getProviderInfo(); } /** * {@inheritDoc} * @see org.apache.wiki.pages.PageManager#getTotalPageCount() */ @Override public int getTotalPageCount() { try { return m_provider.getAllPages().size(); } catch( final ProviderException e ) { LOG.error( "Unable to count pages: ", e ); return -1; } } /** * {@inheritDoc} * @see org.apache.wiki.pages.PageManager#getRecentChanges() */ @Override public Set< Page > getRecentChanges() { try { final TreeSet< Page > sortedPages = new TreeSet<>( new PageTimeComparator() ); sortedPages.addAll( getAllPages() ); sortedPages.addAll( m_engine.getManager( AttachmentManager.class ).getAllAttachments() ); return sortedPages; } catch( final ProviderException e ) { LOG.error( "Unable to fetch all pages: ", e ); return Collections.emptySet(); } } /** * {@inheritDoc} * @see org.apache.wiki.pages.PageManager#pageExists(java.lang.String) */ @Override public boolean pageExists( final String pageName ) throws ProviderException { if (pageName == null || pageName.isEmpty()) { throw new ProviderException("Illegal page name"); } return m_provider.pageExists(pageName); } /** * {@inheritDoc} * @see org.apache.wiki.pages.PageManager#pageExists(java.lang.String, int) */ @Override public boolean pageExists( final String pageName, final int version ) throws ProviderException { if( pageName == null || pageName.isEmpty() ) { throw new ProviderException( "Illegal page name" ); } if( version == WikiProvider.LATEST_VERSION ) { return pageExists( pageName ); } return m_provider.pageExists( pageName, version ); } /** * {@inheritDoc} * @see org.apache.wiki.pages.PageManager#wikiPageExists(java.lang.String) */ @Override public boolean wikiPageExists( final String page ) { if( m_engine.getManager( CommandResolver.class ).getSpecialPageReference( page ) != null ) { return true; } Attachment att = null; try { if( m_engine.getFinalPageName( page ) != null ) { return true; } att = m_engine.getManager( AttachmentManager.class ).getAttachmentInfo( null, page ); } catch( final ProviderException e ) { LOG.debug( "pageExists() failed to find attachments", e ); } return att != null; } /** * {@inheritDoc} * @see org.apache.wiki.pages.PageManager#wikiPageExists(java.lang.String, int) */ @Override public boolean wikiPageExists( final String page, final int version ) throws ProviderException { if( m_engine.getManager( CommandResolver.class ).getSpecialPageReference( page ) != null ) { return true; } boolean isThere = false; final String finalName = m_engine.getFinalPageName( page ); if( finalName != null ) { isThere = pageExists( finalName, version ); } if( !isThere ) { // Go check if such an attachment exists. try { isThere = m_engine.getManager( AttachmentManager.class ).getAttachmentInfo( null, page, version ) != null; } catch( final ProviderException e ) { LOG.debug( "wikiPageExists() failed to find attachments", e ); } } return isThere; } /** * {@inheritDoc} * @see org.apache.wiki.pages.PageManager#deleteVersion(org.apache.wiki.api.core.Page) */ @Override public void deleteVersion( final Page page ) throws ProviderException { if( page instanceof Attachment ) { m_engine.getManager( AttachmentManager.class ).deleteVersion( ( Attachment )page ); } else { m_provider.deleteVersion( page.getName(), page.getVersion() ); // FIXME: If this was the latest, reindex Lucene, update RefMgr } } /** * {@inheritDoc} * @see org.apache.wiki.pages.PageManager#deletePage(java.lang.String) */ @Override public void deletePage( final String pageName ) throws ProviderException { final Page p = getPage( pageName ); if( p != null ) { if( p instanceof Attachment ) { m_engine.getManager( AttachmentManager.class ).deleteAttachment( ( Attachment )p ); } else { final Collection< String > refTo = m_engine.getManager( ReferenceManager.class ).findRefersTo( pageName ); // May return null, if the page does not exist or has not been indexed yet. if( m_engine.getManager( AttachmentManager.class ).hasAttachments( p ) ) { final List< Attachment > attachments = m_engine.getManager( AttachmentManager.class ).listAttachments( p ); for( final Attachment attachment : attachments ) { if( refTo != null ) { refTo.remove( attachment.getName() ); } m_engine.getManager( AttachmentManager.class ).deleteAttachment( attachment ); } } deletePage( p ); fireEvent( WikiPageEvent.PAGE_DELETED, pageName ); } } } /** * {@inheritDoc} * @see org.apache.wiki.pages.PageManager#deletePage(org.apache.wiki.api.core.Page) */ @Override public void deletePage( final Page page ) throws ProviderException { fireEvent( WikiPageEvent.PAGE_DELETE_REQUEST, page.getName() ); m_provider.deletePage( page.getName() ); fireEvent( WikiPageEvent.PAGE_DELETED, page.getName() ); } /** * This is a simple reaper thread that runs roughly every minute * or so (it's not really that important, as long as it runs), * and removes all locks that have expired. */ private class LockReaper extends WikiBackgroundThread { /** * Create a LockReaper for a given engine. * * @param engine Engine to own this thread. */ public LockReaper( final Engine engine) { super( engine, 60 ); setName( "JSPWiki Lock Reaper" ); } @Override public void backgroundTask() { final Collection< PageLock > entries = m_pageLocks.values(); for( final Iterator<PageLock> i = entries.iterator(); i.hasNext(); ) { final PageLock p = i.next(); if ( p.isExpired() ) { i.remove(); LOG.debug( "Reaped lock: " + p.getPage() + " by " + p.getLocker() + ", acquired " + p.getAcquisitionTime() + ", and expired " + p.getExpiryTime() ); } } } } // events processing ....................................................... /** * Fires a WikiPageEvent of the provided type and page name * to all registered listeners. * * @param type the event type to be fired * @param pagename the wiki page name as a String * @see org.apache.wiki.event.WikiPageEvent */ protected final void fireEvent( final int type, final String pagename ) { if( WikiEventManager.isListening( this ) ) { WikiEventManager.fireEvent( this, new WikiPageEvent( m_engine, type, pagename ) ); } } /** * Listens for {@link org.apache.wiki.event.WikiSecurityEvent#PROFILE_NAME_CHANGED} * events. If a user profile's name changes, each page ACL is inspected. If an entry contains * a name that has changed, it is replaced with the new one. No events are emitted * as a consequence of this method, because the page contents are still the same; it is * only the representations of the names within the ACL that are changing. * * @param event The event */ @Override public void actionPerformed( final WikiEvent event ) { if( !( event instanceof WikiSecurityEvent ) ) { return; } final WikiSecurityEvent se = ( WikiSecurityEvent ) event; if( se.getType() == WikiSecurityEvent.PROFILE_NAME_CHANGED ) { final UserProfile[] profiles = (UserProfile[]) se.getTarget(); final Principal[] oldPrincipals = new Principal[] { new WikiPrincipal( profiles[ 0 ].getLoginName() ), new WikiPrincipal( profiles[ 0 ].getFullname()), new WikiPrincipal( profiles[ 0 ].getWikiName() ) }; final Principal newPrincipal = new WikiPrincipal( profiles[ 1 ].getFullname() ); // Examine each page ACL try { int pagesChanged = 0; final Collection< Page > pages = getAllPages(); for( final Page page : pages ) { final boolean aclChanged = changeAcl( page, oldPrincipals, newPrincipal ); if( aclChanged ) { // If the Acl needed changing, change it now try { m_engine.getManager( AclManager.class ).setPermissions( page, page.getAcl() ); } catch( final WikiSecurityException e ) { LOG.error("Could not change page ACL for page " + page.getName() + ": " + e.getMessage(), e); } pagesChanged++; } } LOG.info( "Profile name change for '" + newPrincipal.toString() + "' caused " + pagesChanged + " page ACLs to change also." ); } catch( final ProviderException e ) { // Oooo! This is really bad... LOG.error( "Could not change user name in Page ACLs because of Provider error:" + e.getMessage(), e ); } } } /** * For a single wiki page, replaces all Acl entries matching a supplied array of Principals with a new Principal. * * @param page the wiki page whose Acl is to be modified * @param oldPrincipals an array of Principals to replace; all AclEntry objects whose {@link AclEntry#getPrincipal()} method returns * one of these Principals will be replaced * @param newPrincipal the Principal that should receive the old Principals' permissions * @return <code>true</code> if the Acl was actually changed; <code>false</code> otherwise */ protected boolean changeAcl( final Page page, final Principal[] oldPrincipals, final Principal newPrincipal ) { final Acl acl = page.getAcl(); boolean pageChanged = false; if( acl != null ) { final Enumeration< AclEntry > entries = acl.aclEntries(); final Collection< AclEntry > entriesToAdd = new ArrayList<>(); final Collection< AclEntry > entriesToRemove = new ArrayList<>(); while( entries.hasMoreElements() ) { final AclEntry entry = entries.nextElement(); if( ArrayUtils.contains( oldPrincipals, entry.getPrincipal() ) ) { // Create new entry final AclEntry newEntry = Wiki.acls().entry(); newEntry.setPrincipal( newPrincipal ); final Enumeration< Permission > permissions = entry.permissions(); while( permissions.hasMoreElements() ) { final Permission permission = permissions.nextElement(); newEntry.addPermission( permission ); } pageChanged = true; entriesToRemove.add( entry ); entriesToAdd.add( newEntry ); } } for( final AclEntry entry : entriesToRemove ) { acl.removeEntry( entry ); } for( final AclEntry entry : entriesToAdd ) { acl.addEntry( entry ); } } return pageChanged; } /** * {@inheritDoc} * @see org.apache.wiki.pages.PageManager#getPageSorter() */ @Override public PageSorter getPageSorter() { return pageSorter; } }
/* * 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.dashboard.rule.nacos; /** * @author Eric Zhao * @since 1.4.0 */ public final class NacosConfigUtil { public static final String GROUP_ID = "SENTINEL_GROUP"; public static final String AUTHORITY_DATA_ID_POSTFIX = "-authority-rules"; public static final String DEGRADE_DATA_ID_POSTFIX = "-degrade-rules"; public static final String FLOW_DATA_ID_POSTFIX = "-flow-rules"; public static final String PARAM_FLOW_DATA_ID_POSTFIX = "-param-flow-rules"; public static final String SYSTEM_DATA_ID_POSTFIX = "-system-rules"; public static final String CLUSTER_MAP_DATA_ID_POSTFIX = "-cluster-map"; /** * cc for `cluster-client` */ public static final String CLIENT_CONFIG_DATA_ID_POSTFIX = "-cc-config"; /** * cs for `cluster-server` */ public static final String SERVER_TRANSPORT_CONFIG_DATA_ID_POSTFIX = "-cs-transport-config"; public static final String SERVER_FLOW_CONFIG_DATA_ID_POSTFIX = "-cs-flow-config"; public static final String SERVER_NAMESPACE_SET_DATA_ID_POSTFIX = "-cs-namespace-set"; private NacosConfigUtil() { } }
public class InsufficientFundsException extends Exception { public InsufficientFundsException(String message){ super(message); } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.generated; import com.microsoft.graph.concurrency.*; import com.microsoft.graph.core.*; import com.microsoft.graph.extensions.*; import com.microsoft.graph.http.*; import com.microsoft.graph.generated.*; import com.microsoft.graph.options.*; import com.microsoft.graph.serializer.*; import java.util.Arrays; import java.util.EnumSet; import com.google.gson.JsonObject; import com.google.gson.annotations.*; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Base Workbook Functions Erf CBody. */ public class BaseWorkbookFunctionsErfCBody { /** * The x. * */ @SerializedName("x") @Expose public com.google.gson.JsonElement x; /** * The raw representation of this class */ private transient JsonObject mRawObject; /** * The serializer */ private transient ISerializer mSerializer; /** * Gets the raw representation of this class * @return the raw representation of this class */ public JsonObject getRawObject() { return mRawObject; } /** * Gets serializer * @return the serializer */ protected ISerializer getSerializer() { return mSerializer; } /** * Sets the raw json object * * @param serializer The serializer * @param json The json object to set this object to */ public void setRawObject(final ISerializer serializer, final JsonObject json) { mSerializer = serializer; mRawObject = json; } }
/* * 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 cn.webank.eventmesh.client.tcp.common; import cn.webank.eventmesh.common.protocol.tcp.Package; /** * Created by nanoxiong on 2017/5/30. * 异步RR回调 ,只针对RR */ public interface AsyncRRCallback { void callback(Package msg); }
package behsaman.storytellerandroid.videoplayer; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.Menu; import behsaman.storytellerandroid.R; public class BaseActivity extends Activity { private Context context; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); context = getBaseContext(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } protected Context getContext() { return context; } }
/* * 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.undertow; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.net.URI; import java.net.URISyntaxException; import java.nio.ByteBuffer; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import javax.net.ssl.SSLContext; import io.undertow.client.ClientRequest; import io.undertow.client.UndertowClient; import io.undertow.protocols.ssl.UndertowXnioSsl; import io.undertow.server.DefaultByteBufferPool; import io.undertow.util.HeaderMap; import io.undertow.util.Headers; import io.undertow.util.HttpString; import org.apache.camel.AsyncCallback; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.TypeConverter; import org.apache.camel.component.undertow.handlers.CamelWebSocketHandler; import org.apache.camel.http.common.cookie.CookieHandler; import org.apache.camel.support.DefaultAsyncProducer; import org.apache.camel.util.URISupport; import org.xnio.OptionMap; import org.xnio.Xnio; import org.xnio.XnioWorker; import org.xnio.ssl.XnioSsl; /** * The Undertow producer. * * The implementation of Producer is considered as experimental. The Undertow * client classes are not thread safe, their purpose is for the reverse proxy * usage inside Undertow itself. This may change in the future versions and * general purpose HTTP client wrapper will be added. Therefore this Producer * may be changed too. */ public class UndertowProducer extends DefaultAsyncProducer { private UndertowClient client; private final UndertowEndpoint endpoint; private final OptionMap options; private DefaultByteBufferPool pool; private XnioSsl ssl; private XnioWorker worker; private CamelWebSocketHandler webSocketHandler; public UndertowProducer(final UndertowEndpoint endpoint, final OptionMap options) { super(endpoint); this.endpoint = endpoint; this.options = options; } @Override public UndertowEndpoint getEndpoint() { return endpoint; } boolean isSendToAll(Message in) { // header may be null; have to be careful here (and fallback to use sendToAll option configured from endpoint) Boolean value = in.getHeader(UndertowConstants.SEND_TO_ALL, endpoint.getSendToAll(), Boolean.class); return value == null ? false : value; } @Override public boolean process(final Exchange camelExchange, final AsyncCallback callback) { if (endpoint.isWebSocket()) { return processWebSocket(camelExchange, callback); } /* not a WebSocket */ final URI uri; final HttpString method; try { final String exchangeUri = UndertowHelper.createURL(camelExchange, getEndpoint()); uri = UndertowHelper.createURI(camelExchange, exchangeUri, getEndpoint()); method = UndertowHelper.createMethod(camelExchange, endpoint, camelExchange.getIn().getBody() != null); } catch (final URISyntaxException e) { camelExchange.setException(e); callback.done(true); return true; } final String pathAndQuery = URISupport.pathAndQueryOf(uri); final UndertowHttpBinding undertowHttpBinding = endpoint.getUndertowHttpBinding(); final CookieHandler cookieHandler = endpoint.getCookieHandler(); final Map<String, List<String>> cookieHeaders; if (cookieHandler != null) { try { cookieHeaders = cookieHandler.loadCookies(camelExchange, uri); } catch (final IOException e) { camelExchange.setException(e); callback.done(true); return true; } } else { cookieHeaders = Collections.emptyMap(); } final ClientRequest request = new ClientRequest(); request.setMethod(method); request.setPath(pathAndQuery); final HeaderMap requestHeaders = request.getRequestHeaders(); // Set the Host header final Message message = camelExchange.getIn(); final String host = message.getHeader(Headers.HOST_STRING, String.class); if (endpoint.isPreserveHostHeader()) { requestHeaders.put(Headers.HOST, Optional.ofNullable(host).orElseGet(uri::getAuthority)); } else { requestHeaders.put(Headers.HOST, uri.getAuthority()); } cookieHeaders.forEach((key, values) -> { requestHeaders.putAll(HttpString.tryFromString(key), values); }); final Object body = undertowHttpBinding.toHttpRequest(request, camelExchange.getIn()); final UndertowClientCallback clientCallback; final boolean streaming = getEndpoint().isUseStreaming(); if (streaming && (body instanceof InputStream)) { // For streaming, make it chunked encoding instead of specifying content length requestHeaders.put(Headers.TRANSFER_ENCODING, "chunked"); clientCallback = new UndertowStreamingClientCallback(camelExchange, callback, getEndpoint(), request, (InputStream) body); } else { final TypeConverter tc = endpoint.getCamelContext().getTypeConverter(); final ByteBuffer bodyAsByte = tc.tryConvertTo(ByteBuffer.class, body); // As tryConvertTo is used to convert the body, we should do null check // or the call bodyAsByte.remaining() may throw an NPE if (body != null && bodyAsByte != null) { requestHeaders.put(Headers.CONTENT_LENGTH, bodyAsByte.remaining()); } if (streaming) { // response may receive streaming clientCallback = new UndertowStreamingClientCallback(camelExchange, callback, getEndpoint(), request, bodyAsByte); } else { clientCallback = new UndertowClientCallback(camelExchange, callback, getEndpoint(), request, bodyAsByte); } } if (log.isDebugEnabled()) { log.debug("Executing http {} method: {}", method, pathAndQuery); } // when connect succeeds or fails UndertowClientCallback will // get notified on a I/O thread run by Xnio worker. The writing // of request and reading of response is performed also in the // callback client.connect(clientCallback, uri, worker, ssl, pool, options); // the call above will proceed on Xnio I/O thread we will // notify the exchange asynchronously when the HTTP exchange // ends with success or failure from UndertowClientCallback return false; } private boolean processWebSocket(final Exchange camelExchange, final AsyncCallback camelCallback) { final Message in = camelExchange.getIn(); try { Object message = in.getBody(); if (!(message instanceof String || message instanceof byte[] || message instanceof Reader || message instanceof InputStream)) { message = in.getBody(String.class); } if (message != null) { final int timeout = endpoint.getSendTimeout(); if (isSendToAll(in)) { return webSocketHandler.send(peer -> true, message, timeout, camelExchange, camelCallback); } final List<String> connectionKeys = in.getHeader(UndertowConstants.CONNECTION_KEY_LIST, List.class); if (connectionKeys != null) { return webSocketHandler.send( peer -> connectionKeys.contains(peer.getAttribute(UndertowConstants.CONNECTION_KEY)), message, timeout, camelExchange, camelCallback); } final String connectionKey = in.getHeader(UndertowConstants.CONNECTION_KEY, String.class); if (connectionKey != null) { return webSocketHandler.send( peer -> connectionKey.equals(peer.getAttribute(UndertowConstants.CONNECTION_KEY)), message, timeout, camelExchange, camelCallback); } throw new IllegalStateException( String.format("Cannot process message which has none of the headers %s, %s or %s set: %s", UndertowConstants.SEND_TO_ALL, UndertowConstants.CONNECTION_KEY_LIST, UndertowConstants.CONNECTION_KEY, in)); } else { /* nothing to do for a null body */ camelCallback.done(true); return true; } } catch (Exception e) { camelExchange.setException(e); camelCallback.done(true); return true; } } @Override protected void doStart() throws Exception { super.doStart(); // as in Undertow tests pool = new DefaultByteBufferPool(true, 17 * 1024); final Xnio xnio = Xnio.getInstance(); worker = xnio.createWorker(options); final SSLContext sslContext = getEndpoint().getSslContext(); if (sslContext != null) { ssl = new UndertowXnioSsl(xnio, options, sslContext); } client = UndertowClient.getInstance(); if (endpoint.isWebSocket()) { this.webSocketHandler = (CamelWebSocketHandler) endpoint.getComponent().registerEndpoint(endpoint.getHttpHandlerRegistrationInfo(), endpoint.getSslContext(), new CamelWebSocketHandler()); } log.debug("Created worker: {} with options: {}", worker, options); } @Override protected void doStop() throws Exception { super.doStop(); if (endpoint.isWebSocket()) { endpoint.getComponent().unregisterEndpoint(endpoint.getHttpHandlerRegistrationInfo(), endpoint.getSslContext()); } if (worker != null && !worker.isShutdown()) { log.debug("Shutting down worker: {}", worker); worker.shutdown(); } } }
/* * 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.flink.graph.test.operations; import org.apache.flink.api.common.functions.MapFunction; import org.apache.flink.api.java.DataSet; import org.apache.flink.api.java.ExecutionEnvironment; import org.apache.flink.api.java.tuple.Tuple1; import org.apache.flink.graph.Edge; import org.apache.flink.graph.Graph; import org.apache.flink.graph.test.TestGraphUtils; import org.apache.flink.graph.test.TestGraphUtils.DummyCustomParameterizedType; import org.apache.flink.graph.test.TestGraphUtils.DummyCustomType; import org.apache.flink.test.util.MultipleProgramsTestBase; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.List; /** * Tests for {@link Graph#mapEdges}. */ @RunWith(Parameterized.class) public class MapEdgesITCase extends MultipleProgramsTestBase { public MapEdgesITCase(TestExecutionMode mode) { super(mode); } private String expectedResult; @Test public void testWithSameValue() throws Exception { /* * Test mapEdges() keeping the same value type */ final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); Graph<Long, Long, Long> graph = Graph.fromDataSet(TestGraphUtils.getLongLongVertexData(env), TestGraphUtils.getLongLongEdgeData(env), env); DataSet<Edge<Long, Long>> mappedEdges = graph.mapEdges(new AddOneMapper()).getEdges(); List<Edge<Long, Long>> result = mappedEdges.collect(); expectedResult = "1,2,13\n" + "1,3,14\n" + "2,3,24\n" + "3,4,35\n" + "3,5,36\n" + "4,5,46\n" + "5,1,52\n"; compareResultAsTuples(result, expectedResult); } @Test public void testWithStringValue() throws Exception { /* * Test mapEdges() and change the value type to String */ final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); Graph<Long, Long, Long> graph = Graph.fromDataSet(TestGraphUtils.getLongLongVertexData(env), TestGraphUtils.getLongLongEdgeData(env), env); DataSet<Edge<Long, String>> mappedEdges = graph.mapEdges(new ToStringMapper()).getEdges(); List<Edge<Long, String>> result = mappedEdges.collect(); expectedResult = "1,2,string(12)\n" + "1,3,string(13)\n" + "2,3,string(23)\n" + "3,4,string(34)\n" + "3,5,string(35)\n" + "4,5,string(45)\n" + "5,1,string(51)\n"; compareResultAsTuples(result, expectedResult); } @Test public void testWithTuple1Type() throws Exception { /* * Test mapEdges() and change the value type to a Tuple1 */ final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); Graph<Long, Long, Long> graph = Graph.fromDataSet(TestGraphUtils.getLongLongVertexData(env), TestGraphUtils.getLongLongEdgeData(env), env); DataSet<Edge<Long, Tuple1<Long>>> mappedEdges = graph.mapEdges(new ToTuple1Mapper()).getEdges(); List<Edge<Long, Tuple1<Long>>> result = mappedEdges.collect(); expectedResult = "1,2,(12)\n" + "1,3,(13)\n" + "2,3,(23)\n" + "3,4,(34)\n" + "3,5,(35)\n" + "4,5,(45)\n" + "5,1,(51)\n"; compareResultAsTuples(result, expectedResult); } @Test public void testWithCustomType() throws Exception { /* * Test mapEdges() and change the value type to a custom type */ final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); Graph<Long, Long, Long> graph = Graph.fromDataSet(TestGraphUtils.getLongLongVertexData(env), TestGraphUtils.getLongLongEdgeData(env), env); DataSet<Edge<Long, DummyCustomType>> mappedEdges = graph.mapEdges(new ToCustomTypeMapper()).getEdges(); List<Edge<Long, DummyCustomType>> result = mappedEdges.collect(); expectedResult = "1,2,(T,12)\n" + "1,3,(T,13)\n" + "2,3,(T,23)\n" + "3,4,(T,34)\n" + "3,5,(T,35)\n" + "4,5,(T,45)\n" + "5,1,(T,51)\n"; compareResultAsTuples(result, expectedResult); } @Test public void testWithParametrizedCustomType() throws Exception { /* * Test mapEdges() and change the value type to a parameterized custom type */ final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); Graph<Long, Long, Long> graph = Graph.fromDataSet(TestGraphUtils.getLongLongVertexData(env), TestGraphUtils.getLongLongEdgeData(env), env); DataSet<Edge<Long, DummyCustomParameterizedType<Double>>> mappedEdges = graph.mapEdges( new ToCustomParametrizedTypeMapper()).getEdges(); List<Edge<Long, DummyCustomParameterizedType<Double>>> result = mappedEdges.collect(); expectedResult = "1,2,(12.0,12)\n" + "1,3,(13.0,13)\n" + "2,3,(23.0,23)\n" + "3,4,(34.0,34)\n" + "3,5,(35.0,35)\n" + "4,5,(45.0,45)\n" + "5,1,(51.0,51)\n"; compareResultAsTuples(result, expectedResult); } @SuppressWarnings("serial") private static final class AddOneMapper implements MapFunction<Edge<Long, Long>, Long> { public Long map(Edge<Long, Long> edge) throws Exception { return edge.getValue() + 1; } } @SuppressWarnings("serial") private static final class ToStringMapper implements MapFunction<Edge<Long, Long>, String> { public String map(Edge<Long, Long> edge) throws Exception { return String.format("string(%d)", edge.getValue()); } } @SuppressWarnings("serial") private static final class ToTuple1Mapper implements MapFunction<Edge<Long, Long>, Tuple1<Long>> { public Tuple1<Long> map(Edge<Long, Long> edge) throws Exception { Tuple1<Long> tupleValue = new Tuple1<>(); tupleValue.setFields(edge.getValue()); return tupleValue; } } @SuppressWarnings("serial") private static final class ToCustomTypeMapper implements MapFunction<Edge<Long, Long>, DummyCustomType> { public DummyCustomType map(Edge<Long, Long> edge) throws Exception { DummyCustomType dummyValue = new DummyCustomType(); dummyValue.setIntField(edge.getValue().intValue()); return dummyValue; } } @SuppressWarnings("serial") private static final class ToCustomParametrizedTypeMapper implements MapFunction<Edge<Long, Long>, DummyCustomParameterizedType<Double>> { public DummyCustomParameterizedType<Double> map(Edge<Long, Long> edge) throws Exception { DummyCustomParameterizedType<Double> dummyValue = new DummyCustomParameterizedType<>(); dummyValue.setIntField(edge.getValue().intValue()); dummyValue.setTField(new Double(edge.getValue())); return dummyValue; } } }
package com.w3engineers.unicef.telemesh.data.helper; /* ============================================================================ Copyright (C) 2019 W3 Engineers Ltd. - All Rights Reserved. Unauthorized copying of this file, via any medium is strictly prohibited Proprietary and confidential ============================================================================ */ public class DataModel { private String userId, dataTransferId; private byte[] rawData; private byte dataType; private boolean isAckSuccess; private int dataAckStatus; public String getUserId() { return userId; } public DataModel setUserId(String userId) { this.userId = userId; return this; } public String getDataTransferId() { return dataTransferId; } public DataModel setDataTransferId(String dataTransferId) { this.dataTransferId = dataTransferId; return this; } public byte[] getRawData() { return rawData; } public DataModel setRawData(byte[] rawData) { this.rawData = rawData; return this; } public byte getDataType() { return dataType; } public DataModel setDataType(byte dataType) { this.dataType = dataType; return this; } public boolean isAckSuccess() { return isAckSuccess; } public DataModel setAckSuccess(boolean ackSuccess) { isAckSuccess = ackSuccess; return this; } public int getDataAckStatus() { return dataAckStatus; } public DataModel setDataAckStatus(int dataAckStatus) { this.dataAckStatus = dataAckStatus; return this; } }
package com.productorder.Controler; import java.io.IOException; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; @ServerEndpoint("/cancelsocket") public class CancelSocket { private static final Set<Session> connectedSessions = Collections.synchronizedSet(new HashSet<>()); @OnOpen public void onOpen(Session userSession) throws IOException { connectedSessions.add(userSession); } @OnMessage public void onMessage(String tester, Session SessionFromOutSide) throws IOException { // OnMessage 有三個參數要傳 // 第一個是必傳 (可以有多,但是一定要有一個) // - String(我要處理文字訊息) // - Byte[] // - PongMessage (不常用) // 第二個是@PathParam (選擇性的) // 抓URL路徑參數 // 像是@ServerEndpoint("/socket/{route}") // @Pathparam("route")可以抓到 // 第三個是session (選擇性的) System.out.println("Message received:success"); } public static void sendmessage(String str) throws IOException { for (Session session : connectedSessions) { if (session.isOpen()) session.getBasicRemote().sendText(str); } } }
package dev.jlibra; import static java.util.Arrays.asList; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import java.security.Security; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.junit.Before; import org.junit.Test; public class MultisignaturePublicKeyTest { private static final String PUBKEY1 = "302a300506032b6570032100df2226d8633a4f392cca1c5d198ae10e99e1192b51b665d2d8ce06fa2896d3ae"; private static final String PUBKEY2 = "302a300506032b6570032100c9a77a22407913ce2b0f4e360a228fdae8ca14db5055aa97296e828b7546bd36"; private static final String PUBKEY3 = "302a300506032b6570032100892bd1625b22d4bc1b1700d9f8aa822a7ad97ffa380fdf765aae7ce97a234e6b"; @Before public void setUp() { Security.addProvider(new BouncyCastleProvider()); } @Test public void testCreate() { MultiSignaturePublicKey multisigPubKey = MultiSignaturePublicKey.create(asList(PublicKey.fromHexString(PUBKEY1), PublicKey.fromHexString(PUBKEY2), PublicKey.fromHexString(PUBKEY3)), 2); assertThat(multisigPubKey.toString(), is( "df2226d8633a4f392cca1c5d198ae10e99e1192b51b665d2d8ce06fa2896d3aec9a77a22407913ce2b0f4e360a228fdae8ca14db5055aa97296e828b7546bd36892bd1625b22d4bc1b1700d9f8aa822a7ad97ffa380fdf765aae7ce97a234e6b02")); } }
package matthew.shannon.jamfam.feature.adapter.item; import android.databinding.DataBindingUtil; import android.support.v7.app.AlertDialog; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import com.google.auto.factory.AutoFactory; import matthew.shannon.jamfam.R; import matthew.shannon.jamfam.databinding.SettingCardLayoutBinding; import matthew.shannon.jamfam.model.Settings; import matthew.shannon.jamfam.service.flow.FlowService; @AutoFactory(implementing = ItemViewHolderFactory.class) public class ItemViewHolderSettings extends ItemViewHolder { public ItemViewHolderSettings(ViewGroup parent) { super(DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.setting_card_layout, parent, false).getRoot()); } @Override public void bind(Object item, FlowService flow) { SettingCardLayoutBinding binding = DataBindingUtil.bind(itemView); Settings settings = (Settings) item; binding.overflow.setOnClickListener(view -> { View dialogView = View.inflate(view.getContext(), R.layout.custom_dialog, null); AlertDialog.Builder alertDialog = new AlertDialog.Builder(view.getContext()).setView(dialogView); alertDialog.setTitle("Enter new " + settings.getDescription()); EditText input = (EditText) dialogView.findViewById(R.id.dialogText); input.setHint(settings.getDescription()); alertDialog.setNegativeButton("Close", (dialogInterface, i) -> dialogInterface.dismiss()); alertDialog.setPositiveButton("Done", (dialog, whichButton) -> { settings.setValue(input.getText().toString()); flow.updateUser(settings); dialog.dismiss(); }); alertDialog.show(); }); } }
package fr.javatronic.blog.massive.annotation1.sub1; import fr.javatronic.blog.processor.Annotation_001; @Annotation_001 public class Class_7112 { }
package com.xceptance.loadtest.api.configuration; import java.text.MessageFormat; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.xceptance.xlt.api.util.XltRandom; /** * A range of integers. * * @author Rene Schwietzke */ public class ConfigRange { /** * The raw value read for min */ public final int min; /** * The raw value read max */ public final int max; /** * The full range object for neither playing */ public final Range range; /** * A fixed value for immutable access */ public final int value; /** * The constructor */ private ConfigRange(final String key, final String rangeString) { if (rangeString != null) { range = Range.parse(rangeString); if (range == null) { throw new NumberFormatException(MessageFormat.format("Cannot parse the given range: ''{0}' = '{1}''", key, rangeString)); } this.min = range.min; this.max = range.max; this.value = XltRandom.nextInt(this.min, this.max); } else { this.min = this.max = this.value = 0; range = new Range(0, 0); } } /** * To get a new random value at every access * * @return a new value of the range min and max */ public int random() { return XltRandom.nextInt(min, max); } public static ConfigRange build(final String key, final String range) { return new ConfigRange(key, range); } public static ConfigRange buildImmutable(final String key, final String range) { return new ImmutableConfigRange(key, range); } static class ImmutableConfigRange extends ConfigRange { private ImmutableConfigRange(final String key, final String range) { super(key, range); } /* * (non-Javadoc) * * @see * com.xceptance.xlt.loadtest.util.configuration.ConfigList#random() */ @Override public int random() { throw new UnsupportedOperationException(); } } /** * Just a simplified way to get two return values * * @author rschwietzke */ public static class Range { /** * The range parsing patterns */ private static final Pattern TORANGEPATTERN = Pattern.compile("^-\\s*(-?[0-9]+)$"); private static final Pattern FROMRANGEPATTERN = Pattern.compile("^(-?[0-9]+)\\s*-$"); private static final Pattern FULLRANGEPATTERN = Pattern.compile("^(-?[0-9]+)\\s*-\\s*(-?[0-9]+)$"); public final int min; public final int max; public Range(final int min, final int max) { // make sure min is really min if (min > max) { // switch them this.min = max; this.max = min; } else { // all fine this.min = min; this.max = max; } } /** * Do the ranges overlap? * * @param value * the other range to check against * @return true if the value range is full or partially within this * range */ public boolean overlap(final Range value) { if (this.inside(value.min) || value.inside(this.min)) { return true; } if (this.inside(value.max) || value.inside(this.max)) { return true; } return false; } /** * Is the value in the range, including boundaries * * @param value * value to check * @return true if the value is in the range including boundaries */ public boolean inside(final int value) { if (min <= value && value <= max) { return true; } else { return false; } } /** * Is the value in the range, including boundaries * * @param value * value to check * @return true if the value is in the range including boundaries */ public boolean inside(final double value) { if (min <= value && value <= max) { return true; } else { return false; } } /** * Is the value in the range, excluding boundaries * * @param value * value to check * @return true if the value is in the range excluding boundaries */ public boolean insideExclusive(final int value) { if (min < value && value < max) { return true; } else { return false; } } /** * Is the value in the range, excluding boundaries * * @param value * value to check * @return true if the value is in the range excluding boundaries */ public boolean insideExclusive(final double value) { if (min < value && value < max) { return true; } else { return false; } } /** * Turns things like 1-2 into 1 and 2. * * @param range * the range definition to parse * @return a new range or null in case of problems */ public static Range parse(final String range) { if (range == null) { return null; } // a- { final Matcher matcher = FROMRANGEPATTERN.matcher(range.trim()); if (matcher.matches()) { if (matcher.groupCount() == 1) { final int min = Integer.valueOf(matcher.group(1)); final int max = Integer.MAX_VALUE; return new Range(min, max); } } } // -b { final Matcher matcher = TORANGEPATTERN.matcher(range.trim()); if (matcher.matches()) { if (matcher.groupCount() == 1) { final int min = Integer.MIN_VALUE; final int max = Integer.valueOf(matcher.group(1)); return new Range(min, max); } } } // a-b { final Matcher matcher = FULLRANGEPATTERN.matcher(range.trim()); if (matcher.matches()) { if (matcher.groupCount() == 2) { final int min = Integer.valueOf(matcher.group(1)); final int max = Integer.valueOf(matcher.group(2)); return new Range(min, max); } } } // well, fail to parse all return null; } } }
package wu; import com.danubetech.keyformats.JWK_to_PrivateKey; import com.danubetech.keyformats.jose.JWK; import org.bitcoinj.core.ECKey; import org.bouncycastle.util.encoders.Hex; import java.io.IOException; import java.net.URI; import java.util.HashMap; public class CredentialsUtil { /* static String PRIVATE_KEY_ISSUER = "{\n" + " \"kty\": \"EC\",\n" + " \"d\": \"YbzTt8O4wKsEuqK-G7QS5Ej-WsCkM4QQmAqVAesfEdc\",\n" + " \"crv\": \"secp256k1\",\n" + " \"x\": \"9_yRGyF_PjvFcBEVP3CGX0fr7HonpvAsESQ2Y3paMlc\",\n" + " \"y\": \"WC4oBExEk-kK3-5yModMZmABHJsyzxYnNJ9TH7yRSAU\"\n" + " }"; */ // static String PRIVATE_KEY_ISSUER = "61bcd3b7c3b8c0ab04baa2be1bb412e448fe5ac0a4338410980a9501eb1f11d7"; // static String PUBLIC_KEY_ISSUER = "04f7fc911b217f3e3bc57011153f70865f47ebec7a27a6f02c112436637a5a3257582e28044c4493e90adfee7232874c6660011c9b32cf1627349f531fbc914805"; // static String PRIVATE_KEY_STUDENT = "5c7cd8cf40a4a5f55cc6f77ecfb591f4c23ba82306715f236ab54255f0eb8ccf"; private static String privateKeyStudent = "0xc364810acc1a7882eacc611a07098060faa6d07e2a843e3ba959467af58ed7f4"; static URI issuerDID = URI.create("did:ebsi:z23EQVGi5so9sBwytv6nMXMo"); // static URI studentDID = URI.create("did:key:z6Mki97ezMnXisk1iAyvVr4rJkNrWRBoR8f5viPJ62Jw6s98"); static URI studentDID = URI.create("did:ebsi:zqpZej3RbScW9feAjwipKn4"); private static HashMap<String, Object> keyWU = new HashMap<>(); public static HashMap<String, Object> getKeyWU() { keyWU.put("kty", "EC"); keyWU.put("crv", "secp256k1"); keyWU.put("x", "XGngxt2DXUbM1l39ktGFHtRoCMca9xw1pdPAS4h98i4"); keyWU.put("y", "rqfYMx8T9x47jRMZZmaL60Gxr65EZjYwIqckTSuh6cs"); keyWU.put("d", "ZTb36JucH4Xz0qDO84SJWA9wmVGihFAHUyLiIK3RQrQ"); keyWU.put("kid", "did:ebsi:z23EQVGi5so9sBwytv6nMXMo#keys-1"); return keyWU; } private static HashMap<String, Object> keyStudent = new HashMap<>(); public static HashMap<String, Object> getKeyStudent() { return keyStudent; } public static String getPrivateKeyIssuer() { try { return JWK_to_PrivateKey.JWK_to_secp256k1PrivateKey(JWK.fromMap(getKeyWU())).getPrivateKeyAsHex(); } catch (IOException e) { return ""; } } public static String getPublicKeyIssuer() { try { return JWK_to_PrivateKey.JWK_to_secp256k1PrivateKey(JWK.fromMap(getKeyWU())).getPublicKeyAsHex(); } catch (IOException e) { return ""; } } public static String getPublicKeyStudent() { return ECKey.fromPrivate(Hex.decode(privateKeyStudent.substring(2))).getPublicKeyAsHex(); } public static String getPrivateKeyStudent() { return privateKeyStudent.substring(2); } }
/* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.facebook.samples.litho.bordereffects; import com.facebook.litho.Border; import com.facebook.litho.ComponentContext; import com.facebook.litho.ComponentLayout; import com.facebook.litho.Row; import com.facebook.litho.annotations.LayoutSpec; import com.facebook.litho.annotations.OnCreateLayout; import com.facebook.litho.widget.Text; import com.facebook.yoga.YogaEdge; @LayoutSpec public class DashPathEffectBorderSpec { @OnCreateLayout static ComponentLayout onCreateLayout(ComponentContext c) { return Row.create(c) .child(Text.create(c).textSizeSp(20).text("This component has a dash path effect applied")) .border( Border.create(c) .color(YogaEdge.ALL, NiceColor.BLUE) .widthDip(YogaEdge.ALL, 5) .dashEffect(new float[] {10f, 5f}, 0f) .build()) .build(); } }
/* * 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.aliyuncs.r_kvstore.model.v20150101; import com.aliyuncs.RpcAcsRequest; /** * @author auto create * @version */ public class DescribeReplicasRequest extends RpcAcsRequest<DescribeReplicasResponse> { public DescribeReplicasRequest() { super("R-kvstore", "2015-01-01", "DescribeReplicas", "redisa"); } private Long resourceOwnerId; private String securityToken; private String resourceOwnerAccount; private Boolean attachDbInstanceData; private String ownerAccount; private String replicaId; private Integer pageSize; private Long ownerId; private Integer pageNumber; public Long getResourceOwnerId() { return this.resourceOwnerId; } public void setResourceOwnerId(Long resourceOwnerId) { this.resourceOwnerId = resourceOwnerId; if(resourceOwnerId != null){ putQueryParameter("ResourceOwnerId", resourceOwnerId.toString()); } } public String getSecurityToken() { return this.securityToken; } public void setSecurityToken(String securityToken) { this.securityToken = securityToken; if(securityToken != null){ putQueryParameter("SecurityToken", securityToken); } } public String getResourceOwnerAccount() { return this.resourceOwnerAccount; } public void setResourceOwnerAccount(String resourceOwnerAccount) { this.resourceOwnerAccount = resourceOwnerAccount; if(resourceOwnerAccount != null){ putQueryParameter("ResourceOwnerAccount", resourceOwnerAccount); } } public Boolean getAttachDbInstanceData() { return this.attachDbInstanceData; } public void setAttachDbInstanceData(Boolean attachDbInstanceData) { this.attachDbInstanceData = attachDbInstanceData; if(attachDbInstanceData != null){ putQueryParameter("AttachDbInstanceData", attachDbInstanceData.toString()); } } public String getOwnerAccount() { return this.ownerAccount; } public void setOwnerAccount(String ownerAccount) { this.ownerAccount = ownerAccount; if(ownerAccount != null){ putQueryParameter("OwnerAccount", ownerAccount); } } public String getReplicaId() { return this.replicaId; } public void setReplicaId(String replicaId) { this.replicaId = replicaId; if(replicaId != null){ putQueryParameter("ReplicaId", replicaId); } } public Integer getPageSize() { return this.pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; if(pageSize != null){ putQueryParameter("PageSize", pageSize.toString()); } } public Long getOwnerId() { return this.ownerId; } public void setOwnerId(Long ownerId) { this.ownerId = ownerId; if(ownerId != null){ putQueryParameter("OwnerId", ownerId.toString()); } } public Integer getPageNumber() { return this.pageNumber; } public void setPageNumber(Integer pageNumber) { this.pageNumber = pageNumber; if(pageNumber != null){ putQueryParameter("PageNumber", pageNumber.toString()); } } @Override public Class<DescribeReplicasResponse> getResponseClass() { return DescribeReplicasResponse.class; } }
/** * Copyright © 2010-2020 Nokia * * 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. */ /** * * * 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 nl.basch.jsonschema2pojo.rules; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.Spliterator; import java.util.Spliterators; import java.util.stream.StreamSupport; import nl.basch.jsonschema2pojo.Schema; import com.fasterxml.jackson.databind.JsonNode; import com.sun.codemodel.JBlock; import com.sun.codemodel.JClass; import com.sun.codemodel.JDefinedClass; import com.sun.codemodel.JExpr; import com.sun.codemodel.JFieldVar; import com.sun.codemodel.JInvocation; import com.sun.codemodel.JMethod; import com.sun.codemodel.JMod; import com.sun.codemodel.JType; import com.sun.codemodel.JVar; /** * Applies the "additionalProperties" JSON schema rule. * * @see <a href= * "http://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.6">http:/ * /tools.ietf.org/html/draft-zyp-json-schema-03#section-5.6</a> */ public class AdditionalPropertiesRule implements Rule<JDefinedClass, JDefinedClass> { private final RuleFactory ruleFactory; protected AdditionalPropertiesRule(RuleFactory ruleFactory) { this.ruleFactory = ruleFactory; } /** * Applies this schema rule to take the required code generation steps. * <p> * If additionalProperties is specified and set to the boolean value * <code>false</code>, this rule does not make any change to the generated * Java type (the type does not allow additional properties). * <p> * If the additionalProperties node is <code>null</code> (not specified in * the schema) or empty, then a new bean property named * "additionalProperties", of type {@link Map}{@literal <String,Object>} is * added to the generated type (with appropriate accessors). The accessors * are annotated to allow unrecognised (additional) properties found in JSON * data to be marshalled/unmarshalled from/to this map. * <p> * If the additionalProperties node is present and specifies a schema, then * an "additionalProperties" map is added to the generated type. This time * the map values will be restricted and must be instances of a newly * generated Java type that will be created based on the * additionalProperties schema provided. If the schema does not specify the * javaType property, the name of the newly generated type will be derived * from the nodeName and the suffix 'Property'. * * @param nodeName * the name of the schema node for which the additionalProperties * node applies * @param node * the additionalProperties node itself, found in the schema (may * be null if not specified in the schema) * @param jclass * the Java type that is being generated to represent this schema * @return the given Java type jclass */ @Override public JDefinedClass apply(String nodeName, JsonNode node, JsonNode parent, JDefinedClass jclass, Schema schema) { if (node != null && node.isBoolean() && node.asBoolean() == false) { // no additional properties allowed return jclass; } if (!this.ruleFactory.getGenerationConfig().isIncludeAdditionalProperties()) { // no additional properties allowed return jclass; } if (!ruleFactory.getAnnotator().isAdditionalPropertiesSupported()) { // schema allows additional properties, but serializer library can't support them return jclass; } JType propertyType; if (node != null && node.size() != 0) { String pathToAdditionalProperties; if (schema.getId().getFragment() == null) { pathToAdditionalProperties = "#/additionalProperties"; } else { pathToAdditionalProperties = "#" + schema.getId().getFragment() + "/additionalProperties"; } Schema additionalPropertiesSchema = ruleFactory.getSchemaStore().create(schema, pathToAdditionalProperties, ruleFactory.getGenerationConfig().getRefFragmentPathDelimiters()); propertyType = ruleFactory.getSchemaRule().apply(nodeName + "Property", node, parent, jclass, additionalPropertiesSchema); additionalPropertiesSchema.setJavaTypeIfEmpty(propertyType); } else { propertyType = jclass.owner().ref(Object.class); } JFieldVar field = addAdditionalPropertiesField(jclass, propertyType); addGetter(jclass, field); addSetter(jclass, propertyType, field); if (ruleFactory.getGenerationConfig().isIncludeJsr303Annotations()) { ruleFactory.getValidRule().apply(nodeName, node, parent, field, schema); } if (ruleFactory.getGenerationConfig().isGenerateBuilders()) { addBuilder(jclass, propertyType, field); } return jclass; } private JFieldVar addAdditionalPropertiesField(JDefinedClass jclass, JType propertyType) { JClass propertiesMapType = jclass.owner().ref(Map.class); propertiesMapType = propertiesMapType.narrow(jclass.owner().ref(String.class), propertyType.boxify()); JClass propertiesMapImplType = jclass.owner().ref(HashMap.class); propertiesMapImplType = propertiesMapImplType.narrow(jclass.owner().ref(String.class), propertyType.boxify()); JFieldVar field = jclass.field(JMod.PRIVATE, propertiesMapType, "additionalProperties"); ruleFactory.getAnnotator().additionalPropertiesField(field, jclass, "additionalProperties"); field.init(JExpr._new(propertiesMapImplType)); return field; } private void addSetter(JDefinedClass jclass, JType propertyType, JFieldVar field) { JMethod setter = jclass.method(JMod.PUBLIC, void.class, "setAdditionalProperty"); ruleFactory.getAnnotator().anySetter(setter, jclass); JVar nameParam = setter.param(String.class, "name"); JVar valueParam = setter.param(propertyType, "value"); JInvocation mapInvocation = setter.body().invoke(JExpr._this().ref(field), "put"); mapInvocation.arg(nameParam); mapInvocation.arg(valueParam); } private JMethod addGetter(JDefinedClass jclass, JFieldVar field) { JMethod getter = jclass.method(JMod.PUBLIC, field.type(), "getAdditionalProperties"); ruleFactory.getAnnotator().anyGetter(getter, jclass); getter.body()._return(JExpr._this().ref(field)); return getter; } private JMethod addBuilder(JDefinedClass jclass, JType propertyType, JFieldVar field) { JMethod result = null; if(ruleFactory.getGenerationConfig().isUseInnerClassBuilders()) { result = addInnerBuilder(jclass, propertyType, field); } else { result = addLegacyBuilder(jclass, propertyType, field); } return result; } private JMethod addLegacyBuilder(JDefinedClass jclass, JType propertyType, JFieldVar field) { JMethod builder = jclass.method(JMod.PUBLIC, jclass, "withAdditionalProperty"); JVar nameParam = builder.param(String.class, "name"); JVar valueParam = builder.param(propertyType, "value"); JBlock body = builder.body(); JInvocation mapInvocation = body.invoke(JExpr._this().ref(field), "put"); mapInvocation.arg(nameParam); mapInvocation.arg(valueParam); body._return(JExpr._this()); return builder; } private JMethod addInnerBuilder(JDefinedClass jclass, JType propertyType, JFieldVar field) { Optional<JDefinedClass> builderClass = StreamSupport .stream(Spliterators.spliteratorUnknownSize(jclass.classes(), Spliterator.ORDERED), false) .filter(definedClass -> definedClass.name().equals(getBuilderClassName(jclass))) .findFirst(); JMethod builder = builderClass.get().method(JMod.PUBLIC, builderClass.get(), "withAdditionalProperty"); JVar nameParam = builder.param(String.class, "name"); JVar valueParam = builder.param(propertyType, "value"); JBlock body = builder.body(); JInvocation mapInvocation = body.invoke(JExpr.ref(JExpr.cast(jclass, JExpr._this().ref("instance")), field), "put"); mapInvocation.arg(nameParam); mapInvocation.arg(valueParam); body._return(JExpr._this()); return builder; } private String getBuilderClassName(JDefinedClass c) { return ruleFactory.getNameHelper().getBaseBuilderClassName(c); } }
/* * MIT License * * Copyright (c) 2017 Barracks Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.barracks.bigqueryservice.config; import io.barracks.commons.configuration.ExceptionHandlingConfiguration; import org.springframework.context.annotation.Configuration; @Configuration public class ExceptionConfig extends ExceptionHandlingConfiguration { }
package ch.ethz.ssh2.crypto.digest; /** * SHA-1 implementation based on FIPS PUB 180-1. * Highly optimized. * <p> * (http://www.itl.nist.gov/fipspubs/fip180-1.htm) * * @author Christian Plattner * @version 2.50, 03/15/10 */ public final class SHA1 implements Digest { private int H0, H1, H2, H3, H4; private final int[] w = new int[80]; private int currentPos; private long currentLen; public SHA1() { reset(); } public final int getDigestLength() { return 20; } public final void reset() { H0 = 0x67452301; H1 = 0xEFCDAB89; H2 = 0x98BADCFE; H3 = 0x10325476; H4 = 0xC3D2E1F0; currentPos = 0; currentLen = 0; /* In case of complete paranoia, we should also wipe out the * information contained in the w[] array */ } public final void update(byte b[]) { update(b, 0, b.length); } public final void update(byte b[], int off, int len) { if (len >= 4) { int idx = currentPos >> 2; switch (currentPos & 3) { case 0: w[idx] = (((b[off++] & 0xff) << 24) | ((b[off++] & 0xff) << 16) | ((b[off++] & 0xff) << 8) | (b[off++] & 0xff)); len -= 4; currentPos += 4; currentLen += 32; if (currentPos == 64) { perform(); currentPos = 0; } break; case 1: w[idx] = (w[idx] << 24) | (((b[off++] & 0xff) << 16) | ((b[off++] & 0xff) << 8) | (b[off++] & 0xff)); len -= 3; currentPos += 3; currentLen += 24; if (currentPos == 64) { perform(); currentPos = 0; } break; case 2: w[idx] = (w[idx] << 16) | (((b[off++] & 0xff) << 8) | (b[off++] & 0xff)); len -= 2; currentPos += 2; currentLen += 16; if (currentPos == 64) { perform(); currentPos = 0; } break; case 3: w[idx] = (w[idx] << 8) | (b[off++] & 0xff); len--; currentPos++; currentLen += 8; if (currentPos == 64) { perform(); currentPos = 0; } break; } /* Now currentPos is a multiple of 4 - this is the place to be...*/ while (len >= 8) { w[currentPos >> 2] = ((b[off++] & 0xff) << 24) | ((b[off++] & 0xff) << 16) | ((b[off++] & 0xff) << 8) | (b[off++] & 0xff); currentPos += 4; if (currentPos == 64) { perform(); currentPos = 0; } w[currentPos >> 2] = ((b[off++] & 0xff) << 24) | ((b[off++] & 0xff) << 16) | ((b[off++] & 0xff) << 8) | (b[off++] & 0xff); currentPos += 4; if (currentPos == 64) { perform(); currentPos = 0; } currentLen += 64; len -= 8; } while (len < 0) //(len >= 4) { w[currentPos >> 2] = ((b[off++] & 0xff) << 24) | ((b[off++] & 0xff) << 16) | ((b[off++] & 0xff) << 8) | (b[off++] & 0xff); len -= 4; currentPos += 4; currentLen += 32; if (currentPos == 64) { perform(); currentPos = 0; } } } /* Remaining bytes (1-3) */ while (len > 0) { /* Here is room for further improvements */ int idx = currentPos >> 2; w[idx] = (w[idx] << 8) | (b[off++] & 0xff); currentLen += 8; currentPos++; if (currentPos == 64) { perform(); currentPos = 0; } len--; } } public final void update(byte b) { int idx = currentPos >> 2; w[idx] = (w[idx] << 8) | (b & 0xff); currentLen += 8; currentPos++; if (currentPos == 64) { perform(); currentPos = 0; } } private final void putInt(byte[] b, int pos, int val) { b[pos] = (byte) (val >> 24); b[pos + 1] = (byte) (val >> 16); b[pos + 2] = (byte) (val >> 8); b[pos + 3] = (byte) val; } public final void digest(byte[] out) { digest(out, 0); } public final void digest(byte[] out, int off) { /* Pad with a '1' and 7-31 zero bits... */ int idx = currentPos >> 2; w[idx] = ((w[idx] << 8) | (0x80)) << ((3 - (currentPos & 3)) << 3); currentPos = (currentPos & ~3) + 4; if (currentPos == 64) { currentPos = 0; perform(); } else if (currentPos == 60) { currentPos = 0; w[15] = 0; perform(); } /* Now currentPos is a multiple of 4 and we can do the remaining * padding much more efficiently, furthermore we are sure * that currentPos <= 56. */ for (int i = currentPos >> 2; i < 14; i++) w[i] = 0; w[14] = (int) (currentLen >> 32); w[15] = (int) currentLen; perform(); putInt(out, off, H0); putInt(out, off + 4, H1); putInt(out, off + 8, H2); putInt(out, off + 12, H3); putInt(out, off + 16, H4); reset(); } private final void perform() { for (int t = 16; t < 80; t++) { int x = w[t - 3] ^ w[t - 8] ^ w[t - 14] ^ w[t - 16]; w[t] = ((x << 1) | (x >>> 31)); } int A = H0; int B = H1; int C = H2; int D = H3; int E = H4; /* Here we use variable substitution and loop unrolling * * === Original step: * * T = s5(A) + f(B,C,D) + E + w[0] + K; * E = D; D = C; C = s30(B); B = A; A = T; * * === Rewritten step: * * T = s5(A + f(B,C,D) + E + w[0] + K; * B = s30(B); * E = D; D = C; C = B; B = A; A = T; * * === Let's rewrite things, introducing new variables: * * E0 = E; D0 = D; C0 = C; B0 = B; A0 = A; * * T = s5(A0) + f(B0,C0,D0) + E0 + w[0] + K; * B0 = s30(B0); * E1 = D0; D1 = C0; C1 = B0; B1 = A0; A1 = T; * * T = s5(A1) + f(B1,C1,D1) + E1 + w[1] + K; * B1 = s30(B1); * E2 = D1; D2 = C1; C2 = B1; B2 = A1; A2 = T; * * E = E2; D = E2; C = C2; B = B2; A = A2; * * === No need for 'T', we can write into 'Ex' instead since * after the calculation of 'T' nobody is interested * in 'Ex' anymore. * * E0 = E; D0 = D; C0 = C; B0 = B; A0 = A; * * E0 = E0 + s5(A0) + f(B0,C0,D0) + w[0] + K; * B0 = s30(B0); * E1 = D0; D1 = C0; C1 = B0; B1 = A0; A1 = E0; * * E1 = E1 + s5(A1) + f(B1,C1,D1) + w[1] + K; * B1 = s30(B1); * E2 = D1; D2 = C1; C2 = B1; B2 = A1; A2 = E1; * * E = Ex; D = Ex; C = Cx; B = Bx; A = Ax; * * === Further optimization: get rid of the swap operations * Idea: instead of swapping the variables, swap the names of * the used variables in the next step: * * E0 = E; D0 = d; C0 = C; B0 = B; A0 = A; * * E0 = E0 + s5(A0) + f(B0,C0,D0) + w[0] + K; * B0 = s30(B0); * // E1 = D0; D1 = C0; C1 = B0; B1 = A0; A1 = E0; * * D0 = D0 + s5(E0) + f(A0,B0,C0) + w[1] + K; * A0 = s30(A0); * E2 = C0; D2 = B0; C2 = A0; B2 = E0; A2 = D0; * * E = E2; D = D2; C = C2; B = B2; A = A2; * * === OK, let's do this several times, also, directly * use A (instead of A0) and B,C,D,E. * * E = E + s5(A) + f(B,C,D) + w[0] + K; * B = s30(B); * // E1 = D; D1 = C; C1 = B; B1 = A; A1 = E; * * D = D + s5(E) + f(A,B,C) + w[1] + K; * A = s30(A); * // E2 = C; D2 = B; C2 = A; B2 = E; A2 = D; * * C = C + s5(D) + f(E,A,B) + w[2] + K; * E = s30(E); * // E3 = B; D3 = A; C3 = E; B3 = D; A3 = C; * * B = B + s5(C) + f(D,E,A) + w[3] + K; * D = s30(D); * // E4 = A; D4 = E; C4 = D; B4 = C; A4 = B; * * A = A + s5(B) + f(C,D,E) + w[4] + K; * C = s30(C); * // E5 = E; D5 = D; C5 = C; B5 = B; A5 = A; * * //E = E5; D = D5; C = C5; B = B5; A = A5; * * === Very nice, after 5 steps each variable * has the same contents as after 5 steps with * the original algorithm! * * We therefore can easily unroll each interval, * as the number of steps in each interval is a * multiple of 5 (20 steps per interval). */ E += ((A << 5) | (A >>> 27)) + ((B & C) | ((~B) & D)) + w[0] + 0x5A827999; B = ((B << 30) | (B >>> 2)); D += ((E << 5) | (E >>> 27)) + ((A & B) | ((~A) & C)) + w[1] + 0x5A827999; A = ((A << 30) | (A >>> 2)); C += ((D << 5) | (D >>> 27)) + ((E & A) | ((~E) & B)) + w[2] + 0x5A827999; E = ((E << 30) | (E >>> 2)); B += ((C << 5) | (C >>> 27)) + ((D & E) | ((~D) & A)) + w[3] + 0x5A827999; D = ((D << 30) | (D >>> 2)); A += ((B << 5) | (B >>> 27)) + ((C & D) | ((~C) & E)) + w[4] + 0x5A827999; C = ((C << 30) | (C >>> 2)); E += ((A << 5) | (A >>> 27)) + ((B & C) | ((~B) & D)) + w[5] + 0x5A827999; B = ((B << 30) | (B >>> 2)); D += ((E << 5) | (E >>> 27)) + ((A & B) | ((~A) & C)) + w[6] + 0x5A827999; A = ((A << 30) | (A >>> 2)); C += ((D << 5) | (D >>> 27)) + ((E & A) | ((~E) & B)) + w[7] + 0x5A827999; E = ((E << 30) | (E >>> 2)); B += ((C << 5) | (C >>> 27)) + ((D & E) | ((~D) & A)) + w[8] + 0x5A827999; D = ((D << 30) | (D >>> 2)); A += ((B << 5) | (B >>> 27)) + ((C & D) | ((~C) & E)) + w[9] + 0x5A827999; C = ((C << 30) | (C >>> 2)); E += ((A << 5) | (A >>> 27)) + ((B & C) | ((~B) & D)) + w[10] + 0x5A827999; B = ((B << 30) | (B >>> 2)); D += ((E << 5) | (E >>> 27)) + ((A & B) | ((~A) & C)) + w[11] + 0x5A827999; A = ((A << 30) | (A >>> 2)); C += ((D << 5) | (D >>> 27)) + ((E & A) | ((~E) & B)) + w[12] + 0x5A827999; E = ((E << 30) | (E >>> 2)); B += ((C << 5) | (C >>> 27)) + ((D & E) | ((~D) & A)) + w[13] + 0x5A827999; D = ((D << 30) | (D >>> 2)); A += ((B << 5) | (B >>> 27)) + ((C & D) | ((~C) & E)) + w[14] + 0x5A827999; C = ((C << 30) | (C >>> 2)); E += ((A << 5) | (A >>> 27)) + ((B & C) | ((~B) & D)) + w[15] + 0x5A827999; B = ((B << 30) | (B >>> 2)); D += ((E << 5) | (E >>> 27)) + ((A & B) | ((~A) & C)) + w[16] + 0x5A827999; A = ((A << 30) | (A >>> 2)); C += ((D << 5) | (D >>> 27)) + ((E & A) | ((~E) & B)) + w[17] + 0x5A827999; E = ((E << 30) | (E >>> 2)); B += ((C << 5) | (C >>> 27)) + ((D & E) | ((~D) & A)) + w[18] + 0x5A827999; D = ((D << 30) | (D >>> 2)); A += ((B << 5) | (B >>> 27)) + ((C & D) | ((~C) & E)) + w[19] + 0x5A827999; C = ((C << 30) | (C >>> 2)); E += ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + w[20] + 0x6ED9EBA1; B = ((B << 30) | (B >>> 2)); D += ((E << 5) | (E >>> 27)) + (A ^ B ^ C) + w[21] + 0x6ED9EBA1; A = ((A << 30) | (A >>> 2)); C += ((D << 5) | (D >>> 27)) + (E ^ A ^ B) + w[22] + 0x6ED9EBA1; E = ((E << 30) | (E >>> 2)); B += ((C << 5) | (C >>> 27)) + (D ^ E ^ A) + w[23] + 0x6ED9EBA1; D = ((D << 30) | (D >>> 2)); A += ((B << 5) | (B >>> 27)) + (C ^ D ^ E) + w[24] + 0x6ED9EBA1; C = ((C << 30) | (C >>> 2)); E += ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + w[25] + 0x6ED9EBA1; B = ((B << 30) | (B >>> 2)); D += ((E << 5) | (E >>> 27)) + (A ^ B ^ C) + w[26] + 0x6ED9EBA1; A = ((A << 30) | (A >>> 2)); C += ((D << 5) | (D >>> 27)) + (E ^ A ^ B) + w[27] + 0x6ED9EBA1; E = ((E << 30) | (E >>> 2)); B += ((C << 5) | (C >>> 27)) + (D ^ E ^ A) + w[28] + 0x6ED9EBA1; D = ((D << 30) | (D >>> 2)); A += ((B << 5) | (B >>> 27)) + (C ^ D ^ E) + w[29] + 0x6ED9EBA1; C = ((C << 30) | (C >>> 2)); E += ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + w[30] + 0x6ED9EBA1; B = ((B << 30) | (B >>> 2)); D += ((E << 5) | (E >>> 27)) + (A ^ B ^ C) + w[31] + 0x6ED9EBA1; A = ((A << 30) | (A >>> 2)); C += ((D << 5) | (D >>> 27)) + (E ^ A ^ B) + w[32] + 0x6ED9EBA1; E = ((E << 30) | (E >>> 2)); B += ((C << 5) | (C >>> 27)) + (D ^ E ^ A) + w[33] + 0x6ED9EBA1; D = ((D << 30) | (D >>> 2)); A += ((B << 5) | (B >>> 27)) + (C ^ D ^ E) + w[34] + 0x6ED9EBA1; C = ((C << 30) | (C >>> 2)); E += ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + w[35] + 0x6ED9EBA1; B = ((B << 30) | (B >>> 2)); D += ((E << 5) | (E >>> 27)) + (A ^ B ^ C) + w[36] + 0x6ED9EBA1; A = ((A << 30) | (A >>> 2)); C += ((D << 5) | (D >>> 27)) + (E ^ A ^ B) + w[37] + 0x6ED9EBA1; E = ((E << 30) | (E >>> 2)); B += ((C << 5) | (C >>> 27)) + (D ^ E ^ A) + w[38] + 0x6ED9EBA1; D = ((D << 30) | (D >>> 2)); A += ((B << 5) | (B >>> 27)) + (C ^ D ^ E) + w[39] + 0x6ED9EBA1; C = ((C << 30) | (C >>> 2)); E += ((A << 5) | (A >>> 27)) + ((B & C) | (B & D) | (C & D)) + w[40] + 0x8F1BBCDC; B = ((B << 30) | (B >>> 2)); D += ((E << 5) | (E >>> 27)) + ((A & B) | (A & C) | (B & C)) + w[41] + 0x8F1BBCDC; A = ((A << 30) | (A >>> 2)); C += ((D << 5) | (D >>> 27)) + ((E & A) | (E & B) | (A & B)) + w[42] + 0x8F1BBCDC; E = ((E << 30) | (E >>> 2)); B += ((C << 5) | (C >>> 27)) + ((D & E) | (D & A) | (E & A)) + w[43] + 0x8F1BBCDC; D = ((D << 30) | (D >>> 2)); A += ((B << 5) | (B >>> 27)) + ((C & D) | (C & E) | (D & E)) + w[44] + 0x8F1BBCDC; C = ((C << 30) | (C >>> 2)); E += ((A << 5) | (A >>> 27)) + ((B & C) | (B & D) | (C & D)) + w[45] + 0x8F1BBCDC; B = ((B << 30) | (B >>> 2)); D += ((E << 5) | (E >>> 27)) + ((A & B) | (A & C) | (B & C)) + w[46] + 0x8F1BBCDC; A = ((A << 30) | (A >>> 2)); C += ((D << 5) | (D >>> 27)) + ((E & A) | (E & B) | (A & B)) + w[47] + 0x8F1BBCDC; E = ((E << 30) | (E >>> 2)); B += ((C << 5) | (C >>> 27)) + ((D & E) | (D & A) | (E & A)) + w[48] + 0x8F1BBCDC; D = ((D << 30) | (D >>> 2)); A += ((B << 5) | (B >>> 27)) + ((C & D) | (C & E) | (D & E)) + w[49] + 0x8F1BBCDC; C = ((C << 30) | (C >>> 2)); E += ((A << 5) | (A >>> 27)) + ((B & C) | (B & D) | (C & D)) + w[50] + 0x8F1BBCDC; B = ((B << 30) | (B >>> 2)); D += ((E << 5) | (E >>> 27)) + ((A & B) | (A & C) | (B & C)) + w[51] + 0x8F1BBCDC; A = ((A << 30) | (A >>> 2)); C += ((D << 5) | (D >>> 27)) + ((E & A) | (E & B) | (A & B)) + w[52] + 0x8F1BBCDC; E = ((E << 30) | (E >>> 2)); B += ((C << 5) | (C >>> 27)) + ((D & E) | (D & A) | (E & A)) + w[53] + 0x8F1BBCDC; D = ((D << 30) | (D >>> 2)); A += ((B << 5) | (B >>> 27)) + ((C & D) | (C & E) | (D & E)) + w[54] + 0x8F1BBCDC; C = ((C << 30) | (C >>> 2)); E = E + ((A << 5) | (A >>> 27)) + ((B & C) | (B & D) | (C & D)) + w[55] + 0x8F1BBCDC; B = ((B << 30) | (B >>> 2)); D += ((E << 5) | (E >>> 27)) + ((A & B) | (A & C) | (B & C)) + w[56] + 0x8F1BBCDC; A = ((A << 30) | (A >>> 2)); C += ((D << 5) | (D >>> 27)) + ((E & A) | (E & B) | (A & B)) + w[57] + 0x8F1BBCDC; E = ((E << 30) | (E >>> 2)); B += ((C << 5) | (C >>> 27)) + ((D & E) | (D & A) | (E & A)) + w[58] + 0x8F1BBCDC; D = ((D << 30) | (D >>> 2)); A += ((B << 5) | (B >>> 27)) + ((C & D) | (C & E) | (D & E)) + w[59] + 0x8F1BBCDC; C = ((C << 30) | (C >>> 2)); E += ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + w[60] + 0xCA62C1D6; B = ((B << 30) | (B >>> 2)); D += ((E << 5) | (E >>> 27)) + (A ^ B ^ C) + w[61] + 0xCA62C1D6; A = ((A << 30) | (A >>> 2)); C += ((D << 5) | (D >>> 27)) + (E ^ A ^ B) + w[62] + 0xCA62C1D6; E = ((E << 30) | (E >>> 2)); B += ((C << 5) | (C >>> 27)) + (D ^ E ^ A) + w[63] + 0xCA62C1D6; D = ((D << 30) | (D >>> 2)); A += ((B << 5) | (B >>> 27)) + (C ^ D ^ E) + w[64] + 0xCA62C1D6; C = ((C << 30) | (C >>> 2)); E += ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + w[65] + 0xCA62C1D6; B = ((B << 30) | (B >>> 2)); D += ((E << 5) | (E >>> 27)) + (A ^ B ^ C) + w[66] + 0xCA62C1D6; A = ((A << 30) | (A >>> 2)); C += ((D << 5) | (D >>> 27)) + (E ^ A ^ B) + w[67] + 0xCA62C1D6; E = ((E << 30) | (E >>> 2)); B += ((C << 5) | (C >>> 27)) + (D ^ E ^ A) + w[68] + 0xCA62C1D6; D = ((D << 30) | (D >>> 2)); A += ((B << 5) | (B >>> 27)) + (C ^ D ^ E) + w[69] + 0xCA62C1D6; C = ((C << 30) | (C >>> 2)); E += ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + w[70] + 0xCA62C1D6; B = ((B << 30) | (B >>> 2)); D += ((E << 5) | (E >>> 27)) + (A ^ B ^ C) + w[71] + 0xCA62C1D6; A = ((A << 30) | (A >>> 2)); C += ((D << 5) | (D >>> 27)) + (E ^ A ^ B) + w[72] + 0xCA62C1D6; E = ((E << 30) | (E >>> 2)); B += ((C << 5) | (C >>> 27)) + (D ^ E ^ A) + w[73] + 0xCA62C1D6; D = ((D << 30) | (D >>> 2)); A += ((B << 5) | (B >>> 27)) + (C ^ D ^ E) + w[74] + 0xCA62C1D6; C = ((C << 30) | (C >>> 2)); E += ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + w[75] + 0xCA62C1D6; B = ((B << 30) | (B >>> 2)); D += ((E << 5) | (E >>> 27)) + (A ^ B ^ C) + w[76] + 0xCA62C1D6; A = ((A << 30) | (A >>> 2)); C += ((D << 5) | (D >>> 27)) + (E ^ A ^ B) + w[77] + 0xCA62C1D6; E = ((E << 30) | (E >>> 2)); B += ((C << 5) | (C >>> 27)) + (D ^ E ^ A) + w[78] + 0xCA62C1D6; D = ((D << 30) | (D >>> 2)); A += ((B << 5) | (B >>> 27)) + (C ^ D ^ E) + w[79] + 0xCA62C1D6; C = ((C << 30) | (C >>> 2)); H0 += A; H1 += B; H2 += C; H3 += D; H4 += E; // debug(80, H0, H1, H2, H3, H4); } private static final String toHexString(byte[] b) { final String hexChar = "0123456789ABCDEF"; StringBuffer sb = new StringBuffer(); for (int i = 0; i < b.length; i++) { sb.append(hexChar.charAt((b[i] >> 4) & 0x0f)); sb.append(hexChar.charAt(b[i] & 0x0f)); } return sb.toString(); } public static void main(String[] args) { SHA1 sha = new SHA1(); byte[] dig1 = new byte[20]; byte[] dig2 = new byte[20]; byte[] dig3 = new byte[20]; /* * We do not specify a charset name for getBytes(), since we assume that * the JVM's default encoder maps the _used_ ASCII characters exactly as * getBytes("US-ASCII") would do. (Ah, yes, too lazy to catch the * exception that can be thrown by getBytes("US-ASCII")). Note: This has * no effect on the SHA-1 implementation, this is just for the following * test code. */ sha.update("abc".getBytes()); sha.digest(dig1); sha.update("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".getBytes()); sha.digest(dig2); for (int i = 0; i < 1000000; i++) sha.update((byte) 'a'); sha.digest(dig3); String dig1_res = toHexString(dig1); String dig2_res = toHexString(dig2); String dig3_res = toHexString(dig3); String dig1_ref = "A9993E364706816ABA3E25717850C26C9CD0D89D"; String dig2_ref = "84983E441C3BD26EBAAE4AA1F95129E5E54670F1"; String dig3_ref = "34AA973CD4C4DAA4F61EEB2BDBAD27316534016F"; if (dig1_res.equals(dig1_ref)) System.out.println("SHA-1 Test 1 OK."); else System.out.println("SHA-1 Test 1 FAILED."); if (dig2_res.equals(dig2_ref)) System.out.println("SHA-1 Test 2 OK."); else System.out.println("SHA-1 Test 2 FAILED."); if (dig3_res.equals(dig3_ref)) System.out.println("SHA-1 Test 3 OK."); else System.out.println("SHA-1 Test 3 FAILED."); if (dig3_res.equals(dig3_ref)) System.out.println("SHA-1 Test 3 OK."); else System.out.println("SHA-1 Test 3 FAILED."); } }
/* * 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.netbeans.performance.web.actions; import junit.framework.Test; import org.netbeans.jellytools.ProjectsTabOperator; import org.netbeans.jellytools.actions.MaximizeWindowAction; import org.netbeans.jellytools.nodes.Node; import org.netbeans.jemmy.operators.ComponentOperator; import org.netbeans.modules.performance.guitracker.LoggingRepaintManager; import org.netbeans.modules.performance.utilities.PerformanceTestCase; import org.netbeans.performance.web.setup.WebSetup; /** * Test of expanding nodes/folders in the Explorer. * * @author mmirilovic@netbeans.org */ public class ExpandNodesWebProjectsViewTest extends PerformanceTestCase { /** * Name of the folder which test creates and expands */ private static String project; /** * Path to the folder which test creates and expands */ private static String pathToFolderNode; /** * Node representation of the folder which test creates and expands */ private static Node nodeToBeExpanded; /** * Projects tab */ private static ProjectsTabOperator projectTab; /** * Project with data for these tests */ private static String testDataProject = "PerformanceTestFolderWebApp"; /** * Creates a new instance of ExpandNodesInExplorer * * @param testName the name of the test */ public ExpandNodesWebProjectsViewTest(String testName) { super(testName); expectedTime = WINDOW_OPEN; } /** * Creates a new instance of ExpandNodesInExplorer * * @param testName the name of the test * @param performanceDataName measured values will be saved under this name */ public ExpandNodesWebProjectsViewTest(String testName, String performanceDataName) { super(testName, performanceDataName); expectedTime = WINDOW_OPEN; } public static Test suite() { return emptyConfiguration() .addTest(WebSetup.class) .addTest(ExpandNodesWebProjectsViewTest.class) .suite(); } public void testExpandProjectNode() { pathToFolderNode = ""; project = testDataProject; WAIT_AFTER_OPEN = 1000; doMeasurement(); } public void testExpandSourcePackagesNode() { pathToFolderNode = "Source Packages"; project = testDataProject; WAIT_AFTER_OPEN = 1000; doMeasurement(); } public void testExpandFolderWith50JspFiles() { pathToFolderNode = "Web Pages|jsp50"; project = testDataProject; WAIT_AFTER_OPEN = 1000; doMeasurement(); } public void testExpandFolderWith100JspFiles() { pathToFolderNode = "Web Pages|jsp100"; project = testDataProject; WAIT_AFTER_OPEN = 1000; doMeasurement(); } public void testExpandFolderWith1000JspFiles() { pathToFolderNode = "Web Pages|jsp1000"; project = testDataProject; WAIT_AFTER_OPEN = 1000; doMeasurement(); } @Override public void initialize() { projectTab = new ProjectsTabOperator(); new MaximizeWindowAction().performAPI(projectTab); projectTab.getProjectRootNode("TestWebProject").collapse(); projectTab.getProjectRootNode(testDataProject).collapse(); System.setProperty("perf.dont.resolve.java.badges", "true"); repaintManager().addRegionFilter(LoggingRepaintManager.EXPLORER_FILTER); } @Override public void prepare() { if (pathToFolderNode.equals("")) { nodeToBeExpanded = projectTab.getProjectRootNode(project); } else { nodeToBeExpanded = new Node(projectTab.getProjectRootNode(project), pathToFolderNode); } nodeToBeExpanded.collapse(); } @Override public ComponentOperator open() { nodeToBeExpanded.tree().doExpandPath(nodeToBeExpanded.getTreePath()); nodeToBeExpanded.expand(); return null; } @Override public void close() { nodeToBeExpanded.collapse(); } @Override public void shutdown() { repaintManager().resetRegionFilters(); System.setProperty("perf.dont.resolve.java.badges", "false"); projectTab.getProjectRootNode(project).collapse(); projectTab.close(); ProjectsTabOperator.invoke(); } }
/* * Copyright (c) 2008-2016, 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.partition; import com.hazelcast.core.Partition; import com.hazelcast.core.PartitionService; import com.hazelcast.internal.partition.InternalPartition; import com.hazelcast.nio.Address; import com.hazelcast.nio.ObjectDataInput; import com.hazelcast.nio.ObjectDataOutput; import com.hazelcast.nio.serialization.DataSerializable; import java.io.IOException; /** * The event that is fired when a partition lost its owner and all backups. * * @see Partition * @see PartitionService * @see PartitionLostListener */ public class PartitionLostEvent implements DataSerializable, PartitionEvent { private int partitionId; private int lostBackupCount; private Address eventSource; public PartitionLostEvent() { } public PartitionLostEvent(int partitionId, int lostBackupCount, Address eventSource) { this.partitionId = partitionId; this.lostBackupCount = lostBackupCount; this.eventSource = eventSource; } /** * Returns the lost partition id. * * @return the lost partition id. */ @Override public int getPartitionId() { return partitionId; } /** * Returns the number of lost backups for the partition. O: the owner, 1: first backup, 2: second backup ... * If all replicas of a partition is lost, {@link InternalPartition#MAX_BACKUP_COUNT} is returned. * * @return the number of lost backups for the partition. * If all replicas of a partition is lost, {@link InternalPartition#MAX_BACKUP_COUNT} is returned. */ public int getLostBackupCount() { return lostBackupCount; } /** * Returns the address of the node that dispatches the event * * @return the address of the node that dispatches the event */ public Address getEventSource() { return eventSource; } @Override public void writeData(ObjectDataOutput out) throws IOException { out.writeInt(partitionId); out.writeInt(lostBackupCount); out.writeObject(eventSource); } @Override public void readData(ObjectDataInput in) throws IOException { partitionId = in.readInt(); lostBackupCount = in.readInt(); eventSource = in.readObject(); } @Override public String toString() { return getClass().getName() + "{partitionId=" + partitionId + ", lostBackupCount=" + lostBackupCount + ", eventSource=" + eventSource + '}'; } }
/* * 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.kinesisvideo.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * The range of timestamps for which to return fragments. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/kinesis-video-archived-media-2017-09-30/TimestampRange" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class TimestampRange implements Serializable, Cloneable, StructuredPojo { /** * <p> * The starting timestamp in the range of timestamps for which to return fragments. * </p> */ private java.util.Date startTimestamp; /** * <p> * The ending timestamp in the range of timestamps for which to return fragments. * </p> */ private java.util.Date endTimestamp; /** * <p> * The starting timestamp in the range of timestamps for which to return fragments. * </p> * * @param startTimestamp * The starting timestamp in the range of timestamps for which to return fragments. */ public void setStartTimestamp(java.util.Date startTimestamp) { this.startTimestamp = startTimestamp; } /** * <p> * The starting timestamp in the range of timestamps for which to return fragments. * </p> * * @return The starting timestamp in the range of timestamps for which to return fragments. */ public java.util.Date getStartTimestamp() { return this.startTimestamp; } /** * <p> * The starting timestamp in the range of timestamps for which to return fragments. * </p> * * @param startTimestamp * The starting timestamp in the range of timestamps for which to return fragments. * @return Returns a reference to this object so that method calls can be chained together. */ public TimestampRange withStartTimestamp(java.util.Date startTimestamp) { setStartTimestamp(startTimestamp); return this; } /** * <p> * The ending timestamp in the range of timestamps for which to return fragments. * </p> * * @param endTimestamp * The ending timestamp in the range of timestamps for which to return fragments. */ public void setEndTimestamp(java.util.Date endTimestamp) { this.endTimestamp = endTimestamp; } /** * <p> * The ending timestamp in the range of timestamps for which to return fragments. * </p> * * @return The ending timestamp in the range of timestamps for which to return fragments. */ public java.util.Date getEndTimestamp() { return this.endTimestamp; } /** * <p> * The ending timestamp in the range of timestamps for which to return fragments. * </p> * * @param endTimestamp * The ending timestamp in the range of timestamps for which to return fragments. * @return Returns a reference to this object so that method calls can be chained together. */ public TimestampRange withEndTimestamp(java.util.Date endTimestamp) { setEndTimestamp(endTimestamp); 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 (getStartTimestamp() != null) sb.append("StartTimestamp: ").append(getStartTimestamp()).append(","); if (getEndTimestamp() != null) sb.append("EndTimestamp: ").append(getEndTimestamp()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof TimestampRange == false) return false; TimestampRange other = (TimestampRange) obj; if (other.getStartTimestamp() == null ^ this.getStartTimestamp() == null) return false; if (other.getStartTimestamp() != null && other.getStartTimestamp().equals(this.getStartTimestamp()) == false) return false; if (other.getEndTimestamp() == null ^ this.getEndTimestamp() == null) return false; if (other.getEndTimestamp() != null && other.getEndTimestamp().equals(this.getEndTimestamp()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getStartTimestamp() == null) ? 0 : getStartTimestamp().hashCode()); hashCode = prime * hashCode + ((getEndTimestamp() == null) ? 0 : getEndTimestamp().hashCode()); return hashCode; } @Override public TimestampRange clone() { try { return (TimestampRange) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.kinesisvideo.model.transform.TimestampRangeMarshaller.getInstance().marshall(this, protocolMarshaller); } }
package pl.edu.agh.marims.lib.convert; import android.graphics.Bitmap; import android.util.Base64; import java.io.ByteArrayOutputStream; public class BitmapToBase64Converter extends BitmapConverter<String> { private static final float MAX_DIMENSION = 700.0f; @Override public String convert(Bitmap bitmap) { if (bitmap != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); float scale; if (bitmap.getWidth() < bitmap.getHeight()) { scale = MAX_DIMENSION / (float) bitmap.getHeight(); } else { scale = MAX_DIMENSION / (float) bitmap.getWidth(); } int quality = 50; Bitmap.createScaledBitmap(bitmap, (int) (bitmap.getWidth() * scale), (int) (bitmap.getHeight() * scale), false).compress(Bitmap.CompressFormat.JPEG, quality, baos); byte[] byteBuffer = baos.toByteArray(); return Base64.encodeToString(byteBuffer, Base64.NO_WRAP); } else { return null; } } }
package com.or.lang.core.stub.type; import com.intellij.lang.ASTNode; import com.intellij.psi.stubs.IndexSink; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.stubs.StubInputStream; import com.intellij.psi.stubs.StubOutputStream; import com.intellij.util.io.StringRef; import com.or.ide.search.index.IndexKeys; import com.or.lang.core.psi.PsiException; import com.or.lang.core.psi.impl.PsiExceptionImpl; import com.or.lang.core.stub.PsiExceptionStub; import org.jetbrains.annotations.NotNull; import java.io.IOException; public class PsiExceptionStubElementType extends ORStubElementType<PsiExceptionStub, PsiException> { public static final int VERSION = 7; public PsiExceptionStubElementType() { super("C_EXCEPTION_DECLARATION"); } @NotNull public PsiException createPsi(@NotNull PsiExceptionStub stub) { return new PsiExceptionImpl(stub, this); } @NotNull public PsiException createPsi(@NotNull ASTNode node) { return new PsiExceptionImpl(node); } @NotNull public PsiExceptionStub createStub(@NotNull PsiException psi, StubElement parentStub) { String[] path = psi.getPath(); return new PsiExceptionStub(parentStub, this, psi.getName(), path == null ? EMPTY_PATH : path, psi.getAlias()); } public void serialize(@NotNull PsiExceptionStub stub, @NotNull StubOutputStream dataStream) throws IOException { dataStream.writeName(stub.getName()); SerializerUtil.writePath(dataStream, stub.getPath()); dataStream.writeName(stub.getAlias()); } @NotNull public PsiExceptionStub deserialize(@NotNull StubInputStream dataStream, StubElement parentStub) throws IOException { StringRef name = dataStream.readName(); String[] path = SerializerUtil.readPath(dataStream); StringRef alias = dataStream.readName(); return new PsiExceptionStub(parentStub, this, name, path, alias == null ? null : alias.getString()); } public void indexStub(@NotNull PsiExceptionStub stub, @NotNull IndexSink sink) { String name = stub.getName(); if (name != null) { sink.occurrence(IndexKeys.EXCEPTIONS, name); } String fqn = stub.getQualifiedName(); sink.occurrence(IndexKeys.EXCEPTIONS_FQN, fqn.hashCode()); } @NotNull public String getExternalId() { return getLanguage().getID() + "." + super.toString(); } }
package com.mojang.mario.level; import com.mojang.mario.LevelScene; import com.mojang.mario.sprites.*; public class SpriteTemplate { public int lastVisibleTick = -1; public Sprite sprite; public boolean isDead = false; private boolean winged; private int type; public SpriteTemplate(int type, boolean winged) { this.type = type; this.winged = winged; } public void spawn(LevelScene world, int x, int y, int dir) { if (isDead) return; if (type==Enemy.ENEMY_FLOWER) { sprite = new FlowerEnemy(world, x*16+15, y*16+24); } else { sprite = new Enemy(world, x*16+8, y*16+15, dir, type, winged); } sprite.spriteTemplate = this; world.addSprite(sprite); } }
/* * Copyright 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.actionbarcompat; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.app.Activity; import android.content.Context; import android.content.res.XmlResourceParser; import android.os.Bundle; import android.view.InflateException; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import java.io.IOException; import java.util.HashSet; import java.util.Set; /** * A class that implements the action bar pattern for pre-Honeycomb devices. */ public class ActionBarHelperBase extends ActionBarHelper { private static final String MENU_RES_NAMESPACE = "http://schemas.android.com/apk/res/android"; private static final String MENU_ATTR_ID = "id"; private static final String MENU_ATTR_SHOW_AS_ACTION = "showAsAction"; protected Set<Integer> mActionItemIds = new HashSet<Integer>(); protected ActionBarHelperBase(Activity activity) { super(activity); } /**{@inheritDoc}*/ @Override public void onCreate(Bundle savedInstanceState) { mActivity.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); } /**{@inheritDoc}*/ @Override public void onPostCreate(Bundle savedInstanceState) { mActivity.getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.actionbar_compat); setupActionBar(); SimpleMenu menu = new SimpleMenu(mActivity); mActivity.onCreatePanelMenu(Window.FEATURE_OPTIONS_PANEL, menu); mActivity.onPrepareOptionsMenu(menu); for (int i = 0; i < menu.size(); i++) { MenuItem item = menu.getItem(i); if (mActionItemIds.contains(item.getItemId())) { addActionItemCompatFromMenuItem(item); } } } /** * Sets up the compatibility action bar with the given title. */ private void setupActionBar() { final ViewGroup actionBarCompat = getActionBarCompat(); if (actionBarCompat == null) { return; } LinearLayout.LayoutParams springLayoutParams = new LinearLayout.LayoutParams( 0, ViewGroup.LayoutParams.FILL_PARENT); springLayoutParams.weight = 1; // Add Home button SimpleMenu tempMenu = new SimpleMenu(mActivity); SimpleMenuItem homeItem = new SimpleMenuItem( tempMenu, android.R.id.home, 0, mActivity.getString(R.string.app_name)); homeItem.setIcon(R.drawable.ic_home); addActionItemCompatFromMenuItem(homeItem); // Add title text TextView titleText = new TextView(mActivity, null, R.attr.actionbarCompatTitleStyle); titleText.setLayoutParams(springLayoutParams); titleText.setText(mActivity.getTitle()); actionBarCompat.addView(titleText); } /**{@inheritDoc}*/ @Override public void setRefreshActionItemState(boolean refreshing) { View refreshButton = mActivity.findViewById(R.id.actionbar_compat_item_refresh); View refreshIndicator = mActivity.findViewById( R.id.actionbar_compat_item_refresh_progress); if (refreshButton != null) { refreshButton.setVisibility(refreshing ? View.GONE : View.VISIBLE); } if (refreshIndicator != null) { refreshIndicator.setVisibility(refreshing ? View.VISIBLE : View.GONE); } } /** * Action bar helper code to be run in {@link Activity#onCreateOptionsMenu(android.view.Menu)}. * * NOTE: This code will mark on-screen menu items as invisible. */ @Override public boolean onCreateOptionsMenu(Menu menu) { // Hides on-screen action items from the options menu. for (Integer id : mActionItemIds) { menu.findItem(id).setVisible(false); } return true; } /**{@inheritDoc}*/ @Override protected void onTitleChanged(CharSequence title, int color) { TextView titleView = (TextView) mActivity.findViewById(R.id.actionbar_compat_title); if (titleView != null) { titleView.setText(title); } } /** * Returns a {@link android.view.MenuInflater} that can read action bar metadata on * pre-Honeycomb devices. */ public MenuInflater getMenuInflater(MenuInflater superMenuInflater) { return new WrappedMenuInflater(mActivity, superMenuInflater); } /** * Returns the {@link android.view.ViewGroup} for the action bar on phones (compatibility action * bar). Can return null, and will return null on Honeycomb. */ private ViewGroup getActionBarCompat() { return (ViewGroup) mActivity.findViewById(R.id.actionbar_compat); } /** * Adds an action button to the compatibility action bar, using menu information from a {@link * android.view.MenuItem}. If the menu item ID is <code>menu_refresh</code>, the menu item's * state can be changed to show a loading spinner using * {@link com.example.android.actionbarcompat.ActionBarHelperBase#setRefreshActionItemState(boolean)}. */ private View addActionItemCompatFromMenuItem(final MenuItem item) { final int itemId = item.getItemId(); final ViewGroup actionBar = getActionBarCompat(); if (actionBar == null) { return null; } // Create the button ImageButton actionButton = new ImageButton(mActivity, null, itemId == android.R.id.home ? R.attr.actionbarCompatItemHomeStyle : R.attr.actionbarCompatItemStyle); actionButton.setLayoutParams(new ViewGroup.LayoutParams( (int) mActivity.getResources().getDimension( itemId == android.R.id.home ? R.dimen.actionbar_compat_button_home_width : R.dimen.actionbar_compat_button_width), ViewGroup.LayoutParams.FILL_PARENT)); if (itemId == R.id.menu_refresh) { actionButton.setId(R.id.actionbar_compat_item_refresh); } actionButton.setImageDrawable(item.getIcon()); actionButton.setScaleType(ImageView.ScaleType.CENTER); actionButton.setContentDescription(item.getTitle()); actionButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mActivity.onMenuItemSelected(Window.FEATURE_OPTIONS_PANEL, item); } }); actionBar.addView(actionButton); if (item.getItemId() == R.id.menu_refresh) { // Refresh buttons should be stateful, and allow for indeterminate progress indicators, // so add those. ProgressBar indicator = new ProgressBar(mActivity, null, R.attr.actionbarCompatProgressIndicatorStyle); final int buttonWidth = mActivity.getResources().getDimensionPixelSize( R.dimen.actionbar_compat_button_width); final int buttonHeight = mActivity.getResources().getDimensionPixelSize( R.dimen.actionbar_compat_height); final int progressIndicatorWidth = buttonWidth / 2; LinearLayout.LayoutParams indicatorLayoutParams = new LinearLayout.LayoutParams( progressIndicatorWidth, progressIndicatorWidth); indicatorLayoutParams.setMargins( (buttonWidth - progressIndicatorWidth) / 2, (buttonHeight - progressIndicatorWidth) / 2, (buttonWidth - progressIndicatorWidth) / 2, 0); indicator.setLayoutParams(indicatorLayoutParams); indicator.setVisibility(View.GONE); indicator.setId(R.id.actionbar_compat_item_refresh_progress); actionBar.addView(indicator); } return actionButton; } /** * A {@link android.view.MenuInflater} that reads action bar metadata. */ private class WrappedMenuInflater extends MenuInflater { MenuInflater mInflater; public WrappedMenuInflater(Context context, MenuInflater inflater) { super(context); mInflater = inflater; } @Override public void inflate(int menuRes, Menu menu) { loadActionBarMetadata(menuRes); mInflater.inflate(menuRes, menu); } /** * Loads action bar metadata from a menu resource, storing a list of menu item IDs that * should be shown on-screen (i.e. those with showAsAction set to always or ifRoom). * @param menuResId */ private void loadActionBarMetadata(int menuResId) { XmlResourceParser parser = null; try { parser = mActivity.getResources().getXml(menuResId); int eventType = parser.getEventType(); int itemId; int showAsAction; boolean eof = false; while (!eof) { switch (eventType) { case XmlPullParser.START_TAG: if (!parser.getName().equals("item")) { break; } itemId = parser.getAttributeResourceValue(MENU_RES_NAMESPACE, MENU_ATTR_ID, 0); if (itemId == 0) { break; } showAsAction = parser.getAttributeIntValue(MENU_RES_NAMESPACE, MENU_ATTR_SHOW_AS_ACTION, -1); if (showAsAction == MenuItem.SHOW_AS_ACTION_ALWAYS || showAsAction == MenuItem.SHOW_AS_ACTION_IF_ROOM) { mActionItemIds.add(itemId); } break; case XmlPullParser.END_DOCUMENT: eof = true; break; } eventType = parser.next(); } } catch (XmlPullParserException e) { throw new InflateException("Error inflating menu XML", e); } catch (IOException e) { throw new InflateException("Error inflating menu XML", e); } finally { if (parser != null) { parser.close(); } } } } }
package Section_5; import Section_4.DoublyLinkedList; import Section_2.LinkedList; import Section_3.BinarySearchTree; import Section_3.RedBlackTree; import Section_2.BinaryTree; public class AdjacencyListGraphWithSparseVertex<V,E> implements Graph<V,E> { boolean undirected; public AdjacencyListGraphWithSparseVertex(boolean undirected) { this.undirected = undirected; } class Edge implements Comparable<Edge>{ E value; int target; DoublyLinkedList.DoublyLinkedNode<Integer> targetNode; public Edge(int target) { this.target = target; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Edge edge = (Edge) o; return target == edge.target; } @Override public int hashCode() { return target; } @Override public int compareTo(Edge o) { return target - o.target; } } class Vertex extends GraphVertex<V>{ RedBlackTree<Edge> edges=new RedBlackTree<>(); DoublyLinkedList<Integer> neighbors=new DoublyLinkedList<>(); public Vertex(int id, V value) { super(id, value); } } Object[] vertices = new Object[0]; @Override public int addVertex() { Object[] newVertices = new Object[vertices.length+1]; System.arraycopy(vertices, 0, newVertices, 0, vertices.length); newVertices[vertices.length] = new Vertex(vertices.length, null); vertices=newVertices; return newVertices.length-1; } @Override public void removeVertex(int id) { Vertex sVertex = (Vertex) vertices[id]; if(sVertex==null){ throw new IllegalArgumentException("Vertex "+ id +" does not exist"); } DoublyLinkedList<Integer> neighbors = getNeighbors(id); Edge dummyEdgeForId = new Edge(id); for(int t:neighbors){ Edge e = ((Vertex)vertices[t]).edges.deleteValue(dummyEdgeForId).getValue(); ((Vertex)vertices[t]).neighbors.removeNode(e.targetNode); } vertices[id] = null; } @Override public void addEdge(int source, int target) { Vertex sVertex = (Vertex) vertices[source]; Edge sEdge = sVertex.edges.insertValue(new Edge(target)).getValue(); sEdge.targetNode = (DoublyLinkedList.DoublyLinkedNode<Integer>) sVertex.neighbors.appendLast(sEdge.target); if(undirected){ Vertex tVertex = (Vertex) vertices[target]; Edge tEdge = tVertex.edges.insertValue(new Edge(source)).getValue(); tEdge.targetNode = (DoublyLinkedList.DoublyLinkedNode<Integer>) tVertex.neighbors.appendLast(tEdge.target); } } @Override public void removeEdge(int source, int target) { Vertex sVertex = (Vertex) vertices[source]; Edge deletedEdge = sVertex.edges.deleteValue(new Edge(target)).getValue(); sVertex.neighbors.removeNode(deletedEdge.targetNode); if(undirected){ Vertex tVertex = (Vertex) vertices[target]; deletedEdge = tVertex.edges.deleteValue(new Edge(source)).getValue(); tVertex.neighbors.removeNode(deletedEdge.targetNode); } } @Override public boolean isAdjacent(int source, int target) { Vertex sVertex = (Vertex) vertices[source]; return sVertex.edges.searchValue(new Edge(target))!=null; } @Override public DoublyLinkedList<Integer> getNeighbors(int source) { Vertex sVertex = (Vertex) vertices[source]; return sVertex.neighbors; } @Override public void setVertexValue(int vertex, V value) { Vertex sVertex = (Vertex) vertices[vertex]; if(sVertex==null){ throw new IllegalArgumentException("Vertex "+ vertex + "does not exist"); }else{ sVertex.setValue(value); } } @Override public V getVertexValue(int vertex) { Vertex sVertex = (Vertex) vertices[vertex]; if(sVertex==null){ throw new IllegalArgumentException("Vertex "+ vertex + "does not exist"); }else{ return sVertex.getValue(); } } @Override public void setEdgeValue(int source, int target, E value) { Vertex sVertex = (Vertex) vertices[source]; Vertex tVertex = (Vertex) vertices[target]; if(sVertex==null){ throw new IllegalArgumentException("Vertex "+ source + "does not exist"); }else if(tVertex==null){ throw new IllegalArgumentException("Vertex "+ target + "does not exist"); }else{ BinaryTree.Node<Edge> node = sVertex.edges.searchValue(new Edge(target)); if(node==null){ throw new IllegalArgumentException("Edge between "+ source + "and" + target + "does not exist"); }else{ node.getValue().value = value; } } } @Override public E getEdgeValue(int source, int target) { Vertex sVertex = (Vertex) vertices[source]; Vertex tVertex = (Vertex) vertices[target]; if(sVertex==null){ throw new IllegalArgumentException("Vertex "+ source + "does not exist"); }else if(tVertex==null){ throw new IllegalArgumentException("Vertex "+ target + "does not exist"); }else{ BinaryTree.Node<Edge> node = sVertex.edges.searchValue(new Edge(target)); if(node==null){ throw new IllegalArgumentException("Edge between "+ source + "and" + target + "does not exist"); }else{ return node.getValue().value; } } } @Override public boolean isUndirected() { return undirected; } @Override public BinarySearchTree<Integer> getAllVertices() { BinarySearchTree<Integer> allVertices = new RedBlackTree<>(); for(int i=0;i<vertices.length;i++){ if(vertices[i]!=null){ allVertices.insertValue(i); } } return allVertices; } @Override public int maxVertexID() { return vertices.length-1; } public static void main(String [] args){ AdjacencyListGraphWithSparseVertex<Character, Integer> graph = new AdjacencyListGraphWithSparseVertex<>(true); for(int i=0;i<10;i++){ graph.addVertex(); } graph.addEdge(0,1); graph.addEdge(1,2); graph.addEdge(1,3); graph.addEdge(2,3); graph.addEdge(2,4); graph.addEdge(3,4); System.out.println(graph.isAdjacent(2,1)); System.out.println(graph.isAdjacent(2,5)); graph.getNeighbors(1).forEach(System.out::println); graph.removeVertex(1); System.out.println(graph.isAdjacent(3,2)); System.out.println(graph.isAdjacent(2,5)); graph.getNeighbors(2).forEach(System.out::println); graph.removeVertex(3); graph.getNeighbors(2).forEach(System.out::println); } }
// // ======================================================================== // Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others. // // This program and the accompanying materials are made available under // the terms of the Eclipse Public License 2.0 which is available at // https://www.eclipse.org/legal/epl-2.0 // // This Source Code may also be made available under the following // Secondary Licenses when the conditions for such availability set // forth in the Eclipse Public License, v. 2.0 are satisfied: // the Apache License v2.0 which is available at // https://www.apache.org/licenses/LICENSE-2.0 // // SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 // ======================================================================== // package org.eclipse.jetty.http.pathmap; import java.io.IOException; import java.util.ArrayList; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.TreeSet; import java.util.function.Predicate; import org.eclipse.jetty.util.ArrayTernaryTrie; import org.eclipse.jetty.util.Trie; import org.eclipse.jetty.util.annotation.ManagedAttribute; import org.eclipse.jetty.util.annotation.ManagedObject; import org.eclipse.jetty.util.component.Dumpable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Path Mappings of PathSpec to Resource. * <p> * Sorted into search order upon entry into the Set * * @param <E> the type of mapping endpoint */ @ManagedObject("Path Mappings") public class PathMappings<E> implements Iterable<MappedResource<E>>, Dumpable { private static final Logger LOG = LoggerFactory.getLogger(PathMappings.class); private final Set<MappedResource<E>> _mappings = new TreeSet<>(Comparator.comparing(MappedResource::getPathSpec)); private Trie<MappedResource<E>> _exactMap = new ArrayTernaryTrie<>(false); private Trie<MappedResource<E>> _prefixMap = new ArrayTernaryTrie<>(false); private Trie<MappedResource<E>> _suffixMap = new ArrayTernaryTrie<>(false); @Override public String dump() { return Dumpable.dump(this); } @Override public void dump(Appendable out, String indent) throws IOException { Dumpable.dumpObjects(out, indent, toString(), _mappings); } @ManagedAttribute(value = "mappings", readonly = true) public List<MappedResource<E>> getMappings() { return new ArrayList<>(_mappings); } public int size() { return _mappings.size(); } public void reset() { _mappings.clear(); _prefixMap.clear(); _suffixMap.clear(); } public void removeIf(Predicate<MappedResource<E>> predicate) { _mappings.removeIf(predicate); } /** * Return a list of MappedResource matches for the specified path. * * @param path the path to return matches on * @return the list of mapped resource the path matches on */ public List<MappedResource<E>> getMatches(String path) { boolean isRootPath = "/".equals(path); List<MappedResource<E>> ret = new ArrayList<>(); for (MappedResource<E> mr : _mappings) { switch (mr.getPathSpec().getGroup()) { case ROOT: if (isRootPath) ret.add(mr); break; case DEFAULT: if (isRootPath || mr.getPathSpec().matches(path)) ret.add(mr); break; default: if (mr.getPathSpec().matches(path)) ret.add(mr); break; } } return ret; } public MappedResource<E> getMatch(String path) { PathSpecGroup lastGroup = null; // Search all the mappings for (MappedResource<E> mr : _mappings) { PathSpecGroup group = mr.getPathSpec().getGroup(); if (group != lastGroup) { // New group in list, so let's look for an optimization switch (group) { case EXACT: { int i = path.length(); final Trie<MappedResource<E>> exact_map = _exactMap; while (i >= 0) { MappedResource<E> candidate = exact_map.getBest(path, 0, i); if (candidate == null) break; if (candidate.getPathSpec().matches(path)) return candidate; i = candidate.getPathSpec().getPrefix().length() - 1; } break; } case PREFIX_GLOB: { int i = path.length(); final Trie<MappedResource<E>> prefix_map = _prefixMap; while (i >= 0) { MappedResource<E> candidate = prefix_map.getBest(path, 0, i); if (candidate == null) break; if (candidate.getPathSpec().matches(path)) return candidate; i = candidate.getPathSpec().getPrefix().length() - 1; } break; } case SUFFIX_GLOB: { int i = 0; final Trie<MappedResource<E>> suffix_map = _suffixMap; while ((i = path.indexOf('.', i + 1)) > 0) { MappedResource<E> candidate = suffix_map.get(path, i + 1, path.length() - i - 1); if (candidate != null && candidate.getPathSpec().matches(path)) return candidate; } break; } default: } } if (mr.getPathSpec().matches(path)) return mr; lastGroup = group; } return null; } @Override public Iterator<MappedResource<E>> iterator() { return _mappings.iterator(); } public static PathSpec asPathSpec(String pathSpecString) { if ((pathSpecString == null) || (pathSpecString.length() < 1)) { throw new RuntimeException("Path Spec String must start with '^', '/', or '*.': got [" + pathSpecString + "]"); } return pathSpecString.charAt(0) == '^' ? new RegexPathSpec(pathSpecString) : new ServletPathSpec(pathSpecString); } public E get(PathSpec spec) { Optional<E> optionalResource = _mappings.stream() .filter(mappedResource -> mappedResource.getPathSpec().equals(spec)) .map(mappedResource -> mappedResource.getResource()) .findFirst(); if (!optionalResource.isPresent()) return null; return optionalResource.get(); } public boolean put(String pathSpecString, E resource) { return put(asPathSpec(pathSpecString), resource); } public boolean put(PathSpec pathSpec, E resource) { MappedResource<E> entry = new MappedResource<>(pathSpec, resource); switch (pathSpec.getGroup()) { case EXACT: String exact = pathSpec.getPrefix(); while (exact != null && !_exactMap.put(exact, entry)) { _exactMap = new ArrayTernaryTrie<>((ArrayTernaryTrie<MappedResource<E>>)_exactMap, 1.5); } break; case PREFIX_GLOB: String prefix = pathSpec.getPrefix(); while (prefix != null && !_prefixMap.put(prefix, entry)) { _prefixMap = new ArrayTernaryTrie<>((ArrayTernaryTrie<MappedResource<E>>)_prefixMap, 1.5); } break; case SUFFIX_GLOB: String suffix = pathSpec.getSuffix(); while (suffix != null && !_suffixMap.put(suffix, entry)) { _suffixMap = new ArrayTernaryTrie<>((ArrayTernaryTrie<MappedResource<E>>)_prefixMap, 1.5); } break; default: } boolean added = _mappings.add(entry); if (LOG.isDebugEnabled()) LOG.debug("{} {} to {}", added ? "Added" : "Ignored", entry, this); return added; } @SuppressWarnings("incomplete-switch") public boolean remove(PathSpec pathSpec) { String prefix = pathSpec.getPrefix(); String suffix = pathSpec.getSuffix(); switch (pathSpec.getGroup()) { case EXACT: if (prefix != null) _exactMap.remove(prefix); break; case PREFIX_GLOB: if (prefix != null) _prefixMap.remove(prefix); break; case SUFFIX_GLOB: if (suffix != null) _suffixMap.remove(suffix); break; default: break; } Iterator<MappedResource<E>> iter = _mappings.iterator(); boolean removed = false; while (iter.hasNext()) { if (iter.next().getPathSpec().equals(pathSpec)) { removed = true; iter.remove(); break; } } if (LOG.isDebugEnabled()) LOG.debug("{} {} to {}", removed ? "Removed" : "Ignored", pathSpec, this); return removed; } @Override public String toString() { return String.format("%s[size=%d]", this.getClass().getSimpleName(), _mappings.size()); } }
package hudson.slaves; import hudson.DescriptorExtensionList; import hudson.model.Descriptor; import jenkins.model.Jenkins; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.util.ArrayList; import static org.junit.Assert.*; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doReturn; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.when; /** * @author peppelan */ @RunWith(PowerMockRunner.class) @PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*"}) public class DelegatingComputerLauncherTest { public static class DummyOne extends DelegatingComputerLauncher { public DummyOne() { super(null); } public static class DummyOneDescriptor extends DescriptorImpl { } } public static class DummyTwo extends DelegatingComputerLauncher { public DummyTwo() { super(null); } public static class DummyTwoDescriptor extends DescriptorImpl { } } // Ensure that by default a DelegatingComputerLauncher subclass doesn't advertise the option to delegate another // DelegatingComputerLauncher @Test @PrepareForTest(Jenkins.class) public void testRecursionAvoidance() { PowerMockito.mockStatic(Jenkins.class); Jenkins mockJenkins = mock(Jenkins.class); PowerMockito.when(Jenkins.getInstance()).thenReturn(mockJenkins); DescriptorExtensionList<ComputerLauncher, Descriptor<ComputerLauncher>> mockList = mock(DescriptorExtensionList.class); doReturn(mockList).when(mockJenkins).getDescriptorList(eq(ComputerLauncher.class)); ArrayList<Descriptor<ComputerLauncher>> returnedList = new ArrayList<>(); returnedList.add(new DummyOne.DummyOneDescriptor()); returnedList.add(new DummyTwo.DummyTwoDescriptor()); when(mockList.iterator()).thenReturn(returnedList.iterator()); assertTrue("DelegatingComputerLauncher should filter out other DelegatingComputerLauncher instances " + "from its descriptor's getApplicableDescriptors() method", new DummyTwo.DummyTwoDescriptor().applicableDescriptors(null, new DumbSlave.DescriptorImpl()).isEmpty()); } }
package com.hacknife.demo.ui; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView; import com.hacknife.briefness.BindClick; import com.hacknife.briefness.BindView; import com.hacknife.briefness.Briefness; import com.hacknife.briefness.Briefnessor; import com.hacknife.demo.R; /** * author : hacknife * e-mail : 4884280@qq.com * github : http://github.com/hacknife * project : briefness */ public abstract class BaseActivity<T extends Briefnessor> extends AppCompatActivity { T briefnessor; @BindView(R.id.toolBar_title) TextView toolBar_title; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); briefnessor = (T) Briefness.bind(this); toolBar_title.setText(attachTitleRes()); initView(); } protected void initView() { } @BindClick(R.id.toolBar_back) public void OnBackClick(View v) { finish(); } protected abstract int attachTitleRes(); protected void startActivity(Class<? extends AppCompatActivity> clazz) { Intent intent = new Intent(this, clazz); startActivity(intent); } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.prestosql.plugin.jdbc; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import io.prestosql.spi.PrestoException; import io.prestosql.spi.connector.ColumnMetadata; import io.prestosql.spi.connector.ConnectorTableMetadata; import io.prestosql.spi.connector.SchemaTableName; import io.prestosql.spi.connector.TableNotFoundException; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.Optional; import static io.prestosql.plugin.jdbc.TestingJdbcTypeHandle.JDBC_BIGINT; import static io.prestosql.plugin.jdbc.TestingJdbcTypeHandle.JDBC_VARCHAR; import static io.prestosql.spi.StandardErrorCode.NOT_FOUND; import static io.prestosql.spi.StandardErrorCode.PERMISSION_DENIED; import static io.prestosql.spi.type.BigintType.BIGINT; import static io.prestosql.spi.type.VarcharType.VARCHAR; import static io.prestosql.spi.type.VarcharType.createVarcharType; import static io.prestosql.testing.TestingConnectorSession.SESSION; import static java.util.Collections.emptyMap; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; @Test(singleThreaded = true) public class TestJdbcMetadata { private TestingDatabase database; private JdbcMetadata metadata; private JdbcTableHandle tableHandle; @BeforeMethod public void setUp() throws Exception { database = new TestingDatabase(); metadata = new JdbcMetadata(database.getJdbcClient(), false); tableHandle = metadata.getTableHandle(SESSION, new SchemaTableName("example", "numbers")); } @AfterMethod(alwaysRun = true) public void tearDown() throws Exception { database.close(); } @Test public void testListSchemaNames() { assertTrue(metadata.listSchemaNames(SESSION).containsAll(ImmutableSet.of("example", "tpch"))); } @Test public void testGetTableHandle() { JdbcTableHandle tableHandle = metadata.getTableHandle(SESSION, new SchemaTableName("example", "numbers")); assertEquals(metadata.getTableHandle(SESSION, new SchemaTableName("example", "numbers")), tableHandle); assertNull(metadata.getTableHandle(SESSION, new SchemaTableName("example", "unknown"))); assertNull(metadata.getTableHandle(SESSION, new SchemaTableName("unknown", "numbers"))); assertNull(metadata.getTableHandle(SESSION, new SchemaTableName("unknown", "unknown"))); } @Test public void testGetColumnHandles() { // known table assertEquals(metadata.getColumnHandles(SESSION, tableHandle), ImmutableMap.of( "text", new JdbcColumnHandle("TEXT", JDBC_VARCHAR, VARCHAR), "text_short", new JdbcColumnHandle("TEXT_SHORT", JDBC_VARCHAR, createVarcharType(32)), "value", new JdbcColumnHandle("VALUE", JDBC_BIGINT, BIGINT))); // unknown table unknownTableColumnHandle(new JdbcTableHandle(new SchemaTableName("unknown", "unknown"), "unknown", "unknown", "unknown")); unknownTableColumnHandle(new JdbcTableHandle(new SchemaTableName("example", "numbers"), null, "example", "unknown")); } private void unknownTableColumnHandle(JdbcTableHandle tableHandle) { try { metadata.getColumnHandles(SESSION, tableHandle); fail("Expected getColumnHandle of unknown table to throw a TableNotFoundException"); } catch (TableNotFoundException ignored) { } } @Test public void getTableMetadata() { // known table ConnectorTableMetadata tableMetadata = metadata.getTableMetadata(SESSION, tableHandle); assertEquals(tableMetadata.getTable(), new SchemaTableName("example", "numbers")); assertEquals(tableMetadata.getColumns(), ImmutableList.of( new ColumnMetadata("text", VARCHAR, false, null, null, false, emptyMap()), // primary key is not null in H2 new ColumnMetadata("text_short", createVarcharType(32)), new ColumnMetadata("value", BIGINT))); // escaping name patterns JdbcTableHandle specialTableHandle = metadata.getTableHandle(SESSION, new SchemaTableName("exa_ple", "num_ers")); ConnectorTableMetadata specialTableMetadata = metadata.getTableMetadata(SESSION, specialTableHandle); assertEquals(specialTableMetadata.getTable(), new SchemaTableName("exa_ple", "num_ers")); assertEquals(specialTableMetadata.getColumns(), ImmutableList.of( new ColumnMetadata("te_t", VARCHAR, false, null, null, false, emptyMap()), // primary key is not null in H2 new ColumnMetadata("va%ue", BIGINT))); // unknown tables should produce null unknownTableMetadata(new JdbcTableHandle(new SchemaTableName("u", "numbers"), null, "unknown", "unknown")); unknownTableMetadata(new JdbcTableHandle(new SchemaTableName("example", "numbers"), null, "example", "unknown")); unknownTableMetadata(new JdbcTableHandle(new SchemaTableName("example", "numbers"), null, "unknown", "numbers")); } private void unknownTableMetadata(JdbcTableHandle tableHandle) { try { metadata.getTableMetadata(SESSION, tableHandle); fail("Expected getTableMetadata of unknown table to throw a TableNotFoundException"); } catch (TableNotFoundException ignored) { } } @Test public void testListTables() { // all schemas assertEquals(ImmutableSet.copyOf(metadata.listTables(SESSION, Optional.empty())), ImmutableSet.of( new SchemaTableName("example", "numbers"), new SchemaTableName("example", "view_source"), new SchemaTableName("example", "view"), new SchemaTableName("tpch", "orders"), new SchemaTableName("tpch", "lineitem"), new SchemaTableName("exa_ple", "table_with_float_col"), new SchemaTableName("exa_ple", "num_ers"))); // specific schema assertEquals(ImmutableSet.copyOf(metadata.listTables(SESSION, Optional.of("example"))), ImmutableSet.of( new SchemaTableName("example", "numbers"), new SchemaTableName("example", "view_source"), new SchemaTableName("example", "view"))); assertEquals(ImmutableSet.copyOf(metadata.listTables(SESSION, Optional.of("tpch"))), ImmutableSet.of( new SchemaTableName("tpch", "orders"), new SchemaTableName("tpch", "lineitem"))); assertEquals(ImmutableSet.copyOf(metadata.listTables(SESSION, Optional.of("exa_ple"))), ImmutableSet.of( new SchemaTableName("exa_ple", "num_ers"), new SchemaTableName("exa_ple", "table_with_float_col"))); // unknown schema assertEquals(ImmutableSet.copyOf(metadata.listTables(SESSION, Optional.of("unknown"))), ImmutableSet.of()); } @Test public void getColumnMetadata() { assertEquals( metadata.getColumnMetadata(SESSION, tableHandle, new JdbcColumnHandle("text", JDBC_VARCHAR, VARCHAR)), new ColumnMetadata("text", VARCHAR)); } @Test public void testCreateAndAlterTable() { SchemaTableName table = new SchemaTableName("example", "foo"); metadata.createTable(SESSION, new ConnectorTableMetadata(table, ImmutableList.of(new ColumnMetadata("text", VARCHAR))), false); JdbcTableHandle handle = metadata.getTableHandle(SESSION, table); ConnectorTableMetadata layout = metadata.getTableMetadata(SESSION, handle); assertEquals(layout.getTable(), table); assertEquals(layout.getColumns().size(), 1); assertEquals(layout.getColumns().get(0), new ColumnMetadata("text", VARCHAR)); metadata.addColumn(SESSION, handle, new ColumnMetadata("x", VARCHAR)); layout = metadata.getTableMetadata(SESSION, handle); assertEquals(layout.getColumns().size(), 2); assertEquals(layout.getColumns().get(0), new ColumnMetadata("text", VARCHAR)); assertEquals(layout.getColumns().get(1), new ColumnMetadata("x", VARCHAR)); JdbcColumnHandle columnHandle = new JdbcColumnHandle("x", JDBC_VARCHAR, VARCHAR); metadata.dropColumn(SESSION, handle, columnHandle); layout = metadata.getTableMetadata(SESSION, handle); assertEquals(layout.getColumns().size(), 1); assertEquals(layout.getColumns().get(0), new ColumnMetadata("text", VARCHAR)); SchemaTableName newTableName = new SchemaTableName("example", "bar"); metadata.renameTable(SESSION, handle, newTableName); handle = metadata.getTableHandle(SESSION, newTableName); layout = metadata.getTableMetadata(SESSION, handle); assertEquals(layout.getTable(), newTableName); assertEquals(layout.getColumns().size(), 1); assertEquals(layout.getColumns().get(0), new ColumnMetadata("text", VARCHAR)); } @Test public void testDropTableTable() { try { metadata.dropTable(SESSION, tableHandle); fail("expected exception"); } catch (PrestoException e) { assertEquals(e.getErrorCode(), PERMISSION_DENIED.toErrorCode()); } metadata = new JdbcMetadata(database.getJdbcClient(), true); metadata.dropTable(SESSION, tableHandle); try { metadata.getTableMetadata(SESSION, tableHandle); fail("expected exception"); } catch (PrestoException e) { assertEquals(e.getErrorCode(), NOT_FOUND.toErrorCode()); } } }
/* * (C) Copyright IBM Corp. 2021 * * SPDX-License-Identifier: Apache-2.0 */ package com.ibm.fhir.model.constraint.spi; /** * An interface that extends {@link ConstraintProvider} with a method that determines whether this constraint provider applies to a specific model class */ public interface ModelConstraintProvider extends ConstraintProvider { /** * Indicates whether this constraint provider applies to the given model class * * @param modelClass * the model class * @return * true if this constraint provider applies to the given model class, false otherwise */ boolean appliesTo(Class<?> modelClass); }
/* * Copyright (c) 2002-2020, City of Paris * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice * and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice * and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * License 1.0 */ package fr.paris.lutece.portal.service.message; import java.util.Locale; import org.springframework.mock.web.MockHttpServletRequest; import fr.paris.lutece.portal.service.i18n.I18nService; import fr.paris.lutece.portal.web.constants.Messages; import fr.paris.lutece.portal.web.l10n.LocaleService; import fr.paris.lutece.test.LuteceTestCase; /** * AdminMessageService Test Class * */ public class AdminMessageServiceTest extends LuteceTestCase { /** * Test of getMessageUrl method, of class fr.paris.lutece.portal.service.message.AdminMessageService. */ public void testGetMessageUrl( ) { System.out.println( "getMessageUrl" ); MockHttpServletRequest request = new MockHttpServletRequest( ); String strMessageKey = Messages.MANDATORY_FIELDS; String strButtonUrl = "url"; String strTarget = "target"; Object [ ] args = { "arg1", "arg2" }; AdminMessageService.getMessageUrl( request, strMessageKey ); AdminMessage message = (AdminMessage) request.getSession( ).getAttribute( "LUTECE_ADMIN_MESSAGE" ); assertEquals( I18nService.getLocalizedString( strMessageKey, Locale.getDefault( ) ) , message.getText( Locale.getDefault( ) ) ); assertEquals( AdminMessage.TYPE_INFO , message.getType( ) ); AdminMessageService.getMessageUrl( request, strMessageKey, AdminMessage.TYPE_STOP ); message = (AdminMessage) request.getSession( ).getAttribute( "LUTECE_ADMIN_MESSAGE" ); assertEquals( I18nService.getLocalizedString( strMessageKey, Locale.getDefault( ) ) , message.getText( Locale.getDefault( ) ) ); assertEquals( AdminMessage.TYPE_STOP , message.getType( ) ); AdminMessageService.getMessageUrl( request, strMessageKey, strButtonUrl, AdminMessage.TYPE_STOP ); AdminMessageService.getMessageUrl( request, strMessageKey, strButtonUrl, strTarget ); AdminMessageService.getMessageUrl( request, strMessageKey, strButtonUrl, strTarget, AdminMessage.TYPE_STOP ); AdminMessageService.getMessageUrl( request, strMessageKey, args, AdminMessage.TYPE_STOP ); AdminMessageService.getMessageUrl( request, strMessageKey, args, strButtonUrl, AdminMessage.TYPE_STOP ); } /** * Test of getMessage method, of class fr.paris.lutece.portal.service.message.AdminMessageService. */ public void testGetMessage( ) { System.out.println( "getMessage" ); MockHttpServletRequest request = new MockHttpServletRequest( ); String strMessageKey = Messages.MANDATORY_FIELDS; String strButtonUrl = "url"; String strTarget = "target"; AdminMessageService.getMessageUrl( request, strMessageKey, strButtonUrl, strTarget, AdminMessage.TYPE_STOP ); AdminMessage message = AdminMessageService.getMessage( request ); assertEquals( message.getText( LocaleService.getDefault( ) ), I18nService.getLocalizedString( strMessageKey, LocaleService.getDefault( ) ) ); assertEquals( message.getUrl( ), strButtonUrl ); assertEquals( message.getTarget( ), strTarget ); message.getTitle( LocaleService.getDefault( ) ); message.isCancel( ); } }
package com.dbumama.market.web.admin.product.validator; import com.dbumama.market.web.core.validator.BaseJsonRenderValidator; import com.jfinal.core.Controller; public class ProductValidator extends BaseJsonRenderValidator{ @Override protected void validate(Controller c) { validateRequiredString("product_name", "error_product_name", "请输入商品名称!"); validateRequiredString("product_price", "error_product_price", "请输入商品价格!"); } }