text
stringlengths
7
1.01M
package org.onap.simulator.presetGenerator.presets.mso; import java.util.Map; import static org.onap.simulator.presetGenerator.presets.mso.PresetMSOServiceInstanceGen2WithNames.Keys.*; public abstract class PresetMSOServiceInstanceGen2WithNames extends PresetMSOBaseCreateInstancePost { public enum Keys { SERVICE_NAME, VNF_NAME, VNF_NAME2, VFM_NAME1, VFM_NAME2, VG_NAME , VNF_GROUP1_ACTION, RELATED_VNF1_ACTION, RELATED_VNF2_ACTION, } protected final Map<Keys, String> names; protected final String suffix; public PresetMSOServiceInstanceGen2WithNames(Map<Keys, String> names, int suffix) { this(names, suffix, PresetMSOBaseCreateInstancePost.DEFAULT_REQUEST_ID); } public PresetMSOServiceInstanceGen2WithNames(Map<Keys, String> names, int suffix, String requestId) { super(requestId); this.names = names; this.suffix = formatSuffix(suffix); } public PresetMSOServiceInstanceGen2WithNames(Map<Keys, String> names, int suffix, String requestId, String responseInstanceId) { super(requestId, responseInstanceId); this.names = names; this.suffix = formatSuffix(suffix); } @Override public boolean isStrictMatch() { return true; } protected String getVnfInstanceParams() { return " {" + " \"vmx_int_net_len\": \"24\"," + " \"vre_a_volume_size_0\": \"100\"," + " \"availability_zone_0\": \"mtpocdv-kvm-az01\"" + "}"; } @Override public Object getRequestBody() { return "{" + " \"requestDetails\": {" + " \"modelInfo\": {" + " \"modelInvariantId\": \"300adb1e-9b0c-4d52-bfb5-fa5393c4eabb\"," + " \"modelVersionId\": \"5c9e863f-2716-467b-8799-4a67f378dcaa\"," + " \"modelName\": \"AIM_TRANSPORT_00004\"," + " \"modelType\": \"service\"," + " \"modelVersion\": \"1.0\"" + " }," + " \"owningEntity\": {" + " \"owningEntityId\": \"someID\"," + " \"owningEntityName\": \"someName\"" + " }," + " \"subscriberInfo\": {" + " \"globalSubscriberId\": \"a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb\"" + " }," + " \"project\": {" + " \"projectName\": \"myProject\"" + " }," + " \"requestInfo\": {" + " \"instanceName\": \""+ names.get(SERVICE_NAME) + suffix + "\"," + " \"productFamilyId\": \"myProductFamilyId\"," + " \"source\": \"VID\"," + " \"suppressRollback\": false," + " \"requestorId\": \"us16807000\"" + " }," + " \"requestParameters\": {" + " \"subscriptionServiceType\": \"mySubType\"," + " \"aLaCarte\": false," + " \"userParams\": [" + " {" + " \"service\": {" + " \"modelInfo\": {" + " \"modelVersionId\": \"5c9e863f-2716-467b-8799-4a67f378dcaa\"," + " \"modelName\": \"AIM_TRANSPORT_00004\"," + " \"modelType\": \"service\"" + " }," + " \"instanceName\": \""+ names.get(SERVICE_NAME) + suffix + "\"," + " \"instanceParams\": []," + " \"resources\": {" + " \"vnfs\": [" + " {" + " \"modelInfo\": {" + " \"modelCustomizationName\": \"2016-73_MOW-AVPN-vPE-BV-L 0\"," + " \"modelCustomizationId\": \"ab153b6e-c364-44c0-bef6-1f2982117f04\"," + " \"modelVersionId\": \"7f40c192-f63c-463e-ba94-286933b895f8\"," + " \"modelName\": \"2016-73_MOW-AVPN-vPE-BV-L\"," + " \"modelType\": \"vnf\"" + " }," + " \"cloudConfiguration\": {" + " \"lcpCloudRegionId\": \"hvf3\"," + addCloudOwnerIfNeeded() + " \"tenantId\": \"greatTenant\"" + " }," + " \"platform\": {" + " \"platformName\": \"platformName\"" + " }," + " \"lineOfBusiness\": {" + " \"lineOfBusinessName\": \"lineOfBusinessName\"" + " }," + " \"productFamilyId\": \"myProductFamilyId\"," + " \"instanceParams\": ["+getVnfInstanceParams()+"]," + " \"vfModules\": [" + " {" + " \"modelInfo\": {" + " \"modelCustomizationId\": \"a25e8e8c-58b8-4eec-810c-97dcc1f5cb7f\"," + " \"modelVersionId\": \"4c75f813-fa91-45a4-89d0-790ff5f1ae79\"," + " \"modelName\": \"201673MowAvpnVpeBvL..AVPN_base_vPE_BV..module-0\"," + " \"modelType\": \"vfModule\"" + " }," + " \"instanceName\": \""+ names.get(VFM_NAME1) + suffix +"\"," + " \"instanceParams\": [" + " {" + " \"vmx_int_net_len\": \"24\"" + " }" + " ]" + " }," + " {" + " \"modelInfo\": {" + " \"modelCustomizationId\": \"72d9d1cd-f46d-447a-abdb-451d6fb05fa8\"," + " \"modelVersionId\": \"56e2b103-637c-4d1a-adc8-3a7f4a6c3240\"," + " \"modelName\": \"201673MowAvpnVpeBvL..AVPN_vRE_BV..module-1\"," + " \"modelType\": \"vfModule\"" + " }," + " \"instanceName\": \"" + names.get(VFM_NAME2) + suffix + "\"," + " \"volumeGroupInstanceName\" : \"" + names.get(VG_NAME) + suffix + "\"," + " \"instanceParams\": [" + " {" + " \"vre_a_volume_size_0\": \"100\"," + " \"availability_zone_0\": \"mtpocdv-kvm-az01\"" + " }" + " ]" + " }" + " ]," + " \"instanceName\": \"" + names.get(VNF_NAME)+ suffix + "\"" + " }" + " ]" + " }" + " }" + " }" + " ]" + " }" + " }" + "}"; } }
package factory.cabaggregator.ola; import factory.cabaggregator.ISedanCab; public class OlaSedanCab implements ISedanCab { @Override public String book() { System.out.println("Ola sedan is booked."); return "olasedan"; } @Override public double expectedPrice() { return 0; } }
package ch.uzh.ifi.seal.soprafs20.repository; import ch.uzh.ifi.seal.soprafs20.entity.Message; import org.springframework.data.jpa.repository.JpaRepository; public interface MessageRepository extends JpaRepository<Message, Long> { }
/* * 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.fineract.cn.dev.listener; import org.apache.fineract.cn.test.listener.EventRecorder; import org.apache.fineract.cn.identity.api.v1.events.ApplicationPermissionEvent; import org.apache.fineract.cn.identity.api.v1.events.ApplicationPermissionUserEvent; import org.apache.fineract.cn.identity.api.v1.events.ApplicationSignatureEvent; import org.apache.fineract.cn.identity.api.v1.events.EventConstants; import org.apache.fineract.cn.lang.config.TenantHeaderFilter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.annotation.JmsListener; import org.springframework.messaging.handler.annotation.Header; import org.springframework.stereotype.Component; /** * @author Myrle Krantz */ @SuppressWarnings("unused") @Component public class IdentityListener { private final EventRecorder eventRecorder; @Autowired public IdentityListener(final EventRecorder eventRecorder) { this.eventRecorder = eventRecorder; } @JmsListener( subscription = EventConstants.DESTINATION, destination = EventConstants.DESTINATION, selector = EventConstants.SELECTOR_POST_USER ) public void onCreateUser( @Header(TenantHeaderFilter.TENANT_HEADER)final String tenant, final String payload) throws Exception { eventRecorder.event(tenant, EventConstants.OPERATION_POST_USER, payload, String.class); } @JmsListener( subscription = EventConstants.DESTINATION, destination = EventConstants.DESTINATION, selector = EventConstants.SELECTOR_PUT_USER_PASSWORD ) public void onChangeUserPassword( @Header(TenantHeaderFilter.TENANT_HEADER)final String tenant, final String payload) throws Exception { eventRecorder.event(tenant, EventConstants.OPERATION_PUT_USER_PASSWORD, payload, String.class); } @JmsListener( subscription = EventConstants.DESTINATION, destination = EventConstants.DESTINATION, selector = EventConstants.SELECTOR_POST_PERMITTABLE_GROUP ) public void onCreatePermittableGroup( @Header(TenantHeaderFilter.TENANT_HEADER)final String tenant, final String payload) throws Exception { eventRecorder.event(tenant, EventConstants.OPERATION_POST_PERMITTABLE_GROUP, payload, String.class); } @JmsListener( subscription = EventConstants.DESTINATION, destination = EventConstants.DESTINATION, selector = EventConstants.SELECTOR_POST_APPLICATION_PERMISSION ) public void onCreateApplicationPermission( @Header(TenantHeaderFilter.TENANT_HEADER)final String tenant, final String payload) throws Exception { eventRecorder.event(tenant, EventConstants.OPERATION_POST_APPLICATION_PERMISSION, payload, ApplicationPermissionEvent.class); } @JmsListener( subscription = EventConstants.DESTINATION, destination = EventConstants.DESTINATION, selector = EventConstants.SELECTOR_PUT_APPLICATION_SIGNATURE ) public void onSetApplicationSignature( @Header(TenantHeaderFilter.TENANT_HEADER)final String tenant, final String payload) throws Exception { eventRecorder.event(tenant, EventConstants.OPERATION_PUT_APPLICATION_SIGNATURE, payload, ApplicationSignatureEvent.class); } @JmsListener( subscription = EventConstants.DESTINATION, destination = EventConstants.DESTINATION, selector = EventConstants.SELECTOR_PUT_APPLICATION_PERMISSION_USER_ENABLED ) public void onPutApplicationPermissionEnabledForUser( @Header(TenantHeaderFilter.TENANT_HEADER)final String tenant, final String payload) throws Exception { eventRecorder.event(tenant, EventConstants.OPERATION_PUT_APPLICATION_PERMISSION_USER_ENABLED, payload, ApplicationPermissionUserEvent.class); } @JmsListener( subscription = EventConstants.DESTINATION, destination = EventConstants.DESTINATION, selector = EventConstants.SELECTOR_POST_ROLE ) public void onCreateRole( @Header(TenantHeaderFilter.TENANT_HEADER)final String tenant, final String payload) throws Exception { eventRecorder.event(tenant, EventConstants.OPERATION_POST_ROLE, payload, String.class); } }
/* Sistema de Gestão de Pistas (C) 2016 Tecsidel Updated by wilson.souza (WR DevInfo) Description: */ package br.com.tk.mcs.Component; import android.content.res.Resources; import android.util.DisplayMetrics; import android.util.TypedValue; import android.widget.EditText; import android.widget.TextView; import br.com.tk.mcs.Generic.ConfigDisplayMetrics; /** * Created by wilsonsouza on 12/02/17. */ public class Font extends Object { public final static float DEFAULT_SIZE = ConfigDisplayMetrics.FontSize; public final static float CAPTION_SIZE = ConfigDisplayMetrics.CaptionSize; //-----------------------------------------------------------------------------------------------------------------// // private Font() {} //-----------------------------------------------------------------------------------------------------------------// public static <T> void SetSize(T view, float fSize, float fScale) { DisplayMetrics dm = Resources.getSystem().getDisplayMetrics(); float fCurSize = 0; if (view instanceof TextView) { TextView p = ((TextView) view); if(fScale == DEFAULT_SIZE) { //fCurSize = TypedValue.applyDimension(ConfigDisplayMetrics.s_nUnits, fCurSize * fScale, dm); fCurSize = DEFAULT_SIZE; //p.setTextAppearance(ConfigDisplayMetrics.TextStyle); } else if(fScale == CAPTION_SIZE) { //fCurSize = TypedValue.applyDimension(ConfigDisplayMetrics.s_nUnits, fCurSize * fScale, dm); fCurSize = CAPTION_SIZE; //p.setTextAppearance(ConfigDisplayMetrics.CaptionStyle); } p.setTextSize ( TypedValue.COMPLEX_UNIT_PX, fCurSize ); return; } if (view instanceof EditText) { EditText p = ((EditText)view); //p.setTextAppearance(ConfigDisplayMetrics.EditStyle); p.setTextSize( TypedValue.COMPLEX_UNIT_PX, DEFAULT_SIZE); } } }
/* * Copyright (C) 2021 cointoss Development Team * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT */ package cointoss.market.liquid; import cointoss.Currency; import cointoss.MarketService; import cointoss.MarketSetting; import cointoss.market.MarketAccount; import cointoss.market.MarketServiceProvider; import kiss.I; public final class Liquid extends MarketServiceProvider { /** Limitation */ private static final int AcquirableSize = 50; static final MarketService BTC_JPY = new LiquidService("BTCJPY", MarketSetting.with.spot() .target(Currency.BTC.minimumSize(0.001)) .base(Currency.JPY.minimumSize(1)) .priceRangeModifier(500) .acquirableExecutionSize(AcquirableSize)); /** * {@inheritDoc} */ @Override public MarketAccount account() { return I.make(LiquidAccount.class); } }
/* * The MIT License (MIT) * * Copyright (c) 2010 Technische Universitaet Berlin * * 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 net.mumie.mathletfactory.math.geom.test; import junit.framework.Test; import junit.framework.TestSuite; import net.mumie.mathletfactory.math.analysis.function.test.AllFunctionTest; import net.mumie.mathletfactory.math.geom.affine.test.AllAffineTest; /** * JUnit testsuite for all classes in {@link net.mumie.mathletfactory.geom}. * * @author Mrose * @mm.docstatus finished * @see <a href="http://junit.sourceforge.net">JUnit</a> */ public class AllGeomTest { /** * Testsuite running * {@link net.mumie.mathletfactory.analysisaffine.test.AllAffineTest} and * {@link net.mumie.mathletfactory.analysis.function.test.AllFunctionTest}. * * @return a <code>Test</code> * */ public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(AllAffineTest.suite()); suite.addTest(AllFunctionTest.suite()); return suite; } /** * Runs the test. * @param args a <code>String[]</code> * */ public static void main(String args[]) { junit.textui.TestRunner.run(suite()); } }
/* * Copyright 2010-2013 Ning, Inc. * * Ning 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.subscription.api.timeline; import java.util.UUID; import org.joda.time.DateTime; import org.killbill.billing.catalog.api.PlanPhaseSpecifier; import org.killbill.billing.subscription.api.SubscriptionBaseTransitionType; import org.killbill.billing.subscription.api.timeline.SubscriptionBaseTimeline.NewEvent; public class DefaultNewEvent implements NewEvent { private final UUID subscriptionId; private final PlanPhaseSpecifier spec; private final DateTime requestedDate; private final SubscriptionBaseTransitionType transitionType; public DefaultNewEvent(final UUID subscriptionId, final PlanPhaseSpecifier spec, final DateTime requestedDate, final SubscriptionBaseTransitionType transitionType) { this.subscriptionId = subscriptionId; this.spec = spec; this.requestedDate = requestedDate; this.transitionType = transitionType; } @Override public PlanPhaseSpecifier getPlanPhaseSpecifier() { return spec; } @Override public DateTime getRequestedDate() { return requestedDate; } @Override public SubscriptionBaseTransitionType getSubscriptionTransitionType() { return transitionType; } public UUID getSubscriptionId() { return subscriptionId; } }
/* * 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.zookeeper.operations; import org.apache.camel.component.zookeeper.ZooKeeperTestSupport; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.ZooKeeper; import org.junit.Test; public class ExistenceChangedOperationTest extends ZooKeeperTestSupport { @Test public void getStatsWhenNodeIsCreated() throws Exception { String path = "/doesNotYetExist"; ExistenceChangedOperation future = setupMonitor(path); client.create(path, "This is a test"); assertEquals(path, future.get().getResult()); assertNotNull(future.get().getStatistics()); } @Test public void getsNotifiedWhenNodeIsDeleted() throws Exception { String path = "/soonToBeDeleted"; client.create(path, "This is a test"); ExistenceChangedOperation future = setupMonitor(path); client.delete(path); assertEquals(path, future.get().getResult()); assertNull(future.get().getStatistics()); } private ExistenceChangedOperation setupMonitor(String path) throws KeeperException, InterruptedException { ZooKeeper connection = getConnection(); ExistenceChangedOperation future = new ExistenceChangedOperation(connection, path); connection.exists(path, future); return future; } }
package net.codingarea.challenges.plugin.challenges.type.abstraction; import net.anweisen.utilities.common.config.Document; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import org.bukkit.*; import org.bukkit.World.Environment; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; /** * @author anweisen | https://github.com/anweisen * @author KxmischesDomi | https://github.com/kxmischesdomi * @since 2.0 */ public abstract class NetherPortalSpawnSetting extends OneEnabledSetting { private static final String id = "netherportal_handle"; private final Map<Location, Location> netherPortalsByOverworldPortals = new HashMap<>(); private final StructureType structureType; private final Collection<Material> groundMaterial; private final String unableToFindMessage; public NetherPortalSpawnSetting(@Nonnull MenuType menu, @Nonnull StructureType structureType, @Nonnull String unableToFindMessage, @Nonnull Material... groundMaterial) { super(menu, id); this.structureType = structureType; this.unableToFindMessage = unableToFindMessage; this.groundMaterial = Arrays.asList(groundMaterial); } public NetherPortalSpawnSetting(@Nonnull MenuType menu, @Nonnull StructureType structureType, @Nonnull String unableToFindMessage, @Nonnull Collection<Material> groundMaterial) { super(menu, id); this.structureType = structureType; this.unableToFindMessage = unableToFindMessage; this.groundMaterial = groundMaterial; } @EventHandler public void onNetherPortal(@Nonnull PlayerTeleportEvent event) { if (!isEnabled()) return; if (event.getCause() != TeleportCause.NETHER_PORTAL) return; if (event.getTo() == null) return; if (event.getTo().getWorld() == null) return; if (event.getTo().getWorld().getEnvironment() == Environment.NETHER) { World world = event.getTo().getWorld(); Location location = getNetherPortal(event.getFrom(), world); if (location == null) { Message.forName(unableToFindMessage).send(event.getPlayer(), Prefix.CHALLENGES); return; } buildPortal(location); event.setTo(location.clone().add(1, 0, 0.5)); // Middle of portal } else if (event.getTo().getWorld().getEnvironment() == Environment.NORMAL) { Location location = getOverworldPortal(event.getFrom()); if (location == null) return; event.setTo(location.clone().add(1, 0, 0.5)); // Middle of portal } } @Nullable private Location getNetherPortal(@Nonnull Location overworldPortal, @Nonnull World nether) { // Look if the current portal was used before for (Entry<Location, Location> entry : netherPortalsByOverworldPortals.entrySet()) { if (overworldPortal.distance(entry.getKey()) < 10) return entry.getValue(); } // Find next structure Location structure = nether.locateNearestStructure(new Location(nether, 0, 100, 0), structureType, 10000, false); if (structure == null) return null; // Look if there's already a portal to this structure for (Entry<Location, Location> entry : netherPortalsByOverworldPortals.entrySet()) { if (structure.distance(entry.getValue()) < 100) return entry.getValue(); } Location target = findNearestStructurePart(structure.clone()); netherPortalsByOverworldPortals.put(overworldPortal, target); return target; } @Nullable private Location getOverworldPortal(@Nonnull Location netherPortal) { for (Entry<Location, Location> entry : netherPortalsByOverworldPortals.entrySet()) { if (netherPortal.distance(entry.getValue()) < 100) return entry.getKey(); } return null; } @Nullable private Location findNearestStructurePart(@Nonnull Location structure) { Chunk chunk = structure.getChunk(); for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { Location location = chunk.getBlock(x, 100, z).getLocation(); // Structures wont be above y=100 while (location.getBlockY() > 30) { // Structures wont be below y=30 location.subtract(0, 1, 0); if (groundMaterial.contains(location.getBlock().getType())) return location.add(0, 1, 0); } } } return null; } private void buildPortal(@Nonnull Location origin) { // Floor origin.clone().add(-1, -1, 0).getBlock().setType(Material.OBSIDIAN); origin.clone().add(0, -1, 0).getBlock().setType(Material.OBSIDIAN); origin.clone().add(1, -1, 0).getBlock().setType(Material.OBSIDIAN); origin.clone().add(2, -1, 0).getBlock().setType(Material.OBSIDIAN); // Above origin.clone().add(-1, 3, 0).getBlock().setType(Material.OBSIDIAN); origin.clone().add(0, 3, 0).getBlock().setType(Material.OBSIDIAN); origin.clone().add(1, 3, 0).getBlock().setType(Material.OBSIDIAN); origin.clone().add(2, 3, 0).getBlock().setType(Material.OBSIDIAN); // Wall left origin.clone().add(-1, 0, 0).getBlock().setType(Material.OBSIDIAN); origin.clone().add(-1, 1, 0).getBlock().setType(Material.OBSIDIAN); origin.clone().add(-1, 2, 0).getBlock().setType(Material.OBSIDIAN); // Wall right origin.clone().add(2, 0, 0).getBlock().setType(Material.OBSIDIAN); origin.clone().add(2, 1, 0).getBlock().setType(Material.OBSIDIAN); origin.clone().add(2, 2, 0).getBlock().setType(Material.OBSIDIAN); // Fill portal origin.clone().add(0, 0, 0).getBlock().setType(Material.NETHER_PORTAL); origin.clone().add(1, 0, 0).getBlock().setType(Material.NETHER_PORTAL); origin.clone().add(0, 1, 0).getBlock().setType(Material.NETHER_PORTAL); origin.clone().add(1, 1, 0).getBlock().setType(Material.NETHER_PORTAL); origin.clone().add(0, 2, 0).getBlock().setType(Material.NETHER_PORTAL); origin.clone().add(1, 2, 0).getBlock().setType(Material.NETHER_PORTAL); // Free some place around for (int x = -1; x <= 2; x++) { for (int y = 0; y <= 3; y++) { origin.clone().add(x, y, 1).getBlock().setType(Material.AIR); origin.clone().add(x, y, 2).getBlock().setType(Material.AIR); origin.clone().add(x, y, -1).getBlock().setType(Material.AIR); origin.clone().add(x, y, -2).getBlock().setType(Material.AIR); } } } @Override public void loadGameState(@Nonnull Document document) { super.loadGameState(document); Document portals = document.getDocument("portals"); for (String key : portals.keys()) { Document portal = portals.getDocument(key); Location from = portal.getSerializable("portal", Location.class); Location to = portal.getSerializable("target", Location.class); if (from == null || to == null) continue; netherPortalsByOverworldPortals.put(from, to); } } @Override public void writeGameState(@Nonnull Document document) { super.writeGameState(document); int index = 0; Document portals = document.getDocument("portals"); for (Entry<Location, Location> entry : netherPortalsByOverworldPortals.entrySet()) { Document portal = portals.getDocument(String.valueOf(index)); portal.set("portal", entry.getKey()); portal.set("target", entry.getValue()); } } }
/* * Copyright 2019-2021 The Polypheny 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 org.polypheny.db.adapter.file; import com.google.common.collect.ImmutableMap; import java.lang.reflect.Method; import java.util.List; import org.apache.calcite.linq4j.tree.Types; import org.polypheny.db.adapter.DataContext; import org.polypheny.db.adapter.file.FileRel.FileImplementor.Operation; import org.polypheny.db.adapter.file.source.QfsSchema; import org.polypheny.db.type.PolyType; public enum FileMethod { EXECUTE( FileStoreSchema.class, "execute", Operation.class, Integer.class, DataContext.class, String.class, Long[].class, PolyType[].class, List.class, Integer[].class, Condition.class, Value[].class ), EXECUTE_MODIFY( FileStoreSchema.class, "executeModify", Operation.class, Integer.class, DataContext.class, String.class, Long[].class, PolyType[].class, List.class, Boolean.class, Object[].class, Condition.class ), EXECUTE_QFS( QfsSchema.class, "execute", Operation.class, Integer.class, DataContext.class, String.class, Long[].class, PolyType[].class, List.class, Integer[].class, Condition.class, Value[].class ); public final Method method; public static final ImmutableMap<Method, FileMethod> MAP; static { final ImmutableMap.Builder<Method, FileMethod> builder = ImmutableMap.builder(); for ( FileMethod value : FileMethod.values() ) { builder.put( value.method, value ); } MAP = builder.build(); } FileMethod( Class clazz, String methodName, Class... argumentTypes ) { this.method = Types.lookupMethod( clazz, methodName, argumentTypes ); } }
package org.ovirt.engine.core.bll.storage.connection; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.when; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; import org.ovirt.engine.core.bll.CommandAssertUtils; import org.ovirt.engine.core.bll.ValidateTestUtils; import org.ovirt.engine.core.common.action.StorageServerConnectionParametersBase; import org.ovirt.engine.core.common.businessentities.StorageServerConnections; import org.ovirt.engine.core.common.businessentities.storage.StorageType; import org.ovirt.engine.core.common.errors.EngineMessage; import org.ovirt.engine.core.common.utils.Pair; import org.ovirt.engine.core.compat.Guid; @MockitoSettings(strictness = Strictness.LENIENT) public class AddStorageServerConnectionCommandTest extends StorageServerConnectionTestCommon<AddStorageServerConnectionCommand<StorageServerConnectionParametersBase>> { @Mock protected ISCSIStorageHelper iscsiStorageHelper; @Override protected AddStorageServerConnectionCommand<StorageServerConnectionParametersBase> createCommand() { parameters = new StorageServerConnectionParametersBase(); parameters.setVdsId(Guid.newGuid()); return new AddStorageServerConnectionCommand<>(parameters, null); } @Test public void addPosixNonEmptyVFSType() { StorageServerConnections newPosixConnection = createPosixConnection("multipass.my.domain.tlv.company.com:/export/allstorage/data1", StorageType.POSIXFS, "nfs", "timeo=30"); parameters.setStorageServerConnection(newPosixConnection); parameters.setVdsId(Guid.Empty); doReturn("").when(command).isConnWithSameDetailsExists(newPosixConnection, null); ValidateTestUtils.runAndAssertValidateSuccess(command); } @Test public void addISCSINonEmptyIqn() { StorageServerConnections newISCSIConnection = createISCSIConnection("10.35.16.25", StorageType.ISCSI, "iqn.2013-04.myhat.com:aaa-target1", "3650", "user1", "mypassword123"); parameters.setStorageServerConnection(newISCSIConnection); parameters.setVdsId(Guid.Empty); doReturn("").when(command).isConnWithSameDetailsExists(newISCSIConnection, null); ValidateTestUtils.runAndAssertValidateSuccess(command); } @Test public void addNFSEmptyConn() { StorageServerConnections newPosixConnection = createPosixConnection("", StorageType.POSIXFS, "nfs", "timeo=30"); parameters.setStorageServerConnection(newPosixConnection); parameters.setVdsId(Guid.Empty); ValidateTestUtils.runAndAssertValidateFailure(command, EngineMessage.VALIDATION_STORAGE_CONNECTION_EMPTY_CONNECTION); } @Test public void addExistingConnection() { StorageServerConnections newPosixConnection = createPosixConnection("multipass.my.domain.tlv.company.com:/export/allstorage/data1", StorageType.POSIXFS, "nfs", "timeo=30"); parameters.setStorageServerConnection(newPosixConnection); parameters.setVdsId(Guid.Empty); String guid = Guid.newGuid().toString(); doReturn(guid).when(command).isConnWithSameDetailsExists(newPosixConnection, null); doReturn("storage_domain_01").when(command).getStorageNameByConnectionId(guid); List<String> messages = ValidateTestUtils.runAndAssertValidateFailure(command, EngineMessage.ACTION_TYPE_FAILED_STORAGE_CONNECTION_ALREADY_EXISTS); assertTrue(messages.contains("$connectionId " + guid) && messages.contains("$storageDomainName storage_domain_01")); } @Test public void addNewConnectionWithVds() { StorageServerConnections newPosixConnection = createPosixConnection("multipass.my.domain.tlv.company.com:/export/allstorage/data1", StorageType.POSIXFS, "nfs", "timeo=30"); newPosixConnection.setId(""); parameters.setStorageServerConnection(newPosixConnection); doReturn("").when(command).isConnWithSameDetailsExists(newPosixConnection, null); Pair<Boolean, Integer> connectResult = new Pair(true, 0); doReturn(connectResult).when(command).connectHostToStorage(); doReturn(null).when(command).getConnectionFromDbById(newPosixConnection.getId()); doNothing().when(command).saveConnection(newPosixConnection); command.executeCommand(); CommandAssertUtils.checkSucceeded(command, true); } @Test public void addNewConnectionEmptyVdsId() { StorageServerConnections newPosixConnection = createPosixConnection("multipass.my.domain.tlv.company.com:/export/allstorage/data1", StorageType.POSIXFS, "nfs", "timeo=30"); newPosixConnection.setId(""); parameters.setStorageServerConnection(newPosixConnection); parameters.setVdsId(Guid.Empty); doReturn("").when(command).isConnWithSameDetailsExists(newPosixConnection, null); doReturn(null).when(command).getConnectionFromDbById(newPosixConnection.getId()); doNothing().when(command).saveConnection(newPosixConnection); command.executeCommand(); CommandAssertUtils.checkSucceeded(command, true); } @Test public void addNewConnectionNullVdsId() { StorageServerConnections newPosixConnection = createPosixConnection("multipass.my.domain.tlv.company.com:/export/allstorage/data1", StorageType.POSIXFS, "nfs", "timeo=30"); newPosixConnection.setId(""); parameters.setStorageServerConnection(newPosixConnection); parameters.setVdsId(null); doReturn("").when(command).isConnWithSameDetailsExists(newPosixConnection, null); doReturn(null).when(command).getConnectionFromDbById(newPosixConnection.getId()); doNothing().when(command).saveConnection(newPosixConnection); command.executeCommand(); CommandAssertUtils.checkSucceeded(command, true); } @Test public void addNotEmptyIdConnection() { StorageServerConnections newPosixConnection = createPosixConnection("multipass.my.domain.tlv.company.com:/export/allstorage/data1", StorageType.POSIXFS, "nfs", "timeo=30"); newPosixConnection.setId(Guid.newGuid().toString()); parameters.setStorageServerConnection(newPosixConnection); parameters.setVdsId(Guid.Empty); ValidateTestUtils.runAndAssertValidateFailure(command, EngineMessage.ACTION_TYPE_FAILED_STORAGE_CONNECTION_ID_NOT_EMPTY); } @Test public void addISCSIEmptyConn() { StorageServerConnections newISCSIConnection = createISCSIConnection("", StorageType.ISCSI, "iqn.2013-04.myhat.com:aaa-target1", "3650", "user1", "mypassword123"); parameters.setStorageServerConnection(newISCSIConnection); parameters.setVdsId(Guid.Empty); ValidateTestUtils.runAndAssertValidateFailure(command, EngineMessage.VALIDATION_STORAGE_CONNECTION_EMPTY_CONNECTION); } @Test public void isConnWithSameDetailsExist() { StorageServerConnections newISCSIConnection = createISCSIConnection("1.2.3.4", StorageType.ISCSI, "iqn.2013-04.myhat.com:aaa-target1", "3650", "user1", "mypassword123"); StorageServerConnections existingConn = createISCSIConnection("1.2.3.4", StorageType.ISCSI, "iqn.2013-04.myhat.com:aaa-target1", "3650", "user1", "mypassword123"); existingConn.setId(Guid.newGuid().toString()); when(iscsiStorageHelper.findConnectionWithSameDetails(newISCSIConnection)).thenReturn(existingConn); String isExists = command.isConnWithSameDetailsExists(newISCSIConnection, null); assertTrue(!isExists.isEmpty()); } @Test public void isLocalDomainConnWithSamePathAndPoolExist() { StorageServerConnections newLocalConnection = populateBasicConnectionDetails(null, "/localSD", StorageType.LOCALFS); StorageServerConnections existingConn = populateBasicConnectionDetails(null, "/localSD", StorageType.LOCALFS); existingConn.setId(Guid.newGuid().toString()); Guid storagePoolId = Guid.newGuid(); List<StorageServerConnections> connections = Collections.singletonList(existingConn); when(storageConnDao.getAllConnectableStorageSeverConnection(storagePoolId)).thenReturn(connections); when(storageConnDao.getAllForStorage(newLocalConnection.getConnection())).thenReturn(connections); String isExists = command.isConnWithSameDetailsExists(newLocalConnection, storagePoolId); assertTrue(!isExists.isEmpty()); } @Test public void isLocalDomainConnWithSamePathAndPoolNotExist() { StorageServerConnections newLocalConnection = populateBasicConnectionDetails(null, "/localSD", StorageType.LOCALFS); StorageServerConnections existingConn = populateBasicConnectionDetails(null, "/localSD", StorageType.LOCALFS); Guid newLocalConnectionStoragePoolId = Guid.newGuid(); Guid existingLocalConnectionStoragePoolId = Guid.newGuid(); List<StorageServerConnections> connections = Collections.singletonList(existingConn); when(storageConnDao.getAllConnectableStorageSeverConnection(existingLocalConnectionStoragePoolId)).thenReturn(connections); when(storageConnDao.getAllForStorage(newLocalConnection.getConnection())).thenReturn(connections); String isExists = command.isConnWithSameDetailsExists(newLocalConnection, newLocalConnectionStoragePoolId); assertFalse(!isExists.isEmpty()); } @Override protected boolean createConnectionWithId() { return false; } }
/** * Autogenerated by Avro * * DO NOT EDIT DIRECTLY */ package org.apache.avro.mapred.tether; /** Transmit outputs from a map or reduce task to parent. */ @org.apache.avro.specific.AvroGenerated public interface OutputProtocol { public static final org.apache.avro.Protocol PROTOCOL = org.apache.avro.Protocol.parse("{\"protocol\":\"OutputProtocol\",\"namespace\":\"org.apache.avro.mapred.tether\",\"doc\":\"Transmit outputs from a map or reduce task to parent.\",\"types\":[],\"messages\":{\"configure\":{\"doc\":\"Transmit outputs from a map or reduce task to parent.\",\"request\":[{\"name\":\"port\",\"type\":\"int\",\"doc\":\"The port to transmit inputs to this task on.\"}],\"response\":\"null\",\"one-way\":true},\"output\":{\"doc\":\"Transmit outputs from a map or reduce task to parent.\",\"request\":[{\"name\":\"datum\",\"type\":\"bytes\",\"doc\":\"A binary-encoded instance of the declared schema.\"}],\"response\":\"null\",\"one-way\":true},\"outputPartitioned\":{\"doc\":\"Transmit outputs from a map or reduce task to parent.\",\"request\":[{\"name\":\"partition\",\"type\":\"int\",\"doc\":\"The map output partition for this datum.\"},{\"name\":\"datum\",\"type\":\"bytes\",\"doc\":\"A binary-encoded instance of the declared schema.\"}],\"response\":\"null\",\"one-way\":true},\"status\":{\"doc\":\"Transmit outputs from a map or reduce task to parent.\",\"request\":[{\"name\":\"message\",\"type\":{\"type\":\"string\",\"avro.java.string\":\"String\"},\"doc\":\"The new status message for the task.\"}],\"response\":\"null\",\"one-way\":true},\"count\":{\"doc\":\"Transmit outputs from a map or reduce task to parent.\",\"request\":[{\"name\":\"group\",\"type\":{\"type\":\"string\",\"avro.java.string\":\"String\"},\"doc\":\"The name of the counter group.\"},{\"name\":\"name\",\"type\":{\"type\":\"string\",\"avro.java.string\":\"String\"},\"doc\":\"The name of the counter to increment.\"},{\"name\":\"amount\",\"type\":\"long\",\"doc\":\"The amount to incrment the counter.\"}],\"response\":\"null\",\"one-way\":true},\"fail\":{\"doc\":\"Transmit outputs from a map or reduce task to parent.\",\"request\":[{\"name\":\"message\",\"type\":{\"type\":\"string\",\"avro.java.string\":\"String\"},\"doc\":\"The new status message for the task.\"}],\"response\":\"null\",\"one-way\":true},\"complete\":{\"doc\":\"Transmit outputs from a map or reduce task to parent.\",\"request\":[],\"response\":\"null\",\"one-way\":true}}}"); /** * Transmit outputs from a map or reduce task to parent. * @param port The port to transmit inputs to this task on. */ void configure(int port); /** * Transmit outputs from a map or reduce task to parent. * @param datum A binary-encoded instance of the declared schema. */ void output(java.nio.ByteBuffer datum); /** * Transmit outputs from a map or reduce task to parent. * @param partition The map output partition for this datum. * @param datum A binary-encoded instance of the declared schema. */ void outputPartitioned(int partition, java.nio.ByteBuffer datum); /** * Transmit outputs from a map or reduce task to parent. * @param message The new status message for the task. */ void status(java.lang.String message); /** * Transmit outputs from a map or reduce task to parent. * @param group The name of the counter group. * @param name The name of the counter to increment. * @param amount The amount to incrment the counter. */ void count(java.lang.String group, java.lang.String name, long amount); /** * Transmit outputs from a map or reduce task to parent. * @param message The new status message for the task. */ void fail(java.lang.String message); /** * Transmit outputs from a map or reduce task to parent. */ void complete(); /** Transmit outputs from a map or reduce task to parent. */ @org.apache.avro.specific.AvroGenerated public interface Callback extends OutputProtocol { public static final org.apache.avro.Protocol PROTOCOL = org.apache.avro.mapred.tether.OutputProtocol.PROTOCOL; } }
/* * Copyright (c) 2007, 2018, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ /* * Copyright 2001-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. */ /* * $Id: StringCall.java,v 1.2.4.1 2005/09/05 09:08:15 pvedula Exp $ */ package goodman.com.sun.org.apache.xalan.internal.xsltc.compiler; import goodman.java.util.Vector; import com.sun.org.apache.bcel.internal.generic.InstructionList; import com.sun.org.apache.xalan.internal.xsltc.compiler.Expression; import com.sun.org.apache.xalan.internal.xsltc.compiler.FunctionCall; import com.sun.org.apache.xalan.internal.xsltc.compiler.QName; import com.sun.org.apache.xalan.internal.xsltc.compiler.SymbolTable; import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ClassGenerator; import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ErrorMsg; import com.sun.org.apache.xalan.internal.xsltc.compiler.util.MethodGenerator; import com.sun.org.apache.xalan.internal.xsltc.compiler.util.Type; import com.sun.org.apache.xalan.internal.xsltc.compiler.util.TypeCheckError; /** * @author Jacek Ambroziak * @author Santiago Pericas-Geertsen */ final class StringCall extends FunctionCall { public StringCall(com.sun.org.apache.xalan.internal.xsltc.compiler.QName fname, Vector arguments) { super(fname, arguments); } public Type typeCheck(SymbolTable stable) throws TypeCheckError { final int argc = argumentCount(); if (argc > 1) { ErrorMsg err = new ErrorMsg(ErrorMsg.ILLEGAL_ARG_ERR, this); throw new TypeCheckError(err); } if (argc > 0) { argument().typeCheck(stable); } return _type = Type.String; } public void translate(ClassGenerator classGen, MethodGenerator methodGen) { final InstructionList il = methodGen.getInstructionList(); Type targ; if (argumentCount() == 0) { il.append(methodGen.loadContextNode()); targ = Type.Node; } else { final com.sun.org.apache.xalan.internal.xsltc.compiler.Expression arg = argument(); arg.translate(classGen, methodGen); arg.startIterator(classGen, methodGen); targ = arg.getType(); } if (!targ.identicalTo(Type.String)) { targ.translateTo(classGen, methodGen, Type.String); } } }
package patterns.strategy.main; public enum SocialNetworks { Telegram { @Override public void send(Message m) { System.out.println(m); } }, Instagram { @Override public void send(Message m) { System.out.println(m); } }, VK { @Override public void send(Message m) { System.out.println(m); } }, OK { @Override public void send(Message m) { System.out.println(m); } }; abstract public void send(Message m); }
package io.vivarium.ga; public abstract class BehaviorBasedFitnessFunction extends FitnessFunction { }
/** * Copyright 2009-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ibatis.submitted.dynsql; import org.apache.ibatis.annotations.Param; public interface DynSqlMapper { String selectDescription(@Param("p") String p); }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.datatorrent.demos.mrmonitor; /** * <p>Constants class.</p> * * @since 0.3.4 */ public interface Constants { public static final int MAX_NUMBER_OF_JOBS = 25; public static final String REDUCE_TASK_TYPE = "REDUCE"; public static final String MAP_TASK_TYPE = "MAP"; public static final String TASK_TYPE = "type"; public static final String TASK_ID = "id"; public static final String LEAGACY_TASK_ID = "taskId"; public static final int MAX_TASKS = 2000; public static final String QUERY_APP_ID = "app_id"; public static final String QUERY_JOB_ID = "job_id"; public static final String QUERY_HADOOP_VERSION = "hadoop_version"; public static final String QUERY_API_VERSION = "api_version"; public static final String QUERY_RM_PORT = "rm_port"; public static final String QUERY_HS_PORT = "hs_port"; public static final String QUERY_HOST_NAME = "hostname"; public static final String QUERY_KEY_COMMAND = "command"; }
/* * Copyright 2016 czy1121 * * 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 ezy.ui.layout; import android.app.Activity; import android.app.Fragment; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.support.annotation.DrawableRes; import android.support.annotation.LayoutRes; import android.util.AttributeSet; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import java.util.HashMap; import java.util.Map; import ezy.library.loadinglayout.R; public class LoadingLayout extends FrameLayout { public interface OnInflateListener { void onInflate(View inflated); } public static LoadingLayout wrap(Activity activity) { return wrap(((ViewGroup)activity.findViewById(android.R.id.content)).getChildAt(0)); } public static LoadingLayout wrap(Fragment fragment) { return wrap(fragment.getView()); } public static LoadingLayout wrap(View view) { if (view == null) { throw new RuntimeException("content view can not be null"); } ViewGroup parent = (ViewGroup)view.getParent(); if (view == null) { throw new RuntimeException("parent view can not be null"); } ViewGroup.LayoutParams lp = view.getLayoutParams(); int index = parent.indexOfChild(view); parent.removeView(view); LoadingLayout layout = new LoadingLayout(view.getContext()); parent.addView(layout, index, lp); layout.addView(view); layout.setContentView(view); return layout; } int mEmptyImage; CharSequence mEmptyText; int mErrorImage; CharSequence mErrorText, mRetryText; View.OnClickListener mRetryButtonClickListener = new OnClickListener() { @Override public void onClick(View v) { if (mRetryListener != null) { mRetryListener.onClick(v); } } }; View.OnClickListener mRetryListener; OnInflateListener mOnEmptyInflateListener; OnInflateListener mOnErrorInflateListener; int mTextColor, mTextSize; int mButtonTextColor, mButtonTextSize; Drawable mButtonBackground; int mEmptyResId = NO_ID, mLoadingResId = NO_ID, mErrorResId = NO_ID; int mContentId = NO_ID; Map<Integer, View> mLayouts = new HashMap<>(); public LoadingLayout(Context context) { this(context, null, R.attr.styleLoadingLayout); } public LoadingLayout(Context context, AttributeSet attrs) { this(context, attrs, R.attr.styleLoadingLayout); } public LoadingLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mInflater = LayoutInflater.from(context); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.LoadingLayout, defStyleAttr, R.style.LoadingLayout_Style); mEmptyImage = a.getResourceId(R.styleable.LoadingLayout_llEmptyImage, NO_ID); mEmptyText = a.getString(R.styleable.LoadingLayout_llEmptyText); mErrorImage = a.getResourceId(R.styleable.LoadingLayout_llErrorImage, NO_ID); mErrorText = a.getString(R.styleable.LoadingLayout_llErrorText); mRetryText = a.getString(R.styleable.LoadingLayout_llRetryText); mTextColor = a.getColor(R.styleable.LoadingLayout_llTextColor, 0xff999999); mTextSize = a.getDimensionPixelSize(R.styleable.LoadingLayout_llTextSize, dp2px(16)); mButtonTextColor = a.getColor(R.styleable.LoadingLayout_llButtonTextColor, 0xff999999); mButtonTextSize = a.getDimensionPixelSize(R.styleable.LoadingLayout_llButtonTextSize, dp2px(16)); mButtonBackground = a.getDrawable(R.styleable.LoadingLayout_llButtonBackground); mEmptyResId = a.getResourceId(R.styleable.LoadingLayout_llEmptyResId, R.layout._loading_layout_empty); mLoadingResId = a.getResourceId(R.styleable.LoadingLayout_llLoadingResId, R.layout._loading_layout_loading); mErrorResId = a.getResourceId(R.styleable.LoadingLayout_llErrorResId, R.layout._loading_layout_error); a.recycle(); } int dp2px(float dp) { return (int) (getResources().getDisplayMetrics().density * dp); } LayoutInflater mInflater; @Override protected void onFinishInflate() { super.onFinishInflate(); if (getChildCount() == 0) { return; } if (getChildCount() > 1) { removeViews(1, getChildCount() - 1); } View view = getChildAt(0); setContentView(view); showLoading(); } private void setContentView(View view) { mContentId = view.getId(); mLayouts.put(mContentId, view); } public LoadingLayout setLoading(@LayoutRes int id) { if (mLoadingResId != id) { remove(mLoadingResId); mLoadingResId = id; } return this; } public LoadingLayout setEmpty(@LayoutRes int id) { if (mEmptyResId != id) { remove(mEmptyResId); mEmptyResId = id; } return this; } public LoadingLayout setOnEmptyInflateListener(OnInflateListener listener) { mOnEmptyInflateListener = listener; if (mOnEmptyInflateListener != null && mLayouts.containsKey(mEmptyResId)) { listener.onInflate(mLayouts.get(mEmptyResId)); } return this; } public LoadingLayout setOnErrorInflateListener(OnInflateListener listener) { mOnErrorInflateListener = listener; if (mOnErrorInflateListener != null && mLayouts.containsKey(mErrorResId)) { listener.onInflate(mLayouts.get(mErrorResId)); } return this; } public LoadingLayout setEmptyImage(@DrawableRes int resId) { mEmptyImage = resId; image(mEmptyResId, R.id.empty_image, mEmptyImage); return this; } public LoadingLayout setEmptyText(String value) { mEmptyText = value; text(mEmptyResId, R.id.empty_text, mEmptyText); return this; } public LoadingLayout setErrorImage(@DrawableRes int resId) { mErrorImage = resId; image(mErrorResId, R.id.error_image, mErrorImage); return this; } public LoadingLayout setErrorText(String value) { mErrorText = value; text(mErrorResId, R.id.error_text, mErrorText); return this; } public LoadingLayout setRetryText(String text) { mRetryText = text; text(mErrorResId, R.id.retry_button, mRetryText); return this; } public LoadingLayout setRetryListener(OnClickListener listener) { mRetryListener = listener; return this; } // public LoadingLayout setTextColor(@ColorInt int color) { // mTextColor = color; // return this; // } // public LoadingLayout setTextSize(@ColorInt int dp) { // mTextColor = dp2px(dp); // return this; // } // public LoadingLayout setButtonTextColor(@ColorInt int color) { // mButtonTextColor = color; // return this; // } // public LoadingLayout setButtonTextSize(@ColorInt int dp) { // mButtonTextColor = dp2px(dp); // return this; // } // public LoadingLayout setButtonBackground(Drawable drawable) { // mButtonBackground = drawable; // return this; // } public void showLoading() { show(mLoadingResId); } public void showEmpty() { show(mEmptyResId); } public void showError() { show(mErrorResId); } public void showContent() { show(mContentId); } private void show(int layoutId) { for (View view : mLayouts.values()) { view.setVisibility(INVISIBLE); } layout(layoutId).setVisibility(VISIBLE); } private void remove(int layoutId) { if (mLayouts.containsKey(layoutId)) { View vg = mLayouts.remove(layoutId); removeView(vg); } } private View layout(int layoutId) { if (mLayouts.containsKey(layoutId)) { return mLayouts.get(layoutId); } View layout = mInflater.inflate(layoutId, this, false); layout.setVisibility(GONE); addView(layout); mLayouts.put(layoutId, layout); if (layoutId == mEmptyResId) { ImageView img = (ImageView) layout.findViewById(R.id.empty_image); if (img != null) { img.setImageResource(mEmptyImage); } TextView view = (TextView) layout.findViewById(R.id.empty_text); if (view != null) { view.setText(mEmptyText); view.setTextColor(mTextColor); view.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize); } if (mOnEmptyInflateListener != null) { mOnEmptyInflateListener.onInflate(layout); } } else if (layoutId == mErrorResId) { ImageView img = (ImageView) layout.findViewById(R.id.error_image); if (img != null) { img.setImageResource(mErrorImage); } TextView txt = (TextView) layout.findViewById(R.id.error_text); if (txt != null) { txt.setText(mErrorText); txt.setTextColor(mTextColor); txt.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize); } TextView btn = (TextView) layout.findViewById(R.id.retry_button); if (btn != null) { btn.setText(mRetryText); btn.setTextColor(mButtonTextColor); btn.setTextSize(TypedValue.COMPLEX_UNIT_PX, mButtonTextSize); btn.setBackground(mButtonBackground); btn.setOnClickListener(mRetryButtonClickListener); } if (mOnErrorInflateListener != null) { mOnErrorInflateListener.onInflate(layout); } } return layout; } private void text(int layoutId, int ctrlId, CharSequence value) { if (mLayouts.containsKey(layoutId)) { TextView view = (TextView) mLayouts.get(layoutId).findViewById(ctrlId); if (view != null) { view.setText(value); } } } private void image(int layoutId, int ctrlId, int resId) { if (mLayouts.containsKey(layoutId)) { ImageView view = (ImageView) mLayouts.get(layoutId).findViewById(ctrlId); if (view != null) { view.setImageResource(resId); } } } }
package servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class HomePageController */ @WebServlet(description = "HomePageController", urlPatterns = { "", "/index", "/home" }) public class HomePageController extends HttpServlet { private static final long serialVersionUID = 1L; /** * Default constructor. */ public HomePageController() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getRequestDispatcher("index.jsp").forward(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
/* * 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.runtime.client; import akka.actor.ActorRef; import akka.actor.Cancellable; import akka.actor.PoisonPill; import akka.actor.Status; import akka.actor.Terminated; import akka.dispatch.OnSuccess; import org.apache.flink.runtime.akka.AkkaUtils; import org.apache.flink.runtime.akka.FlinkUntypedActor; import org.apache.flink.runtime.jobgraph.JobStatus; import org.apache.flink.runtime.leaderretrieval.LeaderRetrievalListener; import org.apache.flink.runtime.leaderretrieval.LeaderRetrievalService; import org.apache.flink.runtime.messages.ExecutionGraphMessages; import org.apache.flink.runtime.messages.JobClientMessages; import org.apache.flink.runtime.messages.JobClientMessages.JobManagerActorRef; import org.apache.flink.runtime.messages.JobClientMessages.JobManagerLeaderAddress; import org.apache.flink.runtime.messages.JobManagerMessages; import org.apache.flink.runtime.util.SerializedThrowable; import org.apache.flink.util.Preconditions; import scala.concurrent.duration.FiniteDuration; import java.util.Objects; import java.util.UUID; /** * Actor which constitutes the bridge between the non-actor code and the JobManager. * This base class handles the connection to the JobManager and notifies in case of timeouts. It also * receives and prints job updates until job completion. */ public abstract class JobClientActor extends FlinkUntypedActor implements LeaderRetrievalListener { private final LeaderRetrievalService leaderRetrievalService; /** timeout for futures */ protected final FiniteDuration timeout; /** true if status messages shall be printed to sysout */ private final boolean sysoutUpdates; /** true if a PoisonPill about to be taken */ private boolean toBeTerminated = false; /** ActorRef to the current leader */ protected ActorRef jobManager; /** leader session ID of the JobManager when this actor was created */ protected UUID leaderSessionID; /** The client which the actor is responsible for */ protected ActorRef client; private Cancellable connectionTimeout; private UUID connectionTimeoutId; public JobClientActor( LeaderRetrievalService leaderRetrievalService, FiniteDuration timeout, boolean sysoutUpdates) { this.leaderRetrievalService = Preconditions.checkNotNull(leaderRetrievalService); this.timeout = Preconditions.checkNotNull(timeout); this.sysoutUpdates = sysoutUpdates; this.jobManager = ActorRef.noSender(); this.leaderSessionID = null; connectionTimeout = null; connectionTimeoutId = null; } @Override public void preStart() { try { leaderRetrievalService.start(this); } catch (Exception e) { LOG.error("Could not start the leader retrieval service."); throw new RuntimeException("Could not start the leader retrieval service.", e); } } @Override public void postStop() { try { leaderRetrievalService.stop(); } catch (Exception e) { LOG.warn("Could not properly stop the leader retrieval service."); } } /** * Hook to be called once a connection has been established with the JobManager. */ protected abstract void connectedToJobManager(); /** * Hook to handle custom client message which are not handled by the base class. * @param message The message to be handled */ protected abstract void handleCustomMessage(Object message); /** * Hook to let the client know about messages that should start a timer for a timeout * @return The message class after which a timeout should be started */ protected abstract Class getClientMessageClass(); @Override protected void handleMessage(Object message) { // =========== State Change Messages =============== if (message instanceof ExecutionGraphMessages.ExecutionStateChanged) { logAndPrintMessage((ExecutionGraphMessages.ExecutionStateChanged) message); } else if (message instanceof ExecutionGraphMessages.JobStatusChanged) { logAndPrintMessage((ExecutionGraphMessages.JobStatusChanged) message); } // ============ JobManager ActorRef resolution =============== else if (message instanceof JobManagerLeaderAddress) { JobManagerLeaderAddress msg = (JobManagerLeaderAddress) message; if (jobManager != null) { // only print this message when we had been connected to a JobManager before logAndPrintMessage("New JobManager elected. Connecting to " + msg.address()); } disconnectFromJobManager(); this.leaderSessionID = msg.leaderSessionID(); if (msg.address() != null) { // Resolve the job manager leader address to obtain an ActorRef AkkaUtils.getActorRefFuture(msg.address(), getContext().system(), timeout) .onSuccess(new OnSuccess<ActorRef>() { @Override public void onSuccess(ActorRef result) throws Throwable { getSelf().tell(decorateMessage(new JobManagerActorRef(result)), ActorRef.noSender()); } }, getContext().dispatcher()); } else if (isClientConnected() && connectionTimeoutId == null) { // msg.address == null means that the leader has lost its leadership registerConnectionTimeout(); } } else if (message instanceof JobManagerActorRef) { // Resolved JobManager ActorRef JobManagerActorRef msg = (JobManagerActorRef) message; connectToJobManager(msg.jobManager()); logAndPrintMessage("Connected to JobManager at " + msg.jobManager() + " with leader session id " + leaderSessionID + '.'); connectedToJobManager(); } // =========== Job Life Cycle Messages =============== // acknowledgement to submit job is only logged, our original // client is only interested in the final job result else if (message instanceof JobManagerMessages.JobResultMessage) { if (LOG.isDebugEnabled()) { LOG.debug("Received {} message from JobManager", message.getClass().getSimpleName()); } // forward the success to the original client if (isClientConnected()) { this.client.tell(decorateMessage(message), getSelf()); } terminate(); } // =========== Actor / Communication Failure / Timeouts =============== else if (message instanceof Terminated) { ActorRef target = ((Terminated) message).getActor(); if (jobManager.equals(target)) { LOG.info("Lost connection to JobManager {}. Triggering connection timeout.", jobManager.path()); disconnectFromJobManager(); if (isClientConnected()) { if (connectionTimeoutId == null) { // only register a connection timeout if we haven't done this before registerConnectionTimeout(); } } } else { LOG.warn("Received 'Terminated' for unknown actor " + target); } } else if (message instanceof JobClientMessages.ConnectionTimeout) { JobClientMessages.ConnectionTimeout timeoutMessage = (JobClientMessages.ConnectionTimeout) message; if (Objects.equals(connectionTimeoutId, timeoutMessage.id())) { // check if we haven't found a job manager yet if (!isJobManagerConnected()) { final JobClientActorConnectionTimeoutException errorMessage = new JobClientActorConnectionTimeoutException("Lost connection to the JobManager."); final Object replyMessage = decorateMessage(new Status.Failure(errorMessage)); if (isClientConnected()) { client.tell( replyMessage, getSelf()); } // Connection timeout reached, let's terminate terminate(); } } else { LOG.debug("Received outdated connection timeout."); } } // =========== Message Delegation =============== else if (!isJobManagerConnected() && getClientMessageClass().equals(message.getClass())) { LOG.info( "Received {} but there is no connection to a JobManager yet.", message); // We want to submit/attach to a job, but we haven't found a job manager yet. // Let's give him another chance to find a job manager within the given timeout. if (connectionTimeoutId == null) { // only register the connection timeout once registerConnectionTimeout(); } handleCustomMessage(message); } else { if (!toBeTerminated) { handleCustomMessage(message); } else { // we're about to receive a PoisonPill because toBeTerminated == true String msg = getClass().getName() + " is about to be terminated. Therefore, the " + "job submission cannot be executed."; LOG.error(msg); getSender().tell( decorateMessage(new Status.Failure(new Exception(msg))), ActorRef.noSender()); } } } @Override protected UUID getLeaderSessionID() { return leaderSessionID; } protected void logAndPrintMessage(String message) { LOG.info(message); if (sysoutUpdates) { System.out.println(message); } } private void logAndPrintMessage(ExecutionGraphMessages.ExecutionStateChanged message) { LOG.info(message.toString()); if (sysoutUpdates) { System.out.println(message.toString()); } } private void logAndPrintMessage(ExecutionGraphMessages.JobStatusChanged message) { // by default, this only prints the status, and not any exception. // in state FAILING, we report the exception in addition if (message.newJobStatus() != JobStatus.FAILING || message.error() == null) { LOG.info(message.toString()); if (sysoutUpdates) { System.out.println(message.toString()); } } else { Throwable error = SerializedThrowable.get(message.error(), getClass().getClassLoader()); LOG.info(message.toString(), error); if (sysoutUpdates) { System.out.println(message.toString()); message.error().printStackTrace(System.out); } } } @Override public void notifyLeaderAddress(String leaderAddress, UUID leaderSessionID) { getSelf().tell( decorateMessage(new JobManagerLeaderAddress(leaderAddress, leaderSessionID)), getSelf()); } @Override public void handleError(Exception exception) { LOG.error("Error occurred in the LeaderRetrievalService.", exception); getSelf().tell(decorateMessage(PoisonPill.getInstance()), getSelf()); } private void disconnectFromJobManager() { LOG.info("Disconnect from JobManager {}.", jobManager); if (jobManager != ActorRef.noSender()) { getContext().unwatch(jobManager); jobManager = ActorRef.noSender(); } leaderSessionID = null; } private void connectToJobManager(ActorRef jobManager) { LOG.info("Connect to JobManager {}.", jobManager); if (jobManager != ActorRef.noSender()) { getContext().unwatch(jobManager); } this.jobManager = jobManager; getContext().watch(jobManager); unregisterConnectionTimeout(); } protected void terminate() { LOG.info("Terminate JobClientActor."); toBeTerminated = true; disconnectFromJobManager(); getSelf().tell(decorateMessage(PoisonPill.getInstance()), ActorRef.noSender()); } private boolean isJobManagerConnected() { return jobManager != ActorRef.noSender(); } protected boolean isClientConnected() { return client != ActorRef.noSender(); } private void registerConnectionTimeout() { if (connectionTimeout != null) { connectionTimeout.cancel(); } connectionTimeoutId = UUID.randomUUID(); connectionTimeout = getContext().system().scheduler().scheduleOnce( timeout, getSelf(), decorateMessage(new JobClientMessages.ConnectionTimeout(connectionTimeoutId)), getContext().dispatcher(), ActorRef.noSender() ); } private void unregisterConnectionTimeout() { if (connectionTimeout != null) { connectionTimeout.cancel(); connectionTimeout = null; connectionTimeoutId = null; } } }
/* * This file is/was part of Treasury. To read more information about Treasury such as its licensing, see <https://github.com/lokka30/Treasury>. */ package me.lokka30.treasury.api.economy; import java.util.Collection; import java.util.HashSet; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.CompletableFuture; import me.lokka30.treasury.api.economy.account.Account; import me.lokka30.treasury.api.economy.account.AccountPermission; import me.lokka30.treasury.api.economy.account.NonPlayerAccount; import me.lokka30.treasury.api.economy.account.PlayerAccount; import me.lokka30.treasury.api.economy.currency.Currency; import me.lokka30.treasury.api.economy.misc.EconomyAPIVersion; import me.lokka30.treasury.api.economy.misc.OptionalEconomyApiFeature; import me.lokka30.treasury.api.economy.response.EconomyException; import me.lokka30.treasury.api.economy.response.EconomyFailureReason; import me.lokka30.treasury.api.economy.response.EconomySubscriber; import me.lokka30.treasury.api.common.misc.TriState; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Implementors providing and managing economy data create a class * which implements this interface to be registered in * the specific platform they're implementing it for. * * @author lokka30, Jikoo, MrIvanPlays, NoahvdAa, creatorfromhell * @since {@link me.lokka30.treasury.api.economy.misc.EconomyAPIVersion#v1_0 v1.0} */ public interface EconomyProvider { /** * Get the version of the Treasury API the {@code EconomyProvider} is based on. * * <p>Warning: The Treasury API version is completely different to any other platform version, * such as the 'api-version' value in the Bukkit implementation's plugin.yml file. * <p>Warning: Do not use {@link EconomyAPIVersion#getCurrentAPIVersion()}, that method is for * internal Treasury use only. * <b>You must only use the constants provided.</b> * * @return the API version * @author lokka30, MrIvanPlays * @since {@link me.lokka30.treasury.api.economy.misc.EconomyAPIVersion#v1_0 v1.0} */ @NotNull EconomyAPIVersion getSupportedAPIVersion(); /** * Check which optional Treasury Economy API features the Economy Provider supports. * * <p>There are a few features which Treasury allows Economy Providers to support * at their option. This is because certain features within Treasury may not be * suitable or appealing for some Economy Providers to implement. We try to enforce * as much of the API to be implemented as possible, however, few features can be * justified as being optional to implement. * * <p>The Economy Provider should return a Set of constants representing which of * Treasury's optional Economy API features are supported by the Economy Provider. * This set can be empty if none of the optional features are supported by the * Economy Provider. * * @return the set of optional supported features from the economy provider/ * @author lokka30 * @see OptionalEconomyApiFeature * @since {@link me.lokka30.treasury.api.economy.misc.EconomyAPIVersion#v1_0 v1.0} */ @NotNull Set<OptionalEconomyApiFeature> getSupportedOptionalEconomyApiFeatures(); /** * Request whether a user has an associated {@link PlayerAccount}. * * @param accountId the {@link UUID} of the account owner * @param subscription the {@link EconomySubscriber} accepting the resulting value * @author Jikoo * @since {@link me.lokka30.treasury.api.economy.misc.EconomyAPIVersion#v1_0 v1.0} */ void hasPlayerAccount( @NotNull UUID accountId, @NotNull EconomySubscriber<Boolean> subscription ); /** * Request an existing {@link PlayerAccount} for a user. * * @param accountId the {@link UUID} of the account owner * @param subscription the {@link EconomySubscriber} accepting the resulting value * @author Jikoo * @since {@link me.lokka30.treasury.api.economy.misc.EconomyAPIVersion#v1_0 v1.0} */ void retrievePlayerAccount( @NotNull UUID accountId, @NotNull EconomySubscriber<PlayerAccount> subscription ); /** * Request the creation of a {@link PlayerAccount} for a user. * * @param accountId the {@link UUID} of the account owner * @param subscription the {@link EconomySubscriber} accepting the resulting value * @author Jikoo * @since {@link me.lokka30.treasury.api.economy.misc.EconomyAPIVersion#v1_0 v1.0} */ void createPlayerAccount( @NotNull UUID accountId, @NotNull EconomySubscriber<PlayerAccount> subscription ); /** * Request all {@link UUID UUIDs} with associated {@link PlayerAccount PlayerAccounts}. * * @param subscription the {@link EconomySubscriber} accepting the resulting value * @author Jikoo * @since {@link me.lokka30.treasury.api.economy.misc.EconomyAPIVersion#v1_0 v1.0} */ void retrievePlayerAccountIds(@NotNull EconomySubscriber<Collection<UUID>> subscription); /** * Request whether an identifier has an associated {@link Account}. * <p> * This method is safe for {@link NonPlayerAccount non-player accounts}. * <p> * This could return an {@link NonPlayerAccount} or an {@link PlayerAccount}. * * @param identifier the identifier of the account * @param subscription the {@link EconomySubscriber} accepting the resulting value * @author Jikoo * @since {@link me.lokka30.treasury.api.economy.misc.EconomyAPIVersion#v1_0 v1.0} */ void hasAccount(@NotNull String identifier, @NotNull EconomySubscriber<Boolean> subscription); /** * Request an existing {@link Account} for a specific identifier. * <p> * This method is safe for {@link NonPlayerAccount non-player accounts}. * <p> * This could return an {@link NonPlayerAccount} or an {@link PlayerAccount}. * * @param identifier the identifier of the account * @param subscription the {@link EconomySubscriber} accepting the resulting value * @author Jikoo * @since {@link me.lokka30.treasury.api.economy.misc.EconomyAPIVersion#v1_0 v1.0} */ void retrieveAccount( @NotNull String identifier, @NotNull EconomySubscriber<Account> subscription ); /** * Request the creation of a {@link Account} for a specific identifier. * <p> * This method is safe for {@link NonPlayerAccount non-player accounts}. * <p> * This could return an {@link NonPlayerAccount} or an {@link PlayerAccount}. * * @param identifier the identifier of the account * @param subscription the {@link EconomySubscriber} accepting the resulting value * @author Jikoo * @since {@link me.lokka30.treasury.api.economy.misc.EconomyAPIVersion#v1_0 v1.0} */ default void createAccount( @NotNull String identifier, @NotNull EconomySubscriber<Account> subscription ) { createAccount(null, identifier, subscription); } /** * Request the creation of a {@link Account} for a specific identifier {@code identifier} with {@link String} {@code * name}. * <p> * This method is safe for {@link NonPlayerAccount non-player accounts}. * <p> * This could return an {@link NonPlayerAccount} or an {@link PlayerAccount}. * * @param name the human-readable name of the account * @param identifier the unique identifier of the account * @param subscription the {@link EconomySubscriber} accepting the resulting value * @author MrIvanPlays, Jikoo * @since {@link EconomyAPIVersion#v1_0 v1.0} */ void createAccount( @Nullable String name, @NotNull String identifier, @NotNull EconomySubscriber<Account> subscription ); /** * Request all identifiers with associated {@link Account Accounts}. * * @param subscription the {@link EconomySubscriber} accepting the resulting value * @author Jikoo * @since {@link me.lokka30.treasury.api.economy.misc.EconomyAPIVersion#v1_0 v1.0} */ void retrieveAccountIds(@NotNull EconomySubscriber<Collection<String>> subscription); /** * Request all identifiers with associated {@link NonPlayerAccount NonPlayer Accounts}. * * @param subscription the {@link EconomySubscriber} accepting the resulting value * @author Jikoo * @since {@link me.lokka30.treasury.api.economy.misc.EconomyAPIVersion#v1_0 v1.0} */ void retrieveNonPlayerAccountIds(@NotNull EconomySubscriber<Collection<String>> subscription); /** * Request all {@link NonPlayerAccount non player accounts} the given player is a member of. * * @param playerId the player * @param subscription the {@link EconomySubscriber} accepting the resulting value * @author MrNemo64, MrIvanPlays * @since {@link me.lokka30.treasury.api.economy.misc.EconomyAPIVersion#v1_0 v1.0} */ default void retrieveAllAccountsPlayerIsMemberOf( @NotNull UUID playerId, @NotNull EconomySubscriber<Collection<String>> subscription ) { Objects.requireNonNull(playerId, "playerId"); Objects.requireNonNull(subscription, "subscription"); EconomySubscriber.asFuture(this::retrieveAccountIds).exceptionally(throwable -> { if (throwable instanceof EconomyException) { subscription.fail((EconomyException) throwable); } else { subscription.fail(new EconomyException(EconomyFailureReason.OTHER_FAILURE, throwable )); } return new HashSet<>(); }).thenAccept(identifiers -> { if (identifiers.isEmpty()) { subscription.succeed(identifiers); return; } Set<String> ret = new HashSet<>(); for (String identifier : identifiers) { EconomySubscriber.<Account>asFuture(subscriber -> retrieveAccount(identifier, subscriber )).exceptionally(throwable -> { if (throwable instanceof EconomyException) { subscription.fail((EconomyException) throwable); } else { subscription.fail(new EconomyException(EconomyFailureReason.OTHER_FAILURE, throwable )); } return null; }).thenCompose(account -> { if (account == null) { return CompletableFuture.completedFuture(false); } if (!(account instanceof NonPlayerAccount)) { return CompletableFuture.completedFuture(false); } return EconomySubscriber.asFuture(subscriber -> account.isMember(playerId, subscriber )); }).thenAccept(val -> { if (val) { ret.add(identifier); } }); } subscription.succeed(ret); }); } /** * Request all the {@link NonPlayerAccount non-player accounts} where the given player has the given permissions. * * @param playerId the player * @param subscription the {@link EconomySubscriber} accepting the resulting value * @param permissions the permissions that the given player has to have on the {@link NonPlayerAccount account} * @author MrNemo64, MrIvanPlays * @see #retrieveAllAccountsPlayerIsMemberOf(UUID, EconomySubscriber) * @since {@link me.lokka30.treasury.api.economy.misc.EconomyAPIVersion#v1_0 v1.0} */ default void retrieveAllAccountsPlayerHasPermission( @NotNull UUID playerId, @NotNull EconomySubscriber<Collection<String>> subscription, @NotNull AccountPermission @NotNull ... permissions ) { Objects.requireNonNull(playerId, "playerId"); Objects.requireNonNull(subscription, "subscription"); Objects.requireNonNull(permissions, "permissions"); EconomySubscriber.asFuture(this::retrieveAccountIds).exceptionally(throwable -> { if (throwable instanceof EconomyException) { subscription.fail((EconomyException) throwable); } else { subscription.fail(new EconomyException(EconomyFailureReason.OTHER_FAILURE, throwable )); } return new HashSet<>(); }).thenAccept(identifiers -> { if (identifiers.isEmpty()) { subscription.succeed(identifiers); return; } Set<String> ret = new HashSet<>(); for (String identifier : identifiers) { EconomySubscriber.<Account>asFuture(subscriber -> retrieveAccount(identifier, subscriber )).exceptionally(throwable -> { if (throwable instanceof EconomyException) { subscription.fail((EconomyException) throwable); } else { subscription.fail(new EconomyException(EconomyFailureReason.OTHER_FAILURE, throwable )); } return null; }).thenCompose(account -> { if (account == null) { return CompletableFuture.completedFuture(false); } if (!(account instanceof NonPlayerAccount)) { return CompletableFuture.completedFuture(false); } CompletableFuture<Boolean> ret1 = new CompletableFuture<>(); account.hasPermission(playerId, new EconomySubscriber<TriState>() { @Override public void succeed(@NotNull final TriState triState) { ret1.complete(triState == TriState.TRUE); } @Override public void fail(@NotNull final EconomyException exception) { ret1.completeExceptionally(exception); } }, permissions); return ret1; }).thenAccept(val -> { if (val) { ret.add(identifier); } }); } subscription.succeed(ret); }); } /** * Get the primary or main {@link Currency} of the economy. * * @return the primary currency * @author Jikoo * @since {@link me.lokka30.treasury.api.economy.misc.EconomyAPIVersion#v1_0 v1.0} */ @NotNull Currency getPrimaryCurrency(); /** * Used to find a currency based on a specific identifier. * * @param identifier The {@link Currency#getIdentifier()} of the {@link Currency} we are searching for. * @return The {@link Optional} containing the search result. This will contain the * resulting {@link Currency} if it exists, otherwise it will return {@link Optional#empty()}. * @author creatorfromhell * @since {@link me.lokka30.treasury.api.economy.misc.EconomyAPIVersion#v1_0 v1.0} */ Optional<Currency> findCurrency(@NotNull String identifier); /** * Used to get a set of every {@link Currency} object for the server. * * @return A set of every {@link Currency} object that is available for the server. * @author creatorfromhell * @since {@link me.lokka30.treasury.api.economy.misc.EconomyAPIVersion#v1_0 v1.0} */ Set<Currency> getCurrencies(); /** * Get the String identifier of the primary or main {@link Currency} of the economy. * * @return the String identifier identifying the primary currency * @author lokka30 * @since {@link me.lokka30.treasury.api.economy.misc.EconomyAPIVersion#v1_0 v1.0} */ @NotNull default String getPrimaryCurrencyId() { return getPrimaryCurrency().getIdentifier(); } /** * Used to register a currency with the {@link EconomyProvider} to be utilized by * other plugins. * * @param currency The currency to register with the {@link EconomyProvider}. * @param subscription The {@link EconomySubscriber} representing the result of the * attempted {@link Currency} registration with an {@link Boolean}. * This will be {@link Boolean#TRUE} if it was registered, otherwise * it'll be {@link Boolean#FALSE}. * @author creatorfromhell * @since {@link me.lokka30.treasury.api.economy.misc.EconomyAPIVersion#v1_0 v1.0} */ void registerCurrency( @NotNull Currency currency, @NotNull EconomySubscriber<Boolean> subscription ); }
package framework.jdbc; /** * DBMng에서 사용되는 status 값 ENUM * @author 박유현 * @since 2018-12-25 */ public enum DBMngStatus { RESOURCES_NOT_CLOSED("DBMng status - unclosed DB resources detected."), //자원이 반환되지 않은 상태 SET_CONNECTION_ERR("DBMng status - Connection error."), //커넥션이 제대로 연결되지 않아 사용할 수 없는 상태 NOT_MATCH_PARAM_ERR("DBMng status - Not matched parameters."), //PreparedStatement 객체의 모든 파라미터가 채워지지 않은 상태 ERROR("DBMng status - Unknown ERROR!"), //알수없는 에러가 발생하여 사용할 수 없는 상태 INCORRECT_STATUS_ERR("DBMng status - Incorrect STATUS."), //메소드 사용 시 알맞지 않는 순서로 접근한 상태 COLUMN_NOT_FOUND_ERR("DBMng status - Columnlabel not found."), //get~~ 메소드에서 컬럼명을 사용해 값을 불러올 시 컬럼명이 맞지않아 오류가 발생한 상태 NOT_CONNECTED("DBMng status - Not initiated yet."), //DBMng객체가 생성만 되어있는 상태 CONNECTED("DBMng status - Connected."), //Connection이 설정된 상태 STATEMENT_READY("DBMng status - Ready to use PreparedStatement."), //PreparedStatement가 선언된 상태 PARAMETER_READY("DBMng status - Ready to execute PreparedStatement."), //PreparedStatement의 파라미터가 모두 추가되었거나 추가할 파라미터가 없어 사용할 준비가 된 상태 EXECUTED("DBMng status - Executed."), //Execute 된 상태 CLOSED("DBMng status - Closed."); //모든 자원이 반환된 상태, setConnection(Connection connection)을 사용하여 새로운 연결을 구성 할 수 있음 private String statusMsg; private DBMngStatus(String statusMsg) { this.statusMsg = statusMsg; } public String getStatusMsg() { return statusMsg; } }
package edu.virginia.vcgr.genii.gjt.gui.fs; import java.awt.Component; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.ListCellRenderer; import edu.virginia.vcgr.genii.gjt.data.fs.FilesystemType; @SuppressWarnings("rawtypes") class FilesystemBoxRenderer extends JLabel implements ListCellRenderer { static final long serialVersionUID = 0L; FilesystemBoxRenderer() { setOpaque(true); setHorizontalAlignment(LEFT); setVerticalAlignment(CENTER); } @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (value == null) value = FilesystemType.Default; FilesystemType filesystemType = (FilesystemType) value; if (isSelected) { setBackground(list.getSelectionBackground()); setForeground(list.getSelectionForeground()); } else { setBackground(list.getBackground()); setForeground(list.getForeground()); } setIcon(filesystemType.icon()); setText(filesystemType.toString()); setFont(list.getFont()); return this; } }
/** * Copyright 2020 Claudio Montenegro Chaves - CMC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package br.tec.cmc.facildb.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class DateUtil { public static final String PATTERN_DATE_HOUR = "yyyy-MM-dd HH:mm:ss"; public static final String PATTERN_DATE_T_HOUR = "yyyy-MM-dd'T'HH:mm:ss"; public static final String PATTERN_DATE_HOUR_MILISECONDS = "yyyy-MM-dd HH:mm:ss.SSS"; public static final String PATTERN_DATE_T_HOUR_MILISECONDS = "yyyy-MM-dd'T'HH:mm:ss.SSS"; public static final String PATTERN_DATE_ONLY = "yyyy-MM-dd"; private DateUtil() { throw new IllegalStateException("Utility class"); } public static String dateToString(Date dt, String pattern) { SimpleDateFormat sdt = new SimpleDateFormat(pattern); return sdt.format(dt); } public static Date stringToDate(String sDate) throws ParseException { return DateUtil.stringToDate(sDate, PATTERN_DATE_HOUR_MILISECONDS); } public static Date stringToDate(String sDate, String pattern) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat(pattern); sDate = sDate.replace("T", " "); return sdf.parse(sDate); } }
package io.github.indicode.fabric.itsmine; import blue.endless.jankson.annotation.Nullable; import io.github.indicode.fabric.permissions.Thimble; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; import net.minecraft.util.Identifier; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Direction; import net.minecraft.world.dimension.DimensionType; import java.security.MessageDigest; import java.util.*; /** * @author Indigo Amann */ public class Claim { public String name; public BlockPos min, max; public @Nullable BlockPos tpPos; public DimensionType dimension; public List<Claim> children = new ArrayList<>(); public ClaimSettings settings = new ClaimSettings(); public PermissionManager permissionManager = new PermissionManager(); public UUID claimBlockOwner = null; public String customOwnerName, enterMessage, leaveMessage; public Claim() { } public Claim(CompoundTag tag) { fromTag(tag); } public Claim(String name, UUID claimBlockOwner, BlockPos min, BlockPos max, DimensionType dimension) { this(name, claimBlockOwner, min, max, dimension, null); } public Claim(String name, UUID claimBlockOwner, BlockPos min, BlockPos max, DimensionType dimension, @Nullable BlockPos tpPos) { this.claimBlockOwner = claimBlockOwner; this.min = min; this.max = max; this.name = name; this.dimension = dimension; this.tpPos = tpPos; } public boolean includesPosition(BlockPos pos) { return pos.getX() >= min.getX() && pos.getY() >= min.getY() && pos.getZ() >= min.getZ() && pos.getX() <= max.getX() && pos.getY() <= max.getY() && pos.getZ() <= max.getZ(); } public boolean intersects(Claim claim) { return intersects(claim, true); } public boolean intersects(Claim claim, boolean checkOther) { if (claim == null) return false; if (!claim.dimension.equals(dimension)) return false; BlockPos a = min, b = max, c = new BlockPos(max.getX(), min.getY(), min.getZ()), d = new BlockPos(min.getX(), max.getY(), min.getZ()), e = new BlockPos(min.getX(), min.getY(), max.getZ()), f = new BlockPos(max.getX(), max.getY(), min.getZ()), g = new BlockPos(max.getX(), min.getY(), max.getZ()), h = new BlockPos(min.getX(), max.getY(), max.getZ()); if ( claim.includesPosition(a) || claim.includesPosition(b) || claim.includesPosition(c) || claim.includesPosition(d) || claim.includesPosition(e) || claim.includesPosition(f) || claim.includesPosition(g) || claim.includesPosition(h) ) return true; else return checkOther && claim.intersects(this, false); } public Claim getZoneCovering(BlockPos pos) { if (includesPosition(pos)) { for (Claim child : children) { Claim value = child.getZoneCovering(pos); if (value != null) return value; } return this; } else return null; } /*public ClaimSettings getSettingsAt(BlockPos pos) { Claim at = getZoneCovering(pos); if (at != null) { return at.settings; } else return settings; } public ClaimPermissions getPermissionsAt(UUID player, BlockPos pos) { Claim at = getZoneCovering(pos); if (at != null) { return at.getPlayerPermissions(player); } else return settings; }*/ public boolean hasPermission(UUID player, Permission permission) { return ClaimManager.INSTANCE.ignoringClaims.contains(player) || permissionManager.hasPermission(player, permission); } //public boolean hasPermissionAt(UUID player, ClaimPermissions.Permission permission, BlockPos pos) { // return player.equals(owner) || ClaimManager.INSTANCE.ignoringClaims.contains(player) || getPermissionsAt(player, pos).hasPermission(permission); //} public void addSubzone(Claim claim) { if (claim != null && claim.dimension == dimension && includesPosition(claim.min) && includesPosition(claim.max)) { children.add(claim); } else throw new IllegalArgumentException("Subzone must be inside the original claim, in the same dimension, and not null"); } public void expand(BlockPos min, BlockPos max) { this.min = this.min.add(min); this.max = this.max.add(max); } public BlockPos getSize() { return max.subtract(min); } public void expand(BlockPos modifier) { if (modifier.getX() > 0) max = max.add(modifier.getX(), 0, 0); else min = min.add(modifier.getX(), 0, 0); if (modifier.getY() > 0) max = max.add(0, modifier.getY(), 0); else min = min.add(0, modifier.getY(), 0); if (modifier.getZ() > 0) max = max.add(0, 0, modifier.getZ()); else min = min.add(0, 0, modifier.getZ()); } public boolean shrink(BlockPos modifier) { if (modifier.getX() < 0) { if (min.getX() - modifier.getX() > max.getX()) return false; min = min.add(-modifier.getX(), 0, 0); } else { if (max.getX() - modifier.getX() < min.getX()) return false; max = max.add(-modifier.getX(), 0, 0); } if (modifier.getY() < 0) { if (min.getY() - modifier.getY() > max.getY()) return false; min = min.add(0, -modifier.getY(), 0); } else { if (max.getY() - modifier.getY() < min.getY()) return false; max = max.add(0, -modifier.getY(), 0); } if (modifier.getZ() < 0) { if (min.getZ() - modifier.getZ() > max.getZ()) return false; min = min.add(0, 0, -modifier.getZ()); } else { if (max.getZ() - modifier.getZ() < min.getZ()) return false; max = max.add(0, 0, -modifier.getZ()); } return true; } public void expand(Direction direction, int distance) { expand(new BlockPos(direction.getOffsetX() * distance, direction.getOffsetY() * distance, direction.getOffsetZ() * distance)); } public boolean shrink(Direction direction, int distance) { return shrink(new BlockPos(direction.getOffsetX() * distance, direction.getOffsetY() * distance, direction.getOffsetZ() * distance)); } public int getArea() { return getSize().getX() * (Config.claims2d ? 1 : getSize().getY()) * getSize().getZ(); } public CompoundTag toTag() { CompoundTag tag = new CompoundTag(); { CompoundTag pos = new CompoundTag(); pos.putInt("minX", min.getX()); pos.putInt("minY", min.getY()); pos.putInt("minZ", min.getZ()); pos.putInt("maxX", max.getX()); pos.putInt("maxY", max.getY()); pos.putInt("maxZ", max.getZ()); pos.putString("dimension", DimensionType.getId(dimension).toString()); if (tpPos != null) { pos.putInt("tpX", this.tpPos.getX()); pos.putInt("tpY", this.tpPos.getY()); pos.putInt("tpZ", this.tpPos.getZ()); } tag.put("position", pos); } { ListTag subzoneList = new ListTag(); children.forEach(it -> subzoneList.add(it.toTag())); tag.put("subzones", subzoneList); } { tag.put("settings", settings.toTag()); tag.put("permissions", permissionManager.toNBT()); if (claimBlockOwner != null) tag.putUuid("top_owner", claimBlockOwner); } { CompoundTag meta = new CompoundTag(); if (this.enterMessage != null) meta.putString("enterMsg", this.enterMessage); if (this.leaveMessage != null) meta.putString("leaveMsg", this.leaveMessage); tag.put("meta", meta); } if (this.customOwnerName != null) tag.putString("cOwnerName", this.customOwnerName); tag.putString("name", name); return tag; } public void fromTag(CompoundTag tag) { { CompoundTag pos = tag.getCompound("position"); int minX = pos.getInt("minX"); int minY = pos.getInt("minY"); int minZ = pos.getInt("minZ"); int maxX = pos.getInt("maxX"); int maxY = pos.getInt("maxY"); int maxZ = pos.getInt("maxZ"); if (maxY == 0) maxY = 255; this.min = new BlockPos(minX, minY, minZ); this.max = new BlockPos(maxX, maxY, maxZ); if (pos.contains("tpX") && pos.contains("tpY") && pos.contains("tpZ")) { this.tpPos = new BlockPos(pos.getInt("tpX"), pos.getInt("tpY"), pos.getInt("tpZ")); } this.dimension = DimensionType.byId(new Identifier(pos.getString("dimension"))); } { children = new ArrayList<>(); ListTag subzoneList = (ListTag) tag.get("subzones"); if (subzoneList != null) { subzoneList.forEach(it -> children.add(new Claim((CompoundTag) it))); } } { this.settings = new ClaimSettings(tag.getCompound("settings")); permissionManager = new PermissionManager(); permissionManager.fromNBT(tag.getCompound("permissions")); if (tag.containsUuid("top_owner")) claimBlockOwner = tag.getUuid("top_owner"); } { CompoundTag meta = tag.getCompound("meta"); if (meta.contains("enterMsg")) this.enterMessage = meta.getString("enterMsg"); if (meta.contains("leaveMsg")) this.leaveMessage = meta.getString("leaveMsg"); } if (tag.contains("cOwnerName")) this.customOwnerName = tag.getString("cOwnerName"); name = tag.getString("name"); } public boolean is2d() { return min.getY() == 0 && max.getY() == 255; } public enum Permission { //Admin DELETE_CLAIM("delete_claim", "Delete Claim"), MODIFY_SIZE("modify_size", "Modify Claim Size"), MODIFY_FLAGS("modify_flags", "Change Claim Flags"), MODIFY_PERMISSIONS("modify_permissions", "Change Permissions"), //Normal MODIFY_PROPERTIES("modify_properties", "Modify Claim Properties"), SPAWN_PROTECT("spawn_protect", "Spawn Protection Bypass"), BUILD("build", "Place/Break Blocks"), INTERACT_BLOCKS("interact_blocks", "Interact With Blocks"), INTERACT_BLOCKS_WITH_ITEMS("interact_blocks_with_items", "Use Block Modifying items"), PRESS_BUTTONS("press_buttons", "Press Buttons"), USE_LEVERS("use_levers", "Use Levers"), OPEN_DOORS("open_doors", "Use Doors"), INTERACT_ENTITY("interact_entity", "Entity Interaction"), ENTITY_DAMAGE("entity_damage", "Hurt Entities"), FLIGHT("flight", "Flight"), TELEPORT("teleport", "Player Teleport Access"), ENTER("enter", "Enter the Claim"); String id, name; Permission(String id, String name) { this.id = id; this.name = name; } public static Permission byId(String id) { for (Permission permission: values()) { if (permission.id.equals(id)) return permission; } return null; } } public static class PermissionManager { public ClaimPermissionMap defaults = new DefaultPermissionMap(); protected Map<UUID, ClaimPermissionMap> playerPermissions = new HashMap<>(); protected Map<String, ClaimPermissionMap> groupPermissions = new HashMap<>(); public boolean isPermissionSet(UUID player, Permission permission) { return playerPermissions.get(player) != null && playerPermissions.get(player).isPermissionSet(permission); } public boolean hasPermission(UUID player, Permission permission) { if (isPermissionSet(player, permission)) return playerPermissions.get(player).hasPermission(permission); for (Map.Entry<String, ClaimPermissionMap> entry : groupPermissions.entrySet()) { if (Thimble.PERMISSIONS.hasPermission(entry.getKey(), player) && entry.getValue().hasPermission(permission)) return true; } return defaults.hasPermission(permission); } public void setPermission(UUID player, Permission permission, boolean enabled) { if (!playerPermissions.containsKey(player)) playerPermissions.put(player, new DefaultPermissionMap()); playerPermissions.get(player).setPermission(permission, enabled); } public void clearPermission(UUID player, Permission permission) { if (!playerPermissions.containsKey(player)) playerPermissions.put(player, new DefaultPermissionMap()); playerPermissions.get(player).clearPermission(permission); } public void resetPermissions(UUID player) { playerPermissions.remove(player); } public boolean isPermissionSet(String group, Permission permission) { return groupPermissions.get(group) != null && groupPermissions.get(group).isPermissionSet(permission); } public boolean hasPermission(String group, Permission permission) { if (isPermissionSet(group, permission)) return groupPermissions.get(group).hasPermission(permission); return defaults.hasPermission(permission); } public void setPermission(String group, Permission permission, boolean enabled) { if (!groupPermissions.containsKey(group)) groupPermissions.put(group, new DefaultPermissionMap()); groupPermissions.get(group).setPermission(permission, enabled); } public void clearPermission(String group, Permission permission) { if (!groupPermissions.containsKey(group)) groupPermissions.put(group, new DefaultPermissionMap()); groupPermissions.get(group).clearPermission(permission); } public void resetPermissions(String group) { groupPermissions.remove(group); } public CompoundTag toNBT() { CompoundTag tag = new CompoundTag(); tag.put("defaults", defaults.toRegisteredNBT()); { CompoundTag players = new CompoundTag(); if (playerPermissions != null) playerPermissions.forEach((player, map) -> {if (player != null && map != null) players.put(player.toString(), map.toRegisteredNBT());}); tag.put("players", players); } { CompoundTag groups = new CompoundTag(); groupPermissions.forEach((group, map) -> groups.put(group, map.toRegisteredNBT())); tag.put("groups", groups); } return tag; } public void fromNBT(CompoundTag tag) { defaults = ClaimPermissionMap.fromRegisteredNBT(tag.getCompound("defaults")); { CompoundTag players = tag.getCompound("players"); playerPermissions.clear(); players.getKeys().forEach(player -> playerPermissions.put(UUID.fromString(player), ClaimPermissionMap.fromRegisteredNBT(players.getCompound(player)))); } { CompoundTag groups = tag.getCompound("groups"); groupPermissions.clear(); groups.getKeys().forEach(group -> groupPermissions.put(group, ClaimPermissionMap.fromRegisteredNBT(groups.getCompound(group)))); } } } public static abstract class ClaimPermissionMap { protected static HashMap<String, Class<? extends ClaimPermissionMap>> mapTypes = new HashMap<>(); protected static HashMap<Class<? extends ClaimPermissionMap>, String> reverseMapTypes = new HashMap<>(); static { mapTypes.put("default", DefaultPermissionMap.class); reverseMapTypes.put(DefaultPermissionMap.class, "default"); mapTypes.put("inverted", InvertedPermissionMap.class); reverseMapTypes.put(InvertedPermissionMap.class, "inverted"); } public abstract boolean isPermissionSet(Permission permission); public abstract boolean hasPermission(Permission permission); public abstract void setPermission(Permission permission, boolean has); public abstract void clearPermission(Permission permission); public abstract void fromNBT(CompoundTag tag); public abstract CompoundTag toNBT(); public CompoundTag toRegisteredNBT() { CompoundTag tag = toNBT(); tag.putString("type", reverseMapTypes.get(this.getClass())); return tag; } public static ClaimPermissionMap fromRegisteredNBT(CompoundTag tag) { String type = tag.getString("type"); tag.remove("type"); Class<? extends ClaimPermissionMap> clazz = mapTypes.get(type); if (clazz == null) return new DefaultPermissionMap(); try { ClaimPermissionMap map = clazz.newInstance(); map.fromNBT(tag); return map; } catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); } return null; } } public static class DefaultPermissionMap extends ClaimPermissionMap { private HashMap<Permission, Boolean> permissions = new HashMap<>(); @Override public boolean isPermissionSet(Permission permission) { return permissions.containsKey(permission); } @Override public boolean hasPermission(Permission permission) { return isPermissionSet(permission) && permissions.get(permission); } @Override public void setPermission(Permission permission, boolean has) { permissions.put(permission, has); } @Override public void clearPermission(Permission permission) { permissions.remove(permission); } @Override public void fromNBT(CompoundTag tag) { permissions.clear(); for (String permissionString : tag.getKeys()) { Permission permission = Permission.byId(permissionString); if (permission == null) continue; boolean allowed = tag.getBoolean(permissionString); permissions.put(permission, allowed); } } @Override public CompoundTag toNBT() { CompoundTag tag = new CompoundTag(); permissions.forEach((permission, allowed) -> { if (allowed != null) tag.putBoolean(permission.id, allowed); }); return tag; } } public static class InvertedPermissionMap extends ClaimPermissionMap { private HashMap<Permission, Boolean> permissions = new HashMap<>(); @Override public boolean isPermissionSet(Permission permission) { return true; } @Override public boolean hasPermission(Permission permission) { return !permissions.containsKey(permission) || permissions.get(permission); } @Override public void setPermission(Permission permission, boolean has) { permissions.put(permission, has); } @Override public void clearPermission(Permission permission) { permissions.remove(permission); } @Override public void fromNBT(CompoundTag tag) { permissions.clear(); for (String permissionString : tag.getKeys()) { Permission permission = Permission.byId(permissionString); if (permission == null) continue; boolean allowed = tag.getBoolean(permissionString); permissions.put(permission, allowed); } } @Override public CompoundTag toNBT() { CompoundTag tag = new CompoundTag(); permissions.forEach((permission, allowed) -> { if (allowed != null) tag.putBoolean(permission.id, allowed); }); return tag; } } public static class ClaimSettings{ public enum Setting { FLIGHT_ALLOWED("flight_allowed", "Allow Flying", true), EXPLOSIONS("explosion_destruction", "Explosions Destroy Blocks", false), FLUID_CROSSES_BORDERS("fluid_crosses_borders", "Fluid Crosses Borders", false), FIRE_CROSSES_BORDERS("fire_crosses_borders", "Fire Crosses Borders", false), PISTON_FROM_INSIDE("pistons_inside_border", "Pistons Cross border from Inside", true), PISTON_FROM_OUTSIDE("pistons_outside_border", "Pistons Cross border from Outside", false), MOB_SPAWNING("mob_spawn", "Natural mob spawning", true), KEEP_INVENTORY("keep_inventory", "Keep Inventory", true), TELEPORT("teleport", "Global Teleport Access", true), ENTER_SOUND("enter_sound", "Enter Sound", true); String id, name; boolean defaultValue; Setting(String id, String name, boolean defaultValue) { this.id = id; this.name = name; this.defaultValue = defaultValue; } @Nullable public static ClaimSettings.Setting byId(String id) { for (ClaimSettings.Setting permission: values()) { if (permission.id.equals(id)) return permission; } return null; } } public Map<Setting, Boolean> settings = new HashMap<>(); public ClaimSettings(CompoundTag tag) { fromTag(tag); } public ClaimSettings() { } public boolean getSetting(Setting setting) { return settings.getOrDefault(setting, setting.defaultValue); } public CompoundTag toTag() { CompoundTag tag = new CompoundTag(); this.settings.forEach((setting, data) -> { tag.putBoolean(setting.id, data); }); return tag; } public void fromTag(CompoundTag tag) { settings.clear(); tag.getKeys().forEach(key -> { Setting setting = Setting.byId(key); if (setting == null) return; this.settings.put(setting, tag.getBoolean(key)); }); } } public enum Event { ENTER_CLAIM("enter", Config.msg_enter_default), LEAVE_CLAIM("leave", Config.msg_leave_default); String id; String defaultValue; Event(String id, String defaultValue) { this.id = id; this.defaultValue = defaultValue; } @Nullable public static Event getById(String id) { for (Event value : values()) { if (value.id.equalsIgnoreCase(id)) { return value; } } return null; } } }
/* * Copyright © Red Gate Software Ltd 2010-2021 * * 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.flywaydb.core.internal.database.sqlserver.synapse; import org.flywaydb.core.api.configuration.Configuration; import org.flywaydb.core.internal.database.base.Database; import org.flywaydb.core.internal.database.sqlserver.SQLServerDatabaseType; import org.flywaydb.core.internal.database.sqlserver.SQLServerEngineEdition; import org.flywaydb.core.internal.exception.FlywaySqlException; import org.flywaydb.core.internal.jdbc.JdbcConnectionFactory; import org.flywaydb.core.internal.jdbc.JdbcTemplate; import org.flywaydb.core.internal.jdbc.StatementInterceptor; import java.sql.Connection; import java.sql.SQLException; public class SynapseDatabaseType extends SQLServerDatabaseType { @Override protected boolean supportsJTDS() { return false; } @Override public String getName() { return "Azure Synapse"; } @Override public int getPriority() { // Synapse needs to be checked in advance of the plain SQL Server type return 1; } @Override public boolean handlesDatabaseProductNameAndVersion(String databaseProductName, String databaseProductVersion, Connection connection) { if (databaseProductName.startsWith("Microsoft SQL Server")) { try { SQLServerEngineEdition engineEdition = SQLServerEngineEdition.fromCode(getJdbcTemplate(connection).queryForInt( "SELECT SERVERPROPERTY('engineedition')")); return engineEdition == SQLServerEngineEdition.SQL_DATA_WAREHOUSE; } catch (SQLException e) { throw new FlywaySqlException("Unable to determine database engine edition.'", e); } } return false; } private JdbcTemplate getJdbcTemplate(Connection connection) { return new JdbcTemplate(connection, this); } @Override public Database createDatabase(Configuration configuration, JdbcConnectionFactory jdbcConnectionFactory, StatementInterceptor statementInterceptor) { return new SynapseDatabase(configuration, jdbcConnectionFactory, statementInterceptor); } }
/* * 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.hadoop.hbase.types; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.Order; import org.apache.hadoop.hbase.util.PositionedByteRange; import org.apache.yetus.audience.InterfaceAudience; /** * An {@code DataType} for interacting with values encoded using * {@link Bytes#putByte(byte[], int, byte)}. Intended to make it easier to transition away from * direct use of {@link Bytes}. * @see Bytes#putByte(byte[], int, byte) */ @InterfaceAudience.Public public class RawByte implements DataType<Byte> { @Override public boolean isOrderPreserving() { return false; } @Override public Order getOrder() { return null; } @Override public boolean isNullable() { return false; } @Override public boolean isSkippable() { return true; } @Override public int encodedLength(Byte val) { return Bytes.SIZEOF_BYTE; } @Override public Class<Byte> encodedClass() { return Byte.class; } @Override public int skip(PositionedByteRange src) { src.setPosition(src.getPosition() + Bytes.SIZEOF_BYTE); return Bytes.SIZEOF_BYTE; } @Override public Byte decode(PositionedByteRange src) { byte val = src.getBytes()[src.getOffset() + src.getPosition()]; skip(src); return val; } @Override public int encode(PositionedByteRange dst, Byte val) { Bytes.putByte(dst.getBytes(), dst.getOffset() + dst.getPosition(), val); return skip(dst); } /** * Read a {@code byte} value from the buffer {@code buff}. */ public byte decodeByte(byte[] buff, int offset) { return buff[offset]; } /** * Write instance {@code val} into buffer {@code buff}. */ public int encodeByte(byte[] buff, int offset, byte val) { return Bytes.putByte(buff, offset, val); } }
import org.checkerframework.checker.nullness.qual.NonNull; public class NonNullIteratorNext { interface MyIterator<E> extends java.util.Iterator<E> { @NonNull E next(); } interface MyList<E> extends java.util.Collection<E> { MyIterator<E> iterator(); } <T> void forEachLoop(MyList<T> list) { for (T elem : list) {} } }
package com.company.hackerrank.problemsolving; import java.io.*; import java.util.*; import java.util.stream.*; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; /*** * https://www.hackerrank.com/challenges/birthday-cake-candles/problem */ class Resultv1 { /* * Complete the 'birthdayCakeCandles' function below. * * The function is expected to return an INTEGER. * The function accepts INTEGER_ARRAY candles as parameter. */ public static int Solutionv1(List<Integer> candles) { // Write your code here int max = candles.stream().max(Integer::compareTo).get(); return (int) candles.stream().filter(x -> x == max).count(); } } public class BirthdayCakeCandles { public static void main(String[] args) throws IOException { String outputFileName = "candels.txt"; BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(outputFileName)); int candlesCount = Integer.parseInt(bufferedReader.readLine().trim()); List<Integer> candles = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" ")) .map(Integer::parseInt) .collect(toList()); int result = Resultv1.Solutionv1(candles); bufferedWriter.write(String.valueOf(result)); bufferedWriter.newLine(); bufferedReader.close(); bufferedWriter.close(); } }
/* * Copyright (c) 2021. StulSoft */ package com.stulsoft.rxjava.flow.validation; import io.reactivex.rxjava3.core.Completable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.function.Function; /** * @author Yuriy Stul */ public class ValidatorTest { private static final Logger logger = LoggerFactory.getLogger(ValidatorTest.class); public static void main(String[] args) { logger.info("==>main"); test1(); test2(); test3(); test4(); } private static void test1() { logger.info("==>test1"); Function<String, Completable> validator1 = s -> s.contains("a") ? Completable.error(new Exception("object contains a")) : Completable.complete(); Function<String, Completable> validator2 = s -> s.endsWith("x") ? Completable.error(new Exception("object ends with x")) : Completable.complete(); String test = "test value"; Validator<String> v1 = new Validator<>(test) .withValidator(validator1) .withValidator(validator2); v1.validate().subscribe( () -> logger.info("{} is valid", test), error -> logger.error("{} is not valid: {}", test, error.getMessage())) .dispose(); } private static void test2() { logger.info("==>test2"); Function<String, Completable> validator1 = s -> s.contains("a") ? Completable.error(new Exception("object contains a")) : Completable.complete(); Function<String, Completable> validator2 = s -> s.endsWith("x") ? Completable.error(new Exception("object ends with x")) : Completable.complete(); String test = null; Validator<String> v1 = new Validator<>(test) .withValidator(validator1) .withValidator(validator2); v1.validate().subscribe( () -> logger.info("{} is valid", test), error -> logger.error("{} is not valid: {}", test, error.getMessage())) .dispose(); } private static void test3() { logger.info("==>test3"); validate("abcx"); validate("uyx"); validate("good text"); } private static void test4() { logger.info("==>test4"); validate2("abcx"); validate2("uyx"); validate2("good text"); } private static void validate(String object) { logger.info("==>validate. object: {}", object); Function<String, Completable> validator1 = s -> s.contains("a") ? Completable.error(new Exception("object contains a")) : Completable.complete(); Function<String, Completable> validator2 = s -> s.endsWith("x") ? Completable.error(new Exception("object ends with x")) : Completable.complete(); Validator<String> v1 = new Validator<>(object) .withValidator(validator1) .withValidator(validator2); v1.validate().subscribe( () -> logger.info("{} is valid", object), error -> logger.error("{} is not valid: {}", object, error.getMessage())) .dispose(); } private static void validate2(String object) { logger.info("==>validate. object: {}", object); Validator<String> validator = new Validator<>(object) .withValidator(s -> s.contains("a") ? Completable.error(new Exception("object contains a")) : Completable.complete()) .withValidator(s -> s.endsWith("x") ? Completable.error(new Exception("object ends with x")) : Completable.complete()); validator.validate().subscribe( () -> logger.info("{} is valid", object), error -> logger.error("{} is not valid: {}", object, error.getMessage())) .dispose(); } }
package com.roger.common.core.utils; import cn.hutool.core.convert.Convert; import com.alibaba.ttl.TransmittableThreadLocal; import com.roger.common.core.constant.SecurityConstants; import com.roger.common.core.domain.dto.JwtUserDto; import org.springframework.security.core.Authentication; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @Author: Roger * @description: * @date: 2022/1/15 2:36 PM */ public class SecurityContextHolder { private static final TransmittableThreadLocal<Map<String, Object>> THREAD_LOCAL = new TransmittableThreadLocal<>(); public static void set(String key, Object value) { Map<String, Object> map = getLocalMap(); map.put(key, value == null ? StringUtils.EMPTY : value); } public static String get(String key) { Map<String, Object> map = getLocalMap(); return Convert.toStr(map.getOrDefault(key, StringUtils.EMPTY)); } public static <T> T get(String key, Class<T> clazz) { Map<String, Object> map = getLocalMap(); return (T) map.getOrDefault(key, null); } public static Map<String, Object> getLocalMap() { Map<String, Object> map = THREAD_LOCAL.get(); if (map == null) { map = new ConcurrentHashMap<>(); THREAD_LOCAL.set(map); } return map; } public static void setLocalMap(Map<String, Object> threadLocalMap) { THREAD_LOCAL.set(threadLocalMap); } public static Long getUserId() { return Convert.toLong(get(SecurityConstants.DETAILS_USER_ID), 0L); } public static void setUserId(String account) { set(SecurityConstants.DETAILS_USER_ID, account); } public static String getUserName() { return get(SecurityConstants.DETAILS_USERNAME); } public static void setUserName(String username) { set(SecurityConstants.DETAILS_USERNAME, username); } public static JwtUserDto getLoginUser() { return get(SecurityConstants.LOGIN_USER, JwtUserDto.class); } public static void setLoginUser(JwtUserDto userDto) { set(SecurityConstants.LOGIN_USER, userDto); } public static void remove() { THREAD_LOCAL.remove(); } }
/* * Copyright (c) 2014, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0, which is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package jakarta.tutorial.converter.web; import java.io.IOException; import java.io.PrintWriter; import java.math.BigDecimal; import jakarta.ejb.EJB; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.tutorial.converter.ejb.ConverterBean; @WebServlet(urlPatterns="/") public class ConverterServlet extends HttpServlet { private static final long serialVersionUID = -8312407323476917087L; @EJB ConverterBean converter; /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); // Output the results out.println("<html lang=\"en\">"); out.println("<head>"); out.println("<title>Servlet ConverterServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet ConverterServlet at " + request.getContextPath() + "</h1>"); try { String amount = request.getParameter("amount"); if (amount != null && amount.length() > 0) { // convert the amount to a BigDecimal from the request parameter BigDecimal d = new BigDecimal(amount); // call the ConverterBean.dollarToYen() method to get the amount // in Yen BigDecimal yenAmount = converter.dollarToYen(d); // call the ConverterBean.yenToEuro() method to get the amount // in Euros BigDecimal euroAmount = converter.yenToEuro(yenAmount); out.println("<p>" + amount + " dollars are " + yenAmount.toPlainString() + " yen.</p>"); out.println("<p>" + yenAmount.toPlainString() + " yen are " + euroAmount.toPlainString() + " Euro.</p>"); } else { out.println("<p>Enter a dollar amount to convert:</p>"); out.println("<form method=\"get\">"); out.println("<p>$ <input title=\"Amount\" type=\"text\" name=\"amount\" size=\"25\"></p>"); out.println("<br/>"); out.println("<input type=\"submit\" value=\"Submit\">" + "<input type=\"reset\" value=\"Reset\">"); out.println("</form>"); } } finally { out.println("</body>"); out.println("</html>"); out.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
/* * Copyright 2013 Zakhar Prykhoda * * 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.midao.jdbc.core.db.oracle; import org.midao.jdbc.core.MjdbcFactory; import org.midao.jdbc.core.MjdbcTypes; import org.midao.jdbc.core.db.*; import org.midao.jdbc.core.exception.ExceptionUtils; import org.midao.jdbc.core.exception.MjdbcException; import org.midao.jdbc.core.handlers.input.query.QueryInputHandler; import org.midao.jdbc.core.handlers.model.CallResults; import org.midao.jdbc.core.handlers.model.QueryParameters; import org.midao.jdbc.core.handlers.output.BeanOutputHandler; import org.midao.jdbc.core.handlers.output.MapOutputHandler; import org.midao.jdbc.core.handlers.output.OutputHandler; import org.midao.jdbc.core.handlers.type.OracleTypeHandler; import org.midao.jdbc.core.service.QueryRunnerService; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; /** */ public class CallTest extends BaseOracle { public void testQueryInputHandler() throws SQLException { if (this.checkConnected(dbName) == false) { return; } QueryRunnerService runner = null; Map<String, Object> values = new HashMap<String, Object>(); final QueryStructure defaultStructure = DBCallQueryStructure.callQueryParameters(values); QueryStructure structure = new QueryStructure(values) { @Override public void create(QueryRunnerService runner) throws SQLException { runner.update(DBConstants.ORACLE_PROCEDURE_INOUT); } @Override public void execute(QueryRunnerService runner) throws SQLException { defaultStructure.execute(runner); } @Override public void drop(QueryRunnerService runner) throws SQLException { defaultStructure.drop(runner); } }; runner = MjdbcFactory.getQueryRunner(this.dataSource); DBCall.callQueryParameters(structure, runner); runner = MjdbcFactory.getQueryRunner(this.conn); DBCall.callQueryParameters(structure, runner); } public void testCallFunction() throws SQLException { if (this.checkConnected(dbName) == false) { return; } QueryRunnerService runner = null; Map<String, Object> values = new HashMap<String, Object>(); final QueryStructure defaultStructure = DBCallQueryStructure.callFunction(values); QueryStructure structure = new QueryStructure(values) { @Override public void create(QueryRunnerService runner) throws SQLException { runner.update(DBConstants.CREATE_STUDENT_TABLE_ORACLE); runner.update(DBConstants.CREATE_STUDENT_TABLE_ORACLE_SEQ); runner.update(DBConstants.CREATE_STUDENT_TABLE_ORACLE_TRG); defaultStructure.create(runner); runner.update(DBConstants.ORACLE_FUNCTION); } @Override public void execute(QueryRunnerService runner) throws SQLException { QueryInputHandler input = null; QueryParameters parameters = new QueryParameters(); parameters.set("id", 2, MjdbcTypes.INTEGER, QueryParameters.Direction.IN, 0); parameters.set("name", null, MjdbcTypes.VARCHAR, QueryParameters.Direction.OUT, 1); input = new QueryInputHandler(DBConstants.ORACLE_CALL_FUNCTION, parameters); QueryParameters result = runner.call(input); this.values.put("result1", result); assertEquals("Doe", result.getValue("name")); parameters.set("id", 1, MjdbcTypes.INTEGER, QueryParameters.Direction.IN, 0); parameters.set("name", null, MjdbcTypes.VARCHAR, QueryParameters.Direction.OUT, 1); input = new QueryInputHandler(DBConstants.ORACLE_CALL_FUNCTION, parameters); this.values.put("result2", runner.call(input)); } @Override public void drop(QueryRunnerService runner) throws SQLException { defaultStructure.drop(runner); runner.update(DBConstants.DROP_STUDENT_TABLE_ORACLE_SEQ); } }; runner = MjdbcFactory.getQueryRunner(this.dataSource); DBCall.callFunction(structure, runner); runner = MjdbcFactory.getQueryRunner(this.conn); DBCall.callFunction(structure, runner); } public void testCallProcedureReturn() throws SQLException { if (this.checkConnected(dbName) == false) { return; } QueryRunnerService runner = null; Map<String, Object> values = new HashMap<String, Object>(); final QueryStructure defaultStructure = DBCallQueryStructure.callOutputHandlerMap(values); QueryStructure structure = new QueryStructure(values) { @Override public void create(QueryRunnerService runner) throws SQLException { runner.update(DBConstants.CREATE_STUDENT_TABLE_ORACLE); runner.update(DBConstants.CREATE_STUDENT_TABLE_ORACLE_SEQ); runner.update(DBConstants.CREATE_STUDENT_TABLE_ORACLE_TRG); defaultStructure.create(runner); runner.update(DBConstants.ORACLE_PROCEDURE_RETURN); } @Override public void execute(QueryRunnerService runner) throws SQLException { QueryInputHandler input = null; QueryParameters parameters = new QueryParameters(); parameters.set("cursor", null, oracle.jdbc.OracleTypes.CURSOR, QueryParameters.Direction.OUT); parameters.set("id", 2, MjdbcTypes.INTEGER, QueryParameters.Direction.IN); input = new QueryInputHandler(DBConstants.ORACLE_CALL_PROCEDURE_RETURN, parameters); CallResults<QueryParameters, Map<String, Object>> result = runner.call(input, new MapOutputHandler()); List<QueryParameters> outputList = (List<QueryParameters>) result.getCallInput().getValue("cursor"); result.setCallOutput(outputList.get(0).toMap()); this.values.put("result", result); } @Override public void drop(QueryRunnerService runner) throws SQLException { //defaultStructure.drop(runner); runner.update(DBConstants.DROP_STUDENT_TABLE); runner.update(DBConstants.DROP_STUDENT_TABLE_ORACLE_SEQ); } }; runner = MjdbcFactory.getQueryRunner(this.dataSource, OracleTypeHandler.class); DBCall.callOutputHandlerMap(structure, runner); runner = MjdbcFactory.getQueryRunner(this.conn, OracleTypeHandler.class); DBCall.callOutputHandlerMap(structure, runner); } public void testCallProcedureReturn2() throws SQLException { if (this.checkConnected(dbName) == false) { return; } QueryRunnerService runner = null; Map<String, Object> values = new HashMap<String, Object>(); final QueryStructure defaultStructure = DBCallQueryStructure.callOutputHandlerBean(values); QueryStructure structure = new QueryStructure(values) { @Override public void create(QueryRunnerService runner) throws SQLException { runner.update(DBConstants.CREATE_STUDENT_TABLE_ORACLE); runner.update(DBConstants.CREATE_STUDENT_TABLE_ORACLE_SEQ); runner.update(DBConstants.CREATE_STUDENT_TABLE_ORACLE_TRG); defaultStructure.create(runner); runner.update(DBConstants.ORACLE_PROCEDURE_RETURN); } @Override public void execute(QueryRunnerService runner) throws SQLException { QueryInputHandler input = null; QueryParameters parameters = new QueryParameters(); parameters.set("cursor", null, oracle.jdbc.OracleTypes.CURSOR, QueryParameters.Direction.OUT); parameters.set("id", 2, MjdbcTypes.INTEGER, QueryParameters.Direction.IN); input = new QueryInputHandler(DBConstants.ORACLE_CALL_PROCEDURE_RETURN, parameters); OutputHandler<Student> outputHandler = new BeanOutputHandler<Student>(Student.class); CallResults<QueryParameters, Student> result = runner.call(input, outputHandler); List<QueryParameters> outputList = (List<QueryParameters>) result.getCallInput().getValue("cursor"); // creating empty technical field, which is required for every OutputHandlers outputList.add(0, new QueryParameters()); try { result.setCallOutput(outputHandler.handle(outputList)); } catch (MjdbcException ex) { ExceptionUtils.rethrow(ex); } this.values.put("result", result); } @Override public void drop(QueryRunnerService runner) throws SQLException { runner.update(DBConstants.DROP_STUDENT_TABLE); runner.update(DBConstants.DROP_STUDENT_TABLE_ORACLE_SEQ); } }; runner = MjdbcFactory.getQueryRunner(this.dataSource, OracleTypeHandler.class); DBCall.callOutputHandlerBean(structure, runner); runner = MjdbcFactory.getQueryRunner(this.conn, OracleTypeHandler.class); DBCall.callOutputHandlerBean(structure, runner); } public void testCallProcedureLargeParameters() throws SQLException { if (this.checkConnected(dbName) == false) { return; } QueryRunnerService runner = null; Map<String, Object> values = new HashMap<String, Object>(); final QueryStructure defaultStructure = DBCallQueryStructure.callLargeParameters(values); QueryStructure structure = new QueryStructure(values) { @Override public void create(QueryRunnerService runner) throws SQLException { runner.update(DBConstants.ORACLE_PROCEDURE_LARGE); } @Override public void execute(QueryRunnerService runner) throws SQLException { defaultStructure.execute(runner); } @Override public void drop(QueryRunnerService runner) throws SQLException { defaultStructure.drop(runner); } }; runner = MjdbcFactory.getQueryRunner(this.dataSource, OracleTypeHandler.class); DBCall.callLargeParameters(structure, runner); runner = MjdbcFactory.getQueryRunner(this.conn, OracleTypeHandler.class); DBCall.callLargeParameters(structure, runner); } public void testCallProcedureLargeParametersStream() throws SQLException { if (this.checkConnected(dbName) == false) { return; } QueryRunnerService runner = null; Map<String, Object> values = new HashMap<String, Object>(); final QueryStructure defaultStructure = DBCallQueryStructure.callLargeParametersStream(values); QueryStructure structure = new QueryStructure(values) { @Override public void create(QueryRunnerService runner) throws SQLException { runner.update(DBConstants.ORACLE_PROCEDURE_LARGE); } @Override public void execute(QueryRunnerService runner) throws SQLException { defaultStructure.execute(runner); } @Override public void drop(QueryRunnerService runner) throws SQLException { defaultStructure.drop(runner); } }; runner = MjdbcFactory.getQueryRunner(this.dataSource, OracleTypeHandler.class); DBCall.callLargeParameters(structure, runner); runner = MjdbcFactory.getQueryRunner(this.conn, OracleTypeHandler.class); DBCall.callLargeParameters(structure, runner); } public void testNamedHandler() throws SQLException { if (this.checkConnected(dbName) == false) { return; } QueryRunnerService runner = null; Map<String, Object> values = new HashMap<String, Object>(); final QueryStructure defaultStructure = DBCallQueryStructure.callNamedHandler(values); QueryStructure structure = new QueryStructure(values) { @Override public void create(QueryRunnerService runner) throws SQLException { runner.update(DBConstants.CREATE_STUDENT_TABLE_ORACLE); runner.update(DBConstants.CREATE_STUDENT_TABLE_ORACLE_SEQ); runner.update(DBConstants.CREATE_STUDENT_TABLE_ORACLE_TRG); defaultStructure.create(runner); runner.update(DBConstants.ORACLE_PROCEDURE_NAMED); } @Override public void execute(QueryRunnerService runner) throws SQLException { defaultStructure.execute(runner); } @Override public void drop(QueryRunnerService runner) throws SQLException { defaultStructure.drop(runner); runner.update(DBConstants.DROP_STUDENT_TABLE_ORACLE_SEQ); } }; runner = MjdbcFactory.getQueryRunner(this.dataSource, OracleTypeHandler.class); DBCall.callNamedHandler(structure, runner); runner = MjdbcFactory.getQueryRunner(this.conn, OracleTypeHandler.class); DBCall.callNamedHandler(structure, runner); } }
/* * 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.pirk.test.distributed; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A container for Apache's Command Line Interface that contains custom functionality for the MapReduce functional tests. */ public class DistributedTestCLI { private static final Logger logger = LoggerFactory.getLogger(DistributedTestCLI.class); private CommandLine commandLine = null; private Options cliOptions = null; /** * Create and parse allowable options * * @param args * - arguments fed into the main method */ public DistributedTestCLI(String[] args) { // create the command line options cliOptions = createOptions(); try { // parse the command line options CommandLineParser parser = new GnuParser(); commandLine = parser.parse(cliOptions, args, true); // if help option is selected, just print help text and exit if (hasOption("h")) { printHelp(); System.exit(1); } // The full path of the jar file must be set if (!hasOption("j")) { logger.info("The full path of the jar file must be set with -j"); System.exit(1); } } catch (Exception e) { e.printStackTrace(); System.exit(1); } } /** * Determine if an option was provided by the user via the CLI * * @param option * - the option of interest * @return true if option was provided, false otherwise */ public boolean hasOption(String option) { return commandLine.hasOption(option); } /** * Obtain the argument of the option provided by the user via the CLI * * @param option * - the option of interest * @return value of the argument of the option */ public String getOptionValue(String option) { return commandLine.getOptionValue(option); } /** * Determine if the argument was provided, which determines if a test should or should not be run * * @param allowed * - argument string you are looking for * @return true if argument was provided via the CLI, false otherwise */ public boolean run(String allowed) { return run(allowed, "t"); } /** * Determine if the argument was provided for the selected option, which determines if a test should or should not be run * * @param allowed * - argument string you are looking for * @param option * - the option of interest * @return true if argument was provided via the CLI, false otherwise */ public boolean run(String allowed, String option) { if (!hasOption(option)) { return true; } String selection = getOptionValue(option); String[] selectionList = selection.split(","); for (String selectionItem : selectionList) { if (selectionItem.equals(allowed)) { return true; } } return false; } /** * Create the options available for the DistributedTestDriver * * @return Apache's CLI Options object */ private Options createOptions() { Options options = new Options(); // help Option optionHelp = new Option("h", "help", false, "Print out the help documentation for this command line execution"); optionHelp.setRequired(false); options.addOption(optionHelp); // jar file Option optionJar = new Option("j", "jar", true, "required -- Fully qualified jar file"); optionJar.setRequired(false); options.addOption(optionJar); // test selection String tests = "testNum = 1: Wideskies Tests\n"; tests += "Subtests:\n"; tests += "E - Elasticsearch MapReduce\n"; tests += "J - JSON/HDFS MapReduce\n"; tests += "ES - Elasticsearch Spark \n"; tests += "JS - JSON/HDFS Spark \n"; tests += "SS - Spark Streaming Tests \n"; tests += "JSS - JSON/HDFS Spark Streaming \n"; tests += "ESS - Elasticsearch Spark Streaming \n"; Option optionTestSelection = new Option("t", "tests", true, "optional -- Select which tests to execute: \n" + tests); optionTestSelection.setRequired(false); optionTestSelection.setArgName("<testNum>:<subtestDesignator>"); optionTestSelection.setType(String.class); options.addOption(optionTestSelection); return options; } /** * Prints out the help message */ private void printHelp() { HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(140); formatter.printHelp("DistributedTestDriver", cliOptions); } }
package com.example.ericrybarczyk.popularmovies.utils; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.widget.Toast; import com.example.ericrybarczyk.popularmovies.R; public class NetworkChecker { /* This method was directly adapted from https://stackoverflow.com/a/4009133/798642 as recommended by Udacity for this project. */ @SuppressWarnings("BooleanMethodIsAlwaysInverted") // I prefer the affirmative (is) method name prefix public static boolean isNetworkConnected(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivityManager == null) { return false; } NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); return (networkInfo != null) && (networkInfo.isConnected()); } public static Toast getNoNetworkToastMessage(Context context) { return Toast.makeText(context, R.string.error_no_network, Toast.LENGTH_LONG); } public static String getNoNetworkLogMessage(Context context) { return context.getString(R.string.log_message_no_network); } }
/** * Copyright 2000-2013 NeuStar, Inc. All rights reserved. * NeuStar, the Neustar logo and related names and logos are registered * trademarks, service marks or tradenames of NeuStar, Inc. All other * product names, company names, marks, logos and symbols may be trademarks * of their respective owners. */ package biz.neustar.nexus.plugins.gitlab.client.rest; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.sonatype.security.usermanagement.DefaultUser; import org.sonatype.security.usermanagement.User; import org.sonatype.security.usermanagement.UserStatus; @JsonIgnoreProperties(ignoreUnknown=true) public class GitlabUser { @JsonProperty private final Integer id; @JsonProperty private final String username; @JsonProperty private final String email; @JsonProperty private final String name; @JsonProperty private final List<Map<String, String>> identities; @JsonProperty private final String private_token; @JsonProperty private final String state; @JsonProperty private final String created_at; @JsonProperty private final Boolean is_admin; @JsonProperty private final Boolean can_create_group; @JsonProperty private final Boolean can_create_team; @JsonProperty private final Boolean can_create_project; public GitlabUser() { id = null; username = ""; email = ""; name = ""; identities = new ArrayList<>(); private_token = ""; state = ""; created_at = ""; is_admin = false; can_create_group = false; can_create_team = false; can_create_project = false; } GitlabUser(String name) { id = null; username = ""; email = ""; this.name = name; identities = new ArrayList<>(); private_token = ""; state = ""; created_at = ""; is_admin = false; can_create_group = false; can_create_team = false; can_create_project = false; } public String getUsername() { return username; } public User toUser() { User user = new DefaultUser(); String fullName = nullToEmpty(this.name); String firstName = fullName; String lastName = ""; int split = fullName.indexOf(','); if (split > 0) { lastName = fullName.substring(0, split).trim(); firstName = fullName.substring(split + 1).trim(); } else { split = fullName.indexOf(' '); if (split > 0) { firstName = fullName.substring(0, split).trim(); lastName = fullName.substring(split + 1).trim(); } } user.setUserId(username); user.setFirstName(firstName); user.setLastName(lastName); user.setEmailAddress(nullToEmpty(email)); user.setStatus(isActive() ? UserStatus.active : UserStatus.disabled); return user; } public boolean isActive() { return nullToEmpty(this.state).equalsIgnoreCase("active"); } public boolean isAdmin() { return is_admin; } public List<Map<String, String>> getIdentities() { if (getProvider("gitlab") == null) { identities.add(generateGitlabProvider()); } return identities; } // return the map if found or else null. public Map<String, String> getProvider(String provider) { for (Map<String, String> identity : identities) { String providerName = identity.get("provider"); if (providerName != null && providerName.equals(provider)) { return identity; } } return null; } protected Map<String, String> generateGitlabProvider() { Map<String, String> gitlab = new HashMap<>(); gitlab.put("id", id.toString()); gitlab.put("username", username); gitlab.put("email", email); gitlab.put("name", name); gitlab.put("provider", "gitlab"); return gitlab; } public static String nullToEmpty(String s) { return s == null ? "" : s; } @Override public String toString() { return username; } }
/** * This file is automatically created by Recurly's OpenAPI generation process and thus any edits you * make by hand will be lost. If you wish to make a change to this file, please create a Github * issue explaining the changes you need and we will usher them to the appropriate places. */ package com.recurly.v3.resources; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.recurly.v3.Constants; import com.recurly.v3.Resource; import org.joda.time.DateTime; public class AccountAcquisition extends Resource { /** Account mini details */ @SerializedName("account") @Expose private AccountMini account; /** * An arbitrary identifier for the marketing campaign that led to the acquisition of this account. */ @SerializedName("campaign") @Expose private String campaign; /** The channel through which the account was acquired. */ @SerializedName("channel") @Expose private Constants.Channel channel; /** Account balance */ @SerializedName("cost") @Expose private AccountAcquisitionCost cost; /** When the account acquisition data was created. */ @SerializedName("created_at") @Expose private DateTime createdAt; @SerializedName("id") @Expose private String id; /** Object type */ @SerializedName("object") @Expose private String object; /** * An arbitrary subchannel string representing a distinction/subcategory within a broader channel. */ @SerializedName("subchannel") @Expose private String subchannel; /** When the account acquisition data was last changed. */ @SerializedName("updated_at") @Expose private DateTime updatedAt; /** Account mini details */ public AccountMini getAccount() { return this.account; } /** @param account Account mini details */ public void setAccount(final AccountMini account) { this.account = account; } /** * An arbitrary identifier for the marketing campaign that led to the acquisition of this account. */ public String getCampaign() { return this.campaign; } /** * @param campaign An arbitrary identifier for the marketing campaign that led to the acquisition * of this account. */ public void setCampaign(final String campaign) { this.campaign = campaign; } /** The channel through which the account was acquired. */ public Constants.Channel getChannel() { return this.channel; } /** @param channel The channel through which the account was acquired. */ public void setChannel(final Constants.Channel channel) { this.channel = channel; } /** Account balance */ public AccountAcquisitionCost getCost() { return this.cost; } /** @param cost Account balance */ public void setCost(final AccountAcquisitionCost cost) { this.cost = cost; } /** When the account acquisition data was created. */ public DateTime getCreatedAt() { return this.createdAt; } /** @param createdAt When the account acquisition data was created. */ public void setCreatedAt(final DateTime createdAt) { this.createdAt = createdAt; } public String getId() { return this.id; } /** @param id */ public void setId(final String id) { this.id = id; } /** Object type */ public String getObject() { return this.object; } /** @param object Object type */ public void setObject(final String object) { this.object = object; } /** * An arbitrary subchannel string representing a distinction/subcategory within a broader channel. */ public String getSubchannel() { return this.subchannel; } /** * @param subchannel An arbitrary subchannel string representing a distinction/subcategory within * a broader channel. */ public void setSubchannel(final String subchannel) { this.subchannel = subchannel; } /** When the account acquisition data was last changed. */ public DateTime getUpdatedAt() { return this.updatedAt; } /** @param updatedAt When the account acquisition data was last changed. */ public void setUpdatedAt(final DateTime updatedAt) { this.updatedAt = updatedAt; } }
package com.jjoe64.graphview_demos.categories; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.jjoe64.graphview_demos.FullscreenExample; import com.jjoe64.graphview_demos.ItemDetailFragment; import com.jjoe64.graphview_demos.R; public class ZoomingAndScrollingFragment extends ItemDetailFragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.zooming_and_scrolling_content, container, false); //GraphView graph = (GraphView) rootView.findViewById(R.id.graph); //new HelloWorld().initGraph(graph); rootView.findViewById(R.id.cardZoomXYGraph).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { openFullscreen(FullscreenExample.SCALING_XY); } }); rootView.findViewById(R.id.imgFullscreen).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { openFullscreen(FullscreenExample.SCALING_XY); } }); rootView.findViewById(R.id.imgSource).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { openSource(FullscreenExample.SCALING_XY); } }); rootView.findViewById(R.id.cardZoomXGraph).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { openFullscreen(FullscreenExample.SCALING_X); } }); rootView.findViewById(R.id.imgFullscreen2).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { openFullscreen(FullscreenExample.SCALING_X); } }); rootView.findViewById(R.id.imgSource2).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { openSource(FullscreenExample.SCALING_X); } }); rootView.findViewById(R.id.cardScrollXGraph).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { openFullscreen(FullscreenExample.SCROLLING_X); } }); rootView.findViewById(R.id.imgFullscreen3).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { openFullscreen(FullscreenExample.SCROLLING_X); } }); rootView.findViewById(R.id.imgSource3).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { openSource(FullscreenExample.SCROLLING_X); } }); return rootView; } }
/* * Copyright (c) 2020-2021 Project CHIP Authors * 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 chip.devicecontroller; import android.bluetooth.BluetoothGatt; import android.util.Log; import androidx.annotation.Nullable; import chip.devicecontroller.GetConnectedDeviceCallbackJni.GetConnectedDeviceCallback; /** Controller to interact with the CHIP device. */ public class ChipDeviceController { private static final String TAG = ChipDeviceController.class.getSimpleName(); private long deviceControllerPtr; private int connectionId; private CompletionListener completionListener; /** * To load class and jni, we need to new AndroidChipPlatform after jni load but before new * ChipDeviceController */ public static void loadJni() { return; } public ChipDeviceController() { deviceControllerPtr = newDeviceController(); } public void setCompletionListener(CompletionListener listener) { completionListener = listener; } public void pairDevice(BluetoothGatt bleServer, int connId, long deviceId, long setupPincode) { pairDevice(bleServer, connId, deviceId, setupPincode, null); } /** * Pair a device connected through BLE. * * @param bleServer the BluetoothGatt representing the BLE connection to the device * @param connId the BluetoothGatt Id representing the BLE connection to the device * @param deviceId the node ID to assign to the device * @param setupPincode the pincode for the device * @param csrNonce the 32-byte CSR nonce to use, or null if we want to use an internally randomly * generated CSR nonce. */ public void pairDevice( BluetoothGatt bleServer, int connId, long deviceId, long setupPincode, @Nullable byte[] csrNonce) { if (connectionId == 0) { connectionId = connId; if (connectionId == 0) { Log.e(TAG, "Failed to add Bluetooth connection."); completionListener.onError(new Exception("Failed to add Bluetooth connection.")); return; } Log.d(TAG, "Bluetooth connection added with ID: " + connectionId); Log.d(TAG, "Pairing device with ID: " + deviceId); pairDevice(deviceControllerPtr, deviceId, connectionId, setupPincode, csrNonce); } else { Log.e(TAG, "Bluetooth connection already in use."); completionListener.onError(new Exception("Bluetooth connection already in use.")); } } public void pairDeviceWithAddress( long deviceId, String address, int port, int discriminator, long pinCode, @Nullable byte[] csrNonce) { pairDeviceWithAddress( deviceControllerPtr, deviceId, address, port, discriminator, pinCode, csrNonce); } public void unpairDevice(long deviceId) { unpairDevice(deviceControllerPtr, deviceId); } /** * Returns a pointer to a device currently being commissioned. This should be used before the * device is operationally available. */ public long getDeviceBeingCommissionedPointer(long nodeId) { return getDeviceBeingCommissionedPointer(deviceControllerPtr, nodeId); } /** * Through GetConnectedDeviceCallback, returns a pointer to a connected device or an error. * * <p>TODO(#8443): This method could benefit from a ChipDevice abstraction to hide the pointer * passing. */ public void getConnectedDevicePointer(long nodeId, GetConnectedDeviceCallback callback) { GetConnectedDeviceCallbackJni jniCallback = new GetConnectedDeviceCallbackJni(callback); getConnectedDevicePointer(deviceControllerPtr, nodeId, jniCallback.getCallbackHandle()); } public boolean disconnectDevice(long deviceId) { return disconnectDevice(deviceControllerPtr, deviceId); } public void onConnectDeviceComplete() { completionListener.onConnectDeviceComplete(); } public void onStatusUpdate(int status) { if (completionListener != null) { completionListener.onStatusUpdate(status); } } public void onPairingComplete(int errorCode) { if (completionListener != null) { completionListener.onPairingComplete(errorCode); } } public void onCommissioningComplete(long nodeId, int errorCode) { if (completionListener != null) { completionListener.onCommissioningComplete(nodeId, errorCode); } } public void onOpCSRGenerationComplete(byte[] csr) { if (completionListener != null) { completionListener.onOpCSRGenerationComplete(csr); } } public void onPairingDeleted(int errorCode) { if (completionListener != null) { completionListener.onPairingDeleted(errorCode); } } public void onNotifyChipConnectionClosed(int connId) { connectionId = 0; Log.d(TAG, "Calling onNotifyChipConnectionClosed()"); completionListener.onNotifyChipConnectionClosed(); } public void onCloseBleComplete(int connId) { if (releaseBluetoothGatt(connId)) { Log.d(TAG, "Calling onCloseBleComplete()"); completionListener.onCloseBleComplete(); } else { Log.d(TAG, "Skipped calling onCloseBleComplete(). Connection has already been closed."); } } public void onError(Throwable error) { completionListener.onError(error); } public void close() { releaseBluetoothGatt(connectionId); } private boolean releaseBluetoothGatt(int connId) { if (connectionId == 0) { return false; } Log.d(TAG, "Closing GATT and removing connection for " + connId); connectionId = 0; return true; } public String getIpAddress(long deviceId) { return getIpAddress(deviceControllerPtr, deviceId); } public long getCompressedFabricId() { return getCompressedFabricId(deviceControllerPtr); } public void updateDevice(long fabricId, long deviceId) { updateDevice(deviceControllerPtr, fabricId, deviceId); } public boolean openPairingWindow(long devicePtr, int duration) { return openPairingWindow(deviceControllerPtr, devicePtr, duration); } public boolean openPairingWindowWithPIN( long devicePtr, int duration, int iteration, int discriminator, long setupPinCode) { return openPairingWindowWithPIN( deviceControllerPtr, devicePtr, duration, iteration, discriminator, setupPinCode); } public boolean isActive(long deviceId) { return isActive(deviceControllerPtr, deviceId); } /* Shutdown all cluster attribute subscriptions for a given device */ public void shutdownSubscriptions(long devicePtr) { shutdownSubscriptions(deviceControllerPtr, devicePtr); } /** * Generates a new PASE verifier and passcode ID for the given setup PIN code. * * @param devicePtr a pointer to the device object for which to generate the PASE verifier * @param setupPincode the PIN code to use * @param iterations the number of iterations for computing the verifier * @param salt the 16-byte salt */ public PaseVerifierParams computePaseVerifier( long devicePtr, long setupPincode, int iterations, byte[] salt) { return computePaseVerifier(deviceControllerPtr, devicePtr, setupPincode, iterations, salt); } private native PaseVerifierParams computePaseVerifier( long deviceControllerPtr, long devicePtr, long setupPincode, int iterations, byte[] salt); private native long newDeviceController(); private native void pairDevice( long deviceControllerPtr, long deviceId, int connectionId, long pinCode, @Nullable byte[] csrNonce); private native void pairDeviceWithAddress( long deviceControllerPtr, long deviceId, String address, int port, int discriminator, long pinCode, @Nullable byte[] csrNonce); private native void unpairDevice(long deviceControllerPtr, long deviceId); private native long getDeviceBeingCommissionedPointer(long deviceControllerPtr, long nodeId); private native void getConnectedDevicePointer( long deviceControllerPtr, long deviceId, long callbackHandle); private native boolean disconnectDevice(long deviceControllerPtr, long deviceId); private native void deleteDeviceController(long deviceControllerPtr); private native String getIpAddress(long deviceControllerPtr, long deviceId); private native long getCompressedFabricId(long deviceControllerPtr); private native void updateDevice(long deviceControllerPtr, long fabricId, long deviceId); private native boolean openPairingWindow(long deviceControllerPtr, long devicePtr, int duration); private native boolean openPairingWindowWithPIN( long deviceControllerPtr, long devicePtr, int duration, int iteration, int discriminator, long setupPinCode); private native boolean isActive(long deviceControllerPtr, long deviceId); private native void shutdownSubscriptions(long deviceControllerPtr, long devicePtr); static { System.loadLibrary("CHIPController"); } @SuppressWarnings("deprecation") protected void finalize() throws Throwable { super.finalize(); if (deviceControllerPtr != 0) { deleteDeviceController(deviceControllerPtr); deviceControllerPtr = 0; } } /** Interface to listen for callbacks from CHIPDeviceController. */ public interface CompletionListener { /** Notifies the completion of "ConnectDevice" command. */ void onConnectDeviceComplete(); /** Notifies the pairing status. */ void onStatusUpdate(int status); /** Notifies the completion of pairing. */ void onPairingComplete(int errorCode); /** Notifies the deletion of pairing session. */ void onPairingDeleted(int errorCode); /** Notifies the completion of commissioning. */ void onCommissioningComplete(long nodeId, int errorCode); /** Notifies that the Chip connection has been closed. */ void onNotifyChipConnectionClosed(); /** Notifies the completion of the "close BLE connection" command. */ void onCloseBleComplete(); /** Notifies the listener of the error. */ void onError(Throwable error); /** Notifies the Commissioner when the OpCSR for the Comissionee is generated. */ void onOpCSRGenerationComplete(byte[] csr); } }
package com.jeesite.modules.test.entity; public class JsJobCalendarsKey { private String schedName; private String calendarName; public String getSchedName() { return schedName; } public void setSchedName(String schedName) { this.schedName = schedName == null ? null : schedName.trim(); } public String getCalendarName() { return calendarName; } public void setCalendarName(String calendarName) { this.calendarName = calendarName == null ? null : calendarName.trim(); } }
package org.togglz.junit.vary; import org.togglz.core.Feature; import org.togglz.core.context.FeatureContext; enum MyFeatures implements Feature { F1, F2, F3; public boolean isActive() { return FeatureContext.getFeatureManager().isActive(this); } @Override public String id() { return name(); } }
package net.silentchaos512.lib.util; public interface TriConsumer<A, B, C> { void accept(A a, B b, C c); }
package io.bdeploy.dcu; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import io.bdeploy.bhive.BHive; import io.bdeploy.bhive.BHive.Operation; import io.bdeploy.bhive.TestHive; @ExtendWith(TestHive.class) public class OperationSynchronizerTest { @Test void testSynchronizer(BHive hive) throws Exception { InstanceNodeOperationSynchronizer sync = new InstanceNodeOperationSynchronizer(); // setup a single operation which is performed by multiple threads at once. It should only be performed once. // Once the operation is done though, another request would be valid. CounterOperation cop = new CounterOperation(); ExecutorService es = Executors.newFixedThreadPool(10); for (int i = 0; i < 10; ++i) { es.submit(new Runnable() { @Override public void run() { sync.perform("a", hive, cop); } }); } es.shutdown(); es.awaitTermination(10, TimeUnit.SECONDS); assertEquals(1, cop.getCounter()); // perform once more, this should now work again sync.perform("a", hive, cop); assertEquals(2, cop.getCounter()); } private static class CounterOperation extends Operation<Void> { private long counter = 0; @Override public Void call() throws Exception { Thread.sleep(200); counter++; return null; } public long getCounter() { return counter; } } }
package butterknife; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface BindArray { int value(); }
package ru.spec.java1.lec6; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.TreeSet; public class FilesTest { public static void main(String[] args) throws FileNotFoundException { System.out.println("Enter any string"); InputStream in = System.in; File file = new File("C:/java/java1.txt"); in = new FileInputStream(file); //in = new URL("http://specialist.ru").openStream(); Scanner scanner = new Scanner(in); Map<String,Integer> stat = new HashMap<>(); ArrayList<String> strings = new ArrayList<>(); strings.listIterator().previousIndex(); TreeSet<String> set = new TreeSet<>(); for (;scanner.hasNextLine();) { //String nextLine = scanner.nextLine(); String [] nextLine = scanner.nextLine().toLowerCase().split("[^а-яё]+"); for (String word:nextLine) { if(!word.isEmpty()) { Integer count = stat.get(word); count=count==null?1:count+1; stat.put(word,count); } } //System.out.println("Your string is " + nextLine); }// TODO Auto-generated method stub stat.forEach((key,val)-> System.out.println(key+" = " +val)); String [] nextLine = scanner.nextLine().toLowerCase().split("[^а-яё]+"); strings.addAll(Arrays.asList(nextLine)); //System.out.println(nextLine); } // set.addAll(strings); // for (String word : set) { // добавляет уникальные значения // // System.out.print (word + "(" +" "+ ")"); // } ///// // //System.out.println(split.length); // System.out.println(set.size())); }
//,temp,NexentaStorAppliance.java,324,334,temp,NexentaStorAppliance.java,141,150 //,3 public class xxx { void createIscsiTarget(String targetName) { try { client.execute(NmsResponse.class, "iscsitarget", "create_target", new CreateIscsiTargetRequestParams(targetName)); } catch (CloudRuntimeException ex) { if (!ex.getMessage().contains("already configured")) { throw ex; } logger.debug("Ignored target creation error: " + ex); } } };
package view.universals.string; import utils.libs.html.HtmlElem; import utils.libs.html.HtmlPage; import utils.libs.html.HtmlText; public class UniversalMessageHtmlView extends HtmlPage { public UniversalMessageHtmlView(String message) { super("ImoProject", h1(new HtmlText("Output")), new HtmlElem("p", new HtmlText(message) ) ); } }
package calofit.storage; import static java.util.Objects.requireNonNull; import java.io.IOException; import java.nio.file.Path; import java.util.Optional; import java.util.logging.Logger; import calofit.commons.core.LogsCenter; import calofit.commons.exceptions.DataConversionException; import calofit.commons.exceptions.IllegalValueException; import calofit.commons.util.FileUtil; import calofit.commons.util.JsonUtil; import calofit.model.CalorieBudget; /** * A class to access {@link CalorieBudget} data stored as a json file on the hard disk. */ public class JsonCalorieBudgetStorage implements CalorieBudgetStorage { private static final Logger logger = LogsCenter.getLogger(JsonCalorieBudgetStorage.class); private Path filePath; public JsonCalorieBudgetStorage(Path filePath) { this.filePath = filePath; } @Override public Path getCalorieBudgetFilePath() { return filePath; } @Override public Optional<CalorieBudget> readCalorieBudget() throws DataConversionException { return readCalorieBudget(filePath); } /** * Similar to {@link #readCalorieBudget()}. * * @param filePath location of the data. Cannot be null. * @throws DataConversionException if the file is not in the correct format. */ @Override public Optional<CalorieBudget> readCalorieBudget(Path filePath) throws DataConversionException { requireNonNull(filePath); Optional<JsonSerializableCalorieBudget> jsonBudget = JsonUtil.readJsonFile( filePath, JsonSerializableCalorieBudget.class); if (!jsonBudget.isPresent()) { return Optional.empty(); } try { return Optional.of(jsonBudget.get().toModelType()); } catch (IllegalValueException ive) { logger.info("Illegal values found in " + filePath + ": " + ive.getMessage()); throw new DataConversionException(ive); } } @Override public void saveCalorieBudget(CalorieBudget budget) throws IOException { saveCalorieBudget(budget, filePath); } /** * Similar to {@link #saveCalorieBudget(CalorieBudget)}. * * @param filePath location of the data. Cannot be null. */ @Override public void saveCalorieBudget(CalorieBudget budget, Path filePath) throws IOException { requireNonNull(budget); requireNonNull(filePath); FileUtil.createIfMissing(filePath); JsonUtil.saveJsonFile(new JsonSerializableCalorieBudget(budget), filePath); } }
package JDescriptors.fr.lip6.quantizer; public interface Quantizer { /** * find the bin corresponding to input vector * @param p the input vector * @return the bin corresponding to the vector */ public int getBin(int[] p); /** * size of the histogram * @return */ public int getBinNumber(); }
package br.com.b2vnauthapi.b2vnauthapi.exceptions.validacao; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class ValidacaoExceptionDetails { private long timestamp; private int status; private String error; private String message; }
/* * 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.jackrabbit.test.api.version.simple; import javax.jcr.InvalidItemStateException; import javax.jcr.RepositoryException; import javax.jcr.UnsupportedRepositoryOperationException; import javax.jcr.version.Version; import javax.jcr.version.VersionManager; /** * <code>CheckinTest</code> covers tests related to {@link javax.jcr.Node#checkin()} * on simple versionable nodes. * */ public class CheckinTest extends AbstractVersionTest { protected void setUp() throws Exception { super.setUp(); try { VersionManager versionManager = versionableNode.getSession().getWorkspace().getVersionManager(); String path = versionableNode.getPath(); versionManager.checkout(path); } catch (RepositoryException e) { cleanUp(); throw e; } } /** * Test if Node.isCheckedOut() return false after calling Node.checkin() * * @throws javax.jcr.RepositoryException */ @SuppressWarnings("deprecation") public void testIsCheckedOut() throws RepositoryException { versionableNode.checkin(); assertTrue("After calling Node.checkin() on a versionable node N, N.isCheckedOut() must return false", versionableNode.isCheckedOut() == false); } /** * Test if VersionManager.isCheckedOut(P) returns false if P is the * absolute path of a checked-in versionable node. * * @throws javax.jcr.RepositoryException */ public void testIsCheckedOutJcr2() throws RepositoryException { VersionManager versionManager = versionableNode.getSession().getWorkspace().getVersionManager(); String path = versionableNode.getPath(); versionManager.checkin(path); assertTrue("VersionManager.isCheckedOut(P) must return false if the path P resolves to a checked-in node.", versionManager.isCheckedOut(path) == false); } /** * Test if Node.checkin() on a checked-in node has no effect. * * @throws RepositoryException */ @SuppressWarnings("deprecation") public void testMultipleCheckinHasNoEffect() throws RepositoryException { Version v = versionableNode.checkin(); try { Version v2 = versionableNode.checkin(); assertTrue("Calling checkin() on a node that is already checked-in must not have an effect.", v.isSame(v2)); } catch (RepositoryException e) { fail("Calling checkin() on a node that is already checked-in must not throw an exception."); } } /** * Test if VersionManager.checkin(P) has no effect if the path P resolves * to a checked-in node. * * @throws RepositoryException */ public void testMultipleCheckinHasNoEffectJcr2() throws RepositoryException { VersionManager versionManager = versionableNode.getSession().getWorkspace().getVersionManager(); String path = versionableNode.getPath(); Version v = versionManager.checkin(path); try { Version v2 = versionManager.checkin(path); assertTrue("Calling VersionManager.checkin(P) must not have an if the path P resolves to a node that is already checked-in.", v.isSame(v2)); } catch (RepositoryException e) { fail("Calling VersionManager.checkin(P) must not throw an exception if the path P resolves to a node that is already checked-in."); } } /** * Test if Node.checkin() throws InvalidItemStateException if the node * has unsaved changes pending. * * @throws RepositoryException */ @SuppressWarnings("deprecation") public void testCheckinWithPendingChanges() throws RepositoryException { try { // modify node without calling save() versionableNode.setProperty(propertyName1, propertyValue); versionableNode.checkin(); fail("InvalidItemStateException must be thrown on attempt to checkin a node having any unsaved changes pending."); } catch (InvalidItemStateException e) { // ok } } /** * Test if VersionManager.checkin(P) throws InvalidItemStateException if * the path P resolves to a node that has unsaved changes pending. * * @throws RepositoryException */ public void testCheckinWithPendingChangesJcr2() throws RepositoryException { try { // modify node without calling save() versionableNode.setProperty(propertyName1, propertyValue); VersionManager versionManager = versionableNode.getSession().getWorkspace().getVersionManager(); String path = versionableNode.getPath(); versionManager.checkin(path); fail("InvalidItemStateException must be thrown on attempt to checkin a node having any unsaved changes pending."); } catch (InvalidItemStateException e) { // ok } } /** * Test if Node.isCheckedOut() returns false after Node.checkin(). * * @throws RepositoryException */ @SuppressWarnings("deprecation") public void testIsNotCheckedOut() throws RepositoryException { versionableNode.checkin(); boolean isCheckedOut = versionableNode.isCheckedOut(); assertFalse("Node.isCheckedOut() must return false after Node.checkin().", isCheckedOut); } /** * Test if VersionManager.isCheckedOut(P) returns false after calling VersionManager.checkin(P). * * @throws RepositoryException */ public void testIsNotCheckedOutJcr2() throws RepositoryException { VersionManager versionManager = versionableNode.getSession().getWorkspace().getVersionManager(); String path = versionableNode.getPath(); versionManager.checkin(path); boolean isCheckedOut = versionManager.isCheckedOut(path); assertFalse("VersionManager.isCheckedOut(P) must return false after VersionManager.checkin(P).", isCheckedOut); } /** * Test if Node.checkin() adds another version to the VersionHistory * * @throws RepositoryException */ @SuppressWarnings("deprecation") public void testCheckinCreatesNewVersion() throws RepositoryException { long initialNumberOfVersions = getNumberOfVersions(versionableNode.getVersionHistory()); versionableNode.checkin(); long numberOfVersions = getNumberOfVersions(versionableNode.getVersionHistory()); assertTrue("Checkin must create a new Version in the VersionHistory.", numberOfVersions == initialNumberOfVersions + 1); } /** * Test if VersionManager.checkin(String) adds another version to the VersionHistory * * @throws RepositoryException */ public void testCheckinCreatesNewVersionJcr2() throws RepositoryException { VersionManager versionManager = versionableNode.getSession().getWorkspace().getVersionManager(); String path = versionableNode.getPath(); long initialNumberOfVersions = getNumberOfVersions(versionManager.getVersionHistory(path)); versionManager.checkin(path); long numberOfVersions = getNumberOfVersions(versionManager.getVersionHistory(path)); assertTrue("Checkin must create a new Version in the VersionHistory.", numberOfVersions == initialNumberOfVersions + 1); } /** * Test calling Node.checkin() on a non-versionable node. * * @throws RepositoryException */ @SuppressWarnings("deprecation") public void testCheckinNonVersionableNode() throws RepositoryException { try { nonVersionableNode.checkin(); fail("Node.checkin() on a non-versionable node must throw UnsupportedRepositoryOperationException"); } catch (UnsupportedRepositoryOperationException e) { //success } } /** * Test calling VersionManager.checkin(P) with the path P resolving to * a non-versionable node. * * @throws RepositoryException */ public void testCheckinNonVersionableNodeJcr2() throws RepositoryException { try { VersionManager versionManager = nonVersionableNode.getSession().getWorkspace().getVersionManager(); String path = nonVersionableNode.getPath(); versionManager.checkin(path); fail("VersionManager.checkin(P) must throw UnsupportedRepositoryOperationException if the path P resolves to a non-versionable node."); } catch (UnsupportedRepositoryOperationException e) { //success } } }
/* * Copyright 2019 Adobe. All rights reserved. * This file is licensed 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 REPRESENTATIONS * OF ANY KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package com.adobe.target.sample.model; import javax.validation.constraints.NotEmpty; import java.util.Calendar; public class Product { private Long id; @NotEmpty(message = "Image url is required.") private String image; @NotEmpty(message = "Summary is required.") private String summary; private Calendar created = Calendar.getInstance(); public Product(Long id, @NotEmpty(message = "Image url is required.") String image, @NotEmpty(message = "Summary is required.") String summary) { this.id = id; this.image = image; this.summary = summary; } public Product() { } public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public Calendar getCreated() { return this.created; } public void setCreated(Calendar created) { this.created = created; } public String getImage() { return this.image; } public void setImage(String text) { this.image = text; } public String getSummary() { return this.summary; } public void setSummary(String summary) { this.summary = summary; } }
/** * Root package of the MqttAdapter Module. */ package org.springframework.integration.mqtt;
package app; import java.io.File; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * @author saikat * Created on 30/3/2019 */ public class JenkinsDataExporter { private static ExecutorService executor= Executors.newFixedThreadPool(10); public static void exportJenkinsData(List<File> buildsDirectory){ buildsDirectory.parallelStream().forEach(dir->{ if(dir.isDirectory()) { executor.submit(new LogScraper(dir)); executor.submit(new XMLScraper(dir)); } }); executor.shutdown(); } }
package org.jsondoc.core.util; import org.jsondoc.core.annotation.ApiObjectField; import org.jsondoc.core.pojo.JSONDocTemplate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Field; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import static java.lang.reflect.Modifier.isFinal; import static java.lang.reflect.Modifier.isStatic; public class JSONDocTemplateBuilder { private static final Logger log = LoggerFactory.getLogger(JSONDocTemplateBuilder.class); private static final Map<Class<?>, Class<?>> primitives = new HashMap<Class<?>, Class<?>>(); static { primitives.put(boolean.class, Boolean.class); primitives.put(byte.class, Byte.class); primitives.put(char.class, String.class); primitives.put(double.class, Double.class); primitives.put(float.class, Float.class); primitives.put(int.class, Integer.class); primitives.put(long.class, Long.class); primitives.put(short.class, Short.class); primitives.put(void.class, Void.class); } public static JSONDocTemplate build(Class<?> clazz, Set<Class<?>> jsondocObjects) { final JSONDocTemplate jsonDocTemplate = new JSONDocTemplate(); if(jsondocObjects.contains(clazz)) { try { Set<JSONDocFieldWrapper> fields = getAllDeclaredFields(clazz); for (JSONDocFieldWrapper jsondocFieldWrapper : fields) { Field field = jsondocFieldWrapper.getField(); if (isFinal(field.getModifiers()) && isStatic(field.getModifiers())) { continue; } String fieldName = field.getName(); ApiObjectField apiObjectField = field.getAnnotation(ApiObjectField.class); if (apiObjectField != null && !apiObjectField.name().isEmpty()) { fieldName = apiObjectField.name(); } Object value; // This condition is to avoid StackOverflow in case class "A" // contains a field of type "A" if (field.getType().equals(clazz) || (apiObjectField != null && !apiObjectField.processtemplate())) { value = getValue(Object.class, field.getGenericType(), fieldName, jsondocObjects); } else { value = getValue(field.getType(), field.getGenericType(), fieldName, jsondocObjects); } jsonDocTemplate.put(fieldName, value); } } catch (Exception e) { log.error("Error in JSONDocTemplate creation for class [" + clazz.getCanonicalName() + "]", e); } } return jsonDocTemplate; } private static Object getValue(Class<?> fieldClass, Type fieldGenericType, String fieldName, Set<Class<?>> jsondocObjects) { if (fieldClass.isPrimitive()) { return getValue(wrap(fieldClass), null, fieldName, jsondocObjects); } else if (Map.class.isAssignableFrom(fieldClass)) { return new HashMap<Object, Object>(); } else if (Number.class.isAssignableFrom(fieldClass)) { return new Integer(0); } else if (String.class.isAssignableFrom(fieldClass) || fieldClass.isEnum()) { return new String(""); } else if (Boolean.class.isAssignableFrom(fieldClass)) { return new Boolean("true"); } else if (fieldClass.isArray() || Collection.class.isAssignableFrom(fieldClass)) { return new ArrayList<Object>(); } else { return build(fieldClass, jsondocObjects); } } private static Set<JSONDocFieldWrapper> getAllDeclaredFields(Class<?> clazz) { Set<JSONDocFieldWrapper> fields = new TreeSet<JSONDocFieldWrapper>(); List<Field> declaredFields = new ArrayList<Field>(); if (clazz.isEnum()) { return fields; } else { declaredFields.addAll(Arrays.asList(clazz.getDeclaredFields())); } for (Field field : declaredFields) { if (field.isAnnotationPresent(ApiObjectField.class)) { ApiObjectField annotation = field.getAnnotation(ApiObjectField.class); fields.add(new JSONDocFieldWrapper(field, annotation.order())); } else { fields.add(new JSONDocFieldWrapper(field, Integer.MAX_VALUE)); } } if (clazz.getSuperclass() != null) { fields.addAll(getAllDeclaredFields(clazz.getSuperclass())); } return fields; } @SuppressWarnings("unchecked") private static <T> Class<T> wrap(Class<T> clazz) { return clazz.isPrimitive() ? (Class<T>) primitives.get(clazz) : clazz; } }
package mcjty.rftoolsdim.dimensions.world.mapgen; import mcjty.rftoolsdim.dimensions.world.GenericChunkGenerator; import mcjty.rftoolsdim.dimensions.world.terrain.BaseTerrainGenerator; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.world.World; import net.minecraft.world.chunk.ChunkPrimer; import java.util.Random; public class MapGenOrbs { private final GenericChunkGenerator provider; private final boolean large; private final int r; public MapGenOrbs(GenericChunkGenerator provider, boolean large) { this.provider = provider; this.large = large; r = large ? 2 : 1; } public void generate(World world, int chunkX, int chunkZ, ChunkPrimer primer) { IBlockState[] blocks = large ? provider.dimensionInformation.getHugeSphereBlocks() : provider.dimensionInformation.getSphereBlocks(); for (int cx = -r ; cx <= r ; cx++) { for (int cz = -r ; cz <= r ; cz++) { Random random = new Random((world.getSeed() + (chunkX+cx)) * 113 + (chunkZ+cz) * 31 + 77); random.nextFloat(); if (random.nextFloat() < .05f) { int x = cx * 16 + random.nextInt(16); int y = 40 + random.nextInt(40); int z = cz * 16 + random.nextInt(16); int radius = random.nextInt(large ? 20 : 6) + (large ? 10 : 4); IBlockState block = Blocks.STONE.getDefaultState(); if (blocks.length > 1) { block = blocks[random.nextInt(blocks.length)]; } else if (blocks.length == 1) { block = blocks[0]; } fillSphere(primer, x, y, z, radius, block); } } } } private void fillSphere(ChunkPrimer primer, int centerx, int centery, int centerz, int radius, IBlockState block) { double sqradius = radius * radius; for (int x = 0 ; x < 16 ; x++) { double dxdx = (x-centerx) * (x-centerx); for (int z = 0 ; z < 16 ; z++) { double dzdz = (z-centerz) * (z-centerz); int index = (x * 16 + z) * 256; for (int y = centery-radius ; y <= centery+radius ; y++) { double dydy = (y-centery) * (y-centery); double sqdist = dxdx + dydy + dzdz; if (sqdist <= sqradius) { BaseTerrainGenerator.setBlockState(primer, index + y, block); } } } } } }
/* * Copyright 2018 Nafundi * * 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.odk.kitaaman.android.openrosa; public class HttpHeadResult { private final int statusCode; private final CaseInsensitiveHeaders headers; public HttpHeadResult(int statusCode, CaseInsensitiveHeaders headers) { this.statusCode = statusCode; this.headers = headers; } public int getStatusCode() { return statusCode; } public CaseInsensitiveHeaders getHeaders() { return headers; } }
package edu.pdx.cs410J.examples; import edu.pdx.cs410J.lang.*; import java.util.*; /** * This class is a <code>Comparator</code> that compares * <code>Object</code>s based on the name of their classes. */ public class ClassComparator implements Comparator<Object> { public int compare(Object o1, Object o2) { String name1 = o1.getClass().getName(); String name2 = o2.getClass().getName(); // Take advantage of String's compartTo method return name1.compareTo(name2); } /** * Create a bunch of object and store them in a set using a * <code>ClassComparator</code>. */ public static void main(String[] args) { Set<Object> set = new TreeSet<Object>(new ClassComparator()); set.add("Hello"); set.add(new Cow("Betty")); set.add(new Vector()); set.add(new Ant("Richard")); // Print out the set Iterator iter = set.iterator(); while (iter.hasNext()) { Object o = iter.next(); String s = o + " (" + o.getClass().getName() + ")"; System.out.println(s); } } }
package me.limeglass.skungee.bungeecord.handlercontroller; import java.net.InetAddress; import java.util.HashSet; import java.util.Map; import java.util.Set; import me.limeglass.skungee.bungeecord.Skungee; import me.limeglass.skungee.objects.SkungeePlayer; import me.limeglass.skungee.objects.packets.SkungeePacket; import me.limeglass.skungee.objects.packets.SkungeePacketType; import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.config.ServerInfo; import net.md_5.bungee.api.connection.ProxiedPlayer; public abstract class SkungeePlayerExecutor extends SkungeeHandler { protected final Map<String, ServerInfo> servers = ProxyServer.getInstance().getServers(); protected Set<ProxiedPlayer> players = new HashSet<ProxiedPlayer>(); public SkungeePlayerExecutor(String name) { super(name); } public SkungeePlayerExecutor(SkungeePacketType... types) { super(types); } public abstract void executePacket(SkungeePacket packet, InetAddress address); @Override public Object handlePacket(SkungeePacket packet, InetAddress address) { executePacket(packet, address); return null; } @Override public boolean onPacketCall(SkungeePacket packet, InetAddress address) { players.clear(); if (packet.getPlayers() != null) { for (SkungeePlayer player : packet.getPlayers()) { ProxiedPlayer proxiedPlayer = null; if (Skungee.getConfig().getBoolean("IncomingUUIDs", true) && player.getUUID() != null) { proxiedPlayer = ProxyServer.getInstance().getPlayer(player.getUUID()); if (proxiedPlayer == null) { proxiedPlayer = ProxyServer.getInstance().getPlayer(player.getName()); //invalid UUID } } else if (player.getName() != null) { proxiedPlayer = ProxyServer.getInstance().getPlayer(player.getName()); } if (proxiedPlayer != null) players.add(proxiedPlayer); } } return !players.isEmpty(); } }
package com.alipay.api.response; import com.alipay.api.internal.mapping.ApiField; import com.alipay.api.AlipayResponse; /** * ALIPAY API: alipay.commerce.logistics.order.istdretry.create response. * * @author auto create * @since 1.0, 2021-03-31 13:48:31 */ public class AlipayCommerceLogisticsOrderIstdretryCreateResponse extends AlipayResponse { private static final long serialVersionUID = 6853945877567135588L; /** * 优惠券费用 */ @ApiField("coupon_fee") private String couponFee; /** * 运费 */ @ApiField("deliver_fee") private String deliverFee; /** * 预计骑手还剩多久接单,单位:秒 */ @ApiField("dispatch_duration") private Long dispatchDuration; /** * 配送距离(单位:米) */ @ApiField("distance") private Long distance; /** * 实际运费 */ @ApiField("fee") private String fee; /** * 收货码,骑手必须输入收货码才能完成订单妥投 */ @ApiField("finish_code") private String finishCode; /** * 保价费用 */ @ApiField("insurance_fee") private String insuranceFee; /** * 支付宝订单流水号 */ @ApiField("order_no") private String orderNo; /** * 支付金额, 实际扣减的费用以此字段为准 */ @ApiField("pay_amount") private String payAmount; /** * 取货码, 骑手必须输入取货码才能从商家取货 */ @ApiField("pickup_code") private String pickupCode; /** * 即时配送运单状态 */ @ApiField("status") private String status; /** * 即时配送运单编号 */ @ApiField("waybill_no") private String waybillNo; public void setCouponFee(String couponFee) { this.couponFee = couponFee; } public String getCouponFee( ) { return this.couponFee; } public void setDeliverFee(String deliverFee) { this.deliverFee = deliverFee; } public String getDeliverFee( ) { return this.deliverFee; } public void setDispatchDuration(Long dispatchDuration) { this.dispatchDuration = dispatchDuration; } public Long getDispatchDuration( ) { return this.dispatchDuration; } public void setDistance(Long distance) { this.distance = distance; } public Long getDistance( ) { return this.distance; } public void setFee(String fee) { this.fee = fee; } public String getFee( ) { return this.fee; } public void setFinishCode(String finishCode) { this.finishCode = finishCode; } public String getFinishCode( ) { return this.finishCode; } public void setInsuranceFee(String insuranceFee) { this.insuranceFee = insuranceFee; } public String getInsuranceFee( ) { return this.insuranceFee; } public void setOrderNo(String orderNo) { this.orderNo = orderNo; } public String getOrderNo( ) { return this.orderNo; } public void setPayAmount(String payAmount) { this.payAmount = payAmount; } public String getPayAmount( ) { return this.payAmount; } public void setPickupCode(String pickupCode) { this.pickupCode = pickupCode; } public String getPickupCode( ) { return this.pickupCode; } public void setStatus(String status) { this.status = status; } public String getStatus( ) { return this.status; } public void setWaybillNo(String waybillNo) { this.waybillNo = waybillNo; } public String getWaybillNo( ) { return this.waybillNo; } }
/* * Copyright© 2000 - 2021 SuperMap Software Co.Ltd. All rights reserved. * This program are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html. */ package com.supermap.gaf.authority.resources; import com.supermap.gaf.authority.commontype.AuthPostRole; import com.supermap.gaf.authority.service.AuthPostRoleService; import com.supermap.gaf.authority.vo.AuthPostRoleSelectVo; import com.supermap.gaf.authority.vo.PostRoleVo; import com.supermap.gaf.authority.vo.TreeVo; import com.supermap.gaf.commontypes.MessageResult; import com.supermap.gaf.validator.StringRange; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.springframework.stereotype.Component; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.util.List; import java.util.Map; /** * @author yangdong * @date:2021/3/25 */ @Component @Api(value = "岗位角色接口") public class AuthPostRoleResource { private final AuthPostRoleService authPostRoleService; public AuthPostRoleResource(AuthPostRoleService authPostRoleService) { this.authPostRoleService = authPostRoleService; } @ApiOperation(value = "查询岗位角色", notes = "根据岗位角色id查询岗位角色") @ApiImplicitParams({ @ApiImplicitParam(name = "postRoleId", value = "岗位角色id", paramType = "path", dataType = "string", required = true) }) @GET @Produces({MediaType.APPLICATION_JSON}) @Path("/{postRoleId}") public MessageResult<AuthPostRole> getById(@PathParam("postRoleId") String postRoleId) { return MessageResult.data(authPostRoleService.getById(postRoleId)).message("查询成功").build(); } @ApiOperation(value = "条件查询岗位角色", notes = "条件查询岗位角色") @ApiImplicitParams({ @ApiImplicitParam(name = "searchFieldName", value = "模糊查询字段名", paramType = "query", dataType = "string"), @ApiImplicitParam(name = "searchFieldValue", value = "模糊查询字段值", paramType = "query", dataType = "string"), @ApiImplicitParam(name = "orderFieldName", value = "排序字段值", paramType = "query", dataType = "string"), @ApiImplicitParam(name = "orderMethod", value = "排序方式。升序为ASC,降序为DESC。默认不排序", allowableValues = "ASC,DESC", paramType = "query", dataType = "string"), @ApiImplicitParam(name = "pageNum", value = "页码", example = "1", defaultValue = "1", allowableValues = "range[1,infinity]", paramType = "query", dataType = "integer"), @ApiImplicitParam(name = "pageSize", value = "每页条数", example = "10", defaultValue = "10", allowableValues = "range(0,infinity]", paramType = "query", dataType = "integer"), }) @GET @Produces({MediaType.APPLICATION_JSON}) public MessageResult<Map<String, Object>> pageList(@StringRange(entityClass = AuthPostRole.class) @QueryParam("searchFieldName") String searchFieldName, @QueryParam("searchFieldValue") String searchFieldValue, @StringRange(entityClass = AuthPostRole.class) @QueryParam("orderFieldName") String orderFieldName, @StringRange({"asc", "desc"}) @QueryParam("orderMethod") String orderMethod, @QueryParam("pageNum") Integer pageNum, @DefaultValue("50") @QueryParam("pageSize") Integer pageSize) { if (pageNum == null || pageNum < 1) { pageNum = 1; } Integer offset = (pageNum - 1) * pageSize; AuthPostRoleSelectVo selectVo = AuthPostRoleSelectVo.builder() .searchFieldName(searchFieldName) .searchFieldValue(searchFieldValue) .orderFieldName(orderFieldName) .orderMethod(orderMethod) .offset(offset) .pageSize(pageSize) .build(); Map<String, Object> result; if (searchFieldName == null & orderFieldName == null) { result = authPostRoleService.pageList(selectVo); } else { result = authPostRoleService.searchList(selectVo); } return MessageResult.data(result).message("查询成功").build(); } @ApiOperation(value = "查询角色树和当前岗位绑定的角色id集合", notes = "返回的结果数据中,rootTreeNodes表示角色树,checkedKeys表示当前岗位绑定的角色id集合") @ApiImplicitParams({ @ApiImplicitParam(name = "postId", value = "岗位id", paramType = "query", dataType = "string", required = true) }) @GET @Produces({MediaType.APPLICATION_JSON}) @Path("/tree") public MessageResult<TreeVo> getRoleTree(@QueryParam("postId") String postId) { return MessageResult.data(authPostRoleService.getRoleTree(postId)).message("查询成功").build(); } @ApiOperation(value = "更新某岗位与角色的关联关系", notes = "传入岗位id和角色id列表,查询到该岗位已绑定的角色,与传入的角色id列表做对比更新") @ApiImplicitParams({ @ApiImplicitParam(name = "postRoleVo", value = "岗位角色关联对象", dataTypeClass = PostRoleVo.class, paramType = "body", required = true) }) @POST @Produces({MediaType.APPLICATION_JSON}) @Path("/handle") public MessageResult<Void> handlePostRole(PostRoleVo postRoleVo) { authPostRoleService.handlePostRole(postRoleVo); return MessageResult.successe(Void.class).status(200).message("关联操作成功").build(); } @ApiOperation(value = "查询岗位已绑定的岗位角色", notes = "根据岗位id条件查询岗位角色") @ApiImplicitParams({ @ApiImplicitParam(name = "postId", value = "岗位id", paramType = "query", dataType = "string", required = true) }) @GET @Produces({MediaType.APPLICATION_JSON}) @Path("/list-by-post/{postId}") public MessageResult<List<AuthPostRole>> listByPost(@PathParam("postId") String postId) { return MessageResult.data(authPostRoleService.listByPost(postId)).message("查询成功").build(); } }
package com.bitwise.marsrover.commands; import org.junit.Assert; import org.junit.Test; import com.bitwise.marsrover.MarsRover; import com.bitwise.marsrover.commands.RotateLeftCommand; import com.bitwise.marsrover.universe.Coordinates; import com.bitwise.marsrover.universe.Direction; import com.bitwise.marsrover.universe.Plateau; public class RotateLeftCommandTest { @Test public void testThatRotateLeftCommandRotatesTheNavigableObjectLeft() { //Given RotateLeftCommand command = new RotateLeftCommand(); Plateau plateau = new Plateau(5,5); Coordinates startingPosition = new Coordinates(1,2); MarsRover rover = new MarsRover(plateau, Direction.N, startingPosition); //When command.execute(rover); //Then Assert.assertEquals("1 2 W", rover.currentLocation()); } }
/* * This file is licensed under the MIT License, part of Roughly Enough Items. * Copyright (c) 2018, 2019, 2020 shedaniel * * 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 me.shedaniel.rei.plugin; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import it.unimi.dsi.fastutil.objects.Object2FloatMap; import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet; import it.unimi.dsi.fastutil.objects.ReferenceSet; import me.shedaniel.math.Rectangle; import me.shedaniel.rei.api.*; import me.shedaniel.rei.api.fluid.FluidSupportProvider; import me.shedaniel.rei.api.plugins.REIPluginV0; import me.shedaniel.rei.plugin.autocrafting.DefaultRecipeBookHandler; import me.shedaniel.rei.plugin.beacon.DefaultBeaconBaseCategory; import me.shedaniel.rei.plugin.beacon.DefaultBeaconBaseDisplay; import me.shedaniel.rei.plugin.beacon_payment.DefaultBeaconPaymentCategory; import me.shedaniel.rei.plugin.beacon_payment.DefaultBeaconPaymentDisplay; import me.shedaniel.rei.plugin.blasting.DefaultBlastingDisplay; import me.shedaniel.rei.plugin.brewing.DefaultBrewingCategory; import me.shedaniel.rei.plugin.brewing.DefaultBrewingDisplay; import me.shedaniel.rei.plugin.brewing.RegisteredBrewingRecipe; import me.shedaniel.rei.plugin.campfire.DefaultCampfireCategory; import me.shedaniel.rei.plugin.campfire.DefaultCampfireDisplay; import me.shedaniel.rei.plugin.composting.DefaultCompostingCategory; import me.shedaniel.rei.plugin.composting.DefaultCompostingDisplay; import me.shedaniel.rei.plugin.cooking.DefaultCookingCategory; import me.shedaniel.rei.plugin.crafting.DefaultCraftingCategory; import me.shedaniel.rei.plugin.crafting.DefaultCustomDisplay; import me.shedaniel.rei.plugin.crafting.DefaultShapedDisplay; import me.shedaniel.rei.plugin.crafting.DefaultShapelessDisplay; import me.shedaniel.rei.plugin.fuel.DefaultFuelCategory; import me.shedaniel.rei.plugin.fuel.DefaultFuelDisplay; import me.shedaniel.rei.plugin.information.DefaultInformationCategory; import me.shedaniel.rei.plugin.information.DefaultInformationDisplay; import me.shedaniel.rei.plugin.pathing.DefaultPathingCategory; import me.shedaniel.rei.plugin.pathing.DefaultPathingDisplay; import me.shedaniel.rei.plugin.pathing.DummyShovelItem; import me.shedaniel.rei.plugin.smelting.DefaultSmeltingDisplay; import me.shedaniel.rei.plugin.smithing.DefaultSmithingCategory; import me.shedaniel.rei.plugin.smithing.DefaultSmithingDisplay; import me.shedaniel.rei.plugin.smoking.DefaultSmokingDisplay; import me.shedaniel.rei.plugin.stonecutting.DefaultStoneCuttingCategory; import me.shedaniel.rei.plugin.stonecutting.DefaultStoneCuttingDisplay; import me.shedaniel.rei.plugin.stripping.DefaultStrippingCategory; import me.shedaniel.rei.plugin.stripping.DefaultStrippingDisplay; import me.shedaniel.rei.plugin.stripping.DummyAxeItem; import me.shedaniel.rei.plugin.tilling.DefaultTillingCategory; import me.shedaniel.rei.plugin.tilling.DefaultTillingDisplay; import me.shedaniel.rei.plugin.tilling.DummyHoeItem; import me.shedaniel.rei.utils.CollectionUtils; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screens.inventory.*; import net.minecraft.client.gui.screens.recipebook.RecipeUpdateListener; import net.minecraft.core.Registry; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.BlockTags; import net.minecraft.tags.ItemTags; import net.minecraft.tags.Tag; import net.minecraft.world.InteractionResultHolder; import net.minecraft.world.item.*; import net.minecraft.world.item.alchemy.Potion; import net.minecraft.world.item.alchemy.PotionBrewing; import net.minecraft.world.item.alchemy.PotionUtils; import net.minecraft.world.item.crafting.*; import net.minecraft.world.item.enchantment.Enchantment; import net.minecraft.world.item.enchantment.EnchantmentHelper; import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.block.ComposterBlock; import net.minecraft.world.level.block.entity.AbstractFurnaceBlockEntity; import net.minecraft.world.level.material.Fluid; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.ApiStatus; import java.util.*; import java.util.function.UnaryOperator; import java.util.stream.Stream; import static me.shedaniel.rei.impl.Internals.attachInstance; @Environment(EnvType.CLIENT) public class DefaultPlugin implements REIPluginV0, BuiltinPlugin { private static final Logger LOGGER = LogManager.getFormatterLogger("REI/DefaultPlugin"); public static final ResourceLocation CRAFTING = BuiltinPlugin.CRAFTING; public static final ResourceLocation SMELTING = BuiltinPlugin.SMELTING; public static final ResourceLocation SMOKING = BuiltinPlugin.SMOKING; public static final ResourceLocation BLASTING = BuiltinPlugin.BLASTING; public static final ResourceLocation CAMPFIRE = BuiltinPlugin.CAMPFIRE; public static final ResourceLocation STONE_CUTTING = BuiltinPlugin.STONE_CUTTING; public static final ResourceLocation STRIPPING = BuiltinPlugin.STRIPPING; public static final ResourceLocation BREWING = BuiltinPlugin.BREWING; public static final ResourceLocation PLUGIN = BuiltinPlugin.PLUGIN; public static final ResourceLocation COMPOSTING = BuiltinPlugin.COMPOSTING; public static final ResourceLocation FUEL = BuiltinPlugin.FUEL; public static final ResourceLocation SMITHING = BuiltinPlugin.SMITHING; public static final ResourceLocation BEACON = BuiltinPlugin.BEACON; public static final ResourceLocation BEACON_PAYMENT = BuiltinPlugin.BEACON_PAYMENT; public static final ResourceLocation TILLING = BuiltinPlugin.TILLING; public static final ResourceLocation PATHING = BuiltinPlugin.PATHING; public static final ResourceLocation INFO = BuiltinPlugin.INFO; private static final ResourceLocation DISPLAY_TEXTURE = new ResourceLocation("roughlyenoughitems", "textures/gui/display.png"); private static final ResourceLocation DISPLAY_TEXTURE_DARK = new ResourceLocation("roughlyenoughitems", "textures/gui/display_dark.png"); public static ResourceLocation getDisplayTexture() { return REIHelper.getInstance().getDefaultDisplayTexture(); } public DefaultPlugin() { attachInstance(this, BuiltinPlugin.class); } @Deprecated @ApiStatus.ScheduledForRemoval public static void registerBrewingDisplay(DefaultBrewingDisplay recipe) { RecipeHelper.getInstance().registerDisplay(recipe); } public static void registerBrewingRecipe(RegisteredBrewingRecipe recipe) { RecipeHelper.getInstance().registerDisplay(new DefaultBrewingDisplay(recipe.input, recipe.ingredient, recipe.output)); } public static void registerInfoDisplay(DefaultInformationDisplay display) { RecipeHelper.getInstance().registerDisplay(display); } @Override public void registerBrewingRecipe(Ingredient input, Ingredient ingredient, ItemStack output) { registerBrewingRecipe(new RegisteredBrewingRecipe(input, ingredient, output)); } @Override public void registerInformation(List<EntryStack> entryStacks, Component name, UnaryOperator<List<Component>> textBuilder) { registerInfoDisplay(DefaultInformationDisplay.createFromEntries(entryStacks, name).lines(textBuilder.apply(Lists.newArrayList()))); } @Override public ResourceLocation getPluginIdentifier() { return PLUGIN; } @Override public void registerEntries(EntryRegistry entryRegistry) { for (Item item : Registry.ITEM) { List<ItemStack> stacks = null; try { stacks = entryRegistry.appendStacksForItem(item); } catch (Exception ignored) { } if (stacks != null) { for (ItemStack stack : entryRegistry.appendStacksForItem(item)) { entryRegistry.registerEntry(EntryStack.create(stack)); } } else entryRegistry.registerEntry(EntryStack.create(item)); } EntryStack stack = EntryStack.create(Items.ENCHANTED_BOOK); List<EntryStack> enchantments = new ArrayList<>(); for (Enchantment enchantment : Registry.ENCHANTMENT) { for (int i = enchantment.getMinLevel(); i <= enchantment.getMaxLevel(); i++) { Map<Enchantment, Integer> map = new HashMap<>(); map.put(enchantment, i); ItemStack itemStack = new ItemStack(Items.ENCHANTED_BOOK); EnchantmentHelper.setEnchantments(map, itemStack); enchantments.add(EntryStack.create(itemStack).setting(EntryStack.Settings.CHECK_TAGS, EntryStack.Settings.TRUE)); } } entryRegistry.registerEntriesAfter(stack, enchantments); for (Fluid fluid : Registry.FLUID) { if (!fluid.defaultFluidState().isEmpty() && fluid.defaultFluidState().isSource()) entryRegistry.registerEntry(EntryStack.create(fluid)); } } @Override public void registerPluginCategories(RecipeHelper recipeHelper) { recipeHelper.registerCategories( new DefaultCraftingCategory(), new DefaultCookingCategory(SMELTING, EntryStack.create(Items.FURNACE), "category.rei.smelting"), new DefaultCookingCategory(SMOKING, EntryStack.create(Items.SMOKER), "category.rei.smoking"), new DefaultCookingCategory(BLASTING, EntryStack.create(Items.BLAST_FURNACE), "category.rei.blasting"), new DefaultCampfireCategory(), new DefaultStoneCuttingCategory(), new DefaultFuelCategory(), new DefaultBrewingCategory(), new DefaultCompostingCategory(), new DefaultStrippingCategory(), new DefaultSmithingCategory(), new DefaultBeaconBaseCategory(), new DefaultBeaconPaymentCategory(), new DefaultTillingCategory(), new DefaultPathingCategory(), new DefaultInformationCategory() ); } @Override public void registerRecipeDisplays(RecipeHelper recipeHelper) { recipeHelper.registerRecipes(CRAFTING, ShapelessRecipe.class, DefaultShapelessDisplay::new); recipeHelper.registerRecipes(CRAFTING, ShapedRecipe.class, DefaultShapedDisplay::new); recipeHelper.registerRecipes(SMELTING, SmeltingRecipe.class, DefaultSmeltingDisplay::new); recipeHelper.registerRecipes(SMOKING, SmokingRecipe.class, DefaultSmokingDisplay::new); recipeHelper.registerRecipes(BLASTING, BlastingRecipe.class, DefaultBlastingDisplay::new); recipeHelper.registerRecipes(CAMPFIRE, CampfireCookingRecipe.class, DefaultCampfireDisplay::new); recipeHelper.registerRecipes(STONE_CUTTING, StonecutterRecipe.class, DefaultStoneCuttingDisplay::new); recipeHelper.registerRecipes(SMITHING, UpgradeRecipe.class, DefaultSmithingDisplay::new); for (Map.Entry<Item, Integer> entry : AbstractFurnaceBlockEntity.getFuel().entrySet()) { recipeHelper.registerDisplay(new DefaultFuelDisplay(EntryStack.create(entry.getKey()), entry.getValue())); } List<EntryStack> arrowStack = Collections.singletonList(EntryStack.create(Items.ARROW)); ReferenceSet<Potion> registeredPotions = new ReferenceOpenHashSet<>(); EntryRegistry.getInstance().getEntryStacks().filter(entry -> entry.getItem() == Items.LINGERING_POTION).forEach(entry -> { Potion potion = PotionUtils.getPotion(entry.getItemStack()); if (registeredPotions.add(potion)) { List<List<EntryStack>> input = new ArrayList<>(); for (int i = 0; i < 4; i++) input.add(arrowStack); input.add(Collections.singletonList(EntryStack.create(entry.getItemStack()))); for (int i = 0; i < 4; i++) input.add(arrowStack); ItemStack outputStack = new ItemStack(Items.TIPPED_ARROW, 8); PotionUtils.setPotion(outputStack, potion); PotionUtils.setCustomEffects(outputStack, PotionUtils.getCustomEffects(entry.getItemStack())); List<EntryStack> output = Collections.singletonList(EntryStack.create(outputStack).addSetting(EntryStack.Settings.CHECK_TAGS, EntryStack.Settings.TRUE)); recipeHelper.registerDisplay(new DefaultCustomDisplay(null, input, output)); } }); if (ComposterBlock.COMPOSTABLES.isEmpty()) ComposterBlock.bootStrap(); Object2FloatMap<ItemLike> compostables = ComposterBlock.COMPOSTABLES; int i = 0; Iterator<List<Object2FloatMap.Entry<ItemLike>>> iterator = Iterators.partition(compostables.object2FloatEntrySet().stream().sorted(Map.Entry.comparingByValue()).iterator(), 48); while (iterator.hasNext()) { List<Object2FloatMap.Entry<ItemLike>> entries = iterator.next(); recipeHelper.registerDisplay(new DefaultCompostingDisplay(i, entries, compostables, new ItemStack(Items.BONE_MEAL))); i++; } DummyAxeItem.getStrippedBlocksMap().entrySet().stream().sorted(Comparator.comparing(b -> Registry.BLOCK.getKey(b.getKey()))).forEach(set -> { recipeHelper.registerDisplay(new DefaultStrippingDisplay(EntryStack.create(set.getKey()), EntryStack.create(set.getValue()))); }); DummyHoeItem.getTilledBlocksMap().entrySet().stream().sorted(Comparator.comparing(b -> Registry.BLOCK.getKey(b.getKey()))).forEach(set -> { recipeHelper.registerDisplay(new DefaultTillingDisplay(EntryStack.create(set.getKey()), EntryStack.create(set.getValue().getBlock()))); }); DummyShovelItem.getPathBlocksMap().entrySet().stream().sorted(Comparator.comparing(b -> Registry.BLOCK.getKey(b.getKey()))).forEach(set -> { recipeHelper.registerDisplay(new DefaultPathingDisplay(EntryStack.create(set.getKey()), EntryStack.create(set.getValue().getBlock()))); }); recipeHelper.registerDisplay(new DefaultBeaconBaseDisplay(CollectionUtils.map(Lists.newArrayList(BlockTags.BEACON_BASE_BLOCKS.getValues()), ItemStack::new))); recipeHelper.registerDisplay(new DefaultBeaconPaymentDisplay(CollectionUtils.map(Lists.newArrayList(ItemTags.BEACON_PAYMENT_ITEMS.getValues()), ItemStack::new))); Set<Potion> potions = Sets.newLinkedHashSet(); for (Ingredient container : PotionBrewing.ALLOWED_CONTAINERS) { for (PotionBrewing.Mix<Potion> mix : PotionBrewing.POTION_MIXES) { Potion from = mix.from; Ingredient ingredient = mix.ingredient; Potion to = mix.to; Ingredient base = Ingredient.of(Arrays.stream(container.getItems()) .map(ItemStack::copy) .map(stack -> PotionUtils.setPotion(stack, from))); ItemStack output = Arrays.stream(container.getItems()) .map(ItemStack::copy) .map(stack -> PotionUtils.setPotion(stack, to)) .findFirst().orElse(ItemStack.EMPTY); registerBrewingRecipe(base, ingredient, output); potions.add(from); potions.add(to); } } for (Potion potion : potions) { for (PotionBrewing.Mix<Item> mix : PotionBrewing.CONTAINER_MIXES) { Item from = mix.from; Ingredient ingredient = mix.ingredient; Item to = mix.to; Ingredient base = Ingredient.of(PotionUtils.setPotion(new ItemStack(from), potion)); ItemStack output = PotionUtils.setPotion(new ItemStack(to), potion); registerBrewingRecipe(base, ingredient, output); } } } @Override public void postRegister() { // TODO Turn this into an API // Sit tight! This will be a fast journey! long time = System.currentTimeMillis(); EntryRegistry.getInstance().getEntryStacks().forEach(this::applyPotionTransformer); for (List<RecipeDisplay> displays : RecipeHelper.getInstance().getAllRecipesNoHandlers().values()) { for (RecipeDisplay display : displays) { for (List<EntryStack> entries : display.getInputEntries()) for (EntryStack stack : entries) applyPotionTransformer(stack); for (List<EntryStack> entries : display.getResultingEntries()) for (EntryStack stack : entries) applyPotionTransformer(stack); } } time = System.currentTimeMillis() - time; LOGGER.info("Applied Check Tags for potion in %dms.", time); } private void applyPotionTransformer(EntryStack stack) { if (stack.getItem() instanceof PotionItem) stack.addSetting(EntryStack.Settings.CHECK_TAGS, EntryStack.Settings.TRUE); } @Override public void registerBounds(DisplayHelper displayHelper) { BaseBoundsHandler baseBoundsHandler = BaseBoundsHandler.getInstance(); baseBoundsHandler.registerExclusionZones(EffectRenderingInventoryScreen.class, new DefaultPotionEffectExclusionZones()); baseBoundsHandler.registerExclusionZones(RecipeUpdateListener.class, new DefaultRecipeBookExclusionZones()); displayHelper.registerProvider(new DisplayHelper.DisplayBoundsProvider<AbstractContainerScreen<?>>() { @Override public Rectangle getScreenBounds(AbstractContainerScreen<?> screen) { return new Rectangle(screen.leftPos, screen.topPos, screen.imageWidth, screen.imageHeight); } @Override public Class<?> getBaseSupportedClass() { return AbstractContainerScreen.class; } }); } @Override public void registerOthers(RecipeHelper recipeHelper) { recipeHelper.registerAutoCraftingHandler(new DefaultRecipeBookHandler()); recipeHelper.registerWorkingStations(CRAFTING, EntryStack.create(Items.CRAFTING_TABLE)); recipeHelper.registerWorkingStations(SMELTING, EntryStack.create(Items.FURNACE)); recipeHelper.registerWorkingStations(SMOKING, EntryStack.create(Items.SMOKER)); recipeHelper.registerWorkingStations(BLASTING, EntryStack.create(Items.BLAST_FURNACE)); recipeHelper.registerWorkingStations(CAMPFIRE, EntryStack.create(Items.CAMPFIRE), EntryStack.create(Items.SOUL_CAMPFIRE)); recipeHelper.registerWorkingStations(FUEL, EntryStack.create(Items.FURNACE), EntryStack.create(Items.SMOKER), EntryStack.create(Items.BLAST_FURNACE)); recipeHelper.registerWorkingStations(BREWING, EntryStack.create(Items.BREWING_STAND)); recipeHelper.registerWorkingStations(STONE_CUTTING, EntryStack.create(Items.STONECUTTER)); recipeHelper.registerWorkingStations(COMPOSTING, EntryStack.create(Items.COMPOSTER)); recipeHelper.registerWorkingStations(SMITHING, EntryStack.create(Items.SMITHING_TABLE)); recipeHelper.registerWorkingStations(BEACON, EntryStack.create(Items.BEACON)); recipeHelper.registerWorkingStations(BEACON_PAYMENT, EntryStack.create(Items.BEACON)); Set<Item> axes = Sets.newHashSet(), hoes = Sets.newHashSet(), shovels = Sets.newHashSet(); EntryRegistry.getInstance().getEntryStacks().filter(stack -> stack.getType() == EntryStack.Type.ITEM).map(EntryStack::getItem).forEach(item -> { if (item instanceof AxeItem && axes.add(item)) { recipeHelper.registerWorkingStations(STRIPPING, EntryStack.create(item)); } if (item instanceof HoeItem && hoes.add(item)) { recipeHelper.registerWorkingStations(TILLING, EntryStack.create(item)); } if (item instanceof ShovelItem && shovels.add(item)) { recipeHelper.registerWorkingStations(PATHING, EntryStack.create(item)); } }); Tag<Item> axesTag = Minecraft.getInstance().getConnection().getTags().getItems().getTag(new ResourceLocation("c", "axes")); if (axesTag != null) { for (Item item : axesTag.getValues()) { if (axes.add(item)) recipeHelper.registerWorkingStations(STRIPPING, EntryStack.create(item)); } } Tag<Item> hoesTag = Minecraft.getInstance().getConnection().getTags().getItems().getTag(new ResourceLocation("c", "hoes")); if (hoesTag != null) { for (Item item : hoesTag.getValues()) { if (hoes.add(item)) recipeHelper.registerWorkingStations(TILLING, EntryStack.create(item)); } } Tag<Item> shovelsTag = Minecraft.getInstance().getConnection().getTags().getItems().getTag(new ResourceLocation("c", "shovels")); if (shovelsTag != null) { for (Item item : shovelsTag.getValues()) { if (shovels.add(item)) recipeHelper.registerWorkingStations(PATHING, EntryStack.create(item)); } } recipeHelper.removeAutoCraftButton(FUEL); recipeHelper.removeAutoCraftButton(COMPOSTING); recipeHelper.removeAutoCraftButton(BEACON); recipeHelper.removeAutoCraftButton(BEACON_PAYMENT); recipeHelper.removeAutoCraftButton(INFO); recipeHelper.registerScreenClickArea(new Rectangle(88, 32, 28, 23), CraftingScreen.class, CRAFTING); recipeHelper.registerScreenClickArea(new Rectangle(137, 29, 10, 13), InventoryScreen.class, CRAFTING); recipeHelper.registerScreenClickArea(new Rectangle(97, 16, 14, 30), BrewingStandScreen.class, BREWING); recipeHelper.registerScreenClickArea(new Rectangle(78, 32, 28, 23), FurnaceScreen.class, SMELTING); recipeHelper.registerScreenClickArea(new Rectangle(78, 32, 28, 23), SmokerScreen.class, SMOKING); recipeHelper.registerScreenClickArea(new Rectangle(78, 32, 28, 23), BlastFurnaceScreen.class, BLASTING); FluidSupportProvider.getInstance().registerProvider(itemStack -> { Item item = itemStack.getItem(); if (item instanceof BucketItem) return InteractionResultHolder.success(Stream.of(EntryStack.create(((BucketItem) item).content, 1000))); return InteractionResultHolder.pass(null); }); // SubsetsRegistry subsetsRegistry = SubsetsRegistry.INSTANCE; // subsetsRegistry.registerPathEntry("roughlyenoughitems:food", EntryStack.create(Items.MILK_BUCKET)); // subsetsRegistry.registerPathEntry("roughlyenoughitems:food/roughlyenoughitems:cookies", EntryStack.create(Items.COOKIE)); } @Override public int getPriority() { return -1; } }
/******************************************************************************* * Copyright (c) quickfixengine.org All rights reserved. * * This file is part of the QuickFIX FIX Engine * * This file may be distributed under the terms of the quickfixengine.org * license as defined by quickfixengine.org and appearing in the file * LICENSE included in the packaging of this file. * * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING * THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE. * * See http://www.quickfixengine.org/LICENSE for licensing information. * * Contact ask@quickfixengine.org if any conditions of this licensing * are not clear to you. ******************************************************************************/ package quickfix.field; import quickfix.IntField; public class AllocMethod extends IntField { static final long serialVersionUID = 20050617; public static final int FIELD = 1002; public static final int AUTOMATIC = 1; public static final int GUARANTOR = 2; public static final int MANUAL = 3; public AllocMethod() { super(1002); } public AllocMethod(int data) { super(1002, data); } }
/* * The MIT License (MIT) * * Copyright (c) 2010 Technische Universitaet Berlin * * 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 net.mumie.util.io; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Iterator; import java.util.Stack; import java.util.StringTokenizer; import java.io.FileFilter; import java.util.List; import java.util.ArrayList; /** * Static i/o utilities. * * @author Tilman Rassy <a href="mailto:rassy@math.tu-berlin.de">rassy@math.tu-berlin.de</a> * @version <code>$Id: IOUtil.java,v 1.18 2009/01/28 10:52:32 rassy Exp $</code> */ public class IOUtil { // -------------------------------------------------------------------------------- // Reading files // -------------------------------------------------------------------------------- /** * Returns the content of the specified file as a string. */ public static String readFile (File file) throws IOException { FileReader fileReader = new FileReader(file); char[] ioBuffer = new char[1024]; StringBuilder content = new StringBuilder(); int length = -1; while ( (length = fileReader.read(ioBuffer)) != -1 ) content.append(ioBuffer, 0, length); return content.toString(); } /** * Returns the content of the file with the specified name as a string. */ public static String readFile (String filename) throws IOException { return readFile(new File(filename)); } // -------------------------------------------------------------------------------- // Writing files // -------------------------------------------------------------------------------- /** * Writes the specified string to the specified file. */ public static void writeFile (File file, String string) throws IOException { FileWriter writer = new FileWriter(file); writer.write(string); writer.flush(); writer.close(); } /** * Writes the specified string to the file with the specified name. * * @param filename the name of the file * @param string the string to write */ public static void writeFile (String filename, String string) throws IOException { writeFile(new File(filename), string); } // -------------------------------------------------------------------------------- // Reading and writing streams // -------------------------------------------------------------------------------- /** * Reads all bytes from the specified input stream and writes them to the specified output * stream. */ public static void redirect (InputStream in, OutputStream out, boolean closeIn, boolean closeOut) throws IOException { byte[] ioBuffer = new byte[1024]; int number = -1; while ( (number = in.read(ioBuffer)) != -1 ) out.write(ioBuffer, 0, number); out.flush(); if ( closeIn ) in.close(); if ( closeOut ) out.close(); } /** * Reads all bytes from the specified input stream and discards them. Closes the stream * after the last byte was read. */ public static void discard (InputStream in) throws IOException { byte[] ioBuffer = new byte[1024]; while ( in.read(ioBuffer) != -1 ); in.close(); } /** * Reads all bytes from the specified input stream, discards them, and returns the total * number of bytes read. Closes the stream after the last byte was read. */ public static long discardAndGetLength (InputStream in) throws IOException { long totalCount = 0; int count = 0; byte[] ioBuffer = new byte[1024]; while ( (count = in.read(ioBuffer)) != -1 ) totalCount += count; in.close(); return totalCount; } // -------------------------------------------------------------------------------- // Copying files // -------------------------------------------------------------------------------- /** * <p> * Copies <code>source</code> to <code>target</code>. If <code>target</code> * is a directory, <code>source</code> is copied to a new file inside that directory; * otherwise, <code>target</code> becomes the copy of <code>source</code>. If * <code>createParents</code> is <code>true</code>, parent directories of * <code>target</code> are created if necessary. * </p> * <p> * If <code>source</code> is a directory, it is copied recursively. In that case, The * files to be copied can be restricted by <code>filter</code>. If <code>filter</code> * is null, all files are copied. Please note: If a directory is excluded by * <code>filter</code>, all its descendent files are not copied, either (this is * slightly different to the behaviour of the {@link #listFiles IOUtil.listFiles} * method). * </p> */ public static void copyFile (File source, File target, boolean createParents, FileFilter filter) throws IOException { // At source name to target if we are copying to a directory: if ( target.isDirectory() ) { String path = target.getPath(); String name = source.getName(); target = new File (path.endsWith(File.separator) ? path + name : path + File.separator + name); } // Checking parents of target file: File parent = target.getParentFile(); if ( parent != null && !parent.exists() ) { if ( createParents ) createDir(parent, false); else throw new IOException("copyFile: Parent directory does not exist: " + target); } if ( source.isDirectory() ) { createDir(target, false); for (File file : source.listFiles(filter)) copyFile(file, target, createParents, filter); } else { // Input stream for the source: FileInputStream in = new FileInputStream(source); // Output stream for the target: FileOutputStream out = new FileOutputStream(target); // Copying: byte[] ioBuffer = new byte[1024]; int number = -1; while ( (number = in.read(ioBuffer)) != -1 ) out.write(ioBuffer, 0, number); out.flush(); // Cleanup: in.close(); out.close(); } } /** * <p> * Copies <code>source</code> to <code>target</code>. If <code>target</code> * is a directory, <code>source</code> is copied to a new file inside that directory; * otherwise, <code>target</code> becomes the copy of <code>source</code>. If * <code>createParents</code> is <code>true</code>, parent directories of * <code>target</code> are created if necessary. If <code>source</code> is a directory, * it is copied recursively. * </p> */ public static void copyFile (File source, File target, boolean createParents) throws IOException { copyFile(source, target, createParents, null); } /** * <p> * Copies <code>source</code> to <code>destination</code>. If <code>destination</code> * is a directory, <code>source</code> is copied to a new file inside that directory; * otherwise, <code>destination</code> becomes the copy of <code>source</code>. * </p> * <p> * Same as {@link #copyFile(File,File,boolean) copyFile(source, destination, false)}. * </p> */ public static void copyFile (File source, File destination) throws IOException { copyFile(source, destination, false); } /** * <p> * Copies file <code>sourceName</code> (the source) to <code>destinationName</code>. If * the latter names a directory, the source is copied to a new file with the same local * name inside that directory; otherwise is is copied to a new file named * <code>destinationName</code>. * </p> * <p> * If <code>createParents</code> is <code>true</code>, parent directories of * <code>destination</code> are created if necessary. * </p> * * @param sourceName name of the source file * @param destinationName name of the destination file * @param createParents whether parent directories should be created if necessary */ public static void copyFile (String sourceName, String destinationName, boolean createParents) throws IOException { copyFile(new File(sourceName), new File(destinationName), createParents); } /** * <p> * Copies file <code>sourceName</code> (the source) to <code>destinationName</code>. If * the latter names a directory, the source is copied to a new file with the same local * name inside that directory; otherwise is is copied to a new file named * <code>destinationName</code>. * </p> * <p> * Same as *{@link #copyFile(String,String,boolean) copyFile(sourceName, destinationName, false)}. * </p> */ public static void copyFile (String sourceName, String destinationName) throws IOException { copyFile(sourceName, destinationName, false); } /** * Resolves <code>".."</code> and <code>"."</code> parts in <code>filename</code> and * returns the result. Example: * <pre> * Util.normalizeFilename("foo/bar/../bazz") * </pre> * yields <code>"foo/bazz"</code>. */ public static String normalizeFilename (String filename) { try { Stack parts = new Stack(); StringTokenizer tokenizer = new StringTokenizer(filename, File.separator); while ( tokenizer.hasMoreTokens() ) { String part = tokenizer.nextToken(); if ( part.equals("..") && !parts.empty() ) parts.pop(); else if ( part.equals(".") ) /* do nothing */ ; else parts.push(part); } StringBuffer normalizedFilename = new StringBuffer(); Iterator iterator = parts.iterator(); boolean first = true; while ( iterator.hasNext() ) { if ( !first || filename.startsWith(File.separator) ) normalizedFilename.append(File.separator); normalizedFilename.append((String)iterator.next()); first = false; } return normalizedFilename.toString(); } catch (Exception exception) { throw new IllegalArgumentException ("Can not normalize filename: " + filename + ": " + exception.toString()); } } /** * <p> * Concatenates two path fragments, taking care of leading/trailing path separators. * <code>path1</code> and <code>path2</code> are the first resp. second fragment. * <code>path1</code> may or may not end with a path separator. <code>path2</code> * may or may not start with a path separator. In any case, the resulting string contains * exactly one path separator between the parts specified by <code>path1</code> and * <code>path2</code>. E.g., on Unix systems, regardless whether <code>path1</code> is * </p> * <quote> * <code>"foo"</code> or <code>"foo/"</code> * </quote> * <p> * and <code>path2</code> is * </p> * <quote> * <code>"bar"</code> or <code>"/bar"</code>, * </quote> * <p> * the returned string is always * <quote> * <code>"foo/bar"</code> * </quote> */ public static String concatenatePaths (String path1, String path2) { if ( ( path1 == null ) || ( path1.length() == 0 ) ) return path2; else if ( path1.endsWith(File.separator) ) { if ( path2.startsWith(File.separator) ) return path1.concat(path2.substring(1)); else return path1.concat(path2); } else { if ( path2.startsWith(File.separator) ) return path1.concat(path2); else return path1.concat(File.separator).concat(path2); } } // -------------------------------------------------------------------------------- // Creating directories // -------------------------------------------------------------------------------- /** * Creates the specified directory. Necessary subdirectories are created, too, if not * existing. If <code>failIfExists</code> is true, an exception is thrown if the directory * already exists. If <code>failIfExists</code> is false, the method simply returns if the * directory already exists. If a file with the same name as the directory exists, but is * not a directory, an exception is thrown in any case. Unlike {@link File#mkdirs mkdirs} * in class {@link File File}, this method throws an exception if the creation failed, * instead of returning false. * * @throws IOException if the creation of the directory failed, <code>failIfExists</code> * is true and the directory already exists, or a non-directory file with the same name * exists. */ public static void createDir (File dir, boolean failIfExists) throws IOException { if ( dir.exists() ) { if ( failIfExists ) throw new IOException ("Can not create directory: Directory already exists: " + dir); if ( !dir.isDirectory() ) throw new IOException ("Can not create directory: File exists, but is not a directory: " + dir); } else { if ( !dir.mkdirs() ) throw new IOException("Failed to create directory: " + dir); } } /** * <p> * Creates the specified directory. Necessary subdirectories are created, too, if not * existing. If <code>failIfExists</code> is true, an exception is thrown if the directory * already exists. If <code>failIfExists</code> is false, the method simply returns if the * directory already exists. If a file with the same name as the directory exists, but is * not a directory, an exception is thrown in any case. Unlike {@link File#mkdirs mkdirs} * in class {@link File File}, this method throws an exception if the creation failed, * instead of returning false. * </p> * <p> * Same as {@link #createDir(File,boolean) createDir(new File(dirName), failIfExists)}. * </p> * * @throws IOException if the creation of the directory failed, <code>failIfExists</code> * is true and the directory already exists, or a non-directory file with the same name * exists. */ public static void createDir (String dirName, boolean failIfExists) throws IOException { createDir(new File(dirName), failIfExists); } // -------------------------------------------------------------------------------- // Deleting files and directories // -------------------------------------------------------------------------------- /** * Deletes the specified file. Unlike {@link File#delete delete} in class * {@link File File}, this method throws an exception if the deletion failed instead of * returning false. * * @throws IOException if the file could not be deleted */ public static void deleteFile (File file) throws IOException { if ( !file.delete() ) throw new IOException("Could not delete file: " + file); } /** * Recursively deletes the specified directory. * * @throws IllegalArgumentException if the specified file is not a directory * @throws IOException if the directory could not be deleted */ public static void deleteDir (File dir) throws IOException { if ( !dir.exists() ) return; if ( !dir.isDirectory() ) throw new IllegalArgumentException("Not a directory: " + dir); for (File file : dir.listFiles()) { if ( file.isDirectory() ) deleteDir(file); else deleteFile(file); } deleteFile(dir); } // -------------------------------------------------------------------------------- // Directroy contents // -------------------------------------------------------------------------------- /** * Auxiliary method to implement {@link #listFiles listFiles}. */ protected static void scanFiles (File dir, FileFilter filter, boolean recursive, List<File> files) { if ( !dir.isDirectory() ) throw new IllegalArgumentException("scanFiles: not a directory: " + dir); for (File file : dir.listFiles()) { if ( filter == null || filter.accept(file) ) files.add(file); if ( recursive && file.isDirectory() ) scanFiles(file, filter, recursive, files); } } /** * Returns all files in the specified directory accepted by the specified filter. If * <code>recursive</code> is true, subdirectories are processed recursivly; i.e., files in * descendant directories are returned, too. */ public static File[] listFiles (File dir, FileFilter filter, boolean recursive) { List<File> files = new ArrayList<File>(); scanFiles(dir, filter, recursive, files); return files.toArray(new File[files.size()]); } // -------------------------------------------------------------------------------- // Concatenating paths // -------------------------------------------------------------------------------- /** * Concatenates the specified paths, separated by {@link File#separator File.separator}. */ public static String concatPaths (String... paths) { StringBuffer buffer = new StringBuffer(); for (int i = 0; i < paths.length; i++) { String path = paths[i]; // Ignore some cases: if ( path == null || path.equals("") || path.equals(File.separator) ) continue; // If not the first item, remove a leading file separator: if ( i != 0 && path.startsWith(File.separator) && path.length() > File.separator.length() ) path = path.substring(File.separator.length()); // If not the last item, remove a trailing file separator: if ( i != paths.length && path.endsWith(File.separator) && path.length() > File.separator.length() ) path = path.substring(0, path.length()-File.separator.length()); // Add the item: if ( i > 0 ) buffer.append(File.separator); buffer.append(path); } return buffer.toString(); } // -------------------------------------------------------------------------------- // Comparing file times // -------------------------------------------------------------------------------- /** * Checks if the specified "target" file is outdated with respect of the specified * "source" file. */ public static boolean checkIfOutdated (File target, File source) { if ( source == null ) throw new NullPointerException("checkIfOutdated: source is null"); long sourceLastModified = source.lastModified(); if ( target == null ) return true; else if ( target.isDirectory() ) return checkIfOutdated(sourceLastModified, target); else return ( !target.exists() || target.lastModified() <= sourceLastModified ); // return ( target == null || target.lastModified() <= source.lastModified() ); } /** * Checks if the specified "target" file is outdated with respect of the specified * "source" file. */ public static boolean checkIfOutdated (String targetFilename, String sourceFilename) { return checkIfOutdated(new File(targetFilename), new File(sourceFilename)); } /** * */ protected static boolean checkIfOutdated (long sourceLastModified, File dir) { for (File target : dir.listFiles()) { if ( target.lastModified() <= sourceLastModified ) return true; if ( target.isDirectory() && checkIfOutdated(sourceLastModified, target) ) return true; } return false; } // -------------------------------------------------------------------------------- // Disabled constructor // -------------------------------------------------------------------------------- /** * Throws an exception to indicate that this class must not be instanciated. */ private IOUtil () { throw new RuntimeException("Class must not be instanciated: " + IOUtil.class.getName()); } }
/* * Copyright 2011-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.vertx.java.core.net.impl; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.DefaultFileRegion; import org.jboss.netty.channel.FileRegion; import org.jboss.netty.channel.socket.nio.NioSocketChannelConfig; import org.jboss.netty.handler.ssl.SslHandler; import org.jboss.netty.handler.stream.ChunkedFile; import org.vertx.java.core.Handler; import org.vertx.java.core.SimpleHandler; import org.vertx.java.core.impl.Context; import org.vertx.java.core.impl.VertxInternal; import org.vertx.java.core.logging.Logger; import org.vertx.java.core.logging.impl.LoggerFactory; import org.vertx.java.core.streams.ReadStream; import org.vertx.java.core.streams.WriteStream; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; /** * Abstract base class for TCP connections. * * @author <a href="http://tfox.org">Tim Fox</a> */ public abstract class ConnectionBase { private static final Logger log = LoggerFactory.getLogger(ConnectionBase.class); protected ConnectionBase(VertxInternal vertx, Channel channel, Context context) { this.vertx = vertx; this.channel = channel; this.context = context; } protected final VertxInternal vertx; protected final Channel channel; protected final Context context; protected Handler<Exception> exceptionHandler; protected Handler<Void> closedHandler; /** * Pause the connection, see {@link ReadStream#pause} */ public void pause() { channel.setReadable(false); } /** * Resume the connection, see {@link ReadStream#resume} */ public void resume() { channel.setReadable(true); } /** * Set the max size for the write queue, see {@link WriteStream#setWriteQueueMaxSize} */ public void setWriteQueueMaxSize(int size) { NioSocketChannelConfig conf = (NioSocketChannelConfig) channel.getConfig(); conf.setWriteBufferLowWaterMark(size / 2); conf.setWriteBufferHighWaterMark(size); } /** * Is the write queue full?, see {@link WriteStream#writeQueueFull} */ public boolean writeQueueFull() { return !channel.isWritable(); } /** * Close the connection */ public void close() { channel.close(); } /** * Set an exception handler on the connection */ public void exceptionHandler(Handler<Exception> handler) { this.exceptionHandler = handler; } /** * Set a closed handler on the connection */ public void closedHandler(Handler<Void> handler) { this.closedHandler = handler; } protected Context getContext() { return context; } protected void handleException(Exception e) { if (exceptionHandler != null) { setContext(); try { exceptionHandler.handle(e); } catch (Throwable t) { handleHandlerException(t); } } } protected void handleClosed() { if (closedHandler != null) { setContext(); try { closedHandler.handle(null); } catch (Throwable t) { handleHandlerException(t); } } } protected void addFuture(final Handler<Void> doneHandler, final ChannelFuture future) { future.addListener(new ChannelFutureListener() { public void operationComplete(final ChannelFuture channelFuture) throws Exception { setContext(); vertx.runOnLoop(new SimpleHandler() { public void handle() { if (channelFuture.isSuccess()) { doneHandler.handle(null); } else { Throwable err = channelFuture.getCause(); if (exceptionHandler != null && err instanceof Exception) { exceptionHandler.handle((Exception) err); } else { log.error("Unhandled exception", err); } } } }); } }); } protected void setContext() { Context.setContext(context); } protected void handleHandlerException(Throwable t) { vertx.reportException(t); } protected boolean isSSL() { return channel.getPipeline().get(SslHandler.class) != null; } protected ChannelFuture sendFile(File file) { final RandomAccessFile raf; try { raf = new RandomAccessFile(file, "r"); long fileLength = file.length(); // Write the content. ChannelFuture writeFuture; if (isSSL()) { // Cannot use zero-copy with HTTPS. writeFuture = channel.write(new ChunkedFile(raf, 0, fileLength, 8192)); } else { // No encryption - use zero-copy. final FileRegion region = new DefaultFileRegion(raf.getChannel(), 0, fileLength); writeFuture = channel.write(region); } writeFuture.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { raf.close(); } }); return writeFuture; } catch (IOException e) { handleException(e); return null; } } }
/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2011, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * 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 Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.annotations.cascade.multicircle.nonjpa.identity; /** * No Documentation */ @javax.persistence.Entity public class E extends AbstractEntity { private static final long serialVersionUID = 1226955558L; @javax.persistence.OneToMany(mappedBy = "e") private java.util.Set<D> dCollection = new java.util.HashSet<D>(); @javax.persistence.ManyToOne(optional = true) private F f; public java.util.Set<D> getDCollection() { return dCollection; } public void setDCollection(java.util.Set<D> dCollection) { this.dCollection = dCollection; } public F getF() { return f; } public void setF(F parameter) { this.f = parameter; } }
/* * 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. */ /** * Metadata Storage related API. */ package org.apache.bookkeeper.stream.storage.api.metadata;
/* * 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.rocketmq.client.impl.factory; import java.io.UnsupportedEncodingException; import java.net.DatagramSocket; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.apache.commons.lang3.StringUtils; import org.apache.rocketmq.client.ClientConfig; import org.apache.rocketmq.client.admin.MQAdminExtInner; import org.apache.rocketmq.client.exception.MQBrokerException; import org.apache.rocketmq.client.exception.MQClientException; import org.apache.rocketmq.client.impl.ClientRemotingProcessor; import org.apache.rocketmq.client.impl.FindBrokerResult; import org.apache.rocketmq.client.impl.MQAdminImpl; import org.apache.rocketmq.client.impl.MQClientAPIImpl; import org.apache.rocketmq.client.impl.MQClientManager; import org.apache.rocketmq.client.impl.consumer.DefaultMQPullConsumerImpl; import org.apache.rocketmq.client.impl.consumer.DefaultMQPushConsumerImpl; import org.apache.rocketmq.client.impl.consumer.MQConsumerInner; import org.apache.rocketmq.client.impl.consumer.ProcessQueue; import org.apache.rocketmq.client.impl.consumer.PullMessageService; import org.apache.rocketmq.client.impl.consumer.RebalanceService; import org.apache.rocketmq.client.impl.producer.DefaultMQProducerImpl; import org.apache.rocketmq.client.impl.producer.MQProducerInner; import org.apache.rocketmq.client.impl.producer.TopicPublishInfo; import org.apache.rocketmq.client.log.ClientLogger; import org.apache.rocketmq.client.producer.DefaultMQProducer; import org.apache.rocketmq.client.stat.ConsumerStatsManager; import org.apache.rocketmq.common.MQVersion; import org.apache.rocketmq.common.MixAll; import org.apache.rocketmq.common.ServiceState; import org.apache.rocketmq.common.UtilAll; import org.apache.rocketmq.common.constant.PermName; import org.apache.rocketmq.common.filter.ExpressionType; import org.apache.rocketmq.common.protocol.NamespaceUtil; import org.apache.rocketmq.logging.InternalLogger; import org.apache.rocketmq.common.message.MessageExt; import org.apache.rocketmq.common.message.MessageQueue; import org.apache.rocketmq.common.protocol.body.ConsumeMessageDirectlyResult; import org.apache.rocketmq.common.protocol.body.ConsumerRunningInfo; import org.apache.rocketmq.common.protocol.heartbeat.ConsumeType; import org.apache.rocketmq.common.protocol.heartbeat.ConsumerData; import org.apache.rocketmq.common.protocol.heartbeat.HeartbeatData; import org.apache.rocketmq.common.protocol.heartbeat.ProducerData; import org.apache.rocketmq.common.protocol.heartbeat.SubscriptionData; import org.apache.rocketmq.common.protocol.route.BrokerData; import org.apache.rocketmq.common.protocol.route.QueueData; import org.apache.rocketmq.common.protocol.route.TopicRouteData; import org.apache.rocketmq.remoting.RPCHook; import org.apache.rocketmq.remoting.common.RemotingHelper; import org.apache.rocketmq.remoting.exception.RemotingException; import org.apache.rocketmq.remoting.netty.NettyClientConfig; import org.apache.rocketmq.remoting.protocol.RemotingCommand; /** * MQClientInstance 封装了 RocketMQ 网络处理 API,是消息生产者(Producer)、消息消费者(Consumer)与 NameServer、Broker 打交道的网络通道 */ public class MQClientInstance { private final static long LOCK_TIMEOUT_MILLIS = 3000; private final InternalLogger log = ClientLogger.getLog(); private final ClientConfig clientConfig; private final int instanceIndex; private final String clientId; private final long bootTimestamp = System.currentTimeMillis(); private final ConcurrentMap<String/* group */, MQProducerInner> producerTable = new ConcurrentHashMap<String, MQProducerInner>(); private final ConcurrentMap<String/* group */, MQConsumerInner> consumerTable = new ConcurrentHashMap<String, MQConsumerInner>(); private final ConcurrentMap<String/* group */, MQAdminExtInner> adminExtTable = new ConcurrentHashMap<String, MQAdminExtInner>(); private final NettyClientConfig nettyClientConfig; private final MQClientAPIImpl mQClientAPIImpl; private final MQAdminImpl mQAdminImpl; private final ConcurrentMap<String/* Topic */, TopicRouteData> topicRouteTable = new ConcurrentHashMap<String, TopicRouteData>(); private final Lock lockNamesrv = new ReentrantLock(); private final Lock lockHeartbeat = new ReentrantLock(); private final ConcurrentMap<String/* Broker Name */, HashMap<Long/* brokerId */, String/* address */>> brokerAddrTable = new ConcurrentHashMap<String, HashMap<Long, String>>(); private final ConcurrentMap<String/* Broker Name */, HashMap<String/* address */, Integer>> brokerVersionTable = new ConcurrentHashMap<String, HashMap<String, Integer>>(); private final ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable r) { return new Thread(r, "MQClientFactoryScheduledThread"); } }); private final ClientRemotingProcessor clientRemotingProcessor; private final PullMessageService pullMessageService; // RocketMQ 消息队列重新分布是由 RebalanceService 线程来实现的。一个 MQClientInstance 持有一个 RebalanceService 实现,并随 MQClientInstance 的启动而启动 private final RebalanceService rebalanceService; private final DefaultMQProducer defaultMQProducer; private final ConsumerStatsManager consumerStatsManager; private final AtomicLong sendHeartbeatTimesTotal = new AtomicLong(0); private ServiceState serviceState = ServiceState.CREATE_JUST; private DatagramSocket datagramSocket; private Random random = new Random(); public MQClientInstance(ClientConfig clientConfig, int instanceIndex, String clientId) { this(clientConfig, instanceIndex, clientId, null); } public MQClientInstance(ClientConfig clientConfig, int instanceIndex, String clientId, RPCHook rpcHook) { this.clientConfig = clientConfig; this.instanceIndex = instanceIndex; this.nettyClientConfig = new NettyClientConfig(); this.nettyClientConfig.setClientCallbackExecutorThreads(clientConfig.getClientCallbackExecutorThreads()); this.nettyClientConfig.setUseTLS(clientConfig.isUseTLS()); this.clientRemotingProcessor = new ClientRemotingProcessor(this); this.mQClientAPIImpl = new MQClientAPIImpl(this.nettyClientConfig, this.clientRemotingProcessor, rpcHook, clientConfig); if (this.clientConfig.getNamesrvAddr() != null) { this.mQClientAPIImpl.updateNameServerAddressList(this.clientConfig.getNamesrvAddr()); log.info("user specified name server address: {}", this.clientConfig.getNamesrvAddr()); } this.clientId = clientId; this.mQAdminImpl = new MQAdminImpl(this); this.pullMessageService = new PullMessageService(this); this.rebalanceService = new RebalanceService(this); this.defaultMQProducer = new DefaultMQProducer(MixAll.CLIENT_INNER_PRODUCER_GROUP); this.defaultMQProducer.resetClientConfig(clientConfig); this.consumerStatsManager = new ConsumerStatsManager(this.scheduledExecutorService); log.info("Created a new client Instance, InstanceIndex:{}, ClientID:{}, ClientConfig:{}, ClientVersion:{}, SerializerType:{}", this.instanceIndex, this.clientId, this.clientConfig, MQVersion.getVersionDesc(MQVersion.CURRENT_VERSION), RemotingCommand.getSerializeTypeConfigInThisServer()); } public static TopicPublishInfo topicRouteData2TopicPublishInfo(final String topic, final TopicRouteData route) { TopicPublishInfo info = new TopicPublishInfo(); info.setTopicRouteData(route); // 顺序消息配置内容不为空 if (route.getOrderTopicConf() != null && route.getOrderTopicConf().length() > 0) { String[] brokers = route.getOrderTopicConf().split(";"); for (String broker : brokers) { String[] item = broker.split(":"); int nums = Integer.parseInt(item[1]); for (int i = 0; i < nums; i++) { // item[0] 为 brokerName,item[1] 为 queueId MessageQueue mq = new MessageQueue(topic, item[0], i); info.getMessageQueueList().add(mq); } } info.setOrderTopic(true); } else { // 顺序消息配置内容为空 List<QueueData> qds = route.getQueueDatas(); Collections.sort(qds); // 循环遍历路由信息的 QueueData 信息,如果队列没有写权限,则继续遍历下一个 QueueData for (QueueData qd : qds) { if (PermName.isWriteable(qd.getPerm())) { BrokerData brokerData = null; // 遍历 topic 分布的 broker 元数据 for (BrokerData bd : route.getBrokerDatas()) { // 根据 brokerName 找到 brokerData 信息 if (bd.getBrokerName().equals(qd.getBrokerName())) { brokerData = bd; break; } } // 找不到或没有找到 Master 节点,则遍历下一个 QueueData if (null == brokerData) { continue; } if (!brokerData.getBrokerAddrs().containsKey(MixAll.MASTER_ID)) { continue; } // 根据写队列个数,根据 topic + 序号创建 MessageQueue ,填充 topicPublishInfo 的 List<MessageQueue> 完成消息发送的路由查找 for (int i = 0; i < qd.getWriteQueueNums(); i++) { MessageQueue mq = new MessageQueue(topic, qd.getBrokerName(), i); info.getMessageQueueList().add(mq); } } } info.setOrderTopic(false); } return info; } public static Set<MessageQueue> topicRouteData2TopicSubscribeInfo(final String topic, final TopicRouteData route) { Set<MessageQueue> mqList = new HashSet<MessageQueue>(); List<QueueData> qds = route.getQueueDatas(); // 循环遍历路由信息的 QueueData 信息,如果队列没有读权限,则继续遍历下一个 QueueData for (QueueData qd : qds) { if (PermName.isReadable(qd.getPerm())) { // 根据读队列个数,根据 topic + 序号创建 MessageQueue for (int i = 0; i < qd.getReadQueueNums(); i++) { MessageQueue mq = new MessageQueue(topic, qd.getBrokerName(), i); mqList.add(mq); } } } return mqList; } /** * 启动客户端 * @throws MQClientException */ public void start() throws MQClientException { synchronized (this) { switch (this.serviceState) { case CREATE_JUST: this.serviceState = ServiceState.START_FAILED; // If not specified,looking address from name server if (null == this.clientConfig.getNamesrvAddr()) { // 获取 NameServer 地址 this.mQClientAPIImpl.fetchNameServerAddr(); } // Start request-response channel // 启动 netty this.mQClientAPIImpl.start(); // Start various schedule tasks 开启各种定时任务 this.startScheduledTask(); // Start pull service 消息拉取线程;RocketMQ 使用一个单独的线程 PullMessageService 来负责消息的拉取 this.pullMessageService.start(); // Start rebalance service 消息队列重新负载线程 this.rebalanceService.start(); // Start push service 启动 defaultMQProducer 内部的 defaultMQProducerImpl this.defaultMQProducer.getDefaultMQProducerImpl().start(false); log.info("the client factory [{}] start OK", this.clientId); this.serviceState = ServiceState.RUNNING; break; case START_FAILED: throw new MQClientException("The Factory object[" + this.getClientId() + "] has been created before, and failed.", null); default: break; } } } /** * 开启定时任务 */ private void startScheduledTask() { // 如果没有指定 namesrv,开启动态搜索 namesrv 的定时任务 if (null == this.clientConfig.getNamesrvAddr()) { this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { try { MQClientInstance.this.mQClientAPIImpl.fetchNameServerAddr(); } catch (Exception e) { log.error("ScheduledTask fetchNameServerAddr exception", e); } } }, 1000 * 10, 1000 * 60 * 2, TimeUnit.MILLISECONDS); } // 周期性从 namesrv 拉取主题信息,30秒拉一次 this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { try { // 更新 topic 路由信息。RocketMQ 路由发现是非实时的,当 Topic 路由出现变化后,NameServer 不主动推送给客户端,而是由客户端定时拉取主题最新的路由。根据主题名称拉取路由信息的命令编码为:GET_ROUTEINTO_BY_TOPIC MQClientInstance.this.updateTopicRouteInfoFromNameServer(); } catch (Exception e) { log.error("ScheduledTask updateTopicRouteInfoFromNameServer exception", e); } } }, 10, this.clientConfig.getPollNameServerInterval(), TimeUnit.MILLISECONDS); // 1、清理下线的 broker 2、发送消费者和生产者的心跳信息到 broker this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { try { MQClientInstance.this.cleanOfflineBroker(); MQClientInstance.this.sendHeartbeatToAllBrokerWithLock(); } catch (Exception e) { log.error("ScheduledTask sendHeartbeatToAllBroker exception", e); } } }, 1000, this.clientConfig.getHeartbeatBrokerInterval(), TimeUnit.MILLISECONDS); // 持久化消息消费进度 offset this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { try { // 定时持久化消息消费进度 MQClientInstance.this.persistAllConsumerOffset(); } catch (Exception e) { log.error("ScheduledTask persistAllConsumerOffset exception", e); } } }, 1000 * 10, this.clientConfig.getPersistConsumerOffsetInterval(), TimeUnit.MILLISECONDS); // 动态调整消费者的线程池大小,但是从底层代码来看并没有实现 this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { try { MQClientInstance.this.adjustThreadPool(); } catch (Exception e) { log.error("ScheduledTask adjustThreadPool exception", e); } } }, 1, 1, TimeUnit.MINUTES); } public String getClientId() { return clientId; } public void updateTopicRouteInfoFromNameServer() { Set<String> topicList = new HashSet<String>(); // Consumer { // 提取所有消费者订阅的主题 Iterator<Entry<String, MQConsumerInner>> it = this.consumerTable.entrySet().iterator(); while (it.hasNext()) { Entry<String, MQConsumerInner> entry = it.next(); MQConsumerInner impl = entry.getValue(); if (impl != null) { Set<SubscriptionData> subList = impl.subscriptions(); if (subList != null) { for (SubscriptionData subData : subList) { topicList.add(subData.getTopic()); } } } } } // Producer { // 提取所有生产者发送的主题 Iterator<Entry<String, MQProducerInner>> it = this.producerTable.entrySet().iterator(); while (it.hasNext()) { Entry<String, MQProducerInner> entry = it.next(); MQProducerInner impl = entry.getValue(); if (impl != null) { Set<String> lst = impl.getPublishTopicList(); topicList.addAll(lst); } } } // /遍历更新所有的主题对应的路由信息 for (String topic : topicList) { this.updateTopicRouteInfoFromNameServer(topic); } } /** * @param offsetTable * @param namespace * @return newOffsetTable */ public Map<MessageQueue, Long> parseOffsetTableFromBroker(Map<MessageQueue, Long> offsetTable, String namespace) { HashMap<MessageQueue, Long> newOffsetTable = new HashMap<MessageQueue, Long>(); if (StringUtils.isNotEmpty(namespace)) { for (Entry<MessageQueue, Long> entry : offsetTable.entrySet()) { MessageQueue queue = entry.getKey(); queue.setTopic(NamespaceUtil.withoutNamespace(queue.getTopic(), namespace)); newOffsetTable.put(queue, entry.getValue()); } } else { newOffsetTable.putAll(offsetTable); } return newOffsetTable; } /** * Remove offline broker */ private void cleanOfflineBroker() { try { if (this.lockNamesrv.tryLock(LOCK_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) try { ConcurrentHashMap<String, HashMap<Long, String>> updatedTable = new ConcurrentHashMap<String, HashMap<Long, String>>(); Iterator<Entry<String, HashMap<Long, String>>> itBrokerTable = this.brokerAddrTable.entrySet().iterator(); while (itBrokerTable.hasNext()) { Entry<String, HashMap<Long, String>> entry = itBrokerTable.next(); String brokerName = entry.getKey(); HashMap<Long, String> oneTable = entry.getValue(); HashMap<Long, String> cloneAddrTable = new HashMap<Long, String>(); cloneAddrTable.putAll(oneTable); Iterator<Entry<Long, String>> it = cloneAddrTable.entrySet().iterator(); while (it.hasNext()) { Entry<Long, String> ee = it.next(); String addr = ee.getValue(); if (!this.isBrokerAddrExistInTopicRouteTable(addr)) { it.remove(); log.info("the broker addr[{} {}] is offline, remove it", brokerName, addr); } } if (cloneAddrTable.isEmpty()) { itBrokerTable.remove(); log.info("the broker[{}] name's host is offline, remove it", brokerName); } else { updatedTable.put(brokerName, cloneAddrTable); } } if (!updatedTable.isEmpty()) { this.brokerAddrTable.putAll(updatedTable); } } finally { this.lockNamesrv.unlock(); } } catch (InterruptedException e) { log.warn("cleanOfflineBroker Exception", e); } } public void checkClientInBroker() throws MQClientException { Iterator<Entry<String, MQConsumerInner>> it = this.consumerTable.entrySet().iterator(); while (it.hasNext()) { Entry<String, MQConsumerInner> entry = it.next(); Set<SubscriptionData> subscriptionInner = entry.getValue().subscriptions(); if (subscriptionInner == null || subscriptionInner.isEmpty()) { return; } for (SubscriptionData subscriptionData : subscriptionInner) { if (ExpressionType.isTagType(subscriptionData.getExpressionType())) { continue; } // may need to check one broker every cluster... // assume that the configs of every broker in cluster are the the same. String addr = findBrokerAddrByTopic(subscriptionData.getTopic()); if (addr != null) { try { this.getMQClientAPIImpl().checkClientInBroker( addr, entry.getKey(), this.clientId, subscriptionData, 3 * 1000 ); } catch (Exception e) { if (e instanceof MQClientException) { throw (MQClientException) e; } else { throw new MQClientException("Check client in broker error, maybe because you use " + subscriptionData.getExpressionType() + " to filter message, but server has not been upgraded to support!" + "This error would not affect the launch of consumer, but may has impact on message receiving if you " + "have use the new features which are not supported by server, please check the log!", e); } } } } } } public void sendHeartbeatToAllBrokerWithLock() { if (this.lockHeartbeat.tryLock()) { try { this.sendHeartbeatToAllBroker(); this.uploadFilterClassSource(); } catch (final Exception e) { log.error("sendHeartbeatToAllBroker exception", e); } finally { this.lockHeartbeat.unlock(); } } else { log.warn("lock heartBeat, but failed."); } } private void persistAllConsumerOffset() { Iterator<Entry<String, MQConsumerInner>> it = this.consumerTable.entrySet().iterator(); while (it.hasNext()) { Entry<String, MQConsumerInner> entry = it.next(); MQConsumerInner impl = entry.getValue(); impl.persistConsumerOffset(); } } public void adjustThreadPool() { Iterator<Entry<String, MQConsumerInner>> it = this.consumerTable.entrySet().iterator(); while (it.hasNext()) { Entry<String, MQConsumerInner> entry = it.next(); MQConsumerInner impl = entry.getValue(); if (impl != null) { try { if (impl instanceof DefaultMQPushConsumerImpl) { DefaultMQPushConsumerImpl dmq = (DefaultMQPushConsumerImpl) impl; dmq.adjustThreadPool(); } } catch (Exception e) { } } } } /** * 更新和维护主题路由信息 * @param topic * @return */ public boolean updateTopicRouteInfoFromNameServer(final String topic) { return updateTopicRouteInfoFromNameServer(topic, false, null); } private boolean isBrokerAddrExistInTopicRouteTable(final String addr) { Iterator<Entry<String, TopicRouteData>> it = this.topicRouteTable.entrySet().iterator(); while (it.hasNext()) { Entry<String, TopicRouteData> entry = it.next(); TopicRouteData topicRouteData = entry.getValue(); List<BrokerData> bds = topicRouteData.getBrokerDatas(); for (BrokerData bd : bds) { if (bd.getBrokerAddrs() != null) { boolean exist = bd.getBrokerAddrs().containsValue(addr); if (exist) return true; } } } return false; } private void sendHeartbeatToAllBroker() { final HeartbeatData heartbeatData = this.prepareHeartbeatData(); final boolean producerEmpty = heartbeatData.getProducerDataSet().isEmpty(); final boolean consumerEmpty = heartbeatData.getConsumerDataSet().isEmpty(); if (producerEmpty && consumerEmpty) { log.warn("sending heartbeat, but no consumer and no producer"); return; } if (!this.brokerAddrTable.isEmpty()) { long times = this.sendHeartbeatTimesTotal.getAndIncrement(); Iterator<Entry<String, HashMap<Long, String>>> it = this.brokerAddrTable.entrySet().iterator(); while (it.hasNext()) { Entry<String, HashMap<Long, String>> entry = it.next(); String brokerName = entry.getKey(); HashMap<Long, String> oneTable = entry.getValue(); if (oneTable != null) { for (Map.Entry<Long, String> entry1 : oneTable.entrySet()) { Long id = entry1.getKey(); String addr = entry1.getValue(); if (addr != null) { if (consumerEmpty) { if (id != MixAll.MASTER_ID) continue; } try { int version = this.mQClientAPIImpl.sendHearbeat(addr, heartbeatData, 3000); if (!this.brokerVersionTable.containsKey(brokerName)) { this.brokerVersionTable.put(brokerName, new HashMap<String, Integer>(4)); } this.brokerVersionTable.get(brokerName).put(addr, version); if (times % 20 == 0) { log.info("send heart beat to broker[{} {} {}] success", brokerName, id, addr); log.info(heartbeatData.toString()); } } catch (Exception e) { if (this.isBrokerInNameServer(addr)) { log.info("send heart beat to broker[{} {} {}] failed", brokerName, id, addr, e); } else { log.info("send heart beat to broker[{} {} {}] exception, because the broker not up, forget it", brokerName, id, addr, e); } } } } } } } } private void uploadFilterClassSource() { Iterator<Entry<String, MQConsumerInner>> it = this.consumerTable.entrySet().iterator(); while (it.hasNext()) { Entry<String, MQConsumerInner> next = it.next(); MQConsumerInner consumer = next.getValue(); if (ConsumeType.CONSUME_PASSIVELY == consumer.consumeType()) { Set<SubscriptionData> subscriptions = consumer.subscriptions(); for (SubscriptionData sub : subscriptions) { if (sub.isClassFilterMode() && sub.getFilterClassSource() != null) { final String consumerGroup = consumer.groupName(); final String className = sub.getSubString(); final String topic = sub.getTopic(); final String filterClassSource = sub.getFilterClassSource(); try { this.uploadFilterClassToAllFilterServer(consumerGroup, className, topic, filterClassSource); } catch (Exception e) { log.error("uploadFilterClassToAllFilterServer Exception", e); } } } } } } public boolean updateTopicRouteInfoFromNameServer(final String topic, boolean isDefault, DefaultMQProducer defaultMQProducer) { try { // 加锁 if (this.lockNamesrv.tryLock(LOCK_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) { try { TopicRouteData topicRouteData; // 如果 isDefault 为 true ,则使用默认主题去查询 if (isDefault && defaultMQProducer != null) { // 默认根据 MixAll.AUTO_CREATE_TOPIC_KEY_TOPIC topic 去查询 topicRouteData = this.mQClientAPIImpl.getDefaultTopicRouteInfoFromNameServer(defaultMQProducer.getCreateTopicKey(), 1000 * 3); // 如果查询到路由信息,则替换路由信息中读写队列个数为消息生产者默认的队列个数(defaultTopicQueueNums) if (topicRouteData != null) { for (QueueData data : topicRouteData.getQueueDatas()) { int queueNums = Math.min(defaultMQProducer.getDefaultTopicQueueNums(), data.getReadQueueNums()); data.setReadQueueNums(queueNums); data.setWriteQueueNums(queueNums); } } } else { // 如果 isDefault 为 false ,则使用参数 topic 去查询 topicRouteData = this.mQClientAPIImpl.getTopicRouteInfoFromNameServer(topic, 1000 * 3); } // 如果路由信息找到,与本地缓存中的路由信息进行对比,判断路由信息是否发了改变,如果未发生变化,则直接返回 false if (topicRouteData != null) { // 本地缓存中的路由信息 TopicRouteData old = this.topicRouteTable.get(topic); // NameServer 返回的路由信息与本地缓存中的路由信息进行对比 boolean changed = topicRouteDataIsChange(old, topicRouteData); if (!changed) { // 生产者、消费者本地保存的 topic 是否需要更新 changed = this.isNeedUpdateTopicRouteInfo(topic); } else { log.info("the topic[{}] route info changed, old[{}] ,new[{}]", topic, old, topicRouteData); } if (changed) { // topic 信息改变 TopicRouteData cloneTopicRouteData = topicRouteData.cloneTopicRouteData(); // 将 topic 信息放入 brokerAddrTable 缓存 for (BrokerData bd : topicRouteData.getBrokerDatas()) { this.brokerAddrTable.put(bd.getBrokerName(), bd.getBrokerAddrs()); } // Update Pub info 更新生产者路由信息 { // 根据 topicRouteData 中的 List<QueueData> 转换成 topicPublishInfo 的 List<MessageQueue> 列表 TopicPublishInfo publishInfo = topicRouteData2TopicPublishInfo(topic, topicRouteData); publishInfo.setHaveTopicRouterInfo(true); Iterator<Entry<String, MQProducerInner>> it = this.producerTable.entrySet().iterator(); while (it.hasNext()) { Entry<String, MQProducerInner> entry = it.next(); MQProducerInner impl = entry.getValue(); if (impl != null) { // 更新该 MQClientInstance 所管辖的所有消息发送关于 topic 的路由信息 impl.updateTopicPublishInfo(topic, publishInfo); } } } // Update sub info 更新消费者路由信息 { Set<MessageQueue> subscribeInfo = topicRouteData2TopicSubscribeInfo(topic, topicRouteData); Iterator<Entry<String, MQConsumerInner>> it = this.consumerTable.entrySet().iterator(); while (it.hasNext()) { Entry<String, MQConsumerInner> entry = it.next(); MQConsumerInner impl = entry.getValue(); if (impl != null) { // 更新 rebalanceImpl 的 topicSubscribeInfoTable impl.updateTopicSubscribeInfo(topic, subscribeInfo); } } } log.info("topicRouteTable.put. Topic = {}, TopicRouteData[{}]", topic, cloneTopicRouteData); this.topicRouteTable.put(topic, cloneTopicRouteData); return true; } } else { // 如果未查询到路由信息,则返回 false,表示路由信息未变化 log.warn("updateTopicRouteInfoFromNameServer, getTopicRouteInfoFromNameServer return null, Topic: {}", topic); } } catch (MQClientException e) { if (!topic.startsWith(MixAll.RETRY_GROUP_TOPIC_PREFIX) && !topic.equals(MixAll.AUTO_CREATE_TOPIC_KEY_TOPIC)) { log.warn("updateTopicRouteInfoFromNameServer Exception", e); } } catch (RemotingException e) { log.error("updateTopicRouteInfoFromNameServer Exception", e); throw new IllegalStateException(e); } finally { this.lockNamesrv.unlock(); } } else { log.warn("updateTopicRouteInfoFromNameServer tryLock timeout {}ms", LOCK_TIMEOUT_MILLIS); } } catch (InterruptedException e) { log.warn("updateTopicRouteInfoFromNameServer Exception", e); } return false; } private HeartbeatData prepareHeartbeatData() { HeartbeatData heartbeatData = new HeartbeatData(); // clientID heartbeatData.setClientID(this.clientId); // Consumer for (Map.Entry<String, MQConsumerInner> entry : this.consumerTable.entrySet()) { MQConsumerInner impl = entry.getValue(); if (impl != null) { ConsumerData consumerData = new ConsumerData(); consumerData.setGroupName(impl.groupName()); consumerData.setConsumeType(impl.consumeType()); consumerData.setMessageModel(impl.messageModel()); consumerData.setConsumeFromWhere(impl.consumeFromWhere()); consumerData.getSubscriptionDataSet().addAll(impl.subscriptions()); consumerData.setUnitMode(impl.isUnitMode()); heartbeatData.getConsumerDataSet().add(consumerData); } } // Producer for (Map.Entry<String/* group */, MQProducerInner> entry : this.producerTable.entrySet()) { MQProducerInner impl = entry.getValue(); if (impl != null) { ProducerData producerData = new ProducerData(); producerData.setGroupName(entry.getKey()); heartbeatData.getProducerDataSet().add(producerData); } } return heartbeatData; } private boolean isBrokerInNameServer(final String brokerAddr) { Iterator<Entry<String, TopicRouteData>> it = this.topicRouteTable.entrySet().iterator(); while (it.hasNext()) { Entry<String, TopicRouteData> itNext = it.next(); List<BrokerData> brokerDatas = itNext.getValue().getBrokerDatas(); for (BrokerData bd : brokerDatas) { boolean contain = bd.getBrokerAddrs().containsValue(brokerAddr); if (contain) return true; } } return false; } /** * This method will be removed in the version 5.0.0,because filterServer was removed,and method * <code>subscribe(final String topic, final MessageSelector messageSelector)</code> is recommended. */ @Deprecated private void uploadFilterClassToAllFilterServer(final String consumerGroup, final String fullClassName, final String topic, final String filterClassSource) throws UnsupportedEncodingException { byte[] classBody = null; int classCRC = 0; try { classBody = filterClassSource.getBytes(MixAll.DEFAULT_CHARSET); classCRC = UtilAll.crc32(classBody); } catch (Exception e1) { log.warn("uploadFilterClassToAllFilterServer Exception, ClassName: {} {}", fullClassName, RemotingHelper.exceptionSimpleDesc(e1)); } TopicRouteData topicRouteData = this.topicRouteTable.get(topic); if (topicRouteData != null && topicRouteData.getFilterServerTable() != null && !topicRouteData.getFilterServerTable().isEmpty()) { Iterator<Entry<String, List<String>>> it = topicRouteData.getFilterServerTable().entrySet().iterator(); while (it.hasNext()) { Entry<String, List<String>> next = it.next(); List<String> value = next.getValue(); for (final String fsAddr : value) { try { this.mQClientAPIImpl.registerMessageFilterClass(fsAddr, consumerGroup, topic, fullClassName, classCRC, classBody, 5000); log.info("register message class filter to {} OK, ConsumerGroup: {} Topic: {} ClassName: {}", fsAddr, consumerGroup, topic, fullClassName); } catch (Exception e) { log.error("uploadFilterClassToAllFilterServer Exception", e); } } } } else { log.warn("register message class filter failed, because no filter server, ConsumerGroup: {} Topic: {} ClassName: {}", consumerGroup, topic, fullClassName); } } private boolean topicRouteDataIsChange(TopicRouteData olddata, TopicRouteData nowdata) { if (olddata == null || nowdata == null) return true; TopicRouteData old = olddata.cloneTopicRouteData(); TopicRouteData now = nowdata.cloneTopicRouteData(); Collections.sort(old.getQueueDatas()); Collections.sort(old.getBrokerDatas()); Collections.sort(now.getQueueDatas()); Collections.sort(now.getBrokerDatas()); return !old.equals(now); } private boolean isNeedUpdateTopicRouteInfo(final String topic) { boolean result = false; { Iterator<Entry<String, MQProducerInner>> it = this.producerTable.entrySet().iterator(); while (it.hasNext() && !result) { Entry<String, MQProducerInner> entry = it.next(); MQProducerInner impl = entry.getValue(); if (impl != null) { result = impl.isPublishTopicNeedUpdate(topic); } } } { Iterator<Entry<String, MQConsumerInner>> it = this.consumerTable.entrySet().iterator(); while (it.hasNext() && !result) { Entry<String, MQConsumerInner> entry = it.next(); MQConsumerInner impl = entry.getValue(); if (impl != null) { result = impl.isSubscribeTopicNeedUpdate(topic); } } } return result; } public void shutdown() { // Consumer if (!this.consumerTable.isEmpty()) return; // AdminExt if (!this.adminExtTable.isEmpty()) return; // Producer if (this.producerTable.size() > 1) return; synchronized (this) { switch (this.serviceState) { case CREATE_JUST: break; case RUNNING: this.defaultMQProducer.getDefaultMQProducerImpl().shutdown(false); this.serviceState = ServiceState.SHUTDOWN_ALREADY; this.pullMessageService.shutdown(true); this.scheduledExecutorService.shutdown(); this.mQClientAPIImpl.shutdown(); this.rebalanceService.shutdown(); if (this.datagramSocket != null) { this.datagramSocket.close(); this.datagramSocket = null; } MQClientManager.getInstance().removeClientFactory(this.clientId); log.info("the client factory [{}] shutdown OK", this.clientId); break; case SHUTDOWN_ALREADY: break; default: break; } } } public boolean registerConsumer(final String group, final MQConsumerInner consumer) { if (null == group || null == consumer) { return false; } MQConsumerInner prev = this.consumerTable.putIfAbsent(group, consumer); if (prev != null) { log.warn("the consumer group[" + group + "] exist already."); return false; } return true; } public void unregisterConsumer(final String group) { this.consumerTable.remove(group); this.unregisterClientWithLock(null, group); } private void unregisterClientWithLock(final String producerGroup, final String consumerGroup) { try { if (this.lockHeartbeat.tryLock(LOCK_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) { try { this.unregisterClient(producerGroup, consumerGroup); } catch (Exception e) { log.error("unregisterClient exception", e); } finally { this.lockHeartbeat.unlock(); } } else { log.warn("lock heartBeat, but failed."); } } catch (InterruptedException e) { log.warn("unregisterClientWithLock exception", e); } } private void unregisterClient(final String producerGroup, final String consumerGroup) { Iterator<Entry<String, HashMap<Long, String>>> it = this.brokerAddrTable.entrySet().iterator(); while (it.hasNext()) { Entry<String, HashMap<Long, String>> entry = it.next(); String brokerName = entry.getKey(); HashMap<Long, String> oneTable = entry.getValue(); if (oneTable != null) { for (Map.Entry<Long, String> entry1 : oneTable.entrySet()) { String addr = entry1.getValue(); if (addr != null) { try { this.mQClientAPIImpl.unregisterClient(addr, this.clientId, producerGroup, consumerGroup, 3000); log.info("unregister client[Producer: {} Consumer: {}] from broker[{} {} {}] success", producerGroup, consumerGroup, brokerName, entry1.getKey(), addr); } catch (RemotingException e) { log.error("unregister client exception from broker: " + addr, e); } catch (InterruptedException e) { log.error("unregister client exception from broker: " + addr, e); } catch (MQBrokerException e) { log.error("unregister client exception from broker: " + addr, e); } } } } } } public boolean registerProducer(final String group, final DefaultMQProducerImpl producer) { if (null == group || null == producer) { return false; } MQProducerInner prev = this.producerTable.putIfAbsent(group, producer); if (prev != null) { log.warn("the producer group[{}] exist already.", group); return false; } return true; } public void unregisterProducer(final String group) { this.producerTable.remove(group); this.unregisterClientWithLock(group, null); } public boolean registerAdminExt(final String group, final MQAdminExtInner admin) { if (null == group || null == admin) { return false; } MQAdminExtInner prev = this.adminExtTable.putIfAbsent(group, admin); if (prev != null) { log.warn("the admin group[{}] exist already.", group); return false; } return true; } public void unregisterAdminExt(final String group) { this.adminExtTable.remove(group); } public void rebalanceImmediately() { this.rebalanceService.wakeup(); } /** * 遍历已注册的消费者,对消费者执行 doRebalance() 方法 */ public void doRebalance() { for (Map.Entry<String, MQConsumerInner> entry : this.consumerTable.entrySet()) { MQConsumerInner impl = entry.getValue(); if (impl != null) { try { impl.doRebalance(); } catch (Throwable e) { log.error("doRebalance exception", e); } } } } public MQProducerInner selectProducer(final String group) { return this.producerTable.get(group); } public MQConsumerInner selectConsumer(final String group) { return this.consumerTable.get(group); } public FindBrokerResult findBrokerAddressInAdmin(final String brokerName) { String brokerAddr = null; boolean slave = false; boolean found = false; HashMap<Long/* brokerId */, String/* address */> map = this.brokerAddrTable.get(brokerName); if (map != null && !map.isEmpty()) { for (Map.Entry<Long, String> entry : map.entrySet()) { Long id = entry.getKey(); brokerAddr = entry.getValue(); if (brokerAddr != null) { found = true; if (MixAll.MASTER_ID == id) { slave = false; } else { slave = true; } break; } } // end of for } if (found) { return new FindBrokerResult(brokerAddr, slave, findBrokerVersion(brokerName, brokerAddr)); } return null; } public String findBrokerAddressInPublish(final String brokerName) { HashMap<Long/* brokerId */, String/* address */> map = this.brokerAddrTable.get(brokerName); if (map != null && !map.isEmpty()) { return map.get(MixAll.MASTER_ID); } return null; } /** * 根据 brokerName、brokerId 查找 Broker 地址 * @param brokerName Broker 名称 * @param brokerId BrokerId * @param onlyThisBroker 是否必须返回 brokerId 的 Broker 对应的服务器信息 * @return */ public FindBrokerResult findBrokerAddressInSubscribe( final String brokerName, final long brokerId, final boolean onlyThisBroker ) { String brokerAddr = null; boolean slave = false; boolean found = false; // 从 ConcurrentMap<String/* Broker Name */, HashMap<Long/* brokerId */, String/* address */>> brokerAddrTable 地址缓存表中根据 brokerName 获取所有的 Broker 信息 HashMap<Long/* brokerId */, String/* address */> map = this.brokerAddrTable.get(brokerName); if (map != null && !map.isEmpty()) { // 根据 brokerId 从 Broker 主从缓存表中获取指定 Broker 地址,如果根据 brokerId 未找到相关的条目,此时若 onlyThisBroker 为 false, // 则随机返回 Broker 中任意一个 Broker,否则返回 null brokerAddr = map.get(brokerId); slave = brokerId != MixAll.MASTER_ID; found = brokerAddr != null; if (!found && !onlyThisBroker) { Entry<Long, String> entry = map.entrySet().iterator().next(); brokerAddr = entry.getValue(); slave = entry.getKey() != MixAll.MASTER_ID; found = true; } } if (found) { // 组装 FindBrokerResult 时,需要设置是否是 slave 这个属性。如果 brokerId=O,表示返回的 Broker 是主节点,否则返回的是从节点 return new FindBrokerResult(brokerAddr, slave, findBrokerVersion(brokerName, brokerAddr)); } return null; } public int findBrokerVersion(String brokerName, String brokerAddr) { if (this.brokerVersionTable.containsKey(brokerName)) { if (this.brokerVersionTable.get(brokerName).containsKey(brokerAddr)) { return this.brokerVersionTable.get(brokerName).get(brokerAddr); } } //To do need to fresh the version return 0; } public List<String> findConsumerIdList(final String topic, final String group) { String brokerAddr = this.findBrokerAddrByTopic(topic); if (null == brokerAddr) { this.updateTopicRouteInfoFromNameServer(topic); brokerAddr = this.findBrokerAddrByTopic(topic); } if (null != brokerAddr) { try { return this.mQClientAPIImpl.getConsumerIdListByGroup(brokerAddr, group, 3000); } catch (Exception e) { log.warn("getConsumerIdListByGroup exception, " + brokerAddr + " " + group, e); } } return null; } public String findBrokerAddrByTopic(final String topic) { TopicRouteData topicRouteData = this.topicRouteTable.get(topic); if (topicRouteData != null) { List<BrokerData> brokers = topicRouteData.getBrokerDatas(); if (!brokers.isEmpty()) { int index = random.nextInt(brokers.size()); BrokerData bd = brokers.get(index % brokers.size()); return bd.selectBrokerAddr(); } } return null; } public void resetOffset(String topic, String group, Map<MessageQueue, Long> offsetTable) { DefaultMQPushConsumerImpl consumer = null; try { MQConsumerInner impl = this.consumerTable.get(group); if (impl != null && impl instanceof DefaultMQPushConsumerImpl) { consumer = (DefaultMQPushConsumerImpl) impl; } else { log.info("[reset-offset] consumer dose not exist. group={}", group); return; } consumer.suspend(); ConcurrentMap<MessageQueue, ProcessQueue> processQueueTable = consumer.getRebalanceImpl().getProcessQueueTable(); for (Map.Entry<MessageQueue, ProcessQueue> entry : processQueueTable.entrySet()) { MessageQueue mq = entry.getKey(); if (topic.equals(mq.getTopic()) && offsetTable.containsKey(mq)) { ProcessQueue pq = entry.getValue(); pq.setDropped(true); pq.clear(); } } try { TimeUnit.SECONDS.sleep(10); } catch (InterruptedException e) { } Iterator<MessageQueue> iterator = processQueueTable.keySet().iterator(); while (iterator.hasNext()) { MessageQueue mq = iterator.next(); Long offset = offsetTable.get(mq); if (topic.equals(mq.getTopic()) && offset != null) { try { consumer.updateConsumeOffset(mq, offset); consumer.getRebalanceImpl().removeUnnecessaryMessageQueue(mq, processQueueTable.get(mq)); iterator.remove(); } catch (Exception e) { log.warn("reset offset failed. group={}, {}", group, mq, e); } } } } finally { if (consumer != null) { consumer.resume(); } } } public Map<MessageQueue, Long> getConsumerStatus(String topic, String group) { MQConsumerInner impl = this.consumerTable.get(group); if (impl != null && impl instanceof DefaultMQPushConsumerImpl) { DefaultMQPushConsumerImpl consumer = (DefaultMQPushConsumerImpl) impl; return consumer.getOffsetStore().cloneOffsetTable(topic); } else if (impl != null && impl instanceof DefaultMQPullConsumerImpl) { DefaultMQPullConsumerImpl consumer = (DefaultMQPullConsumerImpl) impl; return consumer.getOffsetStore().cloneOffsetTable(topic); } else { return Collections.EMPTY_MAP; } } public TopicRouteData getAnExistTopicRouteData(final String topic) { return this.topicRouteTable.get(topic); } public MQClientAPIImpl getMQClientAPIImpl() { return mQClientAPIImpl; } public MQAdminImpl getMQAdminImpl() { return mQAdminImpl; } public long getBootTimestamp() { return bootTimestamp; } public ScheduledExecutorService getScheduledExecutorService() { return scheduledExecutorService; } public PullMessageService getPullMessageService() { return pullMessageService; } public DefaultMQProducer getDefaultMQProducer() { return defaultMQProducer; } public ConcurrentMap<String, TopicRouteData> getTopicRouteTable() { return topicRouteTable; } public ConsumeMessageDirectlyResult consumeMessageDirectly(final MessageExt msg, final String consumerGroup, final String brokerName) { MQConsumerInner mqConsumerInner = this.consumerTable.get(consumerGroup); if (null != mqConsumerInner) { DefaultMQPushConsumerImpl consumer = (DefaultMQPushConsumerImpl) mqConsumerInner; ConsumeMessageDirectlyResult result = consumer.getConsumeMessageService().consumeMessageDirectly(msg, brokerName); return result; } return null; } public ConsumerRunningInfo consumerRunningInfo(final String consumerGroup) { MQConsumerInner mqConsumerInner = this.consumerTable.get(consumerGroup); ConsumerRunningInfo consumerRunningInfo = mqConsumerInner.consumerRunningInfo(); List<String> nsList = this.mQClientAPIImpl.getRemotingClient().getNameServerAddressList(); StringBuilder strBuilder = new StringBuilder(); if (nsList != null) { for (String addr : nsList) { strBuilder.append(addr).append(";"); } } String nsAddr = strBuilder.toString(); consumerRunningInfo.getProperties().put(ConsumerRunningInfo.PROP_NAMESERVER_ADDR, nsAddr); consumerRunningInfo.getProperties().put(ConsumerRunningInfo.PROP_CONSUME_TYPE, mqConsumerInner.consumeType().name()); consumerRunningInfo.getProperties().put(ConsumerRunningInfo.PROP_CLIENT_VERSION, MQVersion.getVersionDesc(MQVersion.CURRENT_VERSION)); return consumerRunningInfo; } public ConsumerStatsManager getConsumerStatsManager() { return consumerStatsManager; } public NettyClientConfig getNettyClientConfig() { return nettyClientConfig; } public ClientConfig getClientConfig() { return clientConfig; } }
package co.zisky.flutter; import android.content.Context; import android.util.Log; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.LinkedHashMap; public class JsonUtil { private static ObjectMapper objectMapper = new ObjectMapper(); static { objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true); // objectMapper.registerModule(new JavaTimeModule()); objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true); objectMapper.setDateFormat(new SimpleDateFormat("YYYY-MM-dd'T'HH:mm:ss.SSSZ")); objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); } public static String getAssetJsonData(Context context,String filename) { String json = null; try { InputStream is = context.getAssets().open(filename); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); json = new String(buffer, "UTF-8"); } catch (IOException ex) { ex.printStackTrace(); return null; } Log.d("APP-2020", json);//todo remove when publishing to maven return json; } public static String toJson(Object object) { try { return getJacksonObjectMapper().writeValueAsString(object); } catch (JsonProcessingException e) { LogUtil.w("Error occurred during jackson serialize", e); return null; } } public static ObjectMapper getJacksonObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true); objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true); objectMapper.setDateFormat(DateUtil.DATE_FORMAT); objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); return objectMapper; } public static <T> T clone(T object, Class<T> type) { return fromJson(toJson(object), type); } public static <T> T fromJson(String json, Class<T> type) { try { if (json == null) { return null; } return getJacksonObjectMapper().readValue(json, type); } catch (IOException e) { LogUtil.w("Error occurred during jackson deserialize for type: " + type.getName(), e); return null; } } public static <T> T fromMap(LinkedHashMap map, Class<T> type) { return fromJson(toJson(map), type); } }
package org.apereo.cas.authentication.principal; import org.apereo.cas.authentication.CoreAuthenticationTestUtils; import org.apereo.cas.authentication.credential.UsernamePasswordCredential; import org.apereo.cas.authentication.handler.support.SimpleTestUsernamePasswordAuthenticationHandler; import org.apereo.cas.authentication.principal.resolvers.ChainingPrincipalResolver; import org.apereo.cas.authentication.principal.resolvers.EchoingPrincipalResolver; import org.apereo.cas.authentication.principal.resolvers.PersonDirectoryPrincipalResolver; import org.apereo.cas.config.CasPersonDirectoryConfiguration; import org.apereo.cas.util.junit.EnabledIfContinuousIntegration; import lombok.val; import org.apereo.services.persondir.IPersonAttributeDao; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.TestPropertySource; import java.util.Arrays; import java.util.HashMap; import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; /** * This is {@link PersonDirectoryPrincipalResolverLdaptiveTests}. * * @author Misagh Moayyed * @since 5.0.0 */ @SpringBootTest(classes = { CasPersonDirectoryConfiguration.class, RefreshAutoConfiguration.class }) @TestPropertySource(properties = { "cas.authn.attributeRepository.ldap[0].baseDn=dc=example,dc=org", "cas.authn.attributeRepository.ldap[0].ldapUrl=ldap://localhost:10389", "cas.authn.attributeRepository.ldap[0].searchFilter=cn={user}", "cas.authn.attributeRepository.ldap[0].useSsl=false", "cas.authn.attributeRepository.ldap[0].attributes.cn=cn", "cas.authn.attributeRepository.ldap[0].attributes.description=description", "cas.authn.attributeRepository.ldap[0].bindDn=cn=Directory Manager", "cas.authn.attributeRepository.ldap[0].bindCredential=password" }) @DirtiesContext @Tag("Ldap") @EnabledIfContinuousIntegration public class PersonDirectoryPrincipalResolverLdaptiveTests { @Autowired @Qualifier("attributeRepository") private IPersonAttributeDao attributeRepository; @Test public void verifyResolver() { val resolver = new PersonDirectoryPrincipalResolver(this.attributeRepository); val p = resolver.resolve(new UsernamePasswordCredential("admin", "password"), Optional.of(CoreAuthenticationTestUtils.getPrincipal()), Optional.of(new SimpleTestUsernamePasswordAuthenticationHandler())); assertNotNull(p); assertTrue(p.getAttributes().containsKey("description")); } @Test public void verifyChainedResolver() { val resolver = new PersonDirectoryPrincipalResolver(this.attributeRepository); val chain = new ChainingPrincipalResolver(); chain.setChain(Arrays.asList(new EchoingPrincipalResolver(), resolver)); val attributes = new HashMap<String, Object>(2); attributes.put("a1", "v1"); attributes.put("a2", "v2"); val p = chain.resolve(new UsernamePasswordCredential("admin", "password"), Optional.of(CoreAuthenticationTestUtils.getPrincipal("admin", attributes)), Optional.of(new SimpleTestUsernamePasswordAuthenticationHandler())); assertNotNull(p); assertTrue(p.getAttributes().containsKey("cn")); assertTrue(p.getAttributes().containsKey("a1")); assertTrue(p.getAttributes().containsKey("a2")); } }
/** * 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.hadoop.hbase.security.provider; import java.util.Objects; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.hadoop.hbase.HBaseInterfaceAudience; import org.apache.hadoop.security.UserGroupInformation.AuthenticationMethod; import org.apache.yetus.audience.InterfaceAudience; import org.apache.yetus.audience.InterfaceStability; /** * Describes the way in which some {@link SaslClientAuthenticationProvider} authenticates over SASL. */ @InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.AUTHENTICATION) @InterfaceStability.Evolving public class SaslAuthMethod { private final String name; private final byte code; private final String saslMech; private final AuthenticationMethod method; public SaslAuthMethod(String name, byte code, String saslMech, AuthenticationMethod method) { this.name = name; this.code = code; this.saslMech = saslMech; this.method = method; } /** * Returns the unique name to identify this authentication method among other HBase auth methods. */ public String getName() { return name; } /** * Returns the unique value to identify this authentication method among other HBase auth methods. */ public byte getCode() { return code; } /** * Returns the SASL mechanism used by this authentication method. */ public String getSaslMechanism() { return saslMech; } /** * Returns the Hadoop {@link AuthenticationMethod} for this method. */ public AuthenticationMethod getAuthMethod() { return method; } @Override public boolean equals(Object o) { if (!(o instanceof SaslAuthMethod)) { return false; } SaslAuthMethod other = (SaslAuthMethod) o; return Objects.equals(name, other.name) && code == other.code && Objects.equals(saslMech, other.saslMech) && Objects.equals(method, other.method); } @Override public int hashCode() { return new HashCodeBuilder() .append(name) .append(code) .append(saslMech) .append(method) .toHashCode(); } }
package org.hattrickscoreboard.background.services; public interface ServiceListener { void onServiceStart(); void onServiceError(int code); void onServiceUpdated(); }
package io.github.picodotdev.blogbitix.dddhexagonal.catalog.domain.model.event; public interface EventRepository { EventId getId(); Event findById(EventId id); void persist(Event event); }
package com.lanking.cloud.job.doQuestionRank.DAO.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import com.lanking.cloud.component.db.support.hibernate.Repo; import com.lanking.cloud.component.db.support.hibernate.dao.AbstractHibernateDAO; import com.lanking.cloud.domain.yoomath.stat.DoQuestionSchoolRank; import com.lanking.cloud.job.doQuestionRank.DAO.DoQuestionSchoolRankDAO; import com.lanking.cloud.sdk.data.CursorPage; import com.lanking.cloud.sdk.data.CursorPageable; import com.lanking.cloud.sdk.data.Params; @Component public class DoQuestionSchoolRankDAOImpl extends AbstractHibernateDAO<DoQuestionSchoolRank, Long> implements DoQuestionSchoolRankDAO { @Override public DoQuestionSchoolRank findStudentInSchoolRank(long schoolId, int startDate, int endDate, long userId) { Params param = Params.param(); param.put("schoolId", schoolId); param.put("userId", userId); param.put("startDate", startDate); param.put("endDate", endDate); return repo.find("$findStudentInSchoolRank", param).get(); } @Override public DoQuestionSchoolRank save(DoQuestionSchoolRank doQuestionSchoolRank) { return repo.save(doQuestionSchoolRank); } @Override public List<Long> getSchoolIds(int startDate, int endDate, int startindex, int size) { Params param = Params.param(); param.put("startDate", startDate); param.put("endDate", endDate); param.put("startindex", startindex); param.put("size", size); return repo.find("$findSchoolIds", param).list(Long.class); } @Override public CursorPage<Long, DoQuestionSchoolRank> getSchoolRankPraiseBySchoolId(int startDate, int endDate, Long schoolId, CursorPageable<Long> pageable) { Params param = Params.param(); param.put("startDate", startDate); param.put("endDate", endDate); if (schoolId != null) { param.put("schoolId", schoolId); } return repo.find("$findSchoolRankPraiseBySchoolId", param).fetch(pageable); } @Override public List<DoQuestionSchoolRank> saves(List<DoQuestionSchoolRank> doQuestionSchoolRanks) { return repo.save(doQuestionSchoolRanks); } @Autowired @Qualifier("DoQuestionSchoolRankRepo") @Override public void setRepo(Repo<DoQuestionSchoolRank, Long> repo) { this.repo = repo; } }
/** Automatically generated file. DO NOT MODIFY */ package com.huawei.hmf.tasks; public final class BuildConfig { public final static boolean DEBUG = 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.sling.serviceusermapping; import aQute.bnd.annotation.ConsumerType; /** * The {@code ServiceUserValidator} allows to implement validation of configured * service user mappings. */ @ConsumerType public interface ServiceUserValidator { /** * Validates the configured service user ID. * * @param serviceUserId The ID of the configured service user. * @return {@code true} if the configured service user is valid; {@code false} otherwise. */ boolean isValid(String serviceUserId, String serviceName, String subServiceName); }
/** * Copyright (c) 2016-present, RxJava Contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package io.reactivex.internal.operators.flowable; import static org.junit.Assert.*; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*; import org.junit.Test; import org.reactivestreams.*; import io.reactivex.*; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.*; import io.reactivex.flowables.ConnectableFlowable; import io.reactivex.functions.*; import io.reactivex.internal.functions.Functions; import io.reactivex.internal.fuseable.HasUpstreamPublisher; import io.reactivex.internal.schedulers.ImmediateThinScheduler; import io.reactivex.internal.subscriptions.BooleanSubscription; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.processors.PublishProcessor; import io.reactivex.schedulers.*; import io.reactivex.subscribers.TestSubscriber; public class FlowablePublishTest { @Test public void testPublish() throws InterruptedException { final AtomicInteger counter = new AtomicInteger(); ConnectableFlowable<String> o = Flowable.unsafeCreate(new Publisher<String>() { @Override public void subscribe(final Subscriber<? super String> observer) { observer.onSubscribe(new BooleanSubscription()); new Thread(new Runnable() { @Override public void run() { counter.incrementAndGet(); observer.onNext("one"); observer.onComplete(); } }).start(); } }).publish(); final CountDownLatch latch = new CountDownLatch(2); // subscribe once o.subscribe(new Consumer<String>() { @Override public void accept(String v) { assertEquals("one", v); latch.countDown(); } }); // subscribe again o.subscribe(new Consumer<String>() { @Override public void accept(String v) { assertEquals("one", v); latch.countDown(); } }); Disposable s = o.connect(); try { if (!latch.await(1000, TimeUnit.MILLISECONDS)) { fail("subscriptions did not receive values"); } assertEquals(1, counter.get()); } finally { s.dispose(); } } @Test public void testBackpressureFastSlow() { ConnectableFlowable<Integer> is = Flowable.range(1, Flowable.bufferSize() * 2).publish(); Flowable<Integer> fast = is.observeOn(Schedulers.computation()) .doOnComplete(new Action() { @Override public void run() { System.out.println("^^^^^^^^^^^^^ completed FAST"); } }); Flowable<Integer> slow = is.observeOn(Schedulers.computation()).map(new Function<Integer, Integer>() { int c; @Override public Integer apply(Integer i) { if (c == 0) { try { Thread.sleep(500); } catch (InterruptedException e) { } } c++; return i; } }).doOnComplete(new Action() { @Override public void run() { System.out.println("^^^^^^^^^^^^^ completed SLOW"); } }); TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); Flowable.merge(fast, slow).subscribe(ts); is.connect(); ts.awaitTerminalEvent(); ts.assertNoErrors(); assertEquals(Flowable.bufferSize() * 4, ts.valueCount()); } // use case from https://github.com/ReactiveX/RxJava/issues/1732 @Test public void testTakeUntilWithPublishedStreamUsingSelector() { final AtomicInteger emitted = new AtomicInteger(); Flowable<Integer> xs = Flowable.range(0, Flowable.bufferSize() * 2).doOnNext(new Consumer<Integer>() { @Override public void accept(Integer t1) { emitted.incrementAndGet(); } }); TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); xs.publish(new Function<Flowable<Integer>, Flowable<Integer>>() { @Override public Flowable<Integer> apply(Flowable<Integer> xs) { return xs.takeUntil(xs.skipWhile(new Predicate<Integer>() { @Override public boolean test(Integer i) { return i <= 3; } })); } }).subscribe(ts); ts.awaitTerminalEvent(); ts.assertNoErrors(); ts.assertValues(0, 1, 2, 3); assertEquals(5, emitted.get()); System.out.println(ts.values()); } // use case from https://github.com/ReactiveX/RxJava/issues/1732 @Test public void testTakeUntilWithPublishedStream() { Flowable<Integer> xs = Flowable.range(0, Flowable.bufferSize() * 2); TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); ConnectableFlowable<Integer> xsp = xs.publish(); xsp.takeUntil(xsp.skipWhile(new Predicate<Integer>() { @Override public boolean test(Integer i) { return i <= 3; } })).subscribe(ts); xsp.connect(); System.out.println(ts.values()); } @Test(timeout = 10000) public void testBackpressureTwoConsumers() { final AtomicInteger sourceEmission = new AtomicInteger(); final AtomicBoolean sourceUnsubscribed = new AtomicBoolean(); final Flowable<Integer> source = Flowable.range(1, 100) .doOnNext(new Consumer<Integer>() { @Override public void accept(Integer t1) { sourceEmission.incrementAndGet(); } }) .doOnCancel(new Action() { @Override public void run() { sourceUnsubscribed.set(true); } }).share(); ; final AtomicBoolean child1Unsubscribed = new AtomicBoolean(); final AtomicBoolean child2Unsubscribed = new AtomicBoolean(); final TestSubscriber<Integer> ts2 = new TestSubscriber<Integer>(); final TestSubscriber<Integer> ts1 = new TestSubscriber<Integer>() { @Override public void onNext(Integer t) { if (valueCount() == 2) { source.doOnCancel(new Action() { @Override public void run() { child2Unsubscribed.set(true); } }).take(5).subscribe(ts2); } super.onNext(t); } }; source.doOnCancel(new Action() { @Override public void run() { child1Unsubscribed.set(true); } }).take(5) .subscribe(ts1); ts1.awaitTerminalEvent(); ts2.awaitTerminalEvent(); ts1.assertNoErrors(); ts2.assertNoErrors(); assertTrue(sourceUnsubscribed.get()); assertTrue(child1Unsubscribed.get()); assertTrue(child2Unsubscribed.get()); ts1.assertValues(1, 2, 3, 4, 5); ts2.assertValues(4, 5, 6, 7, 8); assertEquals(8, sourceEmission.get()); } @Test public void testConnectWithNoSubscriber() { TestScheduler scheduler = new TestScheduler(); ConnectableFlowable<Long> co = Flowable.interval(10, 10, TimeUnit.MILLISECONDS, scheduler).take(3).publish(); co.connect(); // Emit 0 scheduler.advanceTimeBy(15, TimeUnit.MILLISECONDS); TestSubscriber<Long> subscriber = new TestSubscriber<Long>(); co.subscribe(subscriber); // Emit 1 and 2 scheduler.advanceTimeBy(50, TimeUnit.MILLISECONDS); subscriber.assertValues(1L, 2L); subscriber.assertNoErrors(); subscriber.assertTerminated(); } @Test public void testSubscribeAfterDisconnectThenConnect() { ConnectableFlowable<Integer> source = Flowable.just(1).publish(); TestSubscriber<Integer> ts1 = new TestSubscriber<Integer>(); source.subscribe(ts1); Disposable s = source.connect(); ts1.assertValue(1); ts1.assertNoErrors(); ts1.assertTerminated(); TestSubscriber<Integer> ts2 = new TestSubscriber<Integer>(); source.subscribe(ts2); Disposable s2 = source.connect(); ts2.assertValue(1); ts2.assertNoErrors(); ts2.assertTerminated(); System.out.println(s); System.out.println(s2); } @Test public void testNoSubscriberRetentionOnCompleted() { FlowablePublish<Integer> source = (FlowablePublish<Integer>)Flowable.just(1).publish(); TestSubscriber<Integer> ts1 = new TestSubscriber<Integer>(); source.subscribe(ts1); ts1.assertNoValues(); ts1.assertNoErrors(); ts1.assertNotComplete(); source.connect(); ts1.assertValue(1); ts1.assertNoErrors(); ts1.assertTerminated(); assertNull(source.current.get()); } @Test public void testNonNullConnection() { ConnectableFlowable<Object> source = Flowable.never().publish(); assertNotNull(source.connect()); assertNotNull(source.connect()); } @Test public void testNoDisconnectSomeoneElse() { ConnectableFlowable<Object> source = Flowable.never().publish(); Disposable s1 = source.connect(); Disposable s2 = source.connect(); s1.dispose(); Disposable s3 = source.connect(); s2.dispose(); assertTrue(checkPublishDisposed(s1)); assertTrue(checkPublishDisposed(s2)); assertFalse(checkPublishDisposed(s3)); } @SuppressWarnings("unchecked") static boolean checkPublishDisposed(Disposable d) { return ((FlowablePublish.PublishSubscriber<Object>)d).isDisposed(); } @Test public void testZeroRequested() { ConnectableFlowable<Integer> source = Flowable.just(1).publish(); TestSubscriber<Integer> ts = new TestSubscriber<Integer>(0L); source.subscribe(ts); ts.assertNoValues(); ts.assertNoErrors(); ts.assertNotComplete(); source.connect(); ts.assertNoValues(); ts.assertNoErrors(); ts.assertNotComplete(); ts.request(5); ts.assertValue(1); ts.assertNoErrors(); ts.assertTerminated(); } @Test public void testConnectIsIdempotent() { final AtomicInteger calls = new AtomicInteger(); Flowable<Integer> source = Flowable.unsafeCreate(new Publisher<Integer>() { @Override public void subscribe(Subscriber<? super Integer> t) { t.onSubscribe(new BooleanSubscription()); calls.getAndIncrement(); } }); ConnectableFlowable<Integer> conn = source.publish(); assertEquals(0, calls.get()); conn.connect(); conn.connect(); assertEquals(1, calls.get()); conn.connect().dispose(); conn.connect(); conn.connect(); assertEquals(2, calls.get()); } @Test public void syncFusedObserveOn() { ConnectableFlowable<Integer> co = Flowable.range(0, 1000).publish(); Flowable<Integer> obs = co.observeOn(Schedulers.computation()); for (int i = 0; i < 1000; i++) { for (int j = 1; j < 6; j++) { List<TestSubscriber<Integer>> tss = new ArrayList<TestSubscriber<Integer>>(); for (int k = 1; k < j; k++) { TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); tss.add(ts); obs.subscribe(ts); } Disposable s = co.connect(); for (TestSubscriber<Integer> ts : tss) { ts.awaitDone(5, TimeUnit.SECONDS) .assertSubscribed() .assertValueCount(1000) .assertNoErrors() .assertComplete(); } s.dispose(); } } } @Test public void syncFusedObserveOn2() { ConnectableFlowable<Integer> co = Flowable.range(0, 1000).publish(); Flowable<Integer> obs = co.observeOn(ImmediateThinScheduler.INSTANCE); for (int i = 0; i < 1000; i++) { for (int j = 1; j < 6; j++) { List<TestSubscriber<Integer>> tss = new ArrayList<TestSubscriber<Integer>>(); for (int k = 1; k < j; k++) { TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); tss.add(ts); obs.subscribe(ts); } Disposable s = co.connect(); for (TestSubscriber<Integer> ts : tss) { ts.awaitDone(5, TimeUnit.SECONDS) .assertSubscribed() .assertValueCount(1000) .assertNoErrors() .assertComplete(); } s.dispose(); } } } @Test public void asyncFusedObserveOn() { ConnectableFlowable<Integer> co = Flowable.range(0, 1000).observeOn(ImmediateThinScheduler.INSTANCE).publish(); for (int i = 0; i < 1000; i++) { for (int j = 1; j < 6; j++) { List<TestSubscriber<Integer>> tss = new ArrayList<TestSubscriber<Integer>>(); for (int k = 1; k < j; k++) { TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); tss.add(ts); co.subscribe(ts); } Disposable s = co.connect(); for (TestSubscriber<Integer> ts : tss) { ts.awaitDone(5, TimeUnit.SECONDS) .assertSubscribed() .assertValueCount(1000) .assertNoErrors() .assertComplete(); } s.dispose(); } } } @Test public void testObserveOn() { ConnectableFlowable<Integer> co = Flowable.range(0, 1000).hide().publish(); Flowable<Integer> obs = co.observeOn(Schedulers.computation()); for (int i = 0; i < 1000; i++) { for (int j = 1; j < 6; j++) { List<TestSubscriber<Integer>> tss = new ArrayList<TestSubscriber<Integer>>(); for (int k = 1; k < j; k++) { TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); tss.add(ts); obs.subscribe(ts); } Disposable s = co.connect(); for (TestSubscriber<Integer> ts : tss) { ts.awaitDone(5, TimeUnit.SECONDS) .assertSubscribed() .assertValueCount(1000) .assertNoErrors() .assertComplete(); } s.dispose(); } } } @Test public void source() { Flowable<Integer> o = Flowable.never(); assertSame(o, (((HasUpstreamPublisher<?>)o.publish()).source())); } @Test public void connectThrows() { ConnectableFlowable<Integer> co = Flowable.<Integer>empty().publish(); try { co.connect(new Consumer<Disposable>() { @Override public void accept(Disposable s) throws Exception { throw new TestException(); } }); } catch (TestException ex) { // expected } } @Test public void addRemoveRace() { for (int i = 0; i < 500; i++) { final ConnectableFlowable<Integer> co = Flowable.<Integer>empty().publish(); final TestSubscriber<Integer> to = co.test(); final TestSubscriber<Integer> to2 = new TestSubscriber<Integer>(); Runnable r1 = new Runnable() { @Override public void run() { co.subscribe(to2); } }; Runnable r2 = new Runnable() { @Override public void run() { to.cancel(); } }; TestHelper.race(r1, r2); } } @Test public void disposeOnArrival() { ConnectableFlowable<Integer> co = Flowable.<Integer>empty().publish(); co.test(Long.MAX_VALUE, true).assertEmpty(); } @Test public void disposeOnArrival2() { Flowable<Integer> co = Flowable.<Integer>never().publish().autoConnect(); co.test(Long.MAX_VALUE, true).assertEmpty(); } @Test public void dispose() { TestHelper.checkDisposed(Flowable.never().publish()); TestHelper.checkDisposed(Flowable.never().publish(Functions.<Flowable<Object>>identity())); } @Test public void empty() { ConnectableFlowable<Integer> co = Flowable.<Integer>empty().publish(); co.connect(); } @Test public void take() { ConnectableFlowable<Integer> co = Flowable.range(1, 2).publish(); TestSubscriber<Integer> to = co.take(1).test(); co.connect(); to.assertResult(1); } @Test public void just() { final PublishProcessor<Integer> ps = PublishProcessor.create(); ConnectableFlowable<Integer> co = ps.publish(); TestSubscriber<Integer> to = new TestSubscriber<Integer>() { @Override public void onNext(Integer t) { super.onNext(t); ps.onComplete(); } }; co.subscribe(to); co.connect(); ps.onNext(1); to.assertResult(1); } @Test public void nextCancelRace() { for (int i = 0; i < 500; i++) { final PublishProcessor<Integer> ps = PublishProcessor.create(); final ConnectableFlowable<Integer> co = ps.publish(); final TestSubscriber<Integer> to = co.test(); Runnable r1 = new Runnable() { @Override public void run() { ps.onNext(1); } }; Runnable r2 = new Runnable() { @Override public void run() { to.cancel(); } }; TestHelper.race(r1, r2); } } @Test public void badSource() { List<Throwable> errors = TestHelper.trackPluginErrors(); try { new Flowable<Integer>() { @Override protected void subscribeActual(Subscriber<? super Integer> observer) { observer.onSubscribe(new BooleanSubscription()); observer.onNext(1); observer.onComplete(); observer.onNext(2); observer.onError(new TestException()); observer.onComplete(); } } .publish() .autoConnect() .test() .assertResult(1); TestHelper.assertUndeliverable(errors, 0, TestException.class); } finally { RxJavaPlugins.reset(); } } @Test public void noErrorLoss() { List<Throwable> errors = TestHelper.trackPluginErrors(); try { ConnectableFlowable<Object> co = Flowable.error(new TestException()).publish(); co.connect(); TestHelper.assertUndeliverable(errors, 0, TestException.class); } finally { RxJavaPlugins.reset(); } } @Test public void subscribeDisconnectRace() { for (int i = 0; i < 500; i++) { final PublishProcessor<Integer> ps = PublishProcessor.create(); final ConnectableFlowable<Integer> co = ps.publish(); final Disposable d = co.connect(); final TestSubscriber<Integer> to = new TestSubscriber<Integer>(); Runnable r1 = new Runnable() { @Override public void run() { d.dispose(); } }; Runnable r2 = new Runnable() { @Override public void run() { co.subscribe(to); } }; TestHelper.race(r1, r2); } } @Test public void selectorDisconnectsIndependentSource() { PublishProcessor<Integer> ps = PublishProcessor.create(); ps.publish(new Function<Flowable<Integer>, Flowable<Integer>>() { @Override public Flowable<Integer> apply(Flowable<Integer> v) throws Exception { return Flowable.range(1, 2); } }) .test() .assertResult(1, 2); assertFalse(ps.hasSubscribers()); } @Test(timeout = 5000) public void selectorLatecommer() { Flowable.range(1, 5) .publish(new Function<Flowable<Integer>, Flowable<Integer>>() { @Override public Flowable<Integer> apply(Flowable<Integer> v) throws Exception { return v.concatWith(v); } }) .test() .assertResult(1, 2, 3, 4, 5); } @Test public void mainError() { Flowable.error(new TestException()) .publish(Functions.<Flowable<Object>>identity()) .test() .assertFailure(TestException.class); } @Test public void selectorInnerError() { PublishProcessor<Integer> ps = PublishProcessor.create(); ps.publish(new Function<Flowable<Integer>, Flowable<Integer>>() { @Override public Flowable<Integer> apply(Flowable<Integer> v) throws Exception { return Flowable.error(new TestException()); } }) .test() .assertFailure(TestException.class); assertFalse(ps.hasSubscribers()); } @Test public void preNextConnect() { for (int i = 0; i < 500; i++) { final ConnectableFlowable<Integer> co = Flowable.<Integer>empty().publish(); co.connect(); Runnable r1 = new Runnable() { @Override public void run() { co.test(); } }; TestHelper.race(r1, r1); } } @Test public void connectRace() { for (int i = 0; i < 500; i++) { final ConnectableFlowable<Integer> co = Flowable.<Integer>empty().publish(); Runnable r1 = new Runnable() { @Override public void run() { co.connect(); } }; TestHelper.race(r1, r1); } } @Test public void selectorCrash() { Flowable.just(1).publish(new Function<Flowable<Integer>, Flowable<Object>>() { @Override public Flowable<Object> apply(Flowable<Integer> v) throws Exception { throw new TestException(); } }) .test() .assertFailure(TestException.class); } @Test public void pollThrows() { Flowable.just(1) .map(new Function<Integer, Object>() { @Override public Object apply(Integer v) throws Exception { throw new TestException(); } }) .publish() .autoConnect() .test() .assertFailure(TestException.class); } @Test public void dryRunCrash() { final TestSubscriber<Object> ts = new TestSubscriber<Object>(1L) { @Override public void onNext(Object t) { super.onNext(t); onComplete(); cancel(); } }; Flowable.range(1, 10) .map(new Function<Integer, Object>() { @Override public Object apply(Integer v) throws Exception { if (v == 2) { throw new TestException(); } return v; } }) .publish() .autoConnect() .subscribe(ts); ts .assertResult(1); } @Test public void overflowQueue() { Flowable.create(new FlowableOnSubscribe<Object>() { @Override public void subscribe(FlowableEmitter<Object> s) throws Exception { for (int i = 0; i < 10; i++) { s.onNext(i); } } }, BackpressureStrategy.MISSING) .publish(8) .autoConnect() .test(0L) .assertFailure(MissingBackpressureException.class); } @Test public void delayedUpstreamOnSubscribe() { final Subscriber<?>[] sub = { null }; new Flowable<Integer>() { @Override protected void subscribeActual(Subscriber<? super Integer> s) { sub[0] = s; } } .publish() .connect() .dispose(); BooleanSubscription bs = new BooleanSubscription(); sub[0].onSubscribe(bs); assertTrue(bs.isCancelled()); } }
/* * 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.druid.pool; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import com.alibaba.druid.pool.DruidPooledPreparedStatement.PreparedStatementKey; import com.alibaba.druid.proxy.jdbc.CallableStatementProxy; import com.alibaba.druid.proxy.jdbc.PreparedStatementProxy; import com.alibaba.druid.support.logging.Log; import com.alibaba.druid.support.logging.LogFactory; import com.alibaba.druid.util.OracleUtils; /** * @author wenshao [szujobs@hotmail.com] */ public class PreparedStatementPool { private final static Log LOG = LogFactory.getLog(PreparedStatementPool.class); //LRU缓存,缓存预处理语句 private final LRUCache map; private final DruidAbstractDataSource dataSource; public PreparedStatementPool(DruidConnectionHolder holder){ this.dataSource = holder.getDataSource(); int initCapacity = holder.getDataSource().getMaxPoolPreparedStatementPerConnectionSize(); if (initCapacity <= 0) { initCapacity = 16; } map = new LRUCache(initCapacity); } public static enum MethodType { M1, M2, M3, M4, M5, M6, Precall_1, Precall_2, Precall_3 } public PreparedStatementHolder get(PreparedStatementKey key) throws SQLException { PreparedStatementHolder holder = map.get(key); if (holder != null) { if (holder.isInUse() && (!dataSource.isSharePreparedStatements())) { return null; } holder.incrementHitCount(); dataSource.incrementCachedPreparedStatementHitCount(); if (holder.isEnterOracleImplicitCache()) { OracleUtils.exitImplicitCacheToActive(holder.statement); } } else { dataSource.incrementCachedPreparedStatementMissCount(); } return holder; } public void remove(PreparedStatementHolder stmtHolder) throws SQLException { if (stmtHolder == null) { return; } map.remove(stmtHolder.key); closeRemovedStatement(stmtHolder); } public void put(PreparedStatementHolder stmtHolder) throws SQLException { PreparedStatement stmt = stmtHolder.statement; if (stmt == null) { return; } if (dataSource.isOracle() && dataSource.isUseOracleImplicitCache()) { OracleUtils.enterImplicitCache(stmt); stmtHolder.setEnterOracleImplicitCache(true); } else { stmtHolder.setEnterOracleImplicitCache(false); } PreparedStatementHolder oldStmtHolder = map.put(stmtHolder.key, stmtHolder); if (oldStmtHolder == stmtHolder) { return; } if (oldStmtHolder != null) { oldStmtHolder.setPooling(false); closeRemovedStatement(oldStmtHolder); } else { if (stmtHolder.getHitCount() == 0) { dataSource.incrementCachedPreparedStatementCount(); } } stmtHolder.setPooling(true); if (LOG.isDebugEnabled()) { String message = null; if (stmtHolder.statement instanceof PreparedStatementProxy) { PreparedStatementProxy stmtProxy = (PreparedStatementProxy) stmtHolder.statement; if (stmtProxy instanceof CallableStatementProxy) { message = "{conn-" + stmtProxy.getConnectionProxy().getId() + ", cstmt-" + stmtProxy.getId() + "} enter cache"; } else { message = "{conn-" + stmtProxy.getConnectionProxy().getId() + ", pstmt-" + stmtProxy.getId() + "} enter cache"; } } else { message = "stmt enter cache"; } LOG.debug(message); } } public void clear() { Iterator<Entry<PreparedStatementKey, PreparedStatementHolder>> iter = map.entrySet().iterator(); while (iter.hasNext()) { Entry<PreparedStatementKey, PreparedStatementHolder> entry = iter.next(); closeRemovedStatement(entry.getValue()); iter.remove(); } } public void closeRemovedStatement(PreparedStatementHolder holder) { if (LOG.isDebugEnabled()) { String message = null; if (holder.statement instanceof PreparedStatementProxy) { PreparedStatementProxy stmtProxy = (PreparedStatementProxy) holder.statement; if (stmtProxy instanceof CallableStatementProxy) { message = "{conn-" + stmtProxy.getConnectionProxy().getId() + ", cstmt-" + stmtProxy.getId() + "} exit cache"; } else { message = "{conn-" + stmtProxy.getConnectionProxy().getId() + ", pstmt-" + stmtProxy.getId() + "} exit cache"; } } else { message = "stmt exit cache"; } LOG.debug(message); } holder.setPooling(false); if (holder.isInUse()) { return; } if (holder.isEnterOracleImplicitCache()) { try { OracleUtils.exitImplicitCacheToClose(holder.statement); } catch (Exception ex) { LOG.error("exitImplicitCacheToClose error", ex); } } dataSource.closePreapredStatement(holder); } public Map<PreparedStatementKey, PreparedStatementHolder> getMap() { return map; } public int size() { return this.map.size(); } public class LRUCache extends LinkedHashMap<PreparedStatementKey, PreparedStatementHolder> { private static final long serialVersionUID = 1L; public LRUCache(int maxSize){ super(maxSize, 0.75f, true); } protected boolean removeEldestEntry(Entry<PreparedStatementKey, PreparedStatementHolder> eldest) { boolean remove = (size() > dataSource.getMaxPoolPreparedStatementPerConnectionSize()); if (remove) { closeRemovedStatement(eldest.getValue()); } return remove; } } }
/* * This file is part of TechReborn, licensed under the MIT License (MIT). * * Copyright (c) 2020 TechReborn * * 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 techreborn.blockentity.machine.misc; import net.minecraft.block.*; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.fluid.Fluid; import net.minecraft.fluid.Fluids; import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import org.jetbrains.annotations.Nullable; import reborncore.api.IToolDrop; import reborncore.common.blockentity.MachineBaseBlockEntity; import reborncore.common.fluid.FluidValue; import reborncore.common.fluid.container.FluidInstance; import reborncore.common.fluid.container.ItemFluidInfo; import reborncore.common.util.Tank; import techreborn.TechReborn; import techreborn.config.TechRebornConfig; import techreborn.init.TRBlockEntities; import techreborn.init.TRContent; public class DrainBlockEntity extends MachineBaseBlockEntity implements IToolDrop { protected Tank internalTank = new Tank("tank", FluidValue.BUCKET, this); public DrainBlockEntity(BlockPos pos, BlockState state) { super(TRBlockEntities.DRAIN, pos, state); } @Override public void tick(World world, BlockPos pos, BlockState state, MachineBaseBlockEntity blockEntity) { super.tick(world, pos, state, blockEntity); if (world == null || world.isClient) { return; } int ticks = TechRebornConfig.ticksUntilNextDrainAttempt; if (ticks > 0 && world.getTime() % ticks == 0) { if (internalTank.isEmpty()) { tryDrain(); } } } @Nullable @Override public Tank getTank() { return internalTank; } private void tryDrain() { // Position above drain BlockPos above = this.getPos().up(); // Block and state above drain BlockState aboveBlockState = world.getBlockState(above); Block aboveBlock = aboveBlockState.getBlock(); if (aboveBlock instanceof FluidDrainable) { ItemStack fluidContainer = ((FluidDrainable) aboveBlock).tryDrainFluid(world, above, aboveBlockState); if (fluidContainer.getItem() instanceof ItemFluidInfo) { Fluid drainFluid = ((ItemFluidInfo) fluidContainer.getItem()).getFluid(fluidContainer); internalTank.setFluidInstance(new FluidInstance(drainFluid, FluidValue.BUCKET)); } else { TechReborn.LOGGER.debug("Could not get Fluid from ItemStack " + fluidContainer.getItem()); } } if (aboveBlock instanceof LeveledCauldronBlock && aboveBlockState.isOf(Blocks.WATER_CAULDRON)) { //ensure Water cauldron Fluid drainFluid = Fluids.WATER; int level; if (aboveBlockState.contains(LeveledCauldronBlock.LEVEL)){ level = aboveBlockState.get(LeveledCauldronBlock.LEVEL); } else { return; } world.setBlockState(above, Blocks.CAULDRON.getDefaultState()); internalTank.setFluidInstance( new FluidInstance(drainFluid, FluidValue.BUCKET.fraction(3).multiply(level)) ); } if (aboveBlock instanceof LavaCauldronBlock){ world.setBlockState(above, Blocks.CAULDRON.getDefaultState()); internalTank.setFluidInstance( new FluidInstance(Fluids.LAVA, FluidValue.BUCKET) ); } } @Override public ItemStack getToolDrop(PlayerEntity p0) { return TRContent.Machine.DRAIN.getStack(); } }
/* * Copyright 2022 (C) Cognizant SoftVision, All rights Reserved */ package com.cognizantsoftvision.maqs.webservices; import com.cognizantsoftvision.maqs.base.BaseTestObject; import com.cognizantsoftvision.maqs.utilities.logging.Logger; import java.net.http.HttpClient; import java.util.function.Supplier; /** * Web service test object class. */ public class WebServiceTestObject extends BaseTestObject { /** * Instantiates a new Web Service Test Object with a supplier. * * @param getDriverSupplier the get driver supplier. * @param logger the Logger. * @param fullyQualifiedTestName the fully qualified test name. */ public WebServiceTestObject(Supplier<HttpClient> getDriverSupplier, Logger logger, String fullyQualifiedTestName) { super(logger, fullyQualifiedTestName); this.getManagerStore().put((WebServiceDriverManager.class).getCanonicalName(), new WebServiceDriverManager(getDriverSupplier, this)); } /** * Initializes a new instance of the WebServiceTestObject. * * @param driver The web service driver. * @param logger The Logger Object. * @param fullyQualifiedTestName The fully qualified test name. */ public WebServiceTestObject(WebServiceDriver driver, Logger logger, String fullyQualifiedTestName) { super(logger, fullyQualifiedTestName); this.getManagerStore().put((WebServiceDriverManager.class).getCanonicalName(), new WebServiceDriverManager(driver, this)); } /** * Get the web service wrapper for the WebServiceTestObject. * * @return A web service driver */ public WebServiceDriver getWebServiceDriver() { return this.getWebServiceDriverManager().getWebServiceDriver(); } /** * Gets the Web Service driver managers. * * @return the web service manager. */ public WebServiceDriverManager getWebServiceDriverManager() { return (WebServiceDriverManager) this.getManagerStore() .get(WebServiceDriverManager.class.getCanonicalName()); } /** * overrides the web service driver using the WebServiceDriver. * * @param driver the Web Service Driver to be committed. */ public void setWebServiceDriver(WebServiceDriver driver) { this.getManagerStore().put(WebServiceDriverManager.class.getCanonicalName(), new WebServiceDriverManager(driver, this)); } /** * overrides the web service driver using a closable Http Client. * * @param httpClient the Http Client to be set. */ public void setWebServiceDriver(HttpClient httpClient) { this.getManagerStore().put(WebServiceDriverManager.class.getCanonicalName(), new WebServiceDriverManager((() -> httpClient), this)); } /** * overrides the Web Service driver using a supplier. * * @param webServiceSupplier the web service driver supplier. */ public void setWebServiceDriver(Supplier<HttpClient> webServiceSupplier) { this.getManagerStore().put(WebServiceDriverManager.class.getCanonicalName(), new WebServiceDriverManager(webServiceSupplier, this)); } }
/* * 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.solr.common; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.BiConsumer; import org.apache.solr.common.params.CommonParams; /** * Represent the field-value information needed to construct and index * a Lucene Document. Like the SolrDocument, the field values should * match those specified in schema.xml * * * @since solr 1.3 */ public class SolrInputDocument extends SolrDocumentBase<SolrInputField, SolrInputDocument> implements Iterable<SolrInputField> { private final Map<String,SolrInputField> _fields; private List<SolrInputDocument> _childDocuments; public SolrInputDocument(String... fields) { _fields = new LinkedHashMap<>(); assert fields.length % 2 == 0; for (int i = 0; i < fields.length; i += 2) { addField(fields[i], fields[i + 1]); } } @Override public void writeMap(EntryWriter ew) throws IOException { BiConsumer<CharSequence, Object> bc = ew.getBiConsumer(); BiConsumer<CharSequence, Object> wrapper = (k, o) -> { if (o instanceof SolrInputField) { o = ((SolrInputField) o).getValue(); } bc.accept(k, o); }; _fields.forEach(wrapper); if (_childDocuments != null) { ew.put(CommonParams.CHILDDOC, _childDocuments); } } public SolrInputDocument(Map<String,SolrInputField> fields) { _fields = fields; } /** * Remove all fields from the document */ @Override public void clear() { if( _fields != null ) { _fields.clear(); } _childDocuments = null; } /////////////////////////////////////////////////////////////////// // Add / Set fields /////////////////////////////////////////////////////////////////// /** * Add a field value to any existing values that may or may not exist. * * The class type of value and the name parameter should match schema.xml. * schema.xml can be found in conf directory under the solr home by default. * * @param name Name of the field, should match one of the field names defined under "fields" tag in schema.xml. * @param value Value of the field, should be of same class type as defined by "type" attribute of the corresponding field in schema.xml. */ public void addField(String name, Object value) { SolrInputField field = _fields.get( name ); if( field == null || field.value == null ) { setField(name, value); } else { field.addValue( value ); } } /** Get the first value for a field. * * @param name name of the field to fetch * @return first value of the field or null if not present */ @Override public Object getFieldValue(String name) { SolrInputField field = getField(name); Object o = null; if (field!=null) o = field.getFirstValue(); return o; } /** Get all the values for a field. * * @param name name of the field to fetch * @return value of the field or null if not set */ @Override public Collection<Object> getFieldValues(String name) { SolrInputField field = getField(name); if (field!=null) { return field.getValues(); } return null; } /** Get all field names. * * @return Set of all field names. */ @Override public Collection<String> getFieldNames() { return _fields.keySet(); } /** Set a field value; replacing the existing value if present. * * @param name name of the field to set * @param value value of the field */ public void setField(String name, Object value ) { SolrInputField field = new SolrInputField( name ); _fields.put( name, field ); field.setValue( value ); } /** * Remove a field from the document * * @param name The field name whose field is to be removed from the document * @return the previous field with <code>name</code>, or * <code>null</code> if there was no field for <code>key</code>. */ public SolrInputField removeField(String name) { return _fields.remove( name ); } /////////////////////////////////////////////////////////////////// // Get the field values /////////////////////////////////////////////////////////////////// public SolrInputField getField( String field ) { return _fields.get( field ); } @Override public Iterator<SolrInputField> iterator() { return _fields.values().iterator(); } @Override public String toString() { return "SolrInputDocument(fields: " + _fields.values() + ( _childDocuments == null ? "" : (", children: " + _childDocuments) ) + ")"; } public SolrInputDocument deepCopy() { SolrInputDocument clone = new SolrInputDocument(); Set<Entry<String,SolrInputField>> entries = _fields.entrySet(); for (Map.Entry<String,SolrInputField> fieldEntry : entries) { clone._fields.put(fieldEntry.getKey(), fieldEntry.getValue().deepCopy()); } if (_childDocuments != null) { clone._childDocuments = new ArrayList<>(_childDocuments.size()); for (SolrInputDocument child : _childDocuments) { clone._childDocuments.add(child.deepCopy()); } } return clone; } //--------------------------------------------------- // MAP interface //--------------------------------------------------- @Override public boolean containsKey(Object key) { return _fields.containsKey(key); } @Override public boolean containsValue(Object value) { return _fields.containsValue(value); } @Override public Set<Entry<String, SolrInputField>> entrySet() { return _fields.entrySet(); } @Override public SolrInputField get(Object key) { return _fields.get(key); } @Override public boolean isEmpty() { return _fields.isEmpty(); } @Override public Set<String> keySet() { return _fields.keySet(); } @Override public SolrInputField put(String key, SolrInputField value) { return _fields.put(key, value); } @Override public void putAll(Map<? extends String, ? extends SolrInputField> t) { _fields.putAll( t ); } @Override public SolrInputField remove(Object key) { return _fields.remove(key); } @Override public int size() { return _fields.size(); } @Override public Collection<SolrInputField> values() { return _fields.values(); } @Override public void addChildDocument(SolrInputDocument child) { if (_childDocuments == null) { _childDocuments = new ArrayList<>(); } _childDocuments.add(child); } public void addChildDocuments(Collection<SolrInputDocument> children) { for (SolrInputDocument child : children) { addChildDocument(child); } } /** Returns the list of child documents, or null if none. */ public List<SolrInputDocument> getChildDocuments() { return _childDocuments; } public boolean hasChildDocuments() { boolean isEmpty = (_childDocuments == null || _childDocuments.isEmpty()); return !isEmpty; } @Override public int getChildDocumentCount() { return hasChildDocuments() ? _childDocuments.size(): 0; } }
package emoji4j; import static org.assertj.core.api.Assertions.*; import org.junit.Test; public class EmoticonTest { @Test public void testEmojiByEmoticons() { Emoji emoji = EmojiUtils.getEmoji(":)"); assertThat(emoji.getEmoji()).isEqualTo("😃"); emoji = EmojiUtils.getEmoji(";]"); assertThat(emoji.getEmoji()).isEqualTo("😉"); // invalid emoticon emoji = EmojiUtils.getEmoji(";|D"); assertThat(emoji).isNull(); } @Test public void testParseEmoticons() { String text = ":):-),:-):-]:-xP=*:*<3:P:p,=-)"; assertThat(EmojiUtils.emojify(text)).isEqualTo("😃😃😅😃😶😝😗😗❤️😛😛😅"); text = "A :cat:, :dog: and a :mouse: became friends<3. For :dog:'s birthday party, they all had :hamburger:s, :fries:s, :cookie:s and :cake:."; assertThat(EmojiUtils.emojify(text)).isEqualTo( "A 🐱, 🐶 and a 🐭 became friends❤️. For 🐶's birthday party, they all had 🍔s, 🍟s, 🍪s and 🍰."); } @Test public void testIssue5() { String text ="a fix for \uD83D\uDE14"; assertThat(EmojiUtils.removeAllEmojis(text)).isEqualTo("a fix for "); } }
/** * Copyright 2020 the original author or authors. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.thierrysquirrel.websocket.init.core.factory; import com.github.thierrysquirrel.websocket.core.container.WebsocketRouteContainer; import com.github.thierrysquirrel.websocket.core.template.WebsocketRouteTemplate; import com.github.thierrysquirrel.websocket.core.template.core.factory.WebsocketRouteTemplateFactory; /** * ClassName: WebsocketRouteInitFactory * Description: * date: 2020/8/17 22:56 * * @author ThierrySquirrel * @since JDK 1.8 */ public class WebsocketRouteInitFactory { private WebsocketRouteInitFactory() { } public static void addWebsocketRouteTemplate(WebsocketRouteTemplate routeTemplate) { String route = WebsocketRouteTemplateFactory.getRoute (routeTemplate); WebsocketRouteContainer.putWebsocketRouteTemplate (route, routeTemplate); } }
package conganh.hcmus; import java.io.Serializable; public class Person implements Serializable { String fullName; int yearOfBirth; String homeTown; public Person(String fullName, int yearOfBirth, String homeTown) { this.fullName = fullName; this.yearOfBirth = yearOfBirth; this.homeTown = homeTown; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public int getYearOfBirth() { return yearOfBirth; } public void setYearOfBirth(int yearOfBirth) { this.yearOfBirth = yearOfBirth; } public String getHomeTown() { return homeTown; } public void setHomeTown(String homeTown) { this.homeTown = homeTown; } @Override public String toString() { return "\nPersonal Information:" + "\nFull Name : " + fullName + "\nYear Of Birth : " + yearOfBirth + "\nHomeTown : '" + homeTown; } }
package com.github.songxzj.wxpay.v3.bean.result.marketing.busifavor; import com.github.songxzj.wxpay.v3.bean.result.BaseWxPayV3Result; import com.google.gson.annotations.SerializedName; import lombok.*; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; @Setter @Getter @ToString @EqualsAndHashCode(callSuper = true) @NoArgsConstructor public class WxBusifavorStockBudgetResult extends BaseWxPayV3Result { private static final long serialVersionUID = -6792495151320843646L; /** * 批次当前最大发放个数 * max_coupons * int * 是 */ @SerializedName("max_coupons") private Integer maxCoupons; /** * 当前单天发放上限个数 * max_coupons_by_day * int * 否 */ @SerializedName("max_coupons_by_day") private Integer maxCouponsByDay; }
// // ======================================================================== // Copyright (c) 1995-2021 Mort Bay Consulting Pty Ltd and others. // // This program and the accompanying materials are made available under the // terms of the Eclipse Public License v. 2.0 which is available at // https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 // which is available at https://www.apache.org/licenses/LICENSE-2.0. // // SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 // ======================================================================== // @Deprecated(forRemoval = true) module org.eclipse.jetty.unixsocket.client { requires org.eclipse.jetty.unixsocket.common; requires org.slf4j; requires transitive org.eclipse.jetty.client; requires transitive org.jnrproject.enxio; requires transitive org.jnrproject.unixsocket; exports org.eclipse.jetty.unixsocket.client; }
package com.example.metropolismayor.mayorcore.income; import com.example.metropolismayor.mayorcore.Game; import com.example.metropolismayor.mayorcore.Player; /** * Defines an income that is dependent on the presence of a building. * INCOME: if (card) then (amount) * These card can be in the players hand or in any players hand (depends). */ public class ConditionalIncome implements Income { int amount; String cardname; public ConditionalIncome(int amount, String cardname) { this.amount = amount; this.cardname = cardname; } @Override public int calculate(Player player) { if (cardname.equals("Universiteit")) { // If the card to watch is the university we want to know if it is globally present return Game.getInstance().isUniversiteit() ? amount : 0; } else { // Any other card must be in the players' hand return player.hand.contains(cardname) ? amount : 0; } } public String toString() { return String.format("%d if %s", amount, cardname); } }
import java.net.URI; import java.net.URISyntaxException; import org.apache.commons.validator.routines.UrlValidator; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.preference.PreferenceManager; import android.view.Gravity; import android.widget.EditText; import android.widget.TextView; /** * Just a place to store an RSS feed easily. Also strips * feed URLs to the domain for convenient storage. For an * actual feed reader you'll have to store the URL somewhere * else if it's stored by the user. * * @author Isaac Whitfield * @version 06/08/2013 */ public class RSSUtil { // Put your RSS feed URL here public static String RSSFEEDURL = "http://blog.zackehh.com/feed/"; // Change to a given feed public static void changeFeed(boolean refresh, Context context){ changeURL(refresh, context); } // Returns the filename of the stored feed public static String getFeedName(){ return getDomainName(RSSFEEDURL); } // Strips a URL to the domain private static String getDomainName(String url) { String domain = null; try { domain = new URI(url).getHost(); } catch (URISyntaxException e) { e.printStackTrace(); } return domain.startsWith("www.") ? domain.substring(4) : domain; } // Takes a string URL as a new feed private static void changeURL(final boolean refresh, final Context context){ // Set the content view AlertDialog.Builder builder = new AlertDialog.Builder(context); // Set an EditText view to get user input final EditText input = new EditText(context); // Set the alert title builder.setTitle("Changing RSS Feed URL:") // Set the alert message .setMessage("Please enter a valid RSS URL:") // Set the view to the dialog .setView(input) // Can't exit via back button .setCancelable(false) // Set the positive button action .setPositiveButton("OK", new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int whichButton){ // Check for a valid URL if(new UrlValidator().isValid(input.getText().toString())){ // Store the new URL we're working with RSSFEEDURL = input.getText().toString(); } // Parse the new feed new LoadRSSFeed(context, RSSFEEDURL).execute(); } }) // Set the negative button actions .setNegativeButton("Cancel", new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int whichButton){ // If it's during initial loading if(!PreferenceManager.getDefaultSharedPreferences(context).getBoolean("isSetup", false)){ // Exit the application ((Activity)context).finish(); } else { // Otherwise do nothing dialog.dismiss(); } } }); // Create dialog from builder AlertDialog alert = builder.create(); // Don't exit the dialog when the screen is touched alert.setCanceledOnTouchOutside(false); // Show the alert alert.show(); // Center the message ((TextView)alert.findViewById(android.R.id.message)).setGravity(Gravity.CENTER); // Center the title of the dialog ((TextView)alert.findViewById((context.getResources().getIdentifier("alertTitle", "id", "android")))).setGravity(Gravity.CENTER); } }
package mil.nga.geopackage.extension.im.portrayal; import java.sql.SQLException; import com.j256.ormlite.support.ConnectionSource; import mil.nga.geopackage.GeoPackageCore; import mil.nga.geopackage.db.GeoPackageCoreConnection; import mil.nga.geopackage.db.GeoPackageDao; /** * @author jyutzler * @since 4.0.0 */ public class SymbolsDao extends GeoPackageDao<Symbols, Long> { /** * Create the DAO * * @param geoPackage * GeoPackage * @return dao */ public static SymbolsDao create(GeoPackageCore geoPackage) { return create(geoPackage.getDatabase()); } /** * Create the DAO * * @param db * database connection * @return dao */ public static SymbolsDao create(GeoPackageCoreConnection db) { return GeoPackageDao.createDao(db, Symbols.class); } /** * Constructor, required by ORMLite * * @param connectionSource * connection source * @param dataClass * data class * @throws SQLException * upon failure */ public SymbolsDao(ConnectionSource connectionSource, Class<Symbols> dataClass) throws SQLException { super(connectionSource, dataClass); } }
package com.mmall.concurrency.example.lock; import java.util.concurrent.locks.StampedLock; public class LockExample4 { class Point { private double x, y; private final StampedLock sl = new StampedLock(); void move(double deltaX, double deltaY) { // an exclusively locked method long stamp = sl.writeLock(); try { x += deltaX; y += deltaY; } finally { sl.unlockWrite(stamp); } } //下面看看乐观读锁案例 double distanceFromOrigin() { // A read-only method long stamp = sl.tryOptimisticRead(); //获得一个乐观读锁 double currentX = x, currentY = y; //将两个字段读入本地局部变量 if (!sl.validate(stamp)) { //检查发出乐观读锁后同时是否有其他写锁发生? stamp = sl.readLock(); //如果没有,我们再次获得一个读悲观锁 try { currentX = x; // 将两个字段读入本地局部变量 currentY = y; // 将两个字段读入本地局部变量 } finally { sl.unlockRead(stamp); } } return Math.sqrt(currentX * currentX + currentY * currentY); } //下面是悲观读锁案例 void moveIfAtOrigin(double newX, double newY) { // upgrade // Could instead start with optimistic, not read mode long stamp = sl.readLock(); try { while (x == 0.0 && y == 0.0) { //循环,检查当前状态是否符合 long ws = sl.tryConvertToWriteLock(stamp); //将读锁转为写锁 if (ws != 0L) { //这是确认转为写锁是否成功 stamp = ws; //如果成功 替换票据 x = newX; //进行状态改变 y = newY; //进行状态改变 break; } else { //如果不能成功转换为写锁 sl.unlockRead(stamp); //我们显式释放读锁 stamp = sl.writeLock(); //显式直接进行写锁 然后再通过循环再试 } } } finally { sl.unlock(stamp); //释放读锁或写锁 } } } }
package com.dcy.workflow.controller; import cn.hutool.core.convert.Convert; import cn.hutool.core.util.PageUtil; import cn.hutool.core.util.StrUtil; import com.dcy.common.model.PageModel; import com.dcy.common.model.PageResult; import com.dcy.common.model.R; import com.dcy.db.base.controller.RBaseController; import com.dcy.workflow.dto.input.ProcessDefinitionSearchInputDTO; import com.dcy.workflow.dto.output.ProcessDefinitionListOutputDTO; import com.dcy.workflow.service.ActTaskService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiOperation; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.flowable.engine.RepositoryService; import org.flowable.engine.repository.Deployment; import org.flowable.engine.repository.ProcessDefinition; import org.flowable.engine.repository.ProcessDefinitionQuery; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.validation.constraints.NotBlank; import java.util.ArrayList; import java.util.List; /** * @Author:dcy * @Description: * @Date: 2021/6/7 10:24 */ @RequiredArgsConstructor @Validated @Slf4j @RestController @RequestMapping("/flow/process") @Api(value = "ProcessController", tags = {"流程操作接口"}) public class ProcessController extends RBaseController { private final RepositoryService repositoryService; private final ActTaskService actTaskService; @ApiOperation(value = "获取流程定义列表") @GetMapping(value = "/page") public R<PageResult<ProcessDefinitionListOutputDTO>> getProcessDefinitionList(ProcessDefinitionSearchInputDTO processDefinitionSearchInputDTO, PageModel pageModel) { PageResult<ProcessDefinitionListOutputDTO> pageResult = new PageResult<>(); ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery().orderByProcessDefinitionId().orderByProcessDefinitionVersion().desc(); if (StrUtil.isNotBlank(processDefinitionSearchInputDTO.getName())) { processDefinitionQuery.processDefinitionNameLike(StrUtil.format("%{}%", processDefinitionSearchInputDTO.getName())); } if (StrUtil.isNotBlank(processDefinitionSearchInputDTO.getKey())) { processDefinitionQuery.processDefinitionKeyLike(StrUtil.format("%{}%", processDefinitionSearchInputDTO.getKey())); } List<ProcessDefinitionListOutputDTO> list = new ArrayList<>(); // 设置首页页码 PageUtil.setFirstPageNo(1); List<ProcessDefinition> processDefinitionList = processDefinitionQuery.listPage(PageUtil.getStart(Convert.toInt(pageModel.getCurrent()), Convert.toInt(pageModel.getSize())), Convert.toInt(pageModel.getSize())); long count = processDefinitionQuery.count(); for (ProcessDefinition processDefinition : processDefinitionList) { String deploymentId = processDefinition.getDeploymentId(); Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult(); list.add(new ProcessDefinitionListOutputDTO(processDefinition, deployment)); } // 赋值 pageResult.setCurrent(pageModel.getCurrent()); pageResult.setTotal(count); pageResult.setSize(pageModel.getSize()); pageResult.setRecords(list); pageResult.setPages(PageUtil.totalPage(Convert.toInt(count), Convert.toInt(pageModel.getSize()))); return success(pageResult); } @ApiOperation(value = "删除部署的流程,级联删除流程实例") @ApiImplicitParam(name = "deploymentId", value = "流程部署id", dataType = "String", paramType = "query") @PostMapping(value = "/delete") public R<Boolean> delete(@NotBlank(message = "流程部署id不能为空") String deploymentId) { repositoryService.deleteDeployment(deploymentId, true); return success(true); } @ApiOperation(value = "删除流程实例") @ApiImplicitParam(name = "processInstanceId", value = "流程实例id", dataType = "String", paramType = "query") @PostMapping(value = "/deleteProcIns") public R<Boolean> deleteProcIns(@NotBlank(message = "流程实例id不能为空") String processInstanceId) { actTaskService.deleteProcess(processInstanceId); return success(true); } @ApiOperation(value = "挂起、激活流程实例") @ApiImplicitParam(name = "processDefinitionId", value = "流程定义id", dataType = "String", paramType = "query") @PostMapping(value = "/hangChange") public R<Boolean> hangChange(@NotBlank(message = "流程定义id不能为空") String processDefinitionId) { // 判断挂起状态,true 挂起, false 未挂起 if (repositoryService.isProcessDefinitionSuspended(processDefinitionId)) { // 激活 repositoryService.activateProcessDefinitionById(processDefinitionId); } else { // 挂起 repositoryService.suspendProcessDefinitionById(processDefinitionId); } return success(true); } }
package com.untamedears.itemexchange.rules.modifiers; import co.aikar.commands.InvalidCommandArgument; import co.aikar.commands.annotation.CommandAlias; import co.aikar.commands.annotation.Description; import co.aikar.commands.annotation.Optional; import co.aikar.commands.annotation.Single; import co.aikar.commands.annotation.Subcommand; import co.aikar.commands.annotation.Syntax; import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.untamedears.itemexchange.ItemExchangeConfig; import com.untamedears.itemexchange.commands.SetCommand; import com.untamedears.itemexchange.rules.ExchangeRule; import com.untamedears.itemexchange.rules.interfaces.Modifier; import com.untamedears.itemexchange.rules.interfaces.ModifierData; import com.untamedears.itemexchange.utility.ModifierHandler; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.Repairable; import vg.civcraft.mc.civmodcore.serialization.NBTCompound; import vg.civcraft.mc.civmodcore.util.MoreClassUtils; /** * <p>This additional represents a repair level condition.</p> * * <ul> * <li>Positive integers and zero mean that repair level specifically, eg: RepairCost == 15</li> * <li>Negative integers mean that that repair level or lower, eg: RepairCost &lt;= 15</li> * </ul> */ @CommandAlias(SetCommand.ALIAS) @Modifier(slug = "REPAIR", order = 600) public final class RepairModifier extends ModifierData { public static final RepairModifier TEMPLATE = new RepairModifier(); public static final String LEVEL_KEY = "repairLevel"; private int level; @Override public RepairModifier construct(ItemStack item) { if (!ItemExchangeConfig.canRepairItem(item.getType())) { return null; } Repairable meta = MoreClassUtils.castOrNull(Repairable.class, item.getItemMeta()); if (meta == null) { return null; } RepairModifier modifier = new RepairModifier(); modifier.level = meta.getRepairCost(); return modifier; } @Override public boolean isBroken() { return false; } @Override public boolean conforms(ItemStack item) { Repairable meta = MoreClassUtils.castOrNull(Repairable.class, item.getItemMeta()); if (meta == null) { return false; } int itemRepair = meta.getRepairCost(); if (this.level < 0) { return itemRepair <= this.level * -1; } else { return itemRepair == this.level; } } @Override public void serialize(NBTCompound nbt) { nbt.setInteger(LEVEL_KEY, getRepairCost()); } @Override public void deserialize(NBTCompound nbt) { setRepairCost(nbt.getInteger(LEVEL_KEY)); } @Override public List<String> getDisplayInfo() { List<String> info = Lists.newArrayList(); int repairCost = getRepairCost(); if (repairCost == 0) { info.add(ChatColor.GOLD + "Never repaired"); } else if (repairCost < 0) { info.add(ChatColor.GOLD + "Repair level " + (repairCost * -1 + 2) + " or less"); } else { info.add(ChatColor.GOLD + "Repair level " + (repairCost + 2)); } return info; } @Override public String toString() { return getSlug() + "{" + "level=" + getRepairCost() + "}"; } // ------------------------------------------------------------ // Commands // ------------------------------------------------------------ @Subcommand("repair|repairlevel") @Description("Sets or resets the exchange's repair level.") @Syntax("[repair level]") public void commandSetRepairLevel(Player player, @Optional @Single String value) { try (ModifierHandler<RepairModifier> handler = new ModifierHandler<>(player, this)) { if (Strings.isNullOrEmpty(value)) { handler.setModifier(null); handler.relay(ChatColor.GREEN + "Successfully removed repair level condition."); return; } RepairModifier modifier = handler.ensureModifier(); if (value.startsWith("@")) { int repairLevel = ExchangeRule.ERROR; try { repairLevel = Integer.parseInt(value.substring(1)); } catch (final NumberFormatException ignored) { } if (repairLevel < 2) { throw new InvalidCommandArgument("You must enter a valid value, e.g: @9"); } modifier.setRepairCost(repairLevel - 2); } else if (StringUtils.equalsIgnoreCase(value, "NEW") || StringUtils.equalsIgnoreCase(value, "MINT")) { modifier.setRepairCost(0); } else { int repairLevel = ExchangeRule.ERROR; try { repairLevel = Integer.parseInt(value); } catch (final NumberFormatException ignored) { } if (repairLevel < 2) { throw new InvalidCommandArgument("You must enter a valid value, e.g: 9"); } modifier.setRepairCost((repairLevel - 2) * -1); } handler.relay(ChatColor.GREEN + "Successfully changed repair level condition."); } } // ------------------------------------------------------------ // Getters + Setters // ------------------------------------------------------------ public int getRepairCost() { return this.level; } public void setRepairCost(int repairLevel) { this.level = repairLevel; } }
/* * 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.compute.model; /** * Model definition for InstanceGroupManagersListErrorsResponse. * * <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 Compute Engine 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 InstanceGroupManagersListErrorsResponse extends com.google.api.client.json.GenericJson { /** * [Output Only] The list of errors of the managed instance group. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<InstanceManagedByIgmError> items; /** * [Output Only] This token allows you to get the next page of results for list requests. If the * number of results is larger than maxResults, use the nextPageToken as a value for the query * parameter pageToken in the next list request. Subsequent list requests will have their own * nextPageToken to continue paging through the results. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String nextPageToken; /** * [Output Only] The list of errors of the managed instance group. * @return value or {@code null} for none */ public java.util.List<InstanceManagedByIgmError> getItems() { return items; } /** * [Output Only] The list of errors of the managed instance group. * @param items items or {@code null} for none */ public InstanceGroupManagersListErrorsResponse setItems(java.util.List<InstanceManagedByIgmError> items) { this.items = items; return this; } /** * [Output Only] This token allows you to get the next page of results for list requests. If the * number of results is larger than maxResults, use the nextPageToken as a value for the query * parameter pageToken in the next list request. Subsequent list requests will have their own * nextPageToken to continue paging through the results. * @return value or {@code null} for none */ public java.lang.String getNextPageToken() { return nextPageToken; } /** * [Output Only] This token allows you to get the next page of results for list requests. If the * number of results is larger than maxResults, use the nextPageToken as a value for the query * parameter pageToken in the next list request. Subsequent list requests will have their own * nextPageToken to continue paging through the results. * @param nextPageToken nextPageToken or {@code null} for none */ public InstanceGroupManagersListErrorsResponse setNextPageToken(java.lang.String nextPageToken) { this.nextPageToken = nextPageToken; return this; } @Override public InstanceGroupManagersListErrorsResponse set(String fieldName, Object value) { return (InstanceGroupManagersListErrorsResponse) super.set(fieldName, value); } @Override public InstanceGroupManagersListErrorsResponse clone() { return (InstanceGroupManagersListErrorsResponse) super.clone(); } }
// Copyright 2000-2018 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.patterns; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiField; import com.intellij.psi.PsiMethod; import com.intellij.psi.util.InheritanceUtil; import com.intellij.util.ProcessingContext; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import static com.intellij.patterns.StandardPatterns.string; /** * @author peter */ public class PsiClassPattern extends PsiMemberPattern<PsiClass, PsiClassPattern>{ protected PsiClassPattern() { super(PsiClass.class); } public PsiClassPattern inheritorOf(final boolean strict, final PsiClassPattern pattern) { return with(new PatternCondition<PsiClass>("inheritorOf") { @Override public boolean accepts(@NotNull PsiClass psiClass, final ProcessingContext context) { return isInheritor(psiClass, pattern, context, !strict); } }); } private static boolean isInheritor(PsiClass psiClass, ElementPattern pattern, final ProcessingContext matchingContext, boolean checkThisClass) { if (psiClass == null) return false; if (checkThisClass && pattern.accepts(psiClass, matchingContext)) return true; if (isInheritor(psiClass.getSuperClass(), pattern, matchingContext, true)) return true; for (final PsiClass aClass : psiClass.getInterfaces()) { if (isInheritor(aClass, pattern, matchingContext, true)) return true; } return false; } public PsiClassPattern inheritorOf(final boolean strict, final String className) { return with(new PatternCondition<PsiClass>("inheritorOf") { @Override public boolean accepts(@NotNull PsiClass psiClass, final ProcessingContext context) { return InheritanceUtil.isInheritor(psiClass, strict, className); } }); } public PsiClassPattern isInterface() { return with(new PatternCondition<PsiClass>("isInterface") { @Override public boolean accepts(@NotNull final PsiClass psiClass, final ProcessingContext context) { return psiClass.isInterface(); } });} public PsiClassPattern isAnnotationType() { return with(new PatternCondition<PsiClass>("isAnnotationType") { @Override public boolean accepts(@NotNull final PsiClass psiClass, final ProcessingContext context) { return psiClass.isAnnotationType(); } });} public PsiClassPattern withMethod(final boolean checkDeep, final ElementPattern<? extends PsiMethod> memberPattern) { return with(new PatternCondition<PsiClass>("withMethod") { @Override public boolean accepts(@NotNull final PsiClass psiClass, final ProcessingContext context) { for (PsiMethod method : (checkDeep ? psiClass.getAllMethods() : psiClass.getMethods())) { if (memberPattern.accepts(method, context)) { return true; } } return false; } }); } public PsiClassPattern withField(final boolean checkDeep, final ElementPattern<? extends PsiField> memberPattern) { return with(new PatternCondition<PsiClass>("withField") { @Override public boolean accepts(@NotNull final PsiClass psiClass, final ProcessingContext context) { for (PsiField field : (checkDeep ? psiClass.getAllFields() : psiClass.getFields())) { if (memberPattern.accepts(field, context)) { return true; } } return false; } }); } public PsiClassPattern nonAnnotationType() { return with(new PatternCondition<PsiClass>("nonAnnotationType") { @Override public boolean accepts(@NotNull final PsiClass psiClass, final ProcessingContext context) { return !psiClass.isAnnotationType(); } }); } public PsiClassPattern withQualifiedName(@NonNls @NotNull final String qname) { return with(new PsiClassNamePatternCondition(string().equalTo(qname))); } public PsiClassPattern withQualifiedName(@NonNls @NotNull final ElementPattern<String> qname) { return with(new PsiClassNamePatternCondition(qname)); } }
/** * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. * This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. */ package com.oracle.bmc.dts.responses; import com.oracle.bmc.dts.model.*; @javax.annotation.Generated(value = "OracleSDKGenerator", comments = "API Version: 1.0.015") @lombok.Builder(builderClassName = "Builder") @lombok.ToString(callSuper = true) @lombok.EqualsAndHashCode @lombok.Getter public class AttachDevicesToTransferPackageResponse { /** * HTTP status code returned by the operation. */ private final int __httpStatusCode__; /** * */ private String opcRequestId; /** * */ private String etag; public static class Builder { /** * Copy method to populate the builder with values from the given instance. * @return this builder instance */ public Builder copy(AttachDevicesToTransferPackageResponse o) { __httpStatusCode__(o.get__httpStatusCode__()); opcRequestId(o.getOpcRequestId()); etag(o.getEtag()); return this; } } }
package com.dianping.phoenix.agent.core.task.processor.kernel.qa; public class DomainHealthCheckInfo { private String domain; private String env; private String host; private int port; private String qaServiceUrlPrefix; public DomainHealthCheckInfo(String domain, String env, String host, int port, String qaServiceUrlPrefix) { this.domain = domain; this.env = env; this.host = host; this.port = port; this.qaServiceUrlPrefix = qaServiceUrlPrefix; } public String getDomain() { return domain; } public String getEnv() { return env; } public String getHost() { return host; } public int getPort() { return port; } public String getQaServiceUrlPrefix() { return qaServiceUrlPrefix; } }
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.texttospeech.v1.stub; import com.google.api.core.BetaApi; import com.google.api.gax.grpc.GrpcCallSettings; import com.google.api.gax.grpc.GrpcCallableFactory; import com.google.api.gax.grpc.GrpcStubCallableFactory; import com.google.api.gax.rpc.BatchingCallSettings; import com.google.api.gax.rpc.BidiStreamingCallable; import com.google.api.gax.rpc.ClientContext; import com.google.api.gax.rpc.ClientStreamingCallable; import com.google.api.gax.rpc.OperationCallSettings; import com.google.api.gax.rpc.OperationCallable; import com.google.api.gax.rpc.PagedCallSettings; import com.google.api.gax.rpc.ServerStreamingCallSettings; import com.google.api.gax.rpc.ServerStreamingCallable; import com.google.api.gax.rpc.StreamingCallSettings; import com.google.api.gax.rpc.UnaryCallSettings; import com.google.api.gax.rpc.UnaryCallable; import com.google.longrunning.stub.OperationsStub; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS /** * gRPC callable factory implementation for Cloud Text-to-Speech API. * * <p>This class is for advanced usage. */ @Generated("by gapic-generator") @BetaApi("The surface for use by generated code is not stable yet and may change in the future.") public class GrpcTextToSpeechCallableFactory implements GrpcStubCallableFactory { @Override public <RequestT, ResponseT> UnaryCallable<RequestT, ResponseT> createUnaryCallable( GrpcCallSettings<RequestT, ResponseT> grpcCallSettings, UnaryCallSettings<RequestT, ResponseT> callSettings, ClientContext clientContext) { return GrpcCallableFactory.createUnaryCallable(grpcCallSettings, callSettings, clientContext); } @Override public <RequestT, ResponseT, PagedListResponseT> UnaryCallable<RequestT, PagedListResponseT> createPagedCallable( GrpcCallSettings<RequestT, ResponseT> grpcCallSettings, PagedCallSettings<RequestT, ResponseT, PagedListResponseT> pagedCallSettings, ClientContext clientContext) { return GrpcCallableFactory.createPagedCallable( grpcCallSettings, pagedCallSettings, clientContext); } @Override public <RequestT, ResponseT> UnaryCallable<RequestT, ResponseT> createBatchingCallable( GrpcCallSettings<RequestT, ResponseT> grpcCallSettings, BatchingCallSettings<RequestT, ResponseT> batchingCallSettings, ClientContext clientContext) { return GrpcCallableFactory.createBatchingCallable( grpcCallSettings, batchingCallSettings, clientContext); } @BetaApi( "The surface for long-running operations is not stable yet and may change in the future.") @Override public <RequestT, ResponseT, MetadataT> OperationCallable<RequestT, ResponseT, MetadataT> createOperationCallable( GrpcCallSettings<RequestT, com.google.longrunning.Operation> grpcCallSettings, OperationCallSettings<RequestT, ResponseT, MetadataT> operationCallSettings, ClientContext clientContext, OperationsStub operationsStub) { return GrpcCallableFactory.createOperationCallable( grpcCallSettings, operationCallSettings, clientContext, operationsStub); } @Override public <RequestT, ResponseT> BidiStreamingCallable<RequestT, ResponseT> createBidiStreamingCallable( GrpcCallSettings<RequestT, ResponseT> grpcCallSettings, StreamingCallSettings<RequestT, ResponseT> streamingCallSettings, ClientContext clientContext) { return GrpcCallableFactory.createBidiStreamingCallable( grpcCallSettings, streamingCallSettings, clientContext); } @Override public <RequestT, ResponseT> ServerStreamingCallable<RequestT, ResponseT> createServerStreamingCallable( GrpcCallSettings<RequestT, ResponseT> grpcCallSettings, ServerStreamingCallSettings<RequestT, ResponseT> streamingCallSettings, ClientContext clientContext) { return GrpcCallableFactory.createServerStreamingCallable( grpcCallSettings, streamingCallSettings, clientContext); } @Override public <RequestT, ResponseT> ClientStreamingCallable<RequestT, ResponseT> createClientStreamingCallable( GrpcCallSettings<RequestT, ResponseT> grpcCallSettings, StreamingCallSettings<RequestT, ResponseT> streamingCallSettings, ClientContext clientContext) { return GrpcCallableFactory.createClientStreamingCallable( grpcCallSettings, streamingCallSettings, clientContext); } }
package kualian.dc.deal.application.ui.camera; /** * Created by 傅令杰 * 请求码存储 */ public class RequestCodes { public static final int TAKE_PHOTO = 4; public static final int PICK_PHOTO = 5; public static final int CROP_PHOTO = 10; public static final int CROP_ERROR = -1; public static final int SCAN = 7; public static final int WX_CROP = 100; public static final int QQ_CROP = 200; }