text
stringlengths
7
1.01M
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 3.0.12 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package io.adaptivecards.objectmodel; public class BaseActionElementVector { private transient long swigCPtr; protected transient boolean swigCMemOwn; protected BaseActionElementVector(long cPtr, boolean cMemoryOwn) { swigCMemOwn = cMemoryOwn; swigCPtr = cPtr; } protected static long getCPtr(BaseActionElementVector obj) { return (obj == null) ? 0 : obj.swigCPtr; } protected void finalize() { delete(); } public synchronized void delete() { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; AdaptiveCardObjectModelJNI.delete_BaseActionElementVector(swigCPtr); } swigCPtr = 0; } } public BaseActionElementVector() { this(AdaptiveCardObjectModelJNI.new_BaseActionElementVector__SWIG_0(), true); } public BaseActionElementVector(long n) { this(AdaptiveCardObjectModelJNI.new_BaseActionElementVector__SWIG_1(n), true); } public long size() { return AdaptiveCardObjectModelJNI.BaseActionElementVector_size(swigCPtr, this); } public long capacity() { return AdaptiveCardObjectModelJNI.BaseActionElementVector_capacity(swigCPtr, this); } public void reserve(long n) { AdaptiveCardObjectModelJNI.BaseActionElementVector_reserve(swigCPtr, this, n); } public boolean isEmpty() { return AdaptiveCardObjectModelJNI.BaseActionElementVector_isEmpty(swigCPtr, this); } public void clear() { AdaptiveCardObjectModelJNI.BaseActionElementVector_clear(swigCPtr, this); } public void add(BaseActionElement x) { AdaptiveCardObjectModelJNI.BaseActionElementVector_add(swigCPtr, this, BaseActionElement.getCPtr(x), x); } public BaseActionElement get(int i) { long cPtr = AdaptiveCardObjectModelJNI.BaseActionElementVector_get(swigCPtr, this, i); return (cPtr == 0) ? null : new BaseActionElement(cPtr, true); } public void set(int i, BaseActionElement val) { AdaptiveCardObjectModelJNI.BaseActionElementVector_set(swigCPtr, this, i, BaseActionElement.getCPtr(val), val); } }
package com.atguigu.gmall.order.feign; import com.atguigu.gmall.oms.api.GmallOmsApi; public interface GmallOmsClient extends GmallOmsApi { }
package com.savor.savorphone.interfaces; public interface HotspotNotifiImp { public void onNotify(); }
package com.trilead.ssh2.signature; import com.trilead.ssh2.crypto.PEMDecoder; import org.apache.commons.io.IOUtils; import org.junit.Test; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.security.GeneralSecurityException; import java.security.KeyPair; import java.security.SecureRandom; import java.security.interfaces.DSAPublicKey; import java.security.interfaces.DSAPrivateKey; import java.security.KeyPairGenerator; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * @author Michael Clarke */ public class DSAKeyAlgorithmTest { @Test public void testEncodeDecodePublicKey() throws GeneralSecurityException, IOException { DSAKeyAlgorithm testCase = new DSAKeyAlgorithm(); KeyPairGenerator factory = KeyPairGenerator.getInstance("DSA"); DSAPublicKey publicKey = (DSAPublicKey) factory.generateKeyPair().getPublic(); byte[] encoded = testCase.encodePublicKey(publicKey); DSAPublicKey decoded = testCase.decodePublicKey(encoded); assertEquals(publicKey, decoded); } @Test public void testEncodeDecodeSignature() throws GeneralSecurityException, IOException { DSAKeyAlgorithm testCase = new DSAKeyAlgorithm(); KeyPairGenerator factory = KeyPairGenerator.getInstance("DSA"); DSAPrivateKey privateKey = (DSAPrivateKey) factory.generateKeyPair().getPrivate(); byte[] signature = testCase.generateSignature("Sign Me".getBytes(StandardCharsets.UTF_8), privateKey, new SecureRandom()); byte[] encoded = testCase.encodeSignature(signature); byte[] decoded = testCase.decodeSignature(encoded); assertArrayEquals(signature, decoded); } @Test public void testSignAndVerify() throws GeneralSecurityException, IOException { DSAKeyAlgorithm testCase = new DSAKeyAlgorithm(); byte[] message = "Signature Test".getBytes(StandardCharsets.UTF_8); KeyPairGenerator factory = KeyPairGenerator.getInstance("DSA"); KeyPair keyPair = factory.generateKeyPair(); DSAPrivateKey privateKey = (DSAPrivateKey) keyPair.getPrivate(); DSAPublicKey publicKey = (DSAPublicKey) keyPair.getPublic(); byte[] signature = testCase.generateSignature(message, privateKey, new SecureRandom()); assertTrue(testCase.verifySignature(message, signature, publicKey)); } @Test public void testSignAndVerifyFailure() throws GeneralSecurityException, IOException { DSAKeyAlgorithm testCase = new DSAKeyAlgorithm(); byte[] message = "Signature Test 2".getBytes(StandardCharsets.UTF_8); KeyPairGenerator factory = KeyPairGenerator.getInstance("DSA"); KeyPair keyPair = factory.generateKeyPair(); DSAPrivateKey privateKey = (DSAPrivateKey) keyPair.getPrivate(); DSAPublicKey publicKey = (DSAPublicKey) keyPair.getPublic(); byte[] signature = testCase.generateSignature("Other Message".getBytes(StandardCharsets.UTF_8), privateKey, new SecureRandom()); assertFalse(testCase.verifySignature(message, signature, publicKey)); } @Test public void testParsePrivateKey() throws IOException { KeyPair oldFormat = PEMDecoder.decodeKeyPair(IOUtils.toCharArray(getClass().getResourceAsStream("dsa-testkey-unprotected.txt")), null); KeyPair newFormat = PEMDecoder.decodeKeyPair(IOUtils.toCharArray(getClass().getResourceAsStream("dsa-testkey-unprotected-newformat.txt")), null); assertEquals(oldFormat.getPublic(), newFormat.getPublic()); assertEquals(oldFormat.getPrivate(), newFormat.getPrivate()); } }
/* * Copyright © 2014 - 2018 Leipzig University (Database Research Group) * * 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.gradoop.flink.model.impl.operators.aggregation.functions.sum; import org.gradoop.flink.model.api.functions.AggregateFunction; /** * Superclass if aggregate functions that sum property values of vertices OR * edges. */ public abstract class SumProperty extends Sum implements AggregateFunction { /** * Prefix of the property key generated by {@link SumProperty} aggregate function. */ private static final String PROPERTY_KEY_PREFIX_SUM = "sum_"; /** * Property key whose value should be aggregated. */ protected final String propertyKey; /** * Constructor. * * @param propertyKey property key to aggregate */ public SumProperty(String propertyKey) { this.propertyKey = propertyKey; } @Override public String getAggregatePropertyKey() { return PROPERTY_KEY_PREFIX_SUM + propertyKey; } }
package pers.huangyuhui.mediator_pattern.mediator_pattern_2; /** * @project: design-patterns * @description: 抽象中介者类 * @author: 黄宇辉 * @date: 10/10/2019-12:49 PM * @version: 1.0 * @website: https://yubuntu0109.github.io/ */ public abstract class Mediator { public abstract void componentChanged(Component component); }
package org.pac4j.core.util; import org.apache.shiro.subject.SimplePrincipalCollection; import org.junit.Test; import org.pac4j.core.exception.TechnicalException; import org.pac4j.core.profile.CommonProfile; import java.util.ArrayList; import static org.junit.Assert.*; /** * Tests {@link JavaSerializationHelper}. * * @author Jerome Leleu * @since 1.8.1 */ public final class JavaSerializationHelperTests implements TestsConstants { private JavaSerializationHelper helper = new JavaSerializationHelper(); private CommonProfile getUserProfile() { final CommonProfile profile = new CommonProfile(); profile.setId(ID); profile.addAttribute(NAME, VALUE); return profile; } @Test public void testBytesSerialization() { final CommonProfile profile = getUserProfile(); final byte[] serialized = helper.serializeToBytes(profile); final CommonProfile profile2 = (CommonProfile) helper.unserializeFromBytes(serialized); assertEquals(profile.getId(), profile2.getId()); assertEquals(profile.getAttribute(NAME), profile2.getAttribute(NAME)); } @Test public void testBytesSerializationUnsecure() { JavaSerializationHelper h = new JavaSerializationHelper(); h.setTrustedPackages(new ArrayList<>()); final CommonProfile profile = getUserProfile(); final byte[] serialized = h.serializeToBytes(profile); assertNull(h.unserializeFromBytes(serialized)); } @Test public void testBytesSerializationMadeSecure() { JavaSerializationHelper h = new JavaSerializationHelper(); h.getTrustedPackages().add("org.apache"); final SimplePrincipalCollection spc = new SimplePrincipalCollection(); final byte[] serialized = h.serializeToBytes(spc); assertNotNull(h.unserializeFromBytes(serialized)); } @Test public void testBytesSerializationUnsecureNullTrustedPackages() { JavaSerializationHelper h = new JavaSerializationHelper(); h.setTrustedPackages(null); final CommonProfile profile = getUserProfile(); final byte[] serialized = h.serializeToBytes(profile); TestsHelper.expectException(() -> h.unserializeFromBytes(serialized), TechnicalException.class, "trustedPackages cannot be null"); } @Test public void testBase64StringSerialization() { final CommonProfile profile = getUserProfile(); final String serialized = helper.serializeToBase64(profile); final CommonProfile profile2 = (CommonProfile) helper.unserializeFromBase64(serialized); assertEquals(profile.getId(), profile2.getId()); assertEquals(profile.getAttribute(NAME), profile2.getAttribute(NAME)); } }
package com.baeldung.hibernate.onetoone; import com.baeldung.hibernate.onetoone.sharedkeybased.Address; import com.baeldung.hibernate.onetoone.sharedkeybased.User; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; public class HibernateOneToOneAnnotationSPKBasedIntegrationTest { private static SessionFactory sessionFactory; private Session session; @BeforeClass public static void beforeTests() { sessionFactory = HibernateUtil.getSessionFactory(Strategy.SHARED_PRIMARY_KEY); } @Before public void setUp() { session = sessionFactory.openSession(); session.beginTransaction(); } @Test public void givenData_whenInsert_thenCreates1to1relationship() { User user = new User(); user.setUserName("alice@baeldung.com"); Address address = new Address(); address.setStreet("SPK Street"); address.setCity("SPK City"); address.setUser(user); user.setAddress(address); //Address entry will automatically be created by hibernate, since cascade type is specified as ALL session.persist(user); session.getTransaction().commit(); assert1to1InsertedData(); } private void assert1to1InsertedData() { @SuppressWarnings("unchecked") List<User> userList = session.createQuery("FROM User").list(); assertNotNull(userList); assertEquals(1, userList.size()); User user = userList.get(0); assertEquals("alice@baeldung.com", user.getUserName()); Address address = user.getAddress(); assertNotNull(address); assertEquals("SPK Street", address.getStreet()); assertEquals("SPK City", address.getCity()); } @After public void tearDown() { session.close(); } @AfterClass public static void afterTests() { sessionFactory.close(); } }
/* * Copyright 2018-2019 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.glowroot.instrumentation.engine.impl; import java.util.Map; import org.junit.Test; import org.glowroot.instrumentation.engine.impl.InstrumentationServiceImpl.Beans2; import static org.assertj.core.api.Assertions.assertThat; public class InstrumentationServiceImplTest { @Test public void shouldReturnAllPropertiesAsText() { Map<String, String> properties = Beans2.propertiesAsText(new SomeObject()); assertThat(properties).containsOnlyKeys("one", "two"); assertThat(properties.get("one")).isEqualTo("1"); assertThat(properties.get("two")).isEqualTo("true"); } @SuppressWarnings("unused") private static class SomeObject { private final String one = "distraction"; private final String two = "distraction"; private final String three = "distraction"; private final String four = "4"; public String get() { return "distraction"; } public String getOne() { return "1"; } public String getone() { return "distraction"; } public String isOne() { return "distraction"; } public String one() { return "distraction"; } public boolean isTwo() { return true; } public boolean two() { return false; } public String three() { return "3"; } } }
package com.alipay.api.request; import com.alipay.api.domain.AntMerchantExpandShopConsultModel; import java.util.Map; import com.alipay.api.AlipayRequest; import com.alipay.api.internal.util.AlipayHashMap; import com.alipay.api.response.AntMerchantExpandShopConsultResponse; import com.alipay.api.AlipayObject; /** * ALIPAY API: ant.merchant.expand.shop.consult request * * @author auto create * @since 1.0, 2022-05-24 15:44:34 */ public class AntMerchantExpandShopConsultRequest implements AlipayRequest<AntMerchantExpandShopConsultResponse> { private AlipayHashMap udfParams; // add user-defined text parameters private String apiVersion="1.0"; /** * 蚂蚁店铺创建咨询 */ private String bizContent; public void setBizContent(String bizContent) { this.bizContent = bizContent; } public String getBizContent() { return this.bizContent; } private String terminalType; private String terminalInfo; private String prodCode; private String notifyUrl; private String returnUrl; private boolean needEncrypt=false; private AlipayObject bizModel=null; public String getNotifyUrl() { return this.notifyUrl; } public void setNotifyUrl(String notifyUrl) { this.notifyUrl = notifyUrl; } public String getReturnUrl() { return this.returnUrl; } public void setReturnUrl(String returnUrl) { this.returnUrl = returnUrl; } public String getApiVersion() { return this.apiVersion; } public void setApiVersion(String apiVersion) { this.apiVersion = apiVersion; } public void setTerminalType(String terminalType){ this.terminalType=terminalType; } public String getTerminalType(){ return this.terminalType; } public void setTerminalInfo(String terminalInfo){ this.terminalInfo=terminalInfo; } public String getTerminalInfo(){ return this.terminalInfo; } public void setProdCode(String prodCode) { this.prodCode=prodCode; } public String getProdCode() { return this.prodCode; } public String getApiMethodName() { return "ant.merchant.expand.shop.consult"; } public Map<String, String> getTextParams() { AlipayHashMap txtParams = new AlipayHashMap(); txtParams.put("biz_content", this.bizContent); if(udfParams != null) { txtParams.putAll(this.udfParams); } return txtParams; } public void putOtherTextParam(String key, String value) { if(this.udfParams == null) { this.udfParams = new AlipayHashMap(); } this.udfParams.put(key, value); } public Class<AntMerchantExpandShopConsultResponse> getResponseClass() { return AntMerchantExpandShopConsultResponse.class; } public boolean isNeedEncrypt() { return this.needEncrypt; } public void setNeedEncrypt(boolean needEncrypt) { this.needEncrypt=needEncrypt; } public AlipayObject getBizModel() { return this.bizModel; } public void setBizModel(AlipayObject bizModel) { this.bizModel=bizModel; } }
/* * Copyright 2019 GridGain Systems, Inc. and Contributors. * * Licensed under the GridGain Community Edition 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://www.gridgain.com/products/software/community-edition/gridgain-community-edition-license * * 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.ignite.internal.processors.service; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.internal.IgniteEx; import org.apache.ignite.internal.util.lang.GridAbsPredicateX; import org.apache.ignite.services.ServiceConfiguration; import org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi; import org.apache.ignite.testframework.GridTestUtils; import org.junit.Test; /** * Single node services test. */ public class GridServiceProcessorMultiNodeConfigSelfTest extends GridServiceProcessorAbstractSelfTest { /** Cluster singleton name. */ private static final String CLUSTER_SINGLE = "serviceConfigSingleton"; /** Node singleton name. */ private static final String NODE_SINGLE = "serviceConfigEachNode"; /** Node singleton name. */ private static final String NODE_SINGLE_BUT_CLIENT = "serviceConfigEachNodeButClient"; /** Node singleton name. */ private static final String NODE_SINGLE_WITH_LIMIT = "serviceConfigWithLimit"; /** Affinity service name. */ private static final String AFFINITY = "serviceConfigAffinity"; /** Affinity key. */ private static final Integer AFFINITY_KEY = 1; /** {@inheritDoc} */ @Override protected int nodeCount() { return 4; } /** {@inheritDoc} */ @Override protected ServiceConfiguration[] services() { ServiceConfiguration cfg = new ServiceConfiguration(); cfg.setName(CLUSTER_SINGLE); cfg.setMaxPerNodeCount(1); cfg.setTotalCount(1); cfg.setService(new DummyService()); List<ServiceConfiguration> cfgs = new ArrayList<>(); cfgs.add(cfg); cfg = new ServiceConfiguration(); cfg.setName(NODE_SINGLE_BUT_CLIENT); cfg.setMaxPerNodeCount(1); cfg.setService(new DummyService()); cfgs.add(cfg); cfg = new ServiceConfiguration(); cfg.setName(AFFINITY); cfg.setCacheName(CACHE_NAME); cfg.setAffinityKey(AFFINITY_KEY); cfg.setMaxPerNodeCount(1); cfg.setTotalCount(1); cfg.setService(new AffinityService(AFFINITY_KEY)); cfgs.add(cfg); cfg = new ServiceConfiguration(); cfg.setName(NODE_SINGLE); cfg.setMaxPerNodeCount(1); cfg.setNodeFilter(new CacheConfiguration.IgniteAllNodesPredicate()); cfg.setService(new DummyService()); cfgs.add(cfg); cfg = new ServiceConfiguration(); cfg.setName(NODE_SINGLE_WITH_LIMIT); cfg.setMaxPerNodeCount(1); cfg.setTotalCount(nodeCount() + 1); cfg.setService(new DummyService()); cfgs.add(cfg); return cfgs.toArray(new ServiceConfiguration[cfgs.size()]); } /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(final String igniteInstanceName) throws Exception { final IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName); ((TcpCommunicationSpi)cfg.getCommunicationSpi()).setIdleConnectionTimeout(10000); return cfg; } /** {@inheritDoc} */ @Override protected void beforeTestsStarted() throws Exception { super.beforeTestsStarted(); GridTestUtils.waitForCondition( new GridAbsPredicateX() { @Override public boolean applyx() { return DummyService.started(CLUSTER_SINGLE) == 1 && DummyService.cancelled(CLUSTER_SINGLE) == 0 && DummyService.started(NODE_SINGLE) == nodeCount() && DummyService.cancelled(NODE_SINGLE) == 0 && DummyService.started(NODE_SINGLE_BUT_CLIENT) == nodeCount() && DummyService.cancelled(NODE_SINGLE_BUT_CLIENT) == 0 && DummyService.started(NODE_SINGLE_WITH_LIMIT) >= nodeCount() && DummyService.cancelled(NODE_SINGLE_WITH_LIMIT) == 0 && actualCount(AFFINITY, randomGrid().services().serviceDescriptors()) == 1; } }, 2000 ); } /** * @throws Exception If failed. */ @Test public void testSingletonUpdateTopology() throws Exception { checkSingletonUpdateTopology(CLUSTER_SINGLE); } /** * @throws Exception If failed. */ @Test public void testDeployOnEachNodeUpdateTopology() throws Exception { checkDeployOnEachNodeUpdateTopology(NODE_SINGLE); } /** * @throws Exception If failed. */ @Test public void testDeployOnEachNodeButClientUpdateTopology() throws Exception { checkDeployOnEachNodeButClientUpdateTopology(NODE_SINGLE_BUT_CLIENT); } /** * @throws Exception If failed. */ @Test public void testAll() throws Exception { checkSingletonUpdateTopology(CLUSTER_SINGLE); DummyService.reset(); checkDeployOnEachNodeButClientUpdateTopology(NODE_SINGLE_BUT_CLIENT); DummyService.reset(); checkDeployOnEachNodeUpdateTopology(NODE_SINGLE); DummyService.reset(); } /** * @throws Exception If failed. */ @Test public void testAffinityUpdateTopology() throws Exception { IgniteEx g = randomGrid(); checkCount(AFFINITY, g, 1); checkAffinityServiceDeployment(g, AFFINITY); int nodeCnt = 2; startExtraNodes(nodeCnt); try { checkCount(AFFINITY, g, 1); checkAffinityServiceDeployment(g, AFFINITY); } finally { stopExtraNodes(nodeCnt); } checkCount(AFFINITY, g, 1); checkAffinityServiceDeployment(g, AFFINITY); } /** * @throws Exception If failed. */ @Test public void testDeployLimits() throws Exception { final IgniteEx g = randomGrid(); final String name = NODE_SINGLE_WITH_LIMIT; waitForDeployment(name, nodeCount()); checkCount(name, g, nodeCount()); CountDownLatch latch = new CountDownLatch(1); DummyService.exeLatch(name, latch); int extraNodes = 2; startExtraNodes(extraNodes); try { latch.await(); waitForDeployment(name, nodeCount() + 1); checkCount(name, g, nodeCount() + 1); } finally { stopExtraNodes(extraNodes); } waitForDeployment(name, nodeCount()); // Service can be redeployed when nodes is stopping one-by-one. assertEquals(0, DummyService.started(name) - DummyService.cancelled(name)); checkCount(name, g, nodeCount()); } /** * @param name Name. * @throws Exception If failed. */ private void checkSingletonUpdateTopology(String name) throws Exception { IgniteEx g = randomGrid(); startExtraNodes(2, 2); try { assertEquals(name, 0, DummyService.started(name)); assertEquals(name, 0, DummyService.cancelled(name)); info(">>> Passed checks."); checkCount(name, g, 1); } finally { stopExtraNodes(4); } } /** * @param name Name. * @throws Exception If failed. */ private void checkDeployOnEachNodeUpdateTopology(String name) throws Exception { IgniteEx g = randomGrid(); int newNodes = 4; CountDownLatch latch = new CountDownLatch(newNodes); DummyService.exeLatch(name, latch); startExtraNodes(2, 2); try { latch.await(); waitForDeployment(name, nodeCount() + newNodes); // Since we start extra nodes, there may be extra start and cancel events, // so we check only the difference between start and cancel and // not start and cancel events individually. assertEquals(name, newNodes, DummyService.started(name) - DummyService.cancelled(name)); checkCount(name, g, nodeCount() + newNodes); } finally { stopExtraNodes(newNodes); } waitForDeployment(name, nodeCount()); checkCount(name, g, nodeCount()); } /** * @param name Name. * @throws Exception If failed. */ private void checkDeployOnEachNodeButClientUpdateTopology(String name) throws Exception { IgniteEx g = randomGrid(); int servers = 2; CountDownLatch latch = new CountDownLatch(servers); DummyService.exeLatch(name, latch); int clients = 2; startExtraNodes(servers, clients); try { latch.await(); waitForDeployment(name, nodeCount() + servers); // Since we start extra nodes, there may be extra start and cancel events, // so we check only the difference between start and cancel and // not start and cancel events individually. assertEquals(name, servers, DummyService.started(name) - DummyService.cancelled(name)); checkCount(name, g, nodeCount() + servers); } finally { stopExtraNodes(servers + clients); } waitForDeployment(name, nodeCount()); checkCount(name, g, nodeCount()); } }
/* * Copyright 2014-2015 Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.rest.resources; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import org.onosproject.net.Device; import org.onosproject.net.DeviceId; import org.onosproject.net.device.DeviceService; import org.onosproject.net.group.DefaultGroupDescription; import org.onosproject.net.group.DefaultGroupKey; import org.onosproject.net.group.Group; import org.onosproject.net.group.GroupDescription; import org.onosproject.net.group.GroupKey; import org.onosproject.net.group.GroupService; import org.onosproject.rest.AbstractWebResource; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import static org.onlab.util.Tools.nullIsNotFound; /** * Query and program group rules. */ @Path("groups") public class GroupsWebResource extends AbstractWebResource { public static final String DEVICE_INVALID = "Invalid deviceId in group creation request"; public static final String GROUP_NOT_FOUND = "Group was not found"; final GroupService groupService = get(GroupService.class); final ObjectNode root = mapper().createObjectNode(); final ArrayNode groupsNode = root.putArray("groups"); /** * Returns all groups of all devices. * * @return array of all the groups in the system * @onos.rsModel Groups */ @GET @Produces(MediaType.APPLICATION_JSON) public Response getGroups() { final Iterable<Device> devices = get(DeviceService.class).getDevices(); devices.forEach(device -> { final Iterable<Group> groups = groupService.getGroups(device.id()); if (groups != null) { groups.forEach(group -> groupsNode.add(codec(Group.class).encode(group, this))); } }); return ok(root).build(); } /** * Returns all groups associated with the given device. * * @param deviceId device identifier * @return array of all the groups in the system * @onos.rsModel Groups */ @GET @Produces(MediaType.APPLICATION_JSON) @Path("{deviceId}") public Response getGroupsByDeviceId(@PathParam("deviceId") String deviceId) { final Iterable<Group> groups = groupService.getGroups(DeviceId.deviceId(deviceId)); groups.forEach(group -> groupsNode.add(codec(Group.class).encode(group, this))); return ok(root).build(); } /** * Returns a group with the given deviceId and appCookie. * * @param deviceId device identifier * @param appCookie group key * @return a group entry in the system * @onos.rsModel Group */ @GET @Produces(MediaType.APPLICATION_JSON) @Path("{deviceId}/{appCookie}") public Response getGroupByDeviceIdAndAppCookie(@PathParam("deviceId") String deviceId, @PathParam("appCookie") String appCookie) { final DeviceId deviceIdInstance = DeviceId.deviceId(deviceId); final GroupKey appCookieInstance = new DefaultGroupKey(appCookie.getBytes()); Group group = nullIsNotFound(groupService.getGroup(deviceIdInstance, appCookieInstance), GROUP_NOT_FOUND); groupsNode.add(codec(Group.class).encode(group, this)); return ok(root).build(); } /** * Create new group rule. Creates and installs a new group rule for the * specified device. * * @param deviceId device identifier * @param stream group rule JSON * @return status of the request - CREATED if the JSON is correct, * BAD_REQUEST if the JSON is invalid * @onos.rsModel GroupsPost */ @POST @Path("{deviceId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response createGroup(@PathParam("deviceId") String deviceId, InputStream stream) { URI location; try { ObjectNode jsonTree = (ObjectNode) mapper().readTree(stream); JsonNode specifiedDeviceId = jsonTree.get("deviceId"); if (specifiedDeviceId != null && !specifiedDeviceId.asText().equals(deviceId)) { throw new IllegalArgumentException(DEVICE_INVALID); } jsonTree.put("deviceId", deviceId); Group group = codec(Group.class).decode(jsonTree, this); GroupDescription description = new DefaultGroupDescription( group.deviceId(), group.type(), group.buckets(), group.appCookie(), group.id().id(), group.appId()); groupService.addGroup(description); location = new URI(Long.toString(group.id().id())); } catch (IOException | URISyntaxException ex) { throw new IllegalArgumentException(ex); } return Response .created(location) .build(); } /** * Removes the specified group. * * @param deviceId device identifier * @param appCookie application cookie to be used for lookup */ @DELETE @Produces(MediaType.APPLICATION_JSON) @Path("{deviceId}/{appCookie}") public void deleteGroupByDeviceIdAndAppCookie(@PathParam("deviceId") String deviceId, @PathParam("appCookie") String appCookie) { DeviceId deviceIdInstance = DeviceId.deviceId(deviceId); GroupKey appCookieInstance = new DefaultGroupKey(appCookie.getBytes()); groupService.removeGroup(deviceIdInstance, appCookieInstance, null); } }
package labyrinth; import org.junit.Assert; import org.junit.Test; public class MazeGeneratorTest { private static final int ALMOST_NO_WALLS_RATIO = Integer.MAX_VALUE; private static final int ONLY_WALL_RATIO = 1; private static final int DUMMY_RATIO = 2; private static final int INVALID_RATIO = 0; private static final int INVALID_SIZE = -1; @Test(expected = IllegalArgumentException.class) public void testGenerateWithIncorrectRatio() throws Exception { new MazeGenerator(0, 0, INVALID_RATIO).generate(); } @Test(expected = IllegalArgumentException.class) public void testGenerateWithIncorrectSizeX() throws Exception { new MazeGenerator(INVALID_SIZE, 0, DUMMY_RATIO).generate(); } @Test(expected = IllegalArgumentException.class) public void testGenerateWithIncorrectSizeY() throws Exception { new MazeGenerator(0, INVALID_SIZE, DUMMY_RATIO).generate(); } @Test public void testGenerateEmpty() throws Exception { boolean[][] maze = new MazeGenerator(0, 0, DUMMY_RATIO).generate(); Assert.assertTrue(maze.length == 0); } @Test public void testGenerateOneWall() throws Exception { boolean[][] maze = new MazeGenerator(1, 1, ONLY_WALL_RATIO).generate(); Assert.assertTrue(!maze[0][0]); } @Test public void testGenerateThousandsWalls() throws Exception { boolean[][] maze = new MazeGenerator(100, 1000, ONLY_WALL_RATIO).generate(); for (int i = 0; i < maze.length; i++) { for (int j = 0; j < maze[0].length; j++) { Assert.assertTrue(!maze[i][j]); } } } @Test public void testGenerate() throws Exception { boolean[][] maze = new MazeGenerator(10, 20, ALMOST_NO_WALLS_RATIO).generate(); boolean roomEncountered = false; for (int i = 0; i < maze.length && !roomEncountered; i++) { for (int j = 0; j < maze[0].length && !roomEncountered; j++) { if (maze[i][j]) { roomEncountered = true; } } } Assert.assertTrue(roomEncountered); } }
package eus.urbieta.datamanagement; public class Word { private long _id; private String _word; private String _definition; public Word(long _id, String _word, String _definition) { this._id = _id; this._word = _word; this._definition = _definition; } public long get_id() { return _id; } public void set_id(long _id) { this._id = _id; } public String get_word() { return _word; } public void set_word(String _word) { this._word = _word; } public String get_definition() { return _definition; } public void set_definition(String _definition) { this._definition = _definition; } @Override public String toString() { return this._word; } }
/* * Copyright © 2019, Ashish Bailkeri. All rights reserved. * * 1. Redistribution in source and in binary forms is permitted * under the condition that credit is given to the creator of the software. * * 2. Any person(s) who have use this code must have this * license present in their code. * * 3. The name of the license holder may not be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package me.ashboss360.pson.nodes; import me.ashboss360.pson.base.ElementProperties; import pson.PSONContainer; import pson.arrays.PSONArray; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.Map; /** * Handles all the value conversions and everything to do with the * values of types that are parsed. * @author Ashish Bailkeri */ public class ValueNode extends Node { public ValueNode() { super("Handles all the values"); } @SuppressWarnings("unchecked") public static Map asArray(PSONContainer pcon, String value) { Map<String, Object> array = new LinkedHashMap<>(); value = value.replace("{", "("); value = value.replace("}", ")"); value = value.replace("=", ": "); System.out.println("TESTDSSD: " + value); PSONArray psonArray = new PSONArray(value); ArrayList<Map<String, Object>> ret = new ArrayList<>(); ret = (ArrayList<Map<String, Object>>) psonArray.parse(pcon); return ret.get(0); } /** Converts the given value to an array */ public static ArrayList<Object> toArray(String value) { ArrayList<Object> array = new ArrayList<>(); if (value.contains(",")) { value = value.replace("]", ""); // array = array.substring(array.indexOf("[")); value = value.replace("[", ""); value = value.replace("\"", ""); value = value.replace(" ", ""); value = value.replace("\n", ""); String[] t = value.split(","); for (String word : t) { array.add(word); } } for (int i = 0; i < array.size(); i++) { if (array.get(i).toString().isEmpty()) { array.remove(i); i--; } } for(int i = 0; i < array.size(); i++) { if(ValueNode.isStringInt(array.get(i).toString())) array.set(i, Integer.parseInt(array.get(i).toString())); if(ValueNode.isStringDouble(array.get(i).toString()) && array.get(i).toString().contains(".")) array.set(i, Double.parseDouble(array.get(i).toString())); if(array.get(i).toString().equals("true") || array.get(i).toString().contains("false")) array.set(i, Boolean.parseBoolean(array.get(i).toString())); } return array; } private static void retrieveArray(String file) { int count = 0; ArrayList<ArrayList<ElementProperties>> a = new ArrayList<>(); ArrayList<Integer> lines = new ArrayList<>(); ArrayList<Integer> lines2 = new ArrayList<>(); ArrayList<Object> u = new ArrayList<>(); System.out.println(u); for(String l : file.split("\n")) { l = l.trim(); count++; for (int i = 0; i < l.length() ; i++) { if(l.contains("(") || l.contains(")")) { lines.add(count); } } } for (int i = 0; i < lines.size() - 2; i++) { if (!lines.get(i).equals(lines.get(i + 1))) lines2.add(lines.get(i)); } lines2.add(lines.get(lines.size() - 1)); for (int i = 0; i < lines2.size() - 1; i++) { // a.add(this.getPropertiesFrom(lines2.get(i), lines2.get(i + 1))); } } /** Converts the given value to a double */ private static double toDouble(String value) { return Double.parseDouble(value); } /** Converts the given value to a string */ private static String toString(Object value) { return value.toString(); } /** Converts the value to an Integer */ private static int toInt(String value) { return Integer.parseInt(value); } /** Converts the value to a boolean */ private static boolean toBoolean(String value) { return Boolean.parseBoolean(value); } /** Checks if the string is a int */ public static boolean isStringInt(String s) { try { toInt(s); return true; } catch (Exception e) { return false; } } /** Checks if the string is a double */ public static boolean isStringDouble(String s) { try { toDouble(s); return true; } catch (Exception e) { return false; } } /** Checks if the string is a boolean */ public static boolean isStringBoolean(String s) { try { toBoolean(s); return true; } catch (Exception e) { return false; } } }
/********************************************************************** Copyright (c) 2003 Mike Martin and others. 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. Contributors: 2003 Andy Jefferson - coding standards 2004 Andy Jefferson - implementation of newScalarExpression, newLiteral 2005 Andy Jefferson - basic serialisation support 2005 Andy Jefferson - updated serialisation using SCOUtils methods ... **********************************************************************/ package org.datanucleus.store.rdbms.mapping.java; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.datanucleus.ExecutionContext; import org.datanucleus.api.ApiAdapter; import org.datanucleus.exceptions.ReachableObjectNotCascadedException; import org.datanucleus.identity.IdentityUtils; import org.datanucleus.metadata.RelationType; import org.datanucleus.state.ObjectProvider; import org.datanucleus.store.rdbms.RDBMSStoreManager; import org.datanucleus.store.rdbms.mapping.MappingCallbacks; import org.datanucleus.store.types.SCO; import org.datanucleus.store.types.SCOUtils; import org.datanucleus.store.types.scostore.MapStore; import org.datanucleus.store.types.wrappers.backed.BackedSCO; import org.datanucleus.util.Localiser; import org.datanucleus.util.NucleusLogger; /** * SCO Mapping for Map types. */ public class MapMapping extends AbstractContainerMapping implements MappingCallbacks { /** * Accessor for the Java type represented here. * @return The java type */ public Class getJavaType() { return Map.class; } // ---------------- Implementation of MappingCallbacks -------------------- public void insertPostProcessing(ObjectProvider ownerOP) { } /** * Method to be called after the insert of the owner class element. * @param ownerOP ObjectProvider of the owner */ public void postInsert(ObjectProvider ownerOP) { ExecutionContext ec = ownerOP.getExecutionContext(); java.util.Map value = (java.util.Map) ownerOP.provideField(getAbsoluteFieldNumber()); if (containerIsStoredInSingleColumn()) { // Do nothing when serialised since we are handled in the main request if (value != null) { if (mmd.getMap().keyIsPersistent() || mmd.getMap().valueIsPersistent()) { // Make sure all persistable keys/values have ObjectProviders Set entries = value.entrySet(); Iterator iter = entries.iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry)iter.next(); if (mmd.getMap().keyIsPersistent() && entry.getKey() != null) { Object key = entry.getKey(); if (ec.findObjectProvider(key) == null || ec.getApiAdapter().getExecutionContext(key) == null) { ec.getNucleusContext().getObjectProviderFactory().newForEmbedded(ec, key, false, ownerOP, mmd.getAbsoluteFieldNumber()); } } if (mmd.getMap().valueIsPersistent() && entry.getValue() != null) { Object val = entry.getValue(); if (ec.findObjectProvider(val) == null || ec.getApiAdapter().getExecutionContext(val) == null) { ec.getNucleusContext().getObjectProviderFactory().newForEmbedded(ec, val, false, ownerOP, mmd.getAbsoluteFieldNumber()); } } } } } return; } if (value == null) { // replace null map with an empty SCO wrapper replaceFieldWithWrapper(ownerOP, null); return; } if (!mmd.isCascadePersist()) { // Check that all keys/values are persistent before continuing and throw exception if necessary if (NucleusLogger.PERSISTENCE.isDebugEnabled()) { NucleusLogger.PERSISTENCE.debug(Localiser.msg("007006", mmd.getFullFieldName())); } ApiAdapter api = ec.getApiAdapter(); Set entries = value.entrySet(); Iterator iter = entries.iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry)iter.next(); if (api.isPersistable(entry.getKey())) { if (!api.isPersistent(entry.getKey()) && !api.isDetached(entry.getKey())) { // Key is not persistent so throw exception throw new ReachableObjectNotCascadedException(mmd.getFullFieldName(), entry.getKey()); } } if (api.isPersistable(entry.getValue())) { if (!api.isPersistent(entry.getValue()) && !api.isDetached(entry.getValue())) { // Value is not persistent so throw exception throw new ReachableObjectNotCascadedException(mmd.getFullFieldName(), entry.getValue()); } } } } else { // Reachability if (NucleusLogger.PERSISTENCE.isDebugEnabled()) { NucleusLogger.PERSISTENCE.debug(Localiser.msg("007007", IdentityUtils.getPersistableIdentityForId(ownerOP.getInternalObjectId()), mmd.getFullFieldName())); } } if (value.size() > 0) { // Add the entries direct to the datastore ((MapStore) table.getStoreManager().getBackingStoreForField(ownerOP.getExecutionContext().getClassLoaderResolver(), mmd, value.getClass())).putAll(ownerOP, value); // Create a SCO wrapper with the entries loaded replaceFieldWithWrapper(ownerOP, value); } else { if (mmd.getRelationType(ownerOP.getExecutionContext().getClassLoaderResolver()) == RelationType.MANY_TO_MANY_BI) { // Create a SCO wrapper, pass in null so it loads any from the datastore (on other side?) replaceFieldWithWrapper(ownerOP, null); } else { // Create a SCO wrapper, pass in empty map to avoid loading from DB (extra SQL) replaceFieldWithWrapper(ownerOP, value); } } } /** * Method to be called after any update of the owner class element. * @param ownerOP ObjectProvider of the owner */ public void postUpdate(ObjectProvider ownerOP) { ExecutionContext ec = ownerOP.getExecutionContext(); RDBMSStoreManager storeMgr = table.getStoreManager(); java.util.Map value = (java.util.Map) ownerOP.provideField(getAbsoluteFieldNumber()); if (containerIsStoredInSingleColumn()) { // Do nothing when serialised since we are handled in the main request if (value != null) { if (mmd.getMap().keyIsPersistent() || mmd.getMap().valueIsPersistent()) { // Make sure all persistable keys/values have ObjectProviders Set entries = value.entrySet(); Iterator iter = entries.iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry)iter.next(); if (mmd.getMap().keyIsPersistent() && entry.getKey() != null) { Object key = entry.getKey(); if (ec.findObjectProvider(key) == null || ec.getApiAdapter().getExecutionContext(key) == null) { ec.getNucleusContext().getObjectProviderFactory().newForEmbedded(ec, key, false, ownerOP, mmd.getAbsoluteFieldNumber()); } } if (mmd.getMap().valueIsPersistent() && entry.getValue() != null) { Object val = entry.getValue(); if (ec.findObjectProvider(val) == null || ec.getApiAdapter().getExecutionContext(val) == null) { ec.getNucleusContext().getObjectProviderFactory().newForEmbedded(ec, val, false, ownerOP, mmd.getAbsoluteFieldNumber()); } } } } } return; } if (value == null) { // remove any entries in the map and replace it with an empty SCO wrapper ((MapStore) storeMgr.getBackingStoreForField(ec.getClassLoaderResolver(), mmd, null)).clear(ownerOP); replaceFieldWithWrapper(ownerOP, null); return; } if (value instanceof BackedSCO) { // Already have a SCO value, so flush outstanding updates ownerOP.getExecutionContext().flushOperationsForBackingStore(((BackedSCO)value).getBackingStore(), ownerOP); return; } if (mmd.isCascadeUpdate()) { if (NucleusLogger.PERSISTENCE.isDebugEnabled()) { NucleusLogger.PERSISTENCE.debug(Localiser.msg("007009", IdentityUtils.getPersistableIdentityForId(ownerOP.getInternalObjectId()), mmd.getFullFieldName())); } // Update the datastore with this value of map (clear old entries and add new ones) // This method could be called in two situations // 1). Update a map field of an object, so UpdateRequest is called, which calls here // 2). Persist a new object, and it needed to wait til the element was inserted so // goes into dirty state and then flush() triggers UpdateRequest, which comes here MapStore store = ((MapStore) storeMgr.getBackingStoreForField(ec.getClassLoaderResolver(), mmd, value.getClass())); // TODO Consider making this more efficient picking the ones to remove/add // e.g use an update() method on the backing store like for CollectionStore store.clear(ownerOP); store.putAll(ownerOP, value); // Replace the field with a wrapper containing these entries replaceFieldWithWrapper(ownerOP, value); } else { // TODO Should this throw exception if the element doesn't exist? // User doesnt want to update by reachability if (NucleusLogger.PERSISTENCE.isDebugEnabled()) { NucleusLogger.PERSISTENCE.debug(Localiser.msg("007008", IdentityUtils.getPersistableIdentityForId(ownerOP.getInternalObjectId()), mmd.getFullFieldName())); } return; } } /** * Method to be called before any delete of the owner class element. * @param ownerOP ObjectProvider of the owner */ public void preDelete(ObjectProvider ownerOP) { // Do nothing - dependent deletion is performed by deleteDependent() if (containerIsStoredInSingleColumn()) { // Do nothing when serialised since we are handled in the main request return; } // makes sure field is loaded ownerOP.isLoaded(getAbsoluteFieldNumber()); java.util.Map value = (java.util.Map) ownerOP.provideField(getAbsoluteFieldNumber()); if (value == null) { // Do nothing return; } if (!(value instanceof SCO)) { // Make sure we have a SCO wrapper so we can clear from the datastore value = (java.util.Map)SCOUtils.wrapSCOField(ownerOP, mmd.getAbsoluteFieldNumber(), value, true); } value.clear(); // Flush any outstanding updates for this backing store ownerOP.getExecutionContext().flushOperationsForBackingStore(((BackedSCO)value).getBackingStore(), ownerOP); } }
/* * Copyright 2018 prasenjit-net * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.prasenjit.identity.entity.user; import com.fasterxml.jackson.annotation.JsonIgnore; import com.nimbusds.openid.connect.sdk.claims.UserInfo; import lombok.Data; import net.prasenjit.identity.entity.converter.UserInfoConverter; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.UserDetails; import javax.persistence.*; import java.time.LocalDateTime; import java.util.Collection; @Data @Entity @Table(name = "T_USER") public class User implements UserDetails { private static final long serialVersionUID = -2840908062923870421L; @Id @Column(name = "USERNAME", length = 50, nullable = false, unique = true) private String username; @JsonIgnore @Column(name = "PASSWORD", length = 200, nullable = false) private String password; @Column(name = "LOCKED", nullable = false) private Boolean locked; @Column(name = "ACTIVE", nullable = false) private Boolean active; @Column(name = "CREATION_DATE", nullable = false) private LocalDateTime creationDate; @Column(name = "EXPIRY_DATE") private LocalDateTime expiryDate; @Column(name = "PASSWORD_EXPIRY_DATE", nullable = false) private LocalDateTime passwordExpiryDate; @Column(name = "ADMIN", nullable = false) private Boolean admin; @Lob @Column(name = "PROFILE", nullable = false) @Convert(converter = UserInfoConverter.class) @JsonIgnore private UserInfo userInfo; @Override @JsonIgnore public Collection<? extends GrantedAuthority> getAuthorities() { return admin ? AuthorityUtils.createAuthorityList("USER", "ADMIN") : AuthorityUtils.createAuthorityList("USER"); } @Override @JsonIgnore public boolean isAccountNonExpired() { LocalDateTime now = LocalDateTime.now(); if (expiryDate != null) { return now.isAfter(creationDate) && now.isBefore(expiryDate); } else { return now.isAfter(creationDate); } } @Override @JsonIgnore public boolean isAccountNonLocked() { return !locked; } @Override @JsonIgnore public boolean isCredentialsNonExpired() { return passwordExpiryDate == null || passwordExpiryDate.isAfter(LocalDateTime.now()); } @Override @JsonIgnore public boolean isEnabled() { return active; } @JsonIgnore public boolean isValid() { return isAccountNonExpired() && isAccountNonLocked() && isEnabled(); } }
/* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.rekognition.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.rekognition.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * StartSegmentDetectionFilters JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class StartSegmentDetectionFiltersJsonUnmarshaller implements Unmarshaller<StartSegmentDetectionFilters, JsonUnmarshallerContext> { public StartSegmentDetectionFilters unmarshall(JsonUnmarshallerContext context) throws Exception { StartSegmentDetectionFilters startSegmentDetectionFilters = new StartSegmentDetectionFilters(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("TechnicalCueFilter", targetDepth)) { context.nextToken(); startSegmentDetectionFilters.setTechnicalCueFilter(StartTechnicalCueDetectionFilterJsonUnmarshaller.getInstance().unmarshall(context)); } if (context.testExpression("ShotFilter", targetDepth)) { context.nextToken(); startSegmentDetectionFilters.setShotFilter(StartShotDetectionFilterJsonUnmarshaller.getInstance().unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return startSegmentDetectionFilters; } private static StartSegmentDetectionFiltersJsonUnmarshaller instance; public static StartSegmentDetectionFiltersJsonUnmarshaller getInstance() { if (instance == null) instance = new StartSegmentDetectionFiltersJsonUnmarshaller(); return instance; } }
/* * Copyright (C) 2016 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.syndesis.connector.kafka; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import io.fabric8.kubernetes.api.model.ObjectMeta; import io.fabric8.kubernetes.api.model.apiextensions.CustomResourceDefinition; import io.fabric8.kubernetes.api.model.apiextensions.CustomResourceDefinitionNames; import io.fabric8.kubernetes.api.model.apiextensions.CustomResourceDefinitionSpec; import io.fabric8.kubernetes.client.DefaultKubernetesClient; import io.fabric8.kubernetes.client.KubernetesClient; import io.syndesis.connector.kafka.model.crd.Listener; import io.syndesis.connector.kafka.model.crd.Address; import io.syndesis.connector.kafka.model.crd.Kafka; import io.syndesis.connector.kafka.model.crd.KafkaResourceDoneable; import io.syndesis.connector.kafka.model.crd.KafkaResourceList; import io.syndesis.connector.support.verifier.api.ComponentMetadataRetrieval; import io.syndesis.connector.support.verifier.api.PropertyPair; import io.syndesis.connector.support.verifier.api.SyndesisMetadata; import io.syndesis.connector.support.verifier.api.SyndesisMetadataProperties; import org.apache.camel.CamelContext; import org.apache.camel.component.extension.MetaDataExtension; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class KafkaMetaDataRetrieval extends ComponentMetadataRetrieval { private static final Logger LOG = LoggerFactory.getLogger(KafkaMetaDataRetrieval.class); public static final String GROUP = "kafka.strimzi.io"; public static final String PLURAL = "kafkas"; /** * TODO: use local extension, remove when switching to camel 2.22.x */ @Override protected MetaDataExtension resolveMetaDataExtension(CamelContext context, Class<? extends MetaDataExtension> metaDataExtensionClass, String componentId, String actionId) { return new KafkaMetaDataExtension(context); } @SuppressWarnings("unchecked") @Override protected SyndesisMetadata adapt(CamelContext context, String componentId, String actionId, Map<String, Object> properties, MetaDataExtension.MetaData metadata) { Set<String> topicsNames = (Set<String>) metadata.getPayload(); List<PropertyPair> topicsResult = new ArrayList<>(); topicsNames.forEach( t -> topicsResult.add(new PropertyPair(t, t)) ); return SyndesisMetadata.of( Collections.singletonMap("topic", topicsResult) ); } /** * Query the strimzi brokers available on this kubernetes environment * to suggest auto discovered urls. */ @Override public SyndesisMetadataProperties fetchProperties(CamelContext context, String componentId, Map<String, Object> properties) { List<PropertyPair> brokers = new ArrayList<>(); try (KubernetesClient client = createKubernetesClient()) { client.customResourceDefinitions().list().getItems() .stream().filter(KafkaMetaDataRetrieval::isKafkaCustomResourceDefinition) .forEach(kafka -> processKafkaCustomResourceDefinition(brokers, client, kafka)); } catch (Exception t) { LOG.warn("Couldn't auto discover any broker."); LOG.debug("Couldn't auto discover any broker.", t); } Map<String, List<PropertyPair>> dynamicProperties = new HashMap<>(); dynamicProperties.put("brokers", brokers); return new SyndesisMetadataProperties(dynamicProperties); } KubernetesClient createKubernetesClient() { return new DefaultKubernetesClient(); } /** * For each Kafka container definition found, process it. */ private static void processKafkaCustomResourceDefinition(List<PropertyPair> brokers, KubernetesClient client, CustomResourceDefinition crd) { KafkaResourceList list = client.customResources(crd, Kafka.class, KafkaResourceList.class, KafkaResourceDoneable.class).inAnyNamespace().list(); for (Kafka item : list.getItems()) { processKafkaResource(brokers, item); } } /** * For each Kafka resource found on Kubernetes, extract the listeners and * add them to the brokers list. */ private static void processKafkaResource(List<PropertyPair> brokers, Kafka item) { //Extract an identifier of this broker final ObjectMeta metadata = item.getMetadata(); List<Listener> listeners = item.getStatus().getListeners(); listeners.stream().filter(KafkaMetaDataRetrieval::typesAllowed).forEach( listener -> getAddress( listener, brokers, String.format("%s::%s (%s)", metadata.getNamespace(), metadata.getName(), listener.getType())) ); } /** * Get the list of addresses for this connection and add it to the brokers list. * * @param listener metadata for this broker * @param brokers list where all brokers are going to be added * @param name identifier of this broker */ private static void getAddress(final Listener listener, final List<PropertyPair> brokers, final String name) { StringBuilder add = new StringBuilder(); List<Address> addresses = listener.getAddresses(); for (Address a : addresses) { if (add.length() > 0) { add.append(','); } add.append(a.getHost()); add.append(':'); add.append(a.getPort()); } brokers.add(new PropertyPair(add.toString(), name)); } /** * Used to filter which types of connections are we interested in. Right now, only plain connections. */ private static boolean typesAllowed(final Listener listener) { return "plain".equalsIgnoreCase(listener.getType()) || "tls".equalsIgnoreCase(listener.getType()); } /** * Used to filter brokers. Right now, based on GROUP and PLURAL. */ static boolean isKafkaCustomResourceDefinition(final CustomResourceDefinition crd) { final CustomResourceDefinitionSpec spec = crd.getSpec(); final String group = spec.getGroup(); final CustomResourceDefinitionNames names = spec.getNames(); final String plural = names.getPlural(); return GROUP.equalsIgnoreCase(group) && PLURAL.equalsIgnoreCase(plural); } }
/** */ package br.unicamp.ic.mo631.Graphql.model.Graphql.provider; import java.util.Collection; import java.util.List; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.edit.provider.IItemPropertyDescriptor; /** * This is the item provider adapter for a {@link br.unicamp.ic.mo631.Graphql.model.Graphql.Float} object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class FloatItemProvider extends ScalarTypeItemProvider { /** * This constructs an instance from a factory and a notifier. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public FloatItemProvider(AdapterFactory adapterFactory) { super(adapterFactory); } /** * This returns the property descriptors for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) { if (itemPropertyDescriptors == null) { super.getPropertyDescriptors(object); } return itemPropertyDescriptors; } /** * This returns Float.gif. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object getImage(Object object) { return overlayImage(object, getResourceLocator().getImage("full/obj16/Float")); } /** * This returns the label text for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getText(Object object) { String label = ((br.unicamp.ic.mo631.Graphql.model.Graphql.Float)object).getName(); return label == null || label.length() == 0 ? getString("_UI_Float_type") : getString("_UI_Float_type") + " " + label; } /** * This handles model notifications by calling {@link #updateChildren} to update any cached * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void notifyChanged(Notification notification) { updateChildren(notification); super.notifyChanged(notification); } /** * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children * that can be created under this object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); } }
package com.company.Models; import com.company.Services.Shopping_list; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; public class Cart implements Shopping_list { // Instance Variables private double total; private final List<Items> items; //Constructor public Cart() { this.total = 0; this.items = new ArrayList<>(); } public List<Items> getItems() { return items; } //Getter total @Override public double getTotal() { return total; } //Function to calculate the total cost @Override public double totalCost() { double t = 0; for (Items item : this.items) { if (item.getAmount() > 0) t = t + (item.getPrice()*item.getAmount()); else t = t + item.getPrice(); } return t; } //Function to change the amount in the cart @Override public void changeAmount(Items item) { System.out.println("Write + to increase the amount with 1 and - to decrease the amount with 1."); Scanner sc = new Scanner(System.in); String change = sc.next(); System.out.println("Write the quantity you want: "); int quan = sc.nextInt(); if("-".equals(change)) { if(item.getAmount()-quan <= 0) this.items.remove(item); else { for (int i = 0; i < quan; i++) { item.substractAmount(); } } } else { for (int i = 0; i < quan; i++) { item.addAmount(); } } this.total = totalCost(); } //Function to print the detail of the cart (ite list + total cost) @Override public void printCart() { for (Items item : this.items) { System.out.println(item.getName() + ", " + String.format("%.2f", item.getPrice()) + " RON, cantitate: " + item.getAmount() + ", ID: " + item.getId()); } System.out.println("Totalul cosului este " + String.format("%.2f",this.total) + " RON."); } //Function to add an item to cart @Override public void addToCart (Items item) { this.items.add(item); this.total = totalCost(); Collections.sort(this.items); } //Function to remove an item from cart @Override public void removeFromCart (Items item) { this.items.remove(item); this.total = totalCost(); } //Function to find an item after the id @Override public Items findId(int id) { int i; for ( i = 0; i < items.size(); i++) { if (id == items.get(i).getId()) { break; } } if (i >= items.size()) { System.out.println("This item is not in cart."); return null; } return items.get(i); } }
package com.sap.mlt.xliff12.api.element.inline; import com.sap.mlt.xliff12.api.attribute.Clone; import com.sap.mlt.xliff12.api.attribute.CtypeDelim; import com.sap.mlt.xliff12.api.attribute.EquivText; import com.sap.mlt.xliff12.api.attribute.Id; import com.sap.mlt.xliff12.api.attribute.Rid; import com.sap.mlt.xliff12.api.attribute.Xid; import com.sap.mlt.xliff12.api.base.InlineBase; import com.sap.mlt.xliff12.api.base.TextFragment; import com.sap.mlt.xliff12.api.element.structural.BinUnit; import com.sap.mlt.xliff12.api.element.structural.TransUnit; /** * Begin paired placeholder - The Bx element is used to replace a beginning * paired code of the original document. It should be used for paired codes that * do not follow XML well-formedness rules (i.e. no overlapping elements). If * the paired codes follow that rule, it is strongly recommended that the * {@link G} element is used because it simplifies processing. The Bx element * should be followed by a matching Ex element. These paired elements are * related via their {@link Rid} attributes. If the {@link Rid} attribute is not * present (in a 1.0 document for example), the attribute {@link Id} is used to * match both tags. The required {@link Id} attribute is used to reference the * replaced code in the skeleton file. The optional {@link CtypeDelim} attribute * allows you to specify what kind of attribute the placeholder represents. The * optional {@link com.sap.mlt.xliff12.api.attribute.Ts} attribute was * DEPRECATED in XLIFF 1.1. The optional {@link Clone} attribute indicates * whether this Bx element may be duplicated. The optional {@link Xid} attribute * references a {@link TransUnit} or {@link BinUnit}, through its {@link Id} * attribute value, which can contain any translatable text from the replaced * code. A list of values for the {@link CtypeDelim} attribute is provided. The * optional {@link EquivText} attribute specifies text to substitute in place of * the inline tag. * * @author D049314 */ public interface Bx extends InlineBase, TextFragment { /** * The element's name. */ static final String NAME = "bx"; /** * Returns the <code>Rid</code> attribute. Might be <code>null</code>. * * @return Returns the <code>Rid</code> attribute. Might be * <code>null</code>. */ Rid getRid(); /** * Sets the <code>Rid</code> attribute. * * @param rid * The <code>Rid</code> attribute. May be <code>null</code>. */ void setRid(Rid rid); /** * Returns the <code>CtypeDelim</code> attribute. Might be <code>null</code> * . * * @return Returns the <code>CtypeDelim</code> attribute. Might be * <code>null</code>. */ CtypeDelim getCtype(); /** * Sets the <code>CtypeDelim</code> attribute. * * @param ctype * The <code>CtypeDelim</code> attribute. May be * <code>null</code>. */ void setCtype(CtypeDelim ctype); /** * Returns the <code>Clone</code> attribute. * * @return Returns the <code>Clone</code> attribute. */ Clone getClone(); /** * Sets the <code>Clone</code> attribute. * * @param clone * The <code>Clone</code> attribute. If this parameter is * <code>null</code>, the attribute is set to the default value * <code>yes</code>. */ void setClone(Clone clone); }
package fun.bookish.blueberry.sip.utils; import fun.bookish.blueberry.sip.digest.MessageDigestTypeEnum; import javax.sip.SipFactory; import javax.sip.header.WWWAuthenticateHeader; import java.util.Date; import java.util.Random; /** * sip header工具类 */ public class SipHeaderUtils { private SipHeaderUtils() { } public static WWWAuthenticateHeader createWWWAuthenticateHeader(SipFactory sipFactory, MessageDigestTypeEnum digestTypeEnum, String realm) { try { WWWAuthenticateHeader header = sipFactory.createHeaderFactory().createWWWAuthenticateHeader("Digest"); header.setParameter("realm", realm); header.setParameter("nonce", generateNonce(digestTypeEnum)); header.setParameter("opaque", ""); header.setParameter("stale", "FALSE"); header.setParameter("algorithm", digestTypeEnum.getDesc()); return header; } catch (Exception e) { throw new RuntimeException("(×) Failed to create a WWWAuthenticateHeader", e); } } /** * 生成nonce * * @param digestTypeEnum * @return */ private static String generateNonce(MessageDigestTypeEnum digestTypeEnum) { // Get the time of day and run MD5 over it. Date date = new Date(); long time = date.getTime(); Random rand = new Random(); long pad = rand.nextLong(); String nonceString = (new Long(time)).toString() + (new Long(pad)).toString(); byte mdbytes[] = MessageDigestUtils.digest(digestTypeEnum, nonceString.getBytes()); // Convert the mdbytes array into a hex string. return MessageDigestUtils.toHexString(mdbytes); } }
package com.reactnativenavigation.controllers; import android.app.Activity; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.view.KeyEvent; public class ActivityCallbacks { public void onActivityCreated(Activity activity, Bundle savedInstanceState) { } public void onActivityStarted(Activity activity) { } public void onActivityResumed(Activity activity) { } public void onActivityPaused(Activity activity) { } public void onActivityStopped(Activity activity) { } public void onActivityResult(int requestCode, int resultCode, Intent data) { } public void onActivityDestroyed(Activity activity) { } public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { } public void onNewIntent(Intent intent) { } public void onConfigurationChanged(Configuration newConfig) { } public void onKeyUp(int keyCode, KeyEvent event) { } }
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.startapp.android.publish.ads.video.tracking; import com.startapp.android.publish.ads.video.c.a.a.c; import com.startapp.android.publish.ads.video.c.a.b; import com.startapp.android.publish.ads.video.c.a.e; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; // Referenced classes of package com.startapp.android.publish.ads.video.tracking: // FractionTrackingLink, AbsoluteTrackingLink, ActionTrackingLink, VideoTrackingLink public class VideoTrackingDetails implements Serializable { public VideoTrackingDetails() { // 0 0:aload_0 // 1 1:invokespecial #37 <Method void Object()> // 2 4:return } public VideoTrackingDetails(e e1) { // 0 0:aload_0 // 1 1:invokespecial #37 <Method void Object()> if(e1 != null) //* 2 4:aload_1 //* 3 5:ifnull 295 { HashMap hashmap = e1.a(); // 4 8:aload_1 // 5 9:invokevirtual #45 <Method HashMap e.a()> // 6 12:astore_2 ArrayList arraylist = new ArrayList(); // 7 13:new #47 <Class ArrayList> // 8 16:dup // 9 17:invokespecial #48 <Method void ArrayList()> // 10 20:astore_3 addFractionUrls((List)hashmap.get(((Object) (b.k))), 0, ((List) (arraylist))); // 11 21:aload_2 // 12 22:getstatic #54 <Field b b.k> // 13 25:invokevirtual #60 <Method Object HashMap.get(Object)> // 14 28:checkcast #62 <Class List> // 15 31:iconst_0 // 16 32:aload_3 // 17 33:invokestatic #66 <Method void addFractionUrls(List, int, List)> addFractionUrls((List)hashmap.get(((Object) (b.l))), 25, ((List) (arraylist))); // 18 36:aload_2 // 19 37:getstatic #69 <Field b b.l> // 20 40:invokevirtual #60 <Method Object HashMap.get(Object)> // 21 43:checkcast #62 <Class List> // 22 46:bipush 25 // 23 48:aload_3 // 24 49:invokestatic #66 <Method void addFractionUrls(List, int, List)> addFractionUrls((List)hashmap.get(((Object) (b.m))), 50, ((List) (arraylist))); // 25 52:aload_2 // 26 53:getstatic #72 <Field b b.m> // 27 56:invokevirtual #60 <Method Object HashMap.get(Object)> // 28 59:checkcast #62 <Class List> // 29 62:bipush 50 // 30 64:aload_3 // 31 65:invokestatic #66 <Method void addFractionUrls(List, int, List)> addFractionUrls((List)hashmap.get(((Object) (b.n))), 75, ((List) (arraylist))); // 32 68:aload_2 // 33 69:getstatic #75 <Field b b.n> // 34 72:invokevirtual #60 <Method Object HashMap.get(Object)> // 35 75:checkcast #62 <Class List> // 36 78:bipush 75 // 37 80:aload_3 // 38 81:invokestatic #66 <Method void addFractionUrls(List, int, List)> addFractionUrls((List)hashmap.get(((Object) (b.o))), 100, ((List) (arraylist))); // 39 84:aload_2 // 40 85:getstatic #78 <Field b b.o> // 41 88:invokevirtual #60 <Method Object HashMap.get(Object)> // 42 91:checkcast #62 <Class List> // 43 94:bipush 100 // 44 96:aload_3 // 45 97:invokestatic #66 <Method void addFractionUrls(List, int, List)> fractionTrackingUrls = (FractionTrackingLink[])((List) (arraylist)).toArray(((Object []) (new FractionTrackingLink[((List) (arraylist)).size()]))); // 46 100:aload_0 // 47 101:aload_3 // 48 102:aload_3 // 49 103:invokeinterface #82 <Method int List.size()> // 50 108:anewarray FractionTrackingLink[] // 51 111:invokeinterface #88 <Method Object[] List.toArray(Object[])> // 52 116:checkcast #89 <Class FractionTrackingLink[]> // 53 119:putfield #91 <Field FractionTrackingLink[] fractionTrackingUrls> impressionUrls = urlToTrackingList(e1.d()); // 54 122:aload_0 // 55 123:aload_1 // 56 124:invokevirtual #95 <Method List e.d()> // 57 127:invokestatic #99 <Method ActionTrackingLink[] urlToTrackingList(List)> // 58 130:putfield #101 <Field ActionTrackingLink[] impressionUrls> soundMuteUrls = trackingToTrackingList((List)hashmap.get(((Object) (b.a)))); // 59 133:aload_0 // 60 134:aload_2 // 61 135:getstatic #103 <Field b b.a> // 62 138:invokevirtual #60 <Method Object HashMap.get(Object)> // 63 141:checkcast #62 <Class List> // 64 144:invokestatic #106 <Method ActionTrackingLink[] trackingToTrackingList(List)> // 65 147:putfield #108 <Field ActionTrackingLink[] soundMuteUrls> soundUnmuteUrls = trackingToTrackingList((List)hashmap.get(((Object) (b.b)))); // 66 150:aload_0 // 67 151:aload_2 // 68 152:getstatic #110 <Field b b.b> // 69 155:invokevirtual #60 <Method Object HashMap.get(Object)> // 70 158:checkcast #62 <Class List> // 71 161:invokestatic #106 <Method ActionTrackingLink[] trackingToTrackingList(List)> // 72 164:putfield #112 <Field ActionTrackingLink[] soundUnmuteUrls> videoPausedUrls = trackingToTrackingList((List)hashmap.get(((Object) (b.c)))); // 73 167:aload_0 // 74 168:aload_2 // 75 169:getstatic #115 <Field b b.c> // 76 172:invokevirtual #60 <Method Object HashMap.get(Object)> // 77 175:checkcast #62 <Class List> // 78 178:invokestatic #106 <Method ActionTrackingLink[] trackingToTrackingList(List)> // 79 181:putfield #117 <Field ActionTrackingLink[] videoPausedUrls> videoResumedUrls = trackingToTrackingList((List)hashmap.get(((Object) (b.d)))); // 80 184:aload_0 // 81 185:aload_2 // 82 186:getstatic #119 <Field b b.d> // 83 189:invokevirtual #60 <Method Object HashMap.get(Object)> // 84 192:checkcast #62 <Class List> // 85 195:invokestatic #106 <Method ActionTrackingLink[] trackingToTrackingList(List)> // 86 198:putfield #121 <Field ActionTrackingLink[] videoResumedUrls> videoSkippedUrls = trackingToTrackingList((List)hashmap.get(((Object) (b.f)))); // 87 201:aload_0 // 88 202:aload_2 // 89 203:getstatic #124 <Field b b.f> // 90 206:invokevirtual #60 <Method Object HashMap.get(Object)> // 91 209:checkcast #62 <Class List> // 92 212:invokestatic #106 <Method ActionTrackingLink[] trackingToTrackingList(List)> // 93 215:putfield #126 <Field ActionTrackingLink[] videoSkippedUrls> videoPausedUrls = trackingToTrackingList((List)hashmap.get(((Object) (b.c)))); // 94 218:aload_0 // 95 219:aload_2 // 96 220:getstatic #115 <Field b b.c> // 97 223:invokevirtual #60 <Method Object HashMap.get(Object)> // 98 226:checkcast #62 <Class List> // 99 229:invokestatic #106 <Method ActionTrackingLink[] trackingToTrackingList(List)> // 100 232:putfield #117 <Field ActionTrackingLink[] videoPausedUrls> videoClosedUrls = trackingToTrackingList((List)hashmap.get(((Object) (b.y)))); // 101 235:aload_0 // 102 236:aload_2 // 103 237:getstatic #129 <Field b b.y> // 104 240:invokevirtual #60 <Method Object HashMap.get(Object)> // 105 243:checkcast #62 <Class List> // 106 246:invokestatic #106 <Method ActionTrackingLink[] trackingToTrackingList(List)> // 107 249:putfield #131 <Field ActionTrackingLink[] videoClosedUrls> inlineErrorTrackingUrls = urlToTrackingList(e1.e()); // 108 252:aload_0 // 109 253:aload_1 // 110 254:invokevirtual #134 <Method List e.e()> // 111 257:invokestatic #99 <Method ActionTrackingLink[] urlToTrackingList(List)> // 112 260:putfield #136 <Field ActionTrackingLink[] inlineErrorTrackingUrls> videoClickTrackingUrls = urlToTrackingList(e1.c().b()); // 113 263:aload_0 // 114 264:aload_1 // 115 265:invokevirtual #139 <Method com.startapp.android.publish.ads.video.c.a.a.e e.c()> // 116 268:invokevirtual #143 <Method List com.startapp.android.publish.ads.video.c.a.a.e.b()> // 117 271:invokestatic #99 <Method ActionTrackingLink[] urlToTrackingList(List)> // 118 274:putfield #145 <Field ActionTrackingLink[] videoClickTrackingUrls> absoluteTrackingUrls = toAbsoluteTrackingList((List)hashmap.get(((Object) (b.s)))); // 119 277:aload_0 // 120 278:aload_0 // 121 279:aload_2 // 122 280:getstatic #148 <Field b b.s> // 123 283:invokevirtual #60 <Method Object HashMap.get(Object)> // 124 286:checkcast #62 <Class List> // 125 289:invokespecial #152 <Method AbsoluteTrackingLink[] toAbsoluteTrackingList(List)> // 126 292:putfield #154 <Field AbsoluteTrackingLink[] absoluteTrackingUrls> } // 127 295:return } private static void addFractionUrls(List list, int i, List list1) { if(list != null) //* 0 0:aload_0 //* 1 1:ifnull 66 { FractionTrackingLink fractiontrackinglink; for(list = ((List) (list.iterator())); ((Iterator) (list)).hasNext(); list1.add(((Object) (fractiontrackinglink)))) //* 2 4:aload_0 //* 3 5:invokeinterface #158 <Method Iterator List.iterator()> //* 4 10:astore_0 //* 5 11:aload_0 //* 6 12:invokeinterface #164 <Method boolean Iterator.hasNext()> //* 7 17:ifeq 66 { c c1 = (c)((Iterator) (list)).next(); // 8 20:aload_0 // 9 21:invokeinterface #168 <Method Object Iterator.next()> // 10 26:checkcast #170 <Class c> // 11 29:astore_3 fractiontrackinglink = new FractionTrackingLink(); // 12 30:new #84 <Class FractionTrackingLink> // 13 33:dup // 14 34:invokespecial #171 <Method void FractionTrackingLink()> // 15 37:astore 4 fractiontrackinglink.setTrackingUrl(c1.a()); // 16 39:aload 4 // 17 41:aload_3 // 18 42:invokevirtual #174 <Method String c.a()> // 19 45:invokevirtual #178 <Method void FractionTrackingLink.setTrackingUrl(String)> fractiontrackinglink.setFraction(i); // 20 48:aload 4 // 21 50:iload_1 // 22 51:invokevirtual #182 <Method void FractionTrackingLink.setFraction(int)> } // 23 54:aload_2 // 24 55:aload 4 // 25 57:invokeinterface #186 <Method boolean List.add(Object)> // 26 62:pop } //* 27 63:goto 11 // 28 66:return } private String printTrackingLinks(VideoTrackingLink avideotrackinglink[]) { if(avideotrackinglink != null) //* 0 0:aload_1 //* 1 1:ifnull 9 return Arrays.toString(((Object []) (avideotrackinglink))); // 2 4:aload_1 // 3 5:invokestatic #196 <Method String Arrays.toString(Object[])> // 4 8:areturn else return ""; // 5 9:ldc1 #198 <String ""> // 6 11:areturn } private AbsoluteTrackingLink[] toAbsoluteTrackingList(List list) { if(list != null) //* 0 0:aload_1 //* 1 1:ifnull 110 { ArrayList arraylist = new ArrayList(list.size()); // 2 4:new #47 <Class ArrayList> // 3 7:dup // 4 8:aload_1 // 5 9:invokeinterface #82 <Method int List.size()> // 6 14:invokespecial #200 <Method void ArrayList(int)> // 7 17:astore_2 AbsoluteTrackingLink absolutetrackinglink; for(list = ((List) (list.iterator())); ((Iterator) (list)).hasNext(); ((List) (arraylist)).add(((Object) (absolutetrackinglink)))) //* 8 18:aload_1 //* 9 19:invokeinterface #158 <Method Iterator List.iterator()> //* 10 24:astore_1 //* 11 25:aload_1 //* 12 26:invokeinterface #164 <Method boolean Iterator.hasNext()> //* 13 31:ifeq 91 { c c1 = (c)((Iterator) (list)).next(); // 14 34:aload_1 // 15 35:invokeinterface #168 <Method Object Iterator.next()> // 16 40:checkcast #170 <Class c> // 17 43:astore_3 absolutetrackinglink = new AbsoluteTrackingLink(); // 18 44:new #202 <Class AbsoluteTrackingLink> // 19 47:dup // 20 48:invokespecial #203 <Method void AbsoluteTrackingLink()> // 21 51:astore 4 absolutetrackinglink.setTrackingUrl(c1.a()); // 22 53:aload 4 // 23 55:aload_3 // 24 56:invokevirtual #174 <Method String c.a()> // 25 59:invokevirtual #204 <Method void AbsoluteTrackingLink.setTrackingUrl(String)> if(c1.b() != -1) //* 26 62:aload_3 //* 27 63:invokevirtual #206 <Method int c.b()> //* 28 66:iconst_m1 //* 29 67:icmpeq 79 absolutetrackinglink.setVideoOffsetMillis(c1.b()); // 30 70:aload 4 // 31 72:aload_3 // 32 73:invokevirtual #206 <Method int c.b()> // 33 76:invokevirtual #209 <Method void AbsoluteTrackingLink.setVideoOffsetMillis(int)> } // 34 79:aload_2 // 35 80:aload 4 // 36 82:invokeinterface #186 <Method boolean List.add(Object)> // 37 87:pop //* 38 88:goto 25 return (AbsoluteTrackingLink[])((List) (arraylist)).toArray(((Object []) (new AbsoluteTrackingLink[((List) (arraylist)).size()]))); // 39 91:aload_2 // 40 92:aload_2 // 41 93:invokeinterface #82 <Method int List.size()> // 42 98:anewarray AbsoluteTrackingLink[] // 43 101:invokeinterface #88 <Method Object[] List.toArray(Object[])> // 44 106:checkcast #210 <Class AbsoluteTrackingLink[]> // 45 109:areturn } else { return new AbsoluteTrackingLink[0]; // 46 110:iconst_0 // 47 111:anewarray AbsoluteTrackingLink[] // 48 114:areturn } } private static ActionTrackingLink[] trackingToTrackingList(List list) { if(list != null) //* 0 0:aload_0 //* 1 1:ifnull 90 { ArrayList arraylist = new ArrayList(list.size()); // 2 4:new #47 <Class ArrayList> // 3 7:dup // 4 8:aload_0 // 5 9:invokeinterface #82 <Method int List.size()> // 6 14:invokespecial #200 <Method void ArrayList(int)> // 7 17:astore_1 ActionTrackingLink actiontrackinglink; for(list = ((List) (list.iterator())); ((Iterator) (list)).hasNext(); ((List) (arraylist)).add(((Object) (actiontrackinglink)))) //* 8 18:aload_0 //* 9 19:invokeinterface #158 <Method Iterator List.iterator()> //* 10 24:astore_0 //* 11 25:aload_0 //* 12 26:invokeinterface #164 <Method boolean Iterator.hasNext()> //* 13 31:ifeq 71 { c c1 = (c)((Iterator) (list)).next(); // 14 34:aload_0 // 15 35:invokeinterface #168 <Method Object Iterator.next()> // 16 40:checkcast #170 <Class c> // 17 43:astore_2 actiontrackinglink = new ActionTrackingLink(); // 18 44:new #213 <Class ActionTrackingLink> // 19 47:dup // 20 48:invokespecial #214 <Method void ActionTrackingLink()> // 21 51:astore_3 actiontrackinglink.setTrackingUrl(c1.a()); // 22 52:aload_3 // 23 53:aload_2 // 24 54:invokevirtual #174 <Method String c.a()> // 25 57:invokevirtual #215 <Method void ActionTrackingLink.setTrackingUrl(String)> } // 26 60:aload_1 // 27 61:aload_3 // 28 62:invokeinterface #186 <Method boolean List.add(Object)> // 29 67:pop //* 30 68:goto 25 return (ActionTrackingLink[])((List) (arraylist)).toArray(((Object []) (new ActionTrackingLink[((List) (arraylist)).size()]))); // 31 71:aload_1 // 32 72:aload_1 // 33 73:invokeinterface #82 <Method int List.size()> // 34 78:anewarray ActionTrackingLink[] // 35 81:invokeinterface #88 <Method Object[] List.toArray(Object[])> // 36 86:checkcast #216 <Class ActionTrackingLink[]> // 37 89:areturn } else { return new ActionTrackingLink[0]; // 38 90:iconst_0 // 39 91:anewarray ActionTrackingLink[] // 40 94:areturn } } private static ActionTrackingLink[] urlToTrackingList(List list) { if(list != null) //* 0 0:aload_0 //* 1 1:ifnull 87 { ArrayList arraylist = new ArrayList(list.size()); // 2 4:new #47 <Class ArrayList> // 3 7:dup // 4 8:aload_0 // 5 9:invokeinterface #82 <Method int List.size()> // 6 14:invokespecial #200 <Method void ArrayList(int)> // 7 17:astore_1 ActionTrackingLink actiontrackinglink; for(list = ((List) (list.iterator())); ((Iterator) (list)).hasNext(); ((List) (arraylist)).add(((Object) (actiontrackinglink)))) //* 8 18:aload_0 //* 9 19:invokeinterface #158 <Method Iterator List.iterator()> //* 10 24:astore_0 //* 11 25:aload_0 //* 12 26:invokeinterface #164 <Method boolean Iterator.hasNext()> //* 13 31:ifeq 68 { String s = (String)((Iterator) (list)).next(); // 14 34:aload_0 // 15 35:invokeinterface #168 <Method Object Iterator.next()> // 16 40:checkcast #219 <Class String> // 17 43:astore_2 actiontrackinglink = new ActionTrackingLink(); // 18 44:new #213 <Class ActionTrackingLink> // 19 47:dup // 20 48:invokespecial #214 <Method void ActionTrackingLink()> // 21 51:astore_3 actiontrackinglink.setTrackingUrl(s); // 22 52:aload_3 // 23 53:aload_2 // 24 54:invokevirtual #215 <Method void ActionTrackingLink.setTrackingUrl(String)> } // 25 57:aload_1 // 26 58:aload_3 // 27 59:invokeinterface #186 <Method boolean List.add(Object)> // 28 64:pop //* 29 65:goto 25 return (ActionTrackingLink[])((List) (arraylist)).toArray(((Object []) (new ActionTrackingLink[((List) (arraylist)).size()]))); // 30 68:aload_1 // 31 69:aload_1 // 32 70:invokeinterface #82 <Method int List.size()> // 33 75:anewarray ActionTrackingLink[] // 34 78:invokeinterface #88 <Method Object[] List.toArray(Object[])> // 35 83:checkcast #216 <Class ActionTrackingLink[]> // 36 86:areturn } else { return new ActionTrackingLink[0]; // 37 87:iconst_0 // 38 88:anewarray ActionTrackingLink[] // 39 91:areturn } } public AbsoluteTrackingLink[] getAbsoluteTrackingUrls() { return absoluteTrackingUrls; // 0 0:aload_0 // 1 1:getfield #154 <Field AbsoluteTrackingLink[] absoluteTrackingUrls> // 2 4:areturn } public ActionTrackingLink[] getCreativeViewUrls() { return creativeViewUrls; // 0 0:aload_0 // 1 1:getfield #226 <Field ActionTrackingLink[] creativeViewUrls> // 2 4:areturn } public FractionTrackingLink[] getFractionTrackingUrls() { return fractionTrackingUrls; // 0 0:aload_0 // 1 1:getfield #91 <Field FractionTrackingLink[] fractionTrackingUrls> // 2 4:areturn } public ActionTrackingLink[] getImpressionUrls() { return impressionUrls; // 0 0:aload_0 // 1 1:getfield #101 <Field ActionTrackingLink[] impressionUrls> // 2 4:areturn } public ActionTrackingLink[] getInlineErrorTrackingUrls() { return inlineErrorTrackingUrls; // 0 0:aload_0 // 1 1:getfield #136 <Field ActionTrackingLink[] inlineErrorTrackingUrls> // 2 4:areturn } public ActionTrackingLink[] getSoundMuteUrls() { return soundMuteUrls; // 0 0:aload_0 // 1 1:getfield #108 <Field ActionTrackingLink[] soundMuteUrls> // 2 4:areturn } public ActionTrackingLink[] getSoundUnmuteUrls() { return soundUnmuteUrls; // 0 0:aload_0 // 1 1:getfield #112 <Field ActionTrackingLink[] soundUnmuteUrls> // 2 4:areturn } public ActionTrackingLink[] getVideoClickTrackingUrls() { return videoClickTrackingUrls; // 0 0:aload_0 // 1 1:getfield #145 <Field ActionTrackingLink[] videoClickTrackingUrls> // 2 4:areturn } public ActionTrackingLink[] getVideoClosedUrls() { return videoClosedUrls; // 0 0:aload_0 // 1 1:getfield #131 <Field ActionTrackingLink[] videoClosedUrls> // 2 4:areturn } public ActionTrackingLink[] getVideoPausedUrls() { return videoPausedUrls; // 0 0:aload_0 // 1 1:getfield #117 <Field ActionTrackingLink[] videoPausedUrls> // 2 4:areturn } public ActionTrackingLink[] getVideoPostRollClosedUrls() { return videoPostRollClosedUrls; // 0 0:aload_0 // 1 1:getfield #238 <Field ActionTrackingLink[] videoPostRollClosedUrls> // 2 4:areturn } public ActionTrackingLink[] getVideoPostRollImpressionUrls() { return videoPostRollImpressionUrls; // 0 0:aload_0 // 1 1:getfield #241 <Field ActionTrackingLink[] videoPostRollImpressionUrls> // 2 4:areturn } public ActionTrackingLink[] getVideoResumedUrls() { return videoResumedUrls; // 0 0:aload_0 // 1 1:getfield #121 <Field ActionTrackingLink[] videoResumedUrls> // 2 4:areturn } public ActionTrackingLink[] getVideoRewardedUrls() { return videoRewardedUrls; // 0 0:aload_0 // 1 1:getfield #245 <Field ActionTrackingLink[] videoRewardedUrls> // 2 4:areturn } public ActionTrackingLink[] getVideoSkippedUrls() { return videoSkippedUrls; // 0 0:aload_0 // 1 1:getfield #126 <Field ActionTrackingLink[] videoSkippedUrls> // 2 4:areturn } public String toString() { return (new StringBuilder()).append("VideoTrackingDetails [fractionTrackingUrls=").append(printTrackingLinks(((VideoTrackingLink []) (fractionTrackingUrls)))).append(", absoluteTrackingUrls=").append(printTrackingLinks(((VideoTrackingLink []) (absoluteTrackingUrls)))).append(", impressionUrls=").append(printTrackingLinks(((VideoTrackingLink []) (impressionUrls)))).append(", creativeViewUrls=").append(printTrackingLinks(((VideoTrackingLink []) (creativeViewUrls)))).append(", soundMuteUrls=").append(printTrackingLinks(((VideoTrackingLink []) (soundMuteUrls)))).append(", soundUnmuteUrls=").append(printTrackingLinks(((VideoTrackingLink []) (soundUnmuteUrls)))).append(", videoPausedUrls=").append(printTrackingLinks(((VideoTrackingLink []) (videoPausedUrls)))).append(", videoResumedUrls=").append(printTrackingLinks(((VideoTrackingLink []) (videoResumedUrls)))).append(", videoSkippedUrls=").append(printTrackingLinks(((VideoTrackingLink []) (videoSkippedUrls)))).append(", videoClosedUrls=").append(printTrackingLinks(((VideoTrackingLink []) (videoClosedUrls)))).append(", videoPostRollImpressionUrls=").append(printTrackingLinks(((VideoTrackingLink []) (videoPostRollImpressionUrls)))).append(", videoPostRollClosedUrls=").append(printTrackingLinks(((VideoTrackingLink []) (videoPostRollClosedUrls)))).append(", videoRewardedUrls=").append(printTrackingLinks(((VideoTrackingLink []) (videoRewardedUrls)))).append(", videoClickTrackingUrls=").append(printTrackingLinks(((VideoTrackingLink []) (videoClickTrackingUrls)))).append(", inlineErrorTrackingUrls=").append(printTrackingLinks(((VideoTrackingLink []) (inlineErrorTrackingUrls)))).append("]").toString(); // 0 0:new #248 <Class StringBuilder> // 1 3:dup // 2 4:invokespecial #249 <Method void StringBuilder()> // 3 7:ldc1 #251 <String "VideoTrackingDetails [fractionTrackingUrls="> // 4 9:invokevirtual #255 <Method StringBuilder StringBuilder.append(String)> // 5 12:aload_0 // 6 13:aload_0 // 7 14:getfield #91 <Field FractionTrackingLink[] fractionTrackingUrls> // 8 17:invokespecial #257 <Method String printTrackingLinks(VideoTrackingLink[])> // 9 20:invokevirtual #255 <Method StringBuilder StringBuilder.append(String)> // 10 23:ldc2 #259 <String ", absoluteTrackingUrls="> // 11 26:invokevirtual #255 <Method StringBuilder StringBuilder.append(String)> // 12 29:aload_0 // 13 30:aload_0 // 14 31:getfield #154 <Field AbsoluteTrackingLink[] absoluteTrackingUrls> // 15 34:invokespecial #257 <Method String printTrackingLinks(VideoTrackingLink[])> // 16 37:invokevirtual #255 <Method StringBuilder StringBuilder.append(String)> // 17 40:ldc2 #261 <String ", impressionUrls="> // 18 43:invokevirtual #255 <Method StringBuilder StringBuilder.append(String)> // 19 46:aload_0 // 20 47:aload_0 // 21 48:getfield #101 <Field ActionTrackingLink[] impressionUrls> // 22 51:invokespecial #257 <Method String printTrackingLinks(VideoTrackingLink[])> // 23 54:invokevirtual #255 <Method StringBuilder StringBuilder.append(String)> // 24 57:ldc2 #263 <String ", creativeViewUrls="> // 25 60:invokevirtual #255 <Method StringBuilder StringBuilder.append(String)> // 26 63:aload_0 // 27 64:aload_0 // 28 65:getfield #226 <Field ActionTrackingLink[] creativeViewUrls> // 29 68:invokespecial #257 <Method String printTrackingLinks(VideoTrackingLink[])> // 30 71:invokevirtual #255 <Method StringBuilder StringBuilder.append(String)> // 31 74:ldc2 #265 <String ", soundMuteUrls="> // 32 77:invokevirtual #255 <Method StringBuilder StringBuilder.append(String)> // 33 80:aload_0 // 34 81:aload_0 // 35 82:getfield #108 <Field ActionTrackingLink[] soundMuteUrls> // 36 85:invokespecial #257 <Method String printTrackingLinks(VideoTrackingLink[])> // 37 88:invokevirtual #255 <Method StringBuilder StringBuilder.append(String)> // 38 91:ldc2 #267 <String ", soundUnmuteUrls="> // 39 94:invokevirtual #255 <Method StringBuilder StringBuilder.append(String)> // 40 97:aload_0 // 41 98:aload_0 // 42 99:getfield #112 <Field ActionTrackingLink[] soundUnmuteUrls> // 43 102:invokespecial #257 <Method String printTrackingLinks(VideoTrackingLink[])> // 44 105:invokevirtual #255 <Method StringBuilder StringBuilder.append(String)> // 45 108:ldc2 #269 <String ", videoPausedUrls="> // 46 111:invokevirtual #255 <Method StringBuilder StringBuilder.append(String)> // 47 114:aload_0 // 48 115:aload_0 // 49 116:getfield #117 <Field ActionTrackingLink[] videoPausedUrls> // 50 119:invokespecial #257 <Method String printTrackingLinks(VideoTrackingLink[])> // 51 122:invokevirtual #255 <Method StringBuilder StringBuilder.append(String)> // 52 125:ldc2 #271 <String ", videoResumedUrls="> // 53 128:invokevirtual #255 <Method StringBuilder StringBuilder.append(String)> // 54 131:aload_0 // 55 132:aload_0 // 56 133:getfield #121 <Field ActionTrackingLink[] videoResumedUrls> // 57 136:invokespecial #257 <Method String printTrackingLinks(VideoTrackingLink[])> // 58 139:invokevirtual #255 <Method StringBuilder StringBuilder.append(String)> // 59 142:ldc2 #273 <String ", videoSkippedUrls="> // 60 145:invokevirtual #255 <Method StringBuilder StringBuilder.append(String)> // 61 148:aload_0 // 62 149:aload_0 // 63 150:getfield #126 <Field ActionTrackingLink[] videoSkippedUrls> // 64 153:invokespecial #257 <Method String printTrackingLinks(VideoTrackingLink[])> // 65 156:invokevirtual #255 <Method StringBuilder StringBuilder.append(String)> // 66 159:ldc2 #275 <String ", videoClosedUrls="> // 67 162:invokevirtual #255 <Method StringBuilder StringBuilder.append(String)> // 68 165:aload_0 // 69 166:aload_0 // 70 167:getfield #131 <Field ActionTrackingLink[] videoClosedUrls> // 71 170:invokespecial #257 <Method String printTrackingLinks(VideoTrackingLink[])> // 72 173:invokevirtual #255 <Method StringBuilder StringBuilder.append(String)> // 73 176:ldc2 #277 <String ", videoPostRollImpressionUrls="> // 74 179:invokevirtual #255 <Method StringBuilder StringBuilder.append(String)> // 75 182:aload_0 // 76 183:aload_0 // 77 184:getfield #241 <Field ActionTrackingLink[] videoPostRollImpressionUrls> // 78 187:invokespecial #257 <Method String printTrackingLinks(VideoTrackingLink[])> // 79 190:invokevirtual #255 <Method StringBuilder StringBuilder.append(String)> // 80 193:ldc2 #279 <String ", videoPostRollClosedUrls="> // 81 196:invokevirtual #255 <Method StringBuilder StringBuilder.append(String)> // 82 199:aload_0 // 83 200:aload_0 // 84 201:getfield #238 <Field ActionTrackingLink[] videoPostRollClosedUrls> // 85 204:invokespecial #257 <Method String printTrackingLinks(VideoTrackingLink[])> // 86 207:invokevirtual #255 <Method StringBuilder StringBuilder.append(String)> // 87 210:ldc2 #281 <String ", videoRewardedUrls="> // 88 213:invokevirtual #255 <Method StringBuilder StringBuilder.append(String)> // 89 216:aload_0 // 90 217:aload_0 // 91 218:getfield #245 <Field ActionTrackingLink[] videoRewardedUrls> // 92 221:invokespecial #257 <Method String printTrackingLinks(VideoTrackingLink[])> // 93 224:invokevirtual #255 <Method StringBuilder StringBuilder.append(String)> // 94 227:ldc2 #283 <String ", videoClickTrackingUrls="> // 95 230:invokevirtual #255 <Method StringBuilder StringBuilder.append(String)> // 96 233:aload_0 // 97 234:aload_0 // 98 235:getfield #145 <Field ActionTrackingLink[] videoClickTrackingUrls> // 99 238:invokespecial #257 <Method String printTrackingLinks(VideoTrackingLink[])> // 100 241:invokevirtual #255 <Method StringBuilder StringBuilder.append(String)> // 101 244:ldc2 #285 <String ", inlineErrorTrackingUrls="> // 102 247:invokevirtual #255 <Method StringBuilder StringBuilder.append(String)> // 103 250:aload_0 // 104 251:aload_0 // 105 252:getfield #136 <Field ActionTrackingLink[] inlineErrorTrackingUrls> // 106 255:invokespecial #257 <Method String printTrackingLinks(VideoTrackingLink[])> // 107 258:invokevirtual #255 <Method StringBuilder StringBuilder.append(String)> // 108 261:ldc2 #287 <String "]"> // 109 264:invokevirtual #255 <Method StringBuilder StringBuilder.append(String)> // 110 267:invokevirtual #289 <Method String StringBuilder.toString()> // 111 270:areturn } private static final long serialVersionUID = 1L; private AbsoluteTrackingLink absoluteTrackingUrls[]; private ActionTrackingLink creativeViewUrls[]; private FractionTrackingLink fractionTrackingUrls[]; private ActionTrackingLink impressionUrls[]; private ActionTrackingLink inlineErrorTrackingUrls[]; private ActionTrackingLink soundMuteUrls[]; private ActionTrackingLink soundUnmuteUrls[]; private ActionTrackingLink videoClickTrackingUrls[]; private ActionTrackingLink videoClosedUrls[]; private ActionTrackingLink videoPausedUrls[]; private ActionTrackingLink videoPostRollClosedUrls[]; private ActionTrackingLink videoPostRollImpressionUrls[]; private ActionTrackingLink videoResumedUrls[]; private ActionTrackingLink videoRewardedUrls[]; private ActionTrackingLink videoSkippedUrls[]; }
package com.github.afezeria.freedao.runtime.classic; 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 AutoFill { /** * 执行sql前填充数据 */ boolean before() default false; /** * 插入时填充 */ boolean insert() default true; /** * 更新时填充 */ boolean update() default false; /** * 用于生成字段值的类 * 默认值时表示字段值由数据库生成 */ Class<? extends ValueGenerator> generator() default ValueGenerator.class; }
package com.shtaigaway.moodmuse.tracking; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.util.Log; import com.shtaigaway.moodmuse.Constants; import com.shtaigaway.moodmuse.R; import java.util.Calendar; /** * Created by Naughty Spirit * on 12/11/14. */ public class Bootstrap { public static synchronized void startAlwaysOnService(Context context, String loadedFrom) { if (!MoodTrackingService.isRunning) { Intent startServiceIntent = new Intent(context, MoodTrackingService.class); startServiceIntent.putExtra(Constants.STARTUP_ACTION_NAME, loadedFrom); context.startService(startServiceIntent); Intent startAlarmIntent = new Intent(context, AlarmBroadcastReceiver.class); startAlarmIntent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); startAlarmIntent.putExtra(Constants.STARTUP_ACTION_NAME, loadedFrom); startAlarmIntent.setAction(context.getString(R.string.alarm_action_name)); PendingIntent sender = PendingIntent.getBroadcast(context, 0, startAlarmIntent, 0); Calendar time = Calendar.getInstance(); time.setTimeInMillis(System.currentTimeMillis()); time.add(Calendar.SECOND, 1); AlarmManager am = (AlarmManager) context .getSystemService(Context.ALARM_SERVICE); am.setRepeating(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(), Constants.ALARM_REPEAT_INTERVAL * 1000, sender); setBootUpListen(context, true); } } public static synchronized void stopAlwaysOnService(Context context) { Intent stopServiceIntent = new Intent(context, MoodTrackingService.class); context.stopService(stopServiceIntent); // cancel alarm restart Intent intent = new Intent(context, AlarmBroadcastReceiver.class); intent.setAction(context.getString(R.string.alarm_action_name)); PendingIntent sender = PendingIntent .getBroadcast(context, 0, intent, 0); AlarmManager alarmManager = (AlarmManager) context .getSystemService(Context.ALARM_SERVICE); alarmManager.cancel(sender); setBootUpListen(context, false); } private static void setBootUpListen(Context context, boolean isEnabled) { int flag = (isEnabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED); ComponentName component = new ComponentName(context, RebootBroadcastReceiver.class); context.getPackageManager().setComponentEnabledSetting(component, flag, PackageManager.DONT_KILL_APP); } }
/** * Copyright 2016 Nikita Koksharov * * 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.redisson.reactive; import org.reactivestreams.Publisher; import org.redisson.api.RObjectReactive; import org.redisson.client.codec.Codec; import org.redisson.client.protocol.RedisCommands; import org.redisson.command.CommandReactiveExecutor; import io.netty.util.concurrent.Future; import reactor.rx.Stream; import reactor.rx.Streams; /** * Base Redisson object * * @author Nikita Koksharov * */ abstract class RedissonObjectReactive implements RObjectReactive { final CommandReactiveExecutor commandExecutor; private final String name; final Codec codec; public RedissonObjectReactive(Codec codec, CommandReactiveExecutor commandExecutor, String name) { this.codec = codec; this.name = name; this.commandExecutor = commandExecutor; } public <R> Publisher<R> reactive(Future<R> future) { return commandExecutor.reactive(future); } public RedissonObjectReactive(CommandReactiveExecutor commandExecutor, String name) { this(commandExecutor.getConnectionManager().getCodec(), commandExecutor, name); } protected <V> Stream<V> newSucceeded(V result) { return Streams.just(result); } @Override public String getName() { return name; } @Override public Publisher<Void> rename(String newName) { return commandExecutor.writeReactive(getName(), RedisCommands.RENAME, getName(), newName); } @Override public Publisher<Void> migrate(String host, int port, int database) { return commandExecutor.writeReactive(getName(), RedisCommands.MIGRATE, host, port, getName(), database); } @Override public Publisher<Boolean> move(int database) { return commandExecutor.writeReactive(getName(), RedisCommands.MOVE, getName(), database); } @Override public Publisher<Boolean> renamenx(String newName) { return commandExecutor.writeReactive(getName(), RedisCommands.RENAMENX, getName(), newName); } @Override public Publisher<Boolean> delete() { return commandExecutor.writeReactive(getName(), RedisCommands.DEL_BOOL, getName()); } @Override public Publisher<Boolean> isExists() { return commandExecutor.readReactive(getName(), codec, RedisCommands.EXISTS, getName()); } }
package basicGame; public class Processor { char[] word; //The word to be played with. boolean[] guessed; //Auxiliary array that keeps track of the letters guessed so far int remainingLetters; //Counter for the remaining characters to be guessed int wrongGuesses = 0; //Counter for the guesses boolean isInWord; //Boolean that remembers if the letter was present in the word or not //Constructor public Processor(char[] word) { remainingLetters = word.length; guessed = new boolean[word.length]; checkForSpaces(word); this.word = word; } /* This method should be used instead of the constructor to save memory public void giveWord(char[] word) { this.word = word; remainingLetters = word.length; guessed = new boolean[word.length]; }*/ void checkForSpaces(char[] wordWithSpaces) { for(int i = 0; i < wordWithSpaces.length;i++) if(wordWithSpaces[i] == ' ') { guessed[i] = true; remainingLetters--; } } //This method is passed to the GUI public String print() { String s = ""; for(int i = 0; i < guessed.length; i++) if(guessed[i] == false) s+= "_ "; else s+= Character.toUpperCase(word[i]) + " "; return s; } public String printLives() { return (6-wrongGuesses) + " lives left"; } public boolean gameOn() { return (remainingLetters > 0) && (wrongGuesses < 6); } public void guessLetter(char currentGuess) { isInWord = false; //Mark where the letters equal to currentGuess are in the word for(int i = 0; i < word.length;i++) if(word[i] == currentGuess) { remainingLetters--; guessed[i] = true; isInWord = true; } //If the letter guessed wasn't in the word, increase wrong guesses if(!isInWord) wrongGuesses++; } //Method passed to endScreen in GUI public String printResult() { //WordLibrary.guessedWord(); //If game ended with less than 6 wrong guesses, the word was guessed and game is won if(wrongGuesses != 6) { return "Congratulations!\nYou guessed the word \"" + this.toString() + "\""; } //Else, the game is lost else return "Game over, the word was: \"" + this.toString() + "\""; } //Helping/cheating method public String toString() { String s = ""; for(int i = 0; i < word.length; i++) s+=Character.toUpperCase(word[i]); return s; } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aliyuncs.ga.model.v20191120; import com.aliyuncs.RpcAcsRequest; import java.util.List; import com.aliyuncs.http.MethodType; import com.aliyuncs.ga.Endpoint; /** * @author auto create * @version */ public class CreateEndpointGroupRequest extends RpcAcsRequest<CreateEndpointGroupResponse> { private String clientToken; private Integer healthCheckIntervalSeconds; private Integer trafficPercentage; private String description; private String healthCheckProtocol; private Integer healthCheckPort; private Integer thresholdCount; private String listenerId; private String healthCheckPath; private List<EndpointConfigurations> endpointConfigurationss; private String endpointGroupRegion; private String name; private String acceleratorId; public CreateEndpointGroupRequest() { super("Ga", "2019-11-20", "CreateEndpointGroup", "gaplus"); setMethod(MethodType.POST); try { com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap); com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType); } catch (Exception e) {} } public String getClientToken() { return this.clientToken; } public void setClientToken(String clientToken) { this.clientToken = clientToken; if(clientToken != null){ putQueryParameter("ClientToken", clientToken); } } public Integer getHealthCheckIntervalSeconds() { return this.healthCheckIntervalSeconds; } public void setHealthCheckIntervalSeconds(Integer healthCheckIntervalSeconds) { this.healthCheckIntervalSeconds = healthCheckIntervalSeconds; if(healthCheckIntervalSeconds != null){ putQueryParameter("HealthCheckIntervalSeconds", healthCheckIntervalSeconds.toString()); } } public Integer getTrafficPercentage() { return this.trafficPercentage; } public void setTrafficPercentage(Integer trafficPercentage) { this.trafficPercentage = trafficPercentage; if(trafficPercentage != null){ putQueryParameter("TrafficPercentage", trafficPercentage.toString()); } } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; if(description != null){ putQueryParameter("Description", description); } } public String getHealthCheckProtocol() { return this.healthCheckProtocol; } public void setHealthCheckProtocol(String healthCheckProtocol) { this.healthCheckProtocol = healthCheckProtocol; if(healthCheckProtocol != null){ putQueryParameter("HealthCheckProtocol", healthCheckProtocol); } } public Integer getHealthCheckPort() { return this.healthCheckPort; } public void setHealthCheckPort(Integer healthCheckPort) { this.healthCheckPort = healthCheckPort; if(healthCheckPort != null){ putQueryParameter("HealthCheckPort", healthCheckPort.toString()); } } public Integer getThresholdCount() { return this.thresholdCount; } public void setThresholdCount(Integer thresholdCount) { this.thresholdCount = thresholdCount; if(thresholdCount != null){ putQueryParameter("ThresholdCount", thresholdCount.toString()); } } public String getListenerId() { return this.listenerId; } public void setListenerId(String listenerId) { this.listenerId = listenerId; if(listenerId != null){ putQueryParameter("ListenerId", listenerId); } } public String getHealthCheckPath() { return this.healthCheckPath; } public void setHealthCheckPath(String healthCheckPath) { this.healthCheckPath = healthCheckPath; if(healthCheckPath != null){ putQueryParameter("HealthCheckPath", healthCheckPath); } } public List<EndpointConfigurations> getEndpointConfigurationss() { return this.endpointConfigurationss; } public void setEndpointConfigurationss(List<EndpointConfigurations> endpointConfigurationss) { this.endpointConfigurationss = endpointConfigurationss; if (endpointConfigurationss != null) { for (int depth1 = 0; depth1 < endpointConfigurationss.size(); depth1++) { putQueryParameter("EndpointConfigurations." + (depth1 + 1) + ".Endpoint" , endpointConfigurationss.get(depth1).getEndpoint()); putQueryParameter("EndpointConfigurations." + (depth1 + 1) + ".Weight" , endpointConfigurationss.get(depth1).getWeight()); putQueryParameter("EndpointConfigurations." + (depth1 + 1) + ".Type" , endpointConfigurationss.get(depth1).getType()); } } } public String getEndpointGroupRegion() { return this.endpointGroupRegion; } public void setEndpointGroupRegion(String endpointGroupRegion) { this.endpointGroupRegion = endpointGroupRegion; if(endpointGroupRegion != null){ putQueryParameter("EndpointGroupRegion", endpointGroupRegion); } } public String getName() { return this.name; } public void setName(String name) { this.name = name; if(name != null){ putQueryParameter("Name", name); } } public String getAcceleratorId() { return this.acceleratorId; } public void setAcceleratorId(String acceleratorId) { this.acceleratorId = acceleratorId; if(acceleratorId != null){ putQueryParameter("AcceleratorId", acceleratorId); } } public static class EndpointConfigurations { private String endpoint; private Integer weight; private String type; public String getEndpoint() { return this.endpoint; } public void setEndpoint(String endpoint) { this.endpoint = endpoint; } public Integer getWeight() { return this.weight; } public void setWeight(Integer weight) { this.weight = weight; } public String getType() { return this.type; } public void setType(String type) { this.type = type; } } @Override public Class<CreateEndpointGroupResponse> getResponseClass() { return CreateEndpointGroupResponse.class; } }
/******************************************************************************* * Copyright (c) 2000, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction.proposals; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.TraverseEvent; import org.eclipse.swt.events.TraverseListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Control; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Status; import org.eclipse.jface.util.Util; import org.eclipse.jface.viewers.StyledCellLabelProvider; import org.eclipse.jface.viewers.StyledString; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRewriteTarget; import org.eclipse.jface.text.contentassist.ICompletionProposalExtension5; import org.eclipse.jface.text.contentassist.ICompletionProposalExtension6; import org.eclipse.jface.text.contentassist.IContextInformation; import org.eclipse.jface.text.link.LinkedModeModel; import org.eclipse.ui.IEditorPart; import org.eclipse.ltk.core.refactoring.Change; import org.eclipse.ltk.core.refactoring.IUndoManager; import org.eclipse.ltk.core.refactoring.NullChange; import org.eclipse.ltk.core.refactoring.RefactoringCore; import org.eclipse.ltk.core.refactoring.RefactoringStatus; import org.eclipse.jdt.internal.corext.util.Messages; import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.text.correction.CorrectionCommandHandler; import org.eclipse.jdt.internal.ui.text.correction.CorrectionMessages; import org.eclipse.jdt.internal.ui.text.correction.ICommandAccess; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; /** * Implementation of a Java completion proposal to be used for quick fix and quick assist proposals * that invoke a {@link Change}. The proposal offers a proposal information but no context * information. * * @author Mohsen Vakilian, nchen - Captured invocation of refactorings through quick assist. * * @since 3.2 */ public class ChangeCorrectionProposal implements IJavaCompletionProposal, ICommandAccess, ICompletionProposalExtension5, ICompletionProposalExtension6 { private Change fChange; private String fName; private int fRelevance; private Image fImage; private String fCommandId; /** * Constructs a change correction proposal. * * @param name The name that is displayed in the proposal selection dialog. * @param change The change that is executed when the proposal is applied or <code>null</code> * if the change will be created by implementors of {@link #createChange()}. * @param relevance The relevance of this proposal. * @param image The image that is displayed for this proposal or <code>null</code> if no image * is desired. */ public ChangeCorrectionProposal(String name, Change change, int relevance, Image image) { if (name == null) { throw new IllegalArgumentException("Name must not be null"); //$NON-NLS-1$ } fName= name; fChange= change; fRelevance= relevance; fImage= image; fCommandId= null; } /* * @see ICompletionProposal#apply(IDocument) */ public void apply(IDocument document) { try { performChange(JavaPlugin.getActivePage().getActiveEditor(), document); } catch (CoreException e) { ExceptionHandler.handle(e, CorrectionMessages.ChangeCorrectionProposal_error_title, CorrectionMessages.ChangeCorrectionProposal_error_message); } } /** * Performs the change associated with this proposal. * * @param activeEditor The editor currently active or <code>null</code> if no editor is active. * @param document The document of the editor currently active or <code>null</code> if no editor * is visible. * @throws CoreException Thrown when the invocation of the change failed. */ protected void performChange(IEditorPart activeEditor, IDocument document) throws CoreException { StyledText disabledStyledText= null; TraverseListener traverseBlocker= null; Change change= null; IRewriteTarget rewriteTarget= null; try { change= getChange(); if (change != null) { if (document != null) { LinkedModeModel.closeAllModels(document); } if (activeEditor != null) { rewriteTarget= (IRewriteTarget)activeEditor.getAdapter(IRewriteTarget.class); if (rewriteTarget != null) { rewriteTarget.beginCompoundChange(); } /* * Workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=195834#c7 : * During change execution, an EventLoopProgressMonitor can process the event queue while the text * widget has focus. When that happens and the user e.g. pressed a key, the event is prematurely * delivered to the text widget and screws up the document. Change execution fails or performs * wrong changes. * * The fix is to temporarily disable the text widget. */ Object control= activeEditor.getAdapter(Control.class); if (control instanceof StyledText) { disabledStyledText= (StyledText)control; if (disabledStyledText.getEditable()) { disabledStyledText.setEditable(false); traverseBlocker= new TraverseListener() { public void keyTraversed(TraverseEvent e) { e.doit= true; e.detail= SWT.TRAVERSE_NONE; } }; disabledStyledText.addTraverseListener(traverseBlocker); } else { disabledStyledText= null; } } } change.initializeValidationData(new NullProgressMonitor()); RefactoringStatus valid= change.isValid(new NullProgressMonitor()); if (valid.hasFatalError()) { IStatus status= new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.ERROR, valid.getMessageMatchingSeverity(RefactoringStatus.FATAL), null); throw new CoreException(status); } else { IUndoManager manager= RefactoringCore.getUndoManager(); Change undoChange; boolean successful= false; try { manager.aboutToPerformChange(change); //CODINGSPECTATOR aboutToPerformChange(); undoChange= change.perform(new NullProgressMonitor()); successful= true; } finally { manager.changePerformed(change, successful); } if (undoChange != null) { undoChange.initializeValidationData(new NullProgressMonitor()); manager.addUndo(getName(), undoChange); } } } } finally { if (disabledStyledText != null) { disabledStyledText.setEditable(true); disabledStyledText.removeTraverseListener(traverseBlocker); } if (rewriteTarget != null) { rewriteTarget.endCompoundChange(); } if (change != null) { change.dispose(); } } } /* * @see ICompletionProposal#getAdditionalProposalInfo() */ public String getAdditionalProposalInfo() { Object info= getAdditionalProposalInfo(new NullProgressMonitor()); return info == null ? null : info.toString(); } /* * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension5#getAdditionalProposalInfo(org.eclipse.core.runtime.IProgressMonitor) * @since 3.5 */ public Object getAdditionalProposalInfo(IProgressMonitor monitor) { StringBuffer buf= new StringBuffer(); buf.append("<p>"); //$NON-NLS-1$ try { Change change= getChange(); if (change != null) { String name= change.getName(); if (name.length() == 0) { return null; } buf.append(name); } else { return null; } } catch (CoreException e) { buf.append("Unexpected error when accessing this proposal:<p><pre>"); //$NON-NLS-1$ buf.append(e.getLocalizedMessage()); buf.append("</pre>"); //$NON-NLS-1$ } buf.append("</p>"); //$NON-NLS-1$ return buf.toString(); } /* * @see ICompletionProposal#getContextInformation() */ public IContextInformation getContextInformation() { return null; } /* * @see ICompletionProposal#getDisplayString() */ public String getDisplayString() { String shortCutString= CorrectionCommandHandler.getShortCutString(getCommandId()); if (shortCutString != null) { return Messages.format(CorrectionMessages.ChangeCorrectionProposal_name_with_shortcut, new String[] { getName(), shortCutString }); } return getName(); } /* (non-Javadoc) * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension6#getStyledDisplayString() */ public StyledString getStyledDisplayString() { StyledString str= new StyledString(getName()); String shortCutString= CorrectionCommandHandler.getShortCutString(getCommandId()); if (shortCutString != null) { String decorated= Messages.format(CorrectionMessages.ChangeCorrectionProposal_name_with_shortcut, new String[] { getName(), shortCutString }); return StyledCellLabelProvider.styleDecoratedString(decorated, StyledString.QUALIFIER_STYLER, str); } return str; } /** * Returns the name of the proposal. * * @return return the name of the proposal */ public String getName() { return fName; } /* * @see ICompletionProposal#getImage() */ public Image getImage() { return fImage; } /* * @see ICompletionProposal#getSelection(IDocument) */ public Point getSelection(IDocument document) { return null; } /** * Sets the proposal's image or <code>null</code> if no image is desired. * * @param image the desired image. */ public void setImage(Image image) { fImage= image; } /** * Returns the change that will be executed when the proposal is applied. * * @return returns the change for this proposal. * @throws CoreException thrown when the change could not be created */ public final Change getChange() throws CoreException { if (Util.isGtk()) { // workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=293995 : // [Widgets] Deadlock while UI thread displaying/computing a change proposal and non-UI thread creating image if (fChange == null) { fChange= createChange(); } } else { synchronized (this) { if (fChange == null) { fChange= createChange(); } } } return fChange; } /** * Creates the text change for this proposal. This method is only called once and only when no * text change has been passed in {@link #ChangeCorrectionProposal(String, Change, int, Image)}. * * @return returns the created change. * @throws CoreException thrown if the creation of the change failed. */ protected Change createChange() throws CoreException { return new NullChange(); } /** * Sets the display name. * * @param name the name to set */ public void setDisplayName(String name) { if (name == null) { throw new IllegalArgumentException("Name must not be null"); //$NON-NLS-1$ } fName= name; } /* (non-Javadoc) * @see org.eclipse.jdt.ui.text.java.IJavaCompletionProposal#getRelevance() */ public int getRelevance() { return fRelevance; } /** * Sets the relevance. * * @param relevance the relevance to set */ public void setRelevance(int relevance) { fRelevance= relevance; } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.text.correction.IShortcutProposal#getProposalId() */ public String getCommandId() { return fCommandId; } /** * Set the proposal id to allow assigning a shortcut to the correction proposal. * * @param commandId The proposal id for this proposal or <code>null</code> if no command should * be assigned to this proposal. */ public void setCommandId(String commandId) { fCommandId= commandId; } ///////////////// //CODINGSPECTATOR ///////////////// /** * RefactoringCorrectionProposal overrides this method to log the refactoring invoked by the * quick assist just before it's performed. */ protected void aboutToPerformChange() { } }
/* * Copyright 2013, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib2.writer; import org.jf.dexlib2.iface.reference.*; import javax.annotation.*; public interface StringSection<StringKey, StringRef extends StringReference> extends NullableIndexSection<StringKey> { int getItemIndex(@Nonnull StringRef key); boolean hasJumboIndexes(); }
package com.qc.security.account.service; import com.qc.base.PaginationResponse; import com.qc.security.account.dto.Account; import com.qc.security.account.exception.AccountExistException; public interface AccountService { Account getAccountByMobile(String mobile); Account getAccountByToken(String token); String refreshAccountToken(Integer accountId); PaginationResponse<Account> list(int pageNum, int pageSize); void openAccount(String mobile, String pass, String authority) throws AccountExistException; void updatePassword(String mobile, String newPass); void delAccount(String mobile); }
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * fetchPaymentCredentials接口风控信息。 Fraud data provided by Apple as outlined in separate Fraud SIA document, if applicable. * * @author auto create * @since 1.0, 2020-02-20 19:41:04 */ public class CredentialsFraudData extends AlipayObject { private static final long serialVersionUID = 2255842636529476233L; /** * Wallet所在设备的设备id映射的uuid。 */ @ApiField("device_identifier") private String deviceIdentifier; /** * 生物核身是否可获取。 true if device is capable of biometric authentication, otherwise false */ @ApiField("is_biometric_capable") private String isBiometricCapable; /** * Wallet登录icloud账户id映射的uuid。 */ @ApiField("user_identifier") private String userIdentifier; public String getDeviceIdentifier() { return this.deviceIdentifier; } public void setDeviceIdentifier(String deviceIdentifier) { this.deviceIdentifier = deviceIdentifier; } public String getIsBiometricCapable() { return this.isBiometricCapable; } public void setIsBiometricCapable(String isBiometricCapable) { this.isBiometricCapable = isBiometricCapable; } public String getUserIdentifier() { return this.userIdentifier; } public void setUserIdentifier(String userIdentifier) { this.userIdentifier = userIdentifier; } }
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencentcloudapi.tsf.v20180326.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class DeployGroupRequest extends AbstractModel{ /** * 部署组ID */ @SerializedName("GroupId") @Expose private String GroupId; /** * 程序包ID */ @SerializedName("PkgId") @Expose private String PkgId; /** * 部署组启动参数 */ @SerializedName("StartupParameters") @Expose private String StartupParameters; /** * Get 部署组ID * @return GroupId 部署组ID */ public String getGroupId() { return this.GroupId; } /** * Set 部署组ID * @param GroupId 部署组ID */ public void setGroupId(String GroupId) { this.GroupId = GroupId; } /** * Get 程序包ID * @return PkgId 程序包ID */ public String getPkgId() { return this.PkgId; } /** * Set 程序包ID * @param PkgId 程序包ID */ public void setPkgId(String PkgId) { this.PkgId = PkgId; } /** * Get 部署组启动参数 * @return StartupParameters 部署组启动参数 */ public String getStartupParameters() { return this.StartupParameters; } /** * Set 部署组启动参数 * @param StartupParameters 部署组启动参数 */ public void setStartupParameters(String StartupParameters) { this.StartupParameters = StartupParameters; } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "GroupId", this.GroupId); this.setParamSimple(map, prefix + "PkgId", this.PkgId); this.setParamSimple(map, prefix + "StartupParameters", this.StartupParameters); } }
/* * Copyright 2010-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.jet.asJava; import com.intellij.lang.Language; import com.intellij.psi.*; import com.intellij.psi.impl.light.LightElement; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; // Copy of com.intellij.psi.impl.light.LightParameterListBuilder public class LightParameterListBuilder extends LightElement implements PsiParameterList { private final List<PsiParameter> myParameters = new ArrayList<PsiParameter>(); private PsiParameter[] myCachedParameters; public LightParameterListBuilder(PsiManager manager, Language language) { super(manager, language); } public void addParameter(PsiParameter parameter) { myParameters.add(parameter); myCachedParameters = null; } @Override public String toString() { return "Light parameter lsit"; } @NotNull @Override public PsiParameter[] getParameters() { if (myCachedParameters == null) { if (myParameters.isEmpty()) { myCachedParameters = PsiParameter.EMPTY_ARRAY; } else { myCachedParameters = myParameters.toArray(new PsiParameter[myParameters.size()]); } } return myCachedParameters; } @Override public int getParameterIndex(PsiParameter parameter) { return myParameters.indexOf(parameter); } @Override public int getParametersCount() { return myParameters.size(); } @Override public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof JavaElementVisitor) { ((JavaElementVisitor) visitor).visitParameterList(this); } } }
/* * Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.config; import com.hazelcast.internal.config.ConfigDataSerializerHook; import com.hazelcast.internal.partition.IPartition; import com.hazelcast.nio.ObjectDataInput; import com.hazelcast.nio.ObjectDataOutput; import com.hazelcast.nio.serialization.IdentifiedDataSerializable; import javax.annotation.Nonnull; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.concurrent.TimeUnit; import static com.hazelcast.internal.serialization.impl.SerializationUtil.readNullableList; import static com.hazelcast.internal.serialization.impl.SerializationUtil.writeNullableList; import static com.hazelcast.internal.util.Preconditions.checkAsyncBackupCount; import static com.hazelcast.internal.util.Preconditions.checkBackupCount; import static com.hazelcast.internal.util.Preconditions.checkNotNull; import static com.hazelcast.internal.util.Preconditions.isNotNull; /** * Simple configuration to hold parsed XML configuration. * CacheConfig depends on the JCache API. If the JCache API is not in the classpath, * you can use CacheSimpleConfig as a communicator between the code and CacheConfig. */ public class CacheSimpleConfig implements IdentifiedDataSerializable, NamedConfig { /** * The minimum number of backups. */ public static final int MIN_BACKUP_COUNT = 0; /** * The maximum number of backups. */ public static final int MAX_BACKUP_COUNT = IPartition.MAX_BACKUP_COUNT; /** * The default number of backups. */ public static final int DEFAULT_BACKUP_COUNT = 1; /** * Default InMemory Format. */ public static final InMemoryFormat DEFAULT_IN_MEMORY_FORMAT = InMemoryFormat.BINARY; private String name; private String keyType; private String valueType; private boolean statisticsEnabled; private boolean managementEnabled; private boolean readThrough; private boolean writeThrough; private String cacheLoaderFactory; private String cacheWriterFactory; private String cacheLoader; private String cacheWriter; private ExpiryPolicyFactoryConfig expiryPolicyFactoryConfig; private List<CacheSimpleEntryListenerConfig> cacheEntryListeners; private int asyncBackupCount = MIN_BACKUP_COUNT; private int backupCount = DEFAULT_BACKUP_COUNT; private InMemoryFormat inMemoryFormat = DEFAULT_IN_MEMORY_FORMAT; // Default values of the eviction configuration are: // * ENTRY_COUNT with 10.000 as the max-size policy. // * LRU as the eviction-policy. private EvictionConfig evictionConfig = new EvictionConfig(); private WanReplicationRef wanReplicationRef; private String splitBrainProtectionName; private List<CachePartitionLostListenerConfig> partitionLostListenerConfigs; private HotRestartConfig hotRestartConfig = new HotRestartConfig(); private EventJournalConfig eventJournalConfig = new EventJournalConfig(); private MergePolicyConfig mergePolicyConfig = new MergePolicyConfig(); /** * Disables invalidation events for per entry but full-flush invalidation events are still enabled. * Full-flush invalidation means the invalidation of events for all entries when clear is called. */ private boolean disablePerEntryInvalidationEvents; @SuppressWarnings("checkstyle:executablestatementcount") public CacheSimpleConfig(CacheSimpleConfig cacheSimpleConfig) { this.name = cacheSimpleConfig.name; this.keyType = cacheSimpleConfig.keyType; this.valueType = cacheSimpleConfig.valueType; this.statisticsEnabled = cacheSimpleConfig.statisticsEnabled; this.managementEnabled = cacheSimpleConfig.managementEnabled; this.readThrough = cacheSimpleConfig.readThrough; this.writeThrough = cacheSimpleConfig.writeThrough; this.cacheLoaderFactory = cacheSimpleConfig.cacheLoaderFactory; this.cacheWriterFactory = cacheSimpleConfig.cacheWriterFactory; this.expiryPolicyFactoryConfig = cacheSimpleConfig.expiryPolicyFactoryConfig; this.cacheEntryListeners = cacheSimpleConfig.cacheEntryListeners == null ? null : new ArrayList<>(cacheSimpleConfig.cacheEntryListeners); this.asyncBackupCount = cacheSimpleConfig.asyncBackupCount; this.backupCount = cacheSimpleConfig.backupCount; this.inMemoryFormat = cacheSimpleConfig.inMemoryFormat; // eviction config cannot be null if (cacheSimpleConfig.evictionConfig != null) { this.evictionConfig = cacheSimpleConfig.evictionConfig; } this.wanReplicationRef = cacheSimpleConfig.wanReplicationRef; this.partitionLostListenerConfigs = cacheSimpleConfig.partitionLostListenerConfigs == null ? null : new ArrayList<>(cacheSimpleConfig.partitionLostListenerConfigs); this.splitBrainProtectionName = cacheSimpleConfig.splitBrainProtectionName; this.mergePolicyConfig = new MergePolicyConfig(cacheSimpleConfig.mergePolicyConfig); this.hotRestartConfig = new HotRestartConfig(cacheSimpleConfig.hotRestartConfig); this.eventJournalConfig = new EventJournalConfig(cacheSimpleConfig.eventJournalConfig); this.disablePerEntryInvalidationEvents = cacheSimpleConfig.disablePerEntryInvalidationEvents; } /** * Create a Cache Simple Config for a cache with a specific name. * * @param name cache name */ public CacheSimpleConfig(String name) { setName(name); } public CacheSimpleConfig() { } /** * Gets the name of this {@link com.hazelcast.cache.ICache}. * * @return the name of the {@link com.hazelcast.cache.ICache} */ public String getName() { return name; } /** * Sets the name of this {@link com.hazelcast.cache.ICache}. * * @param name the name to set for this {@link com.hazelcast.cache.ICache} * @return the current cache config instance */ public CacheSimpleConfig setName(String name) { this.name = name; return this; } /** * Gets the key type for this {@link com.hazelcast.cache.ICache}. * * @return the key type */ public String getKeyType() { return keyType; } /** * Sets the key type for this {@link com.hazelcast.cache.ICache}. * * @param keyType the key type to set for this {@link com.hazelcast.cache.ICache} * @return the current cache config instance */ public CacheSimpleConfig setKeyType(String keyType) { this.keyType = keyType; return this; } /** * Gets the value type for this {@link com.hazelcast.cache.ICache}. * * @return the value type for this {@link com.hazelcast.cache.ICache} */ public String getValueType() { return valueType; } /** * Sets the value type for this {@link com.hazelcast.cache.ICache}. * * @param valueType the value type to set for this {@link com.hazelcast.cache.ICache} * @return the current cache config instance */ public CacheSimpleConfig setValueType(String valueType) { this.valueType = valueType; return this; } /** * Checks if statistics are enabled for this {@link com.hazelcast.cache.ICache}. * * @return {@code true} if statistics are enabled, {@code false} otherwise */ public boolean isStatisticsEnabled() { return statisticsEnabled; } /** * Sets statistics to enabled or disabled for this {@link com.hazelcast.cache.ICache}. * * @param statisticsEnabled {@code true} to enable cache statistics, {@code false} to disable * @return the current cache config instance */ public CacheSimpleConfig setStatisticsEnabled(boolean statisticsEnabled) { this.statisticsEnabled = statisticsEnabled; return this; } /** * Checks if management is enabled for this {@link com.hazelcast.cache.ICache}. * * @return {@code true} if cache management is enabled, {@code false} otherwise */ public boolean isManagementEnabled() { return managementEnabled; } /** * Sets management to enabled or disabled for this {@link com.hazelcast.cache.ICache}. * * @param managementEnabled {@code true} to enable cache management, {@code false} to disable * @return the current cache config instance */ public CacheSimpleConfig setManagementEnabled(boolean managementEnabled) { this.managementEnabled = managementEnabled; return this; } /** * Checks if this {@link com.hazelcast.cache.ICache} is read-through: a read loads the entry from the data store * if it is not already in the cache. * * @return {@code true} if the cache is read-through, {@code false} otherwise */ public boolean isReadThrough() { return readThrough; } /** * Enables or disables read-through: a read loads the entry from the data store if it is not already in the cache. * * @param readThrough {@code true} to enable read-through for this {@link com.hazelcast.cache.ICache}, * {@code false} to disable * @return the current cache config instance */ public CacheSimpleConfig setReadThrough(boolean readThrough) { this.readThrough = readThrough; return this; } /** * Checks if the {@link com.hazelcast.cache.ICache} is write-through: a write to the queue also loads the entry * into the data store. * * @return {@code true} if the cache is write-through, {@code false} otherwise */ public boolean isWriteThrough() { return writeThrough; } /** * Enables or disables write-through for this {@link com.hazelcast.cache.ICache}: a write to the queue also loads * the entry into the data store. * * @param writeThrough {@code true} to enable write-through, {@code false} to disable * @return the current cache config instance */ public CacheSimpleConfig setWriteThrough(boolean writeThrough) { this.writeThrough = writeThrough; return this; } /** * Gets the factory for the {@link javax.cache.integration.CacheLoader}. * * @return the factory for the {@link javax.cache.integration.CacheLoader} */ public String getCacheLoaderFactory() { return cacheLoaderFactory; } /** * Sets the factory for this {@link javax.cache.integration.CacheLoader}. * * @param cacheLoaderFactory the factory to set for this {@link javax.cache.integration.CacheLoader} * @return the current cache config instance */ public CacheSimpleConfig setCacheLoaderFactory(String cacheLoaderFactory) { if (cacheLoader != null && cacheLoaderFactory != null) { throw new IllegalStateException("Cannot set cacheLoaderFactory to '" + cacheLoaderFactory + "', because cacheLoader is already set to '" + cacheLoader + "'."); } this.cacheLoaderFactory = cacheLoaderFactory; return this; } /** * Get classname of a class to be used as {@link javax.cache.integration.CacheLoader}. * * @return classname to be used as {@link javax.cache.integration.CacheLoader} */ public String getCacheLoader() { return cacheLoader; } /** * Set classname of a class to be used as {@link javax.cache.integration.CacheLoader}. * * @param cacheLoader classname to be used as {@link javax.cache.integration.CacheLoader} * @return the current cache config instance */ public CacheSimpleConfig setCacheLoader(String cacheLoader) { if (cacheLoader != null && cacheLoaderFactory != null) { throw new IllegalStateException("Cannot set cacheLoader to '" + cacheLoader + "', because cacheLoaderFactory is already set to '" + cacheLoaderFactory + "'."); } this.cacheLoader = cacheLoader; return this; } /** * Gets the factory for the {@link javax.cache.integration.CacheWriter}. * * @return the factory for the {@link javax.cache.integration.CacheWriter} */ public String getCacheWriterFactory() { return cacheWriterFactory; } /** * Sets the factory for this {@link javax.cache.integration.CacheWriter}. * * @param cacheWriterFactory the factory to set for this {@link javax.cache.integration.CacheWriter} * @return the current cache config instance */ public CacheSimpleConfig setCacheWriterFactory(String cacheWriterFactory) { if (cacheWriter != null && cacheWriterFactory != null) { throw new IllegalStateException("Cannot set cacheWriterFactory to '" + cacheWriterFactory + "', because cacheWriter is already set to '" + cacheWriter + "'."); } this.cacheWriterFactory = cacheWriterFactory; return this; } /** * Get classname of a class to be used as {@link javax.cache.integration.CacheWriter}. * * @return classname to be used as {@link javax.cache.integration.CacheWriter} */ public String getCacheWriter() { return cacheWriter; } /** * Set classname of a class to be used as {@link javax.cache.integration.CacheWriter}. * * @param cacheWriter classname to be used as {@link javax.cache.integration.CacheWriter} * @return the current cache config instance */ public CacheSimpleConfig setCacheWriter(String cacheWriter) { if (cacheWriter != null && cacheWriterFactory != null) { throw new IllegalStateException("Cannot set cacheWriter to '" + cacheWriter + "', because cacheWriterFactory is already set to '" + cacheWriterFactory + "'."); } this.cacheWriter = cacheWriter; return this; } /** * Gets the factory configuration for the {@link javax.cache.expiry.ExpiryPolicy}. * * @return the factory configuration for the {@link javax.cache.expiry.ExpiryPolicy} */ public ExpiryPolicyFactoryConfig getExpiryPolicyFactoryConfig() { return expiryPolicyFactoryConfig; } /** * Sets the factory configuration for this {@link javax.cache.expiry.ExpiryPolicy}. * * @param expiryPolicyFactoryConfig the factory configuration to set for this {@link javax.cache.expiry.ExpiryPolicy} * @return the current cache config instance */ public CacheSimpleConfig setExpiryPolicyFactoryConfig(ExpiryPolicyFactoryConfig expiryPolicyFactoryConfig) { this.expiryPolicyFactoryConfig = expiryPolicyFactoryConfig; return this; } /** * Sets the factory for this {@link javax.cache.expiry.ExpiryPolicy}. * * @param className the factory to set for this {@link javax.cache.expiry.ExpiryPolicy} * @return the current cache config instance */ public CacheSimpleConfig setExpiryPolicyFactory(String className) { this.expiryPolicyFactoryConfig = new ExpiryPolicyFactoryConfig(className); return this; } /** * Adds {@link CacheSimpleEntryListenerConfig} to this {@link com.hazelcast.cache.ICache}. * * @return this {@code CacheSimpleConfig} instance */ public CacheSimpleConfig addEntryListenerConfig(CacheSimpleEntryListenerConfig listenerConfig) { getCacheEntryListeners().add(listenerConfig); return this; } /** * Gets a list of {@link CacheSimpleEntryListenerConfig} from this {@link com.hazelcast.cache.ICache}. * * @return list of {@link CacheSimpleEntryListenerConfig} */ public List<CacheSimpleEntryListenerConfig> getCacheEntryListeners() { if (cacheEntryListeners == null) { cacheEntryListeners = new ArrayList<CacheSimpleEntryListenerConfig>(); } return cacheEntryListeners; } /** * Sets a list of {@link CacheSimpleEntryListenerConfig} for this {@link com.hazelcast.cache.ICache}. * * @param cacheEntryListeners list of {@link CacheSimpleEntryListenerConfig} * @return this {@code CacheSimpleConfig} instance */ public CacheSimpleConfig setCacheEntryListeners(List<CacheSimpleEntryListenerConfig> cacheEntryListeners) { this.cacheEntryListeners = cacheEntryListeners; return this; } /** * Gets the number of asynchronous backups for this {@link com.hazelcast.cache.ICache}. * * @return the number of asynchronous backups for this {@link com.hazelcast.cache.ICache} */ public int getAsyncBackupCount() { return asyncBackupCount; } /** * Sets the number of asynchronous backups for this {@link com.hazelcast.cache.ICache}. * * @param asyncBackupCount the number of asynchronous synchronous backups to set * @return the updated CacheSimpleConfig * @throws IllegalArgumentException if asyncBackupCount smaller than 0, * or larger than the maximum number of backups, * or the sum of the backups and async backups is larger than the maximum number of backups * @see #setBackupCount(int) * @see #getAsyncBackupCount() */ public CacheSimpleConfig setAsyncBackupCount(int asyncBackupCount) { this.asyncBackupCount = checkAsyncBackupCount(backupCount, asyncBackupCount); return this; } /** * Gets the number of synchronous backups for this {@link com.hazelcast.cache.ICache}. * * @return the number of synchronous backups */ public int getBackupCount() { return backupCount; } /** * Sets the number of synchronous backups for this {@link com.hazelcast.cache.ICache}. * * @param backupCount the new backupCount * @return the updated CacheSimpleConfig * @throws IllegalArgumentException if backupCount smaller than 0, * or larger than the maximum number of backup * or the sum of the backups and async backups is larger * than the maximum number of backups */ public CacheSimpleConfig setBackupCount(int backupCount) { this.backupCount = checkBackupCount(backupCount, asyncBackupCount); return this; } /** * Gets the InMemory Format for this {@link com.hazelcast.cache.ICache}. * * @return the InMemory Format */ public InMemoryFormat getInMemoryFormat() { return inMemoryFormat; } /** * Sets the InMemory Format for this {@link com.hazelcast.cache.ICache}. * * @param inMemoryFormat the InMemory Format * @return the updated CacheSimpleConfig */ public CacheSimpleConfig setInMemoryFormat(InMemoryFormat inMemoryFormat) { this.inMemoryFormat = isNotNull(inMemoryFormat, "In-Memory format cannot be null!"); return this; } /** * Gets the eviction configuration for this {@link com.hazelcast.cache.ICache}. * * @return the eviction configuration */ public EvictionConfig getEvictionConfig() { return evictionConfig; } /** * Sets the eviction configuration for this {@link com.hazelcast.cache.ICache}. * * @param evictionConfig the eviction configuration to set * @return the updated CacheSimpleConfig */ public CacheSimpleConfig setEvictionConfig(EvictionConfig evictionConfig) { this.evictionConfig = isNotNull(evictionConfig, "evictionConfig"); return this; } /** * Gets the WAN target replication reference. * * @return the WAN target replication reference */ public WanReplicationRef getWanReplicationRef() { return wanReplicationRef; } /** * Sets the WAN target replication reference. * * @param wanReplicationRef the WAN target replication reference * @return this configuration */ public CacheSimpleConfig setWanReplicationRef(WanReplicationRef wanReplicationRef) { this.wanReplicationRef = wanReplicationRef; return this; } /** * Gets the partition lost listener references added to cache configuration. * * @return List of CachePartitionLostListenerConfig */ public List<CachePartitionLostListenerConfig> getPartitionLostListenerConfigs() { if (partitionLostListenerConfigs == null) { partitionLostListenerConfigs = new ArrayList<>(); } return partitionLostListenerConfigs; } /** * Sets the PartitionLostListenerConfigs. * * @param partitionLostListenerConfigs CachePartitionLostListenerConfig list */ public CacheSimpleConfig setPartitionLostListenerConfigs( List<CachePartitionLostListenerConfig> partitionLostListenerConfigs) { this.partitionLostListenerConfigs = partitionLostListenerConfigs; return this; } /** * Adds the CachePartitionLostListenerConfig to partitionLostListenerConfigs. * * @param listenerConfig CachePartitionLostListenerConfig to be added */ public CacheSimpleConfig addCachePartitionLostListenerConfig(CachePartitionLostListenerConfig listenerConfig) { getPartitionLostListenerConfigs().add(listenerConfig); return this; } /** * Gets the name of the associated split brain protection if any. * * @return the name of the associated split brain protection if any */ public String getSplitBrainProtectionName() { return splitBrainProtectionName; } /** * Associates this cache configuration to a split brain protection. * * @param splitBrainProtectionName name of the desired split brain protection * @return the updated CacheSimpleConfig */ public CacheSimpleConfig setSplitBrainProtectionName(String splitBrainProtectionName) { this.splitBrainProtectionName = splitBrainProtectionName; return this; } /** * Gets the {@link MergePolicyConfig} for this map. * * @return the {@link MergePolicyConfig} for this map */ public MergePolicyConfig getMergePolicyConfig() { return mergePolicyConfig; } /** * Sets the {@link MergePolicyConfig} for this map. * * @return the updated map configuration */ public CacheSimpleConfig setMergePolicyConfig(MergePolicyConfig mergePolicyConfig) { this.mergePolicyConfig = checkNotNull(mergePolicyConfig, "mergePolicyConfig cannot be null!"); return this; } /** * Gets the {@code HotRestartConfig} for this {@code CacheSimpleConfig} * * @return hot restart config */ public HotRestartConfig getHotRestartConfig() { return hotRestartConfig; } /** * Sets the {@code HotRestartConfig} for this {@code CacheSimpleConfig} * * @param hotRestartConfig hot restart config * @return this {@code CacheSimpleConfig} instance */ public CacheSimpleConfig setHotRestartConfig(HotRestartConfig hotRestartConfig) { this.hotRestartConfig = hotRestartConfig; return this; } /** * Gets the {@code EventJournalConfig} for this {@code CacheSimpleConfig} * * @return event journal config */ public EventJournalConfig getEventJournalConfig() { return eventJournalConfig; } /** * Sets the {@code EventJournalConfig} for this {@code CacheSimpleConfig} * * @param eventJournalConfig event journal config * @return this {@code CacheSimpleConfig} instance */ public CacheSimpleConfig setEventJournalConfig(@Nonnull EventJournalConfig eventJournalConfig) { this.eventJournalConfig = checkNotNull(eventJournalConfig, "eventJournalConfig cannot be null!"); return this; } /** * Returns invalidation events disabled status for per entry. * * @return {@code true} if invalidation events are disabled for per entry, {@code false} otherwise */ public boolean isDisablePerEntryInvalidationEvents() { return disablePerEntryInvalidationEvents; } /** * Sets invalidation events disabled status for per entry. * * @param disablePerEntryInvalidationEvents Disables invalidation event sending behaviour if it is {@code true}, * otherwise enables it * @return this configuration */ public CacheSimpleConfig setDisablePerEntryInvalidationEvents(boolean disablePerEntryInvalidationEvents) { this.disablePerEntryInvalidationEvents = disablePerEntryInvalidationEvents; return this; } @Override public int getFactoryId() { return ConfigDataSerializerHook.F_ID; } @Override public int getClassId() { return ConfigDataSerializerHook.SIMPLE_CACHE_CONFIG; } @Override public void writeData(ObjectDataOutput out) throws IOException { out.writeString(name); out.writeString(keyType); out.writeString(valueType); out.writeBoolean(statisticsEnabled); out.writeBoolean(managementEnabled); out.writeBoolean(readThrough); out.writeBoolean(writeThrough); out.writeBoolean(disablePerEntryInvalidationEvents); out.writeString(cacheLoaderFactory); out.writeString(cacheWriterFactory); out.writeString(cacheLoader); out.writeString(cacheWriter); out.writeObject(expiryPolicyFactoryConfig); writeNullableList(cacheEntryListeners, out); out.writeInt(asyncBackupCount); out.writeInt(backupCount); out.writeString(inMemoryFormat.name()); out.writeObject(evictionConfig); out.writeObject(wanReplicationRef); out.writeString(splitBrainProtectionName); writeNullableList(partitionLostListenerConfigs, out); out.writeObject(mergePolicyConfig); out.writeObject(hotRestartConfig); out.writeObject(eventJournalConfig); } @Override public void readData(ObjectDataInput in) throws IOException { name = in.readString(); keyType = in.readString(); valueType = in.readString(); statisticsEnabled = in.readBoolean(); managementEnabled = in.readBoolean(); readThrough = in.readBoolean(); writeThrough = in.readBoolean(); disablePerEntryInvalidationEvents = in.readBoolean(); cacheLoaderFactory = in.readString(); cacheWriterFactory = in.readString(); cacheLoader = in.readString(); cacheWriter = in.readString(); expiryPolicyFactoryConfig = in.readObject(); cacheEntryListeners = readNullableList(in); asyncBackupCount = in.readInt(); backupCount = in.readInt(); inMemoryFormat = InMemoryFormat.valueOf(in.readString()); evictionConfig = in.readObject(); wanReplicationRef = in.readObject(); splitBrainProtectionName = in.readString(); partitionLostListenerConfigs = readNullableList(in); mergePolicyConfig = in.readObject(); hotRestartConfig = in.readObject(); eventJournalConfig = in.readObject(); } @Override @SuppressWarnings({"checkstyle:cyclomaticcomplexity", "checkstyle:npathcomplexity", "checkstyle:methodlength"}) public final boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof CacheSimpleConfig)) { return false; } CacheSimpleConfig that = (CacheSimpleConfig) o; if (statisticsEnabled != that.statisticsEnabled) { return false; } if (managementEnabled != that.managementEnabled) { return false; } if (readThrough != that.readThrough) { return false; } if (writeThrough != that.writeThrough) { return false; } if (asyncBackupCount != that.asyncBackupCount) { return false; } if (backupCount != that.backupCount) { return false; } if (disablePerEntryInvalidationEvents != that.disablePerEntryInvalidationEvents) { return false; } if (!name.equals(that.name)) { return false; } if (!Objects.equals(keyType, that.keyType)) { return false; } if (!Objects.equals(valueType, that.valueType)) { return false; } if (!Objects.equals(cacheLoaderFactory, that.cacheLoaderFactory)) { return false; } if (!Objects.equals(cacheWriterFactory, that.cacheWriterFactory)) { return false; } if (!Objects.equals(cacheLoader, that.cacheLoader)) { return false; } if (!Objects.equals(cacheWriter, that.cacheWriter)) { return false; } if (!Objects.equals(expiryPolicyFactoryConfig, that.expiryPolicyFactoryConfig)) { return false; } if (!Objects.equals(cacheEntryListeners, that.cacheEntryListeners)) { return false; } if (inMemoryFormat != that.inMemoryFormat) { return false; } if (!Objects.equals(evictionConfig, that.evictionConfig)) { return false; } if (!Objects.equals(wanReplicationRef, that.wanReplicationRef)) { return false; } if (!Objects.equals(splitBrainProtectionName, that.splitBrainProtectionName)) { return false; } if (!Objects.equals(partitionLostListenerConfigs, that.partitionLostListenerConfigs)) { return false; } if (!Objects.equals(mergePolicyConfig, that.mergePolicyConfig)) { return false; } if (!Objects.equals(eventJournalConfig, that.eventJournalConfig)) { return false; } return Objects.equals(hotRestartConfig, that.hotRestartConfig); } @Override @SuppressWarnings({"checkstyle:cyclomaticcomplexity", "checkstyle:npathcomplexity"}) public final int hashCode() { int result = name.hashCode(); result = 31 * result + (keyType != null ? keyType.hashCode() : 0); result = 31 * result + (valueType != null ? valueType.hashCode() : 0); result = 31 * result + (statisticsEnabled ? 1 : 0); result = 31 * result + (managementEnabled ? 1 : 0); result = 31 * result + (readThrough ? 1 : 0); result = 31 * result + (writeThrough ? 1 : 0); result = 31 * result + (cacheLoaderFactory != null ? cacheLoaderFactory.hashCode() : 0); result = 31 * result + (cacheWriterFactory != null ? cacheWriterFactory.hashCode() : 0); result = 31 * result + (cacheLoader != null ? cacheLoader.hashCode() : 0); result = 31 * result + (cacheWriter != null ? cacheWriter.hashCode() : 0); result = 31 * result + (expiryPolicyFactoryConfig != null ? expiryPolicyFactoryConfig.hashCode() : 0); result = 31 * result + (cacheEntryListeners != null ? cacheEntryListeners.hashCode() : 0); result = 31 * result + asyncBackupCount; result = 31 * result + backupCount; result = 31 * result + (inMemoryFormat != null ? inMemoryFormat.hashCode() : 0); result = 31 * result + (evictionConfig != null ? evictionConfig.hashCode() : 0); result = 31 * result + (wanReplicationRef != null ? wanReplicationRef.hashCode() : 0); result = 31 * result + (splitBrainProtectionName != null ? splitBrainProtectionName.hashCode() : 0); result = 31 * result + (partitionLostListenerConfigs != null ? partitionLostListenerConfigs.hashCode() : 0); result = 31 * result + (mergePolicyConfig != null ? mergePolicyConfig.hashCode() : 0); result = 31 * result + (hotRestartConfig != null ? hotRestartConfig.hashCode() : 0); result = 31 * result + (eventJournalConfig != null ? eventJournalConfig.hashCode() : 0); result = 31 * result + (disablePerEntryInvalidationEvents ? 1 : 0); return result; } @Override public String toString() { return "CacheSimpleConfig{" + "name='" + name + '\'' + ", asyncBackupCount=" + asyncBackupCount + ", backupCount=" + backupCount + ", inMemoryFormat=" + inMemoryFormat + ", keyType=" + keyType + ", valueType=" + valueType + ", statisticsEnabled=" + statisticsEnabled + ", managementEnabled=" + managementEnabled + ", readThrough=" + readThrough + ", writeThrough=" + writeThrough + ", cacheLoaderFactory='" + cacheLoaderFactory + '\'' + ", cacheWriterFactory='" + cacheWriterFactory + '\'' + ", cacheLoader='" + cacheLoader + '\'' + ", cacheWriter='" + cacheWriter + '\'' + ", expiryPolicyFactoryConfig=" + expiryPolicyFactoryConfig + ", cacheEntryListeners=" + cacheEntryListeners + ", evictionConfig=" + evictionConfig + ", wanReplicationRef=" + wanReplicationRef + ", splitBrainProtectionName=" + splitBrainProtectionName + ", partitionLostListenerConfigs=" + partitionLostListenerConfigs + ", mergePolicyConfig=" + mergePolicyConfig + ", hotRestartConfig=" + hotRestartConfig + ", eventJournal=" + eventJournalConfig + '}'; } /** * Represents configuration for "ExpiryPolicyFactory". */ public static class ExpiryPolicyFactoryConfig implements IdentifiedDataSerializable { private String className; private TimedExpiryPolicyFactoryConfig timedExpiryPolicyFactoryConfig; public ExpiryPolicyFactoryConfig() { } public ExpiryPolicyFactoryConfig(String className) { this.className = className; this.timedExpiryPolicyFactoryConfig = null; } public ExpiryPolicyFactoryConfig(TimedExpiryPolicyFactoryConfig timedExpiryPolicyFactoryConfig) { this.className = null; this.timedExpiryPolicyFactoryConfig = timedExpiryPolicyFactoryConfig; } public String getClassName() { return className; } public TimedExpiryPolicyFactoryConfig getTimedExpiryPolicyFactoryConfig() { return timedExpiryPolicyFactoryConfig; } @Override public int getFactoryId() { return ConfigDataSerializerHook.F_ID; } @Override public int getClassId() { return ConfigDataSerializerHook.SIMPLE_CACHE_CONFIG_EXPIRY_POLICY_FACTORY_CONFIG; } @Override public void writeData(ObjectDataOutput out) throws IOException { out.writeString(className); out.writeObject(timedExpiryPolicyFactoryConfig); } @Override public void readData(ObjectDataInput in) throws IOException { className = in.readString(); timedExpiryPolicyFactoryConfig = in.readObject(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ExpiryPolicyFactoryConfig that = (ExpiryPolicyFactoryConfig) o; if (className != null ? !className.equals(that.className) : that.className != null) { return false; } return timedExpiryPolicyFactoryConfig != null ? timedExpiryPolicyFactoryConfig.equals(that.timedExpiryPolicyFactoryConfig) : that.timedExpiryPolicyFactoryConfig == null; } @Override public int hashCode() { int result = className != null ? className.hashCode() : 0; result = 31 * result + (timedExpiryPolicyFactoryConfig != null ? timedExpiryPolicyFactoryConfig.hashCode() : 0); return result; } @Override public String toString() { return "ExpiryPolicyFactoryConfig{" + "className='" + className + '\'' + ", timedExpiryPolicyFactoryConfig=" + timedExpiryPolicyFactoryConfig + '}'; } /** * Represents configuration for time based "ExpiryPolicyFactory" with duration and time unit. */ public static class TimedExpiryPolicyFactoryConfig implements IdentifiedDataSerializable { private ExpiryPolicyType expiryPolicyType; private DurationConfig durationConfig; public TimedExpiryPolicyFactoryConfig() { } public TimedExpiryPolicyFactoryConfig(ExpiryPolicyType expiryPolicyType, DurationConfig durationConfig) { this.expiryPolicyType = expiryPolicyType; this.durationConfig = durationConfig; } public ExpiryPolicyType getExpiryPolicyType() { return expiryPolicyType; } public DurationConfig getDurationConfig() { return durationConfig; } @Override public int getFactoryId() { return ConfigDataSerializerHook.F_ID; } @Override public int getClassId() { return ConfigDataSerializerHook.SIMPLE_CACHE_CONFIG_TIMED_EXPIRY_POLICY_FACTORY_CONFIG; } @Override public void writeData(ObjectDataOutput out) throws IOException { out.writeString(expiryPolicyType.name()); out.writeObject(durationConfig); } @Override public void readData(ObjectDataInput in) throws IOException { expiryPolicyType = ExpiryPolicyType.valueOf(in.readString()); durationConfig = in.readObject(); } /** * Represents type of the "TimedExpiryPolicyFactoryConfig". */ public enum ExpiryPolicyType { /** * Expiry policy type for the {@link javax.cache.expiry.CreatedExpiryPolicy}. */ CREATED(0), /** * Expiry policy type for the {@link javax.cache.expiry.ModifiedExpiryPolicy}. */ MODIFIED(1), /** * Expiry policy type for the {@link javax.cache.expiry.AccessedExpiryPolicy}. */ ACCESSED(2), /** * Expiry policy type for the {@link javax.cache.expiry.TouchedExpiryPolicy}. */ TOUCHED(3), /** * Expiry policy type for the {@link javax.cache.expiry.EternalExpiryPolicy}. */ ETERNAL(4); private static final int MIN_ID = CREATED.id; private static final int MAX_ID = ETERNAL.id; private static final ExpiryPolicyType[] CACHED_VALUES = values(); private int id; ExpiryPolicyType(int id) { this.id = id; } /** * @return unique ID for the expiry policy type */ public int getId() { return id; } public static ExpiryPolicyType getById(int id) { if (MIN_ID <= id && id <= MAX_ID) { return CACHED_VALUES[id]; } return null; } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TimedExpiryPolicyFactoryConfig that = (TimedExpiryPolicyFactoryConfig) o; if (expiryPolicyType != that.expiryPolicyType) { return false; } return Objects.equals(durationConfig, that.durationConfig); } @Override public int hashCode() { int result = expiryPolicyType != null ? expiryPolicyType.hashCode() : 0; result = 31 * result + (durationConfig != null ? durationConfig.hashCode() : 0); return result; } @Override public String toString() { return "TimedExpiryPolicyFactoryConfig{" + "expiryPolicyType=" + expiryPolicyType + ", durationConfig=" + durationConfig + '}'; } } /** * Represents duration configuration with duration amount and time unit * for the "TimedExpiryPolicyFactoryConfig". */ public static class DurationConfig implements IdentifiedDataSerializable { private long durationAmount; private TimeUnit timeUnit; public DurationConfig() { } public DurationConfig(long durationAmount, TimeUnit timeUnit) { this.durationAmount = durationAmount; this.timeUnit = timeUnit; } public long getDurationAmount() { return durationAmount; } public TimeUnit getTimeUnit() { return timeUnit; } @Override public int getFactoryId() { return ConfigDataSerializerHook.F_ID; } @Override public int getClassId() { return ConfigDataSerializerHook.SIMPLE_CACHE_CONFIG_DURATION_CONFIG; } @Override public void writeData(ObjectDataOutput out) throws IOException { out.writeLong(durationAmount); out.writeString(timeUnit.name()); } @Override public void readData(ObjectDataInput in) throws IOException { durationAmount = in.readLong(); timeUnit = TimeUnit.valueOf(in.readString()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DurationConfig that = (DurationConfig) o; if (durationAmount != that.durationAmount) { return false; } return timeUnit == that.timeUnit; } @Override public int hashCode() { int result = (int) (durationAmount ^ (durationAmount >>> 32)); result = 31 * result + (timeUnit != null ? timeUnit.hashCode() : 0); return result; } @Override public String toString() { return "DurationConfig{" + "durationAmount=" + durationAmount + ", timeUnit" + timeUnit + '}'; } } } }
package io.spotnext.core.infrastructure.interceptor; import io.spotnext.core.infrastructure.exception.ModelCreationException; import io.spotnext.infrastructure.type.Item; /** * <p>ItemCreateInterceptor interface.</p> * * @author mojo2012 * @version 1.0 * @since 1.0 */ public interface ItemCreateInterceptor<T extends Item> extends ItemInterceptor<T> { /** * The newly created item has been initialized from the persistence layer. * Further initialization (eg. default values) can be set here. * * @param item * the newly instantiated item instance * @throws io.spotnext.infrastructure.exception.ModelCreationException * if thrown the item instantiation will be cancelled */ void onCreate(T item) throws ModelCreationException; }
package lumien.randomthings.Items; import cpw.mods.fml.common.registry.GameRegistry; import net.minecraft.item.ItemArmor.ArmorMaterial; import net.minecraftforge.common.util.EnumHelper; import lumien.randomthings.RandomThings; import lumien.randomthings.Configuration.ConfigItems; public class ModItems { public static ItemFilter filter; public static ItemBiomeCapsule biomeCapsule; public static ItemBiomePainter biomePainter; public static ItemIngredient ingredients; public static ItemWhiteStone whitestone; public static ItemMagneticForce magneticForce; public static ItemVoidStone voidStone; public static ItemDropFilter dropFilter; public static ItemEnderLetter enderLetter; public static ItemSpectreKey spectreKey; public static ItemOpSpectreKey opSpectreKey; public static ItemSoundRecorder soundRecorder; public static ItemImbue imbue; public static ItemBloodstone bloodStone; public static ItemCreativeSword creativeSword; public static ItemCreativeGrower creativeGrower; public static ItemCreativeChestGenerator creativeChestGenerator; public static ArmorMaterial spectreArmorMaterial = EnumHelper.addArmorMaterial("Spectre", 35, new int[] { 3, 9, 7, 3 }, 17); public static ItemSpectreArmor spectreHelmet; public static ItemSpectreArmor spectreChestplate; public static ItemSpectreArmor spectreLeggings; public static ItemSpectreArmor spectreBoots; public static ItemSpectreSword spectreSword; public static ItemSpiritBinder spiritBinder; public static ItemGinto ginto; public static void init() { RandomThings.instance.logger.debug("Initializing Items"); if (ConfigItems.biomeCapsule) biomeCapsule = new ItemBiomeCapsule(); if (ConfigItems.biomePainter) biomePainter = new ItemBiomePainter(); if (ConfigItems.whitestone) whitestone = new ItemWhiteStone(); if (ConfigItems.magneticForce) magneticForce = new ItemMagneticForce(); if (ConfigItems.voidStone) voidStone = new ItemVoidStone(); if (ConfigItems.dropFilter) dropFilter = new ItemDropFilter(); if (ConfigItems.enderLetter) enderLetter = new ItemEnderLetter(); if (ConfigItems.spectreKey) spectreKey = new ItemSpectreKey(); if (ConfigItems.opSpectreKey) opSpectreKey = new ItemOpSpectreKey(); if (ConfigItems.spectreArmor) { spectreHelmet = (ItemSpectreArmor) new ItemSpectreArmor(0).setUnlocalizedName("spectreHelmet").setTextureName("RandomThings:armor/spectreHelmet"); spectreChestplate = (ItemSpectreArmor) new ItemSpectreArmor(1).setUnlocalizedName("spectreChestplate").setTextureName("RandomThings:armor/spectreChestplate"); spectreLeggings = (ItemSpectreArmor) new ItemSpectreArmor(2).setUnlocalizedName("spectreLeggings").setTextureName("RandomThings:armor/spectreLeggings"); spectreBoots = (ItemSpectreArmor) new ItemSpectreArmor(3).setUnlocalizedName("spectreBoots").setTextureName("RandomThings:armor/spectreBoots"); GameRegistry.registerItem(spectreHelmet, "spectreHelmet"); GameRegistry.registerItem(spectreChestplate, "spectreChestplate"); GameRegistry.registerItem(spectreLeggings, "spectreLeggings"); GameRegistry.registerItem(spectreBoots, "spectreBoots"); } if (ConfigItems.spectreSword) spectreSword = new ItemSpectreSword(); if (ConfigItems.spiritBinder) spiritBinder = new ItemSpiritBinder(); if (ConfigItems.imbue) imbue = new ItemImbue(); if (ConfigItems.bloodStone) bloodStone = new ItemBloodstone(); if (ConfigItems.creativeSword) creativeSword = new ItemCreativeSword(); if (ConfigItems.creativeGrower) creativeGrower = new ItemCreativeGrower(); if (ConfigItems.creativeChestGenerator) creativeChestGenerator = new ItemCreativeChestGenerator(); if (ConfigItems.soundRecorder) soundRecorder = new ItemSoundRecorder(); if (ConfigItems.ginto) ginto = new ItemGinto(); ingredients = new ItemIngredient(); filter = new ItemFilter(); } }
package org.basex.query.expr.constr; import static org.basex.query.QueryText.*; import org.basex.query.*; import org.basex.query.expr.*; import org.basex.query.iter.*; import org.basex.query.value.item.*; import org.basex.query.value.node.*; import org.basex.query.value.seq.*; import org.basex.query.value.type.*; import org.basex.query.var.*; import org.basex.util.*; import org.basex.util.hash.*; /** * Text fragment. * * @author BaseX Team 2005-19, BSD License * @author Christian Gruen */ public final class CTxt extends CNode { /** Item evaluation flag. */ private boolean simple; /** * Constructor. * @param sc static context * @param info input info * @param text text */ public CTxt(final StaticContext sc, final InputInfo info, final Expr text) { super(sc, info, SeqType.TXT_ZO, text); } @Override public Expr optimize(final CompileContext cc) { final Expr expr = exprs[0]; final SeqType st = expr.seqType(); if(st.zero()) return cc.replaceWith(this, expr); final boolean atom = !st.mayBeArray(); if(st.oneOrMore() && atom) exprType.assign(Occ.ONE); simple = st.zeroOrOne() && atom; return this; } @Override public Item item(final QueryContext qc, final InputInfo ii) throws QueryException { // if possible, retrieve single item final Expr expr = exprs[0]; if(simple) { final Item item = expr.item(qc, info); return new FTxt(item == Empty.VALUE ? Token.EMPTY : item.string(info)); } final TokenBuilder tb = new TokenBuilder(); boolean more = false; final Iter iter = expr.atomIter(qc, info); for(Item item; (item = qc.next(iter)) != null;) { if(more) tb.add(' '); tb.add(item.string(info)); more = true; } return more ? new FTxt(tb.finish()) : Empty.VALUE; } @Override public Expr copy(final CompileContext cc, final IntObjMap<Var> vm) { final CTxt ctxt = copyType(new CTxt(sc, info, exprs[0].copy(cc, vm))); ctxt.simple = simple; return ctxt; } @Override public boolean equals(final Object obj) { return this == obj || obj instanceof CTxt && super.equals(obj); } @Override public String description() { return info(TEXT); } @Override public String toString() { return toString(TEXT); } }
/* * Copyright (C) 2018 The Sylph 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 ideal.sylph.plugins.kafka.spark; import com.github.harbby.gadtry.base.Lazys; import ideal.sylph.annotation.Description; import ideal.sylph.annotation.Name; import ideal.sylph.annotation.Version; import ideal.sylph.etl.SourceContext; import ideal.sylph.etl.api.Source; import ideal.sylph.runner.spark.kafka.SylphKafkaOffset; import kafka.common.TopicAndPartition; import kafka.message.MessageAndMetadata; import kafka.serializer.DefaultDecoder; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.spark.rdd.RDD; import org.apache.spark.sql.Row; import org.apache.spark.sql.catalyst.expressions.GenericRowWithSchema; import org.apache.spark.sql.types.StructType; import org.apache.spark.streaming.Time; import org.apache.spark.streaming.api.java.JavaDStream; import org.apache.spark.streaming.api.java.JavaInputDStream; import org.apache.spark.streaming.api.java.JavaStreamingContext; import org.apache.spark.streaming.dstream.DStream; import org.apache.spark.streaming.kafka.HasOffsetRanges; import org.apache.spark.streaming.kafka.KafkaCluster; import org.apache.spark.streaming.kafka.KafkaUtils; import org.apache.spark.streaming.kafka.KafkaUtils$; import org.apache.spark.streaming.kafka.OffsetRange; import scala.collection.JavaConverters; import scala.collection.immutable.Map$; import scala.collection.mutable.ArrayBuffer; import scala.reflect.ClassTag$; import scala.util.Either; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.function.Supplier; import java.util.stream.Collectors; import static com.github.harbby.gadtry.base.Throwables.throwsThrowable; import static ideal.sylph.runner.spark.SQLHepler.schemaToSparkType; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Objects.requireNonNull; @Name("kafka08") @Version("1.0.0") @Description("this spark kafka 0.8 source inputStream") public class KafkaSource08 implements Source<JavaDStream<Row>> { private final transient Supplier<JavaDStream<Row>> loadStream; public KafkaSource08(JavaStreamingContext ssc, KafkaSourceConfig08 config, SourceContext context) { this.loadStream = Lazys.goLazy(() -> createSource(ssc, config, context)); } public JavaDStream<Row> createSource(JavaStreamingContext ssc, KafkaSourceConfig08 config, SourceContext context) { String topics = requireNonNull(config.getTopics(), "topics not setting"); String brokers = requireNonNull(config.getBrokers(), "brokers not setting"); //需要把集群的host 配置到程序所在机器 String groupId = requireNonNull(config.getGroupid(), "group.id not setting"); //消费者的名字 String offsetMode = requireNonNull(config.getOffsetMode(), "offsetMode not setting"); Map<String, String> otherConfig = config.getOtherConfig().entrySet() .stream() .filter(x -> x.getValue() != null) .collect(Collectors.toMap(Map.Entry::getKey, v -> v.getValue().toString())); Map<String, String> kafkaParams = new HashMap<>(otherConfig); kafkaParams.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, brokers); //kafkaParams.put("auto.commit.enable", true); //不自动提交偏移量 // "fetch.message.max.bytes" -> // "session.timeout.ms" -> "30000", //session默认是30秒 // "heartbeat.interval.ms" -> "5000", //10秒提交一次 心跳周期 kafkaParams.put(ConsumerConfig.GROUP_ID_CONFIG, groupId); //注意不同的流 group.id必须要不同 否则会出现offect commit提交失败的错误 kafkaParams.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, offsetMode); //largest smallest //----get fromOffsets @SuppressWarnings("unchecked") scala.collection.immutable.Map<String, String> map = (scala.collection.immutable.Map<String, String>) Map$.MODULE$.apply(JavaConverters.mapAsScalaMapConverter(kafkaParams).asScala().toSeq()); final KafkaCluster kafkaCluster = new KafkaCluster(map); Map<TopicAndPartition, Long> fromOffsets = getFromOffset(kafkaCluster, topics, groupId); //--- createDirectStream DirectKafkaInputDStream.class org.apache.spark.api.java.function.Function<MessageAndMetadata<byte[], byte[]>, ConsumerRecord<byte[], byte[]>> messageHandler = mmd -> new ConsumerRecord<>(mmd.topic(), mmd.partition(), mmd.key(), mmd.message(), mmd.offset()); @SuppressWarnings("unchecked") Class<ConsumerRecord<byte[], byte[]>> recordClass = (Class<ConsumerRecord<byte[], byte[]>>) ClassTag$.MODULE$.<ConsumerRecord<byte[], byte[]>>apply(ConsumerRecord.class).runtimeClass(); JavaInputDStream<ConsumerRecord<byte[], byte[]>> inputStream = KafkaUtils.createDirectStream(ssc, byte[].class, byte[].class, DefaultDecoder.class, DefaultDecoder.class, recordClass, kafkaParams, fromOffsets, messageHandler ); JavaDStream<ConsumerRecord<byte[], byte[]>> dStream = settingCommit(inputStream, kafkaParams, kafkaCluster, groupId); if ("json".equalsIgnoreCase(config.getValueType())) { JsonSchema jsonParser = new JsonSchema(context.getSchema()); return dStream .map(record -> { return jsonParser.deserialize(record.key(), record.value(), record.topic(), record.partition(), record.offset()); }); } else { StructType structType = schemaToSparkType(context.getSchema()); return dStream .map(record -> { String[] names = structType.names(); Object[] values = new Object[names.length]; for (int i = 0; i < names.length; i++) { switch (names[i]) { case "_topic": values[i] = record.topic(); continue; case "_message": values[i] = new String(record.value(), UTF_8); continue; case "_key": values[i] = new String(record.key(), UTF_8); continue; case "_partition": values[i] = record.partition(); continue; case "_offset": values[i] = record.offset(); default: values[i] = null; } } return (Row) new GenericRowWithSchema(values, structType); }); //.window(Duration(10 * 1000)) } } public static Map<TopicAndPartition, Long> getFromOffset(KafkaCluster kafkaCluster, String topics, String groupId) { Set<String> topicSets = Arrays.stream(topics.split(",")).collect(Collectors.toSet()); return getFromOffset(kafkaCluster, topicSets, groupId); } public static Map<TopicAndPartition, Long> getFromOffset(KafkaCluster kafkaCluster, Set<String> topics, String groupId) { scala.collection.immutable.Set<String> scalaTopicSets = JavaConverters.asScalaSetConverter(topics).asScala().toSet(); Either<ArrayBuffer<Throwable>, scala.collection.immutable.Set<TopicAndPartition>> partitions = kafkaCluster.getPartitions(scalaTopicSets); if (partitions.isLeft()) { throwsThrowable(partitions.left().get().head()); } Either<ArrayBuffer<Throwable>, scala.collection.immutable.Map<TopicAndPartition, Object>> groupOffsets = kafkaCluster.getConsumerOffsets(groupId, partitions.right().get()); scala.collection.immutable.Map<TopicAndPartition, Object> fromOffsets; if (groupOffsets.isRight()) { fromOffsets = groupOffsets.right().get(); } else { fromOffsets = KafkaUtils$.MODULE$.getFromOffsets(kafkaCluster, kafkaCluster.kafkaParams(), scalaTopicSets); } return JavaConverters.mapAsJavaMapConverter(fromOffsets).asJava().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, v -> (long) v.getValue())); } private static JavaDStream<ConsumerRecord<byte[], byte[]>> settingCommit( JavaInputDStream<ConsumerRecord<byte[], byte[]>> inputStream, Map<String, String> kafkaParams, KafkaCluster kafkaCluster, String groupId) { if (kafkaParams.getOrDefault("auto.commit.enable", "true").equals("false")) { return inputStream; } int commitInterval = Integer.parseInt(kafkaParams.getOrDefault(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "90000")); DStream<ConsumerRecord<byte[], byte[]>> sylphKafkaOffset = new SylphKafkaOffset<ConsumerRecord<byte[], byte[]>>(inputStream.inputDStream()) { private final KafkaOffsetCommitter kafkaOffsetCommitter = new KafkaOffsetCommitter( kafkaCluster, groupId, commitInterval); @Override public void initialize(Time time) { super.initialize(time); kafkaOffsetCommitter.setName("Kafka_Offset_Committer"); kafkaOffsetCommitter.start(); } @Override public void commitOffsets(RDD<?> kafkaRdd) { OffsetRange[] offsets = ((HasOffsetRanges) kafkaRdd).offsetRanges(); // Map<TopicAndPartition, Long> internalOffsets = Arrays.stream(offsets) // .collect(Collectors.toMap(k -> k.topicAndPartition(), v -> v.fromOffset())); //log().info("commit Kafka Offsets {}", internalOffsets); kafkaOffsetCommitter.addAll(offsets); } }; JavaDStream<ConsumerRecord<byte[], byte[]>> dStream = new JavaDStream<>(sylphKafkaOffset, ClassTag$.MODULE$.apply(ConsumerRecord.class)); return dStream; // inputStream = inputStream.transform(rdd -> { // OffsetRange[] offsets = ((HasOffsetRanges) rdd.rdd()).offsetRanges(); // Map<TopicAndPartition, Long> internalOffsets = Arrays.stream(offsets) // .collect(Collectors.toMap(k -> k.topicAndPartition(), v -> v.fromOffset())); // commitKafkaOffsets(kafkaCluster, groupId, internalOffsets); // return rdd; // }); } @Override public JavaDStream<Row> getSource() { return loadStream.get(); } }
/* * 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.jena.sparql.expr; import org.apache.jena.sparql.expr.nodevalue.XSDFuncOp ; import org.apache.jena.sparql.sse.Tags ; public class E_DateTimeDay extends ExprFunction1 { private static final String symbol = Tags.tagDay ; public E_DateTimeDay(Expr expr) { super(expr, symbol) ; } @Override public NodeValue eval(NodeValue v) { return XSDFuncOp.getDay(v) ; } @Override public Expr copy(Expr expr) { return new E_DateTimeDay(expr) ; } }
package com.example.lwd18.pictureselecotor.textsearch; import android.content.Intent; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import com.alibaba.fastjson.JSON; import com.deepbaytech.deeplibrary.ActivityManager; import com.deepbaytech.deeplibrary.OneKeyClearEditText; import com.deepbaytech.deeplibrary.manager.CacheManager; import com.example.lwd18.pictureselecotor.ApiConstants; import com.example.lwd18.pictureselecotor.BaseDeepActivity; import com.example.lwd18.pictureselecotor.FlowLayout; import com.example.lwd18.pictureselecotor.PopularText; import com.example.lwd18.pictureselecotor.R; import com.example.lwd18.pictureselecotor.dialog.ConfirmDialog; import com.example.lwd18.pictureselecotor.event.SearchHistoryEvent; import com.example.lwd18.pictureselecotor.textsearch.Eventutil.SearchEvent; import com.zhy.http.okhttp.OkHttpUtils; import com.zhy.http.okhttp.callback.StringCallback; import de.greenrobot.event.EventBus; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import okhttp3.Call; public class DuTextSearchActivity extends BaseDeepActivity { @BindView(R.id.et_search) OneKeyClearEditText etSearch; @BindView(R.id.tv_search_back) TextView tvSearchBack; @BindView(R.id.search_toolbar) Toolbar searchToolbar; @BindView(R.id.iv_search_history) ImageView ivSearchHistory; @BindView(R.id.iv_del_history) ImageView ivDelHistory; @BindView(R.id.fl_history) FlowLayout flHistory; @BindView(R.id.iv_search_hot) ImageView ivSearchHot; @BindView(R.id.fl_hot) FlowLayout flHot; @BindView(R.id.ll_search_text_ware) LinearLayout llSearchTextWare; @BindView(R.id.activity_text_search) RelativeLayout activityTextSearch; @BindView(R.id.rl_search_history) RelativeLayout rlSearchHistory; @BindView(R.id.ll_search_history) LinearLayout llSearchHistory; //edit 输入的搜索词 private String query; private List<String> hotList; private List<String> historyList; int fragmentTab; private boolean hisFlag = false; private ConfirmDialog dialog; private int margin; @Override protected void initActivity() { setContentView(R.layout.activity_text_search); ButterKnife.bind(this); EventBus.getDefault().register(this); fragmentTab = getIntent().getIntExtra("fragmentTab", 0); initToolBar(); initFlowLayout(); } private void initFlowLayout() { OkHttpUtils.get() .url(ApiConstants.POPULAR_TEXT) .addParams("type",1+"") .build().execute(new StringCallback() { @Override public void onError(Call call, Exception e, int id) { } @Override public void onResponse(String response, int id) { PopularText popularText = JSON.parseObject(response, PopularText.class); if (popularText.getState() == 0) { hotList = popularText.getData().getTexts(); addChildText(flHot, hotList); } } }); historyList = CacheManager.getInstance().getSearchHistory(); if (historyList != null && historyList.size() > 0) { rlSearchHistory.setVisibility(View.VISIBLE); llSearchHistory.setVisibility(View.VISIBLE); hisFlag = true; addChildText(flHistory, historyList); } } /** * * @param flowLayout * @param list */ private void addChildText(FlowLayout flowLayout, List<String> list) { if (list != null) { Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { String text = iterator.next(); addText(flowLayout, text, false); } } } /** * 向FlowLayout中添加数据 * xx 是否添加在最前面 */ private void addText(FlowLayout flowLayout, String text, boolean xx) { final TextView tvChild = (TextView) LayoutInflater.from(this) .inflate(R.layout.view_textview_flowflag, flowLayout, false); tvChild.setText(text); tvChild.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String flowKey = tvChild.getText().toString(); EventBus.getDefault().post(new SearchHistoryEvent(flowKey)); } }); if (xx) { flowLayout.addView(tvChild, 0); } else { flowLayout.addView(tvChild); } } /** * Toolbar * OneKeyClearEditText */ private void initToolBar() { searchToolbar.setTitle(""); setSupportActionBar(searchToolbar); if (getIntent() != null && getIntent().getStringExtra("searchKey") != null) { String searchKey = getIntent().getStringExtra("searchKey"); etSearch.setText(searchKey); etSearch.setSelection(searchKey.length()); } etSearch.setImeOptions(EditorInfo.IME_ACTION_SEARCH); etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEARCH) { query = etSearch.getText().toString().trim(); if (!query.isEmpty()) { EventBus.getDefault().post(new SearchEvent(query)); //goTextSearchResultActivity(query); } else { EventBus.getDefault().post(new SearchEvent(etSearch.getHint().toString())); } } return false; } }); } private void goTextSearchResultActivity(String query) { //1.0版本的搜索结果页面(先注销掉) //Intent intent = new Intent(DuTextSearchActivity.this, TextSearchResultActivity.class); Intent intent = new Intent(DuTextSearchActivity.this, ProductDetailActivity.class); intent.putExtra("searchKey", query); startActivity(intent); } /** * 获取搜索历史 */ private void initSearchHistory(List<String> list) { if (list != null && list.size() > 0) { rlSearchHistory.setVisibility(View.VISIBLE); llSearchHistory.setVisibility(View.VISIBLE); hisFlag = true; } else { rlSearchHistory.setVisibility(View.GONE); llSearchHistory.setVisibility(View.GONE); hisFlag = false; } } /** * 删除搜索历史 */ private void clearSearchHistory() { CacheManager.getInstance().saveSearchHistory(null); initSearchHistory(null); } /** * 先添加flowlayout * 后保存搜索历史 */ private void saveSearchHistory(String query) { List<String> list = CacheManager.getInstance().getSearchHistory(); boolean flag = false; if (list == null) { list = new ArrayList<>(); list.add(0, query); } else { Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { String item = iterator.next(); if (TextUtils.equals(query, item)) { iterator.remove(); flag = true; } } list.add(0, query); } if (flag == false) { addText(flHistory, query, true); } int size = list.size(); if (size > 10) { // 最多保存20条 for (int i = size - 1; i >= 10; i--) { list.remove(i); } } CacheManager.getInstance().saveSearchHistory(list); initSearchHistory(list); goTextSearchResultActivity(query); } /** * 点击flowlayout */ public void onEvent(SearchHistoryEvent event) { etSearch.setText(event.getMsg()); etSearch.setSelection(event.getMsg().toString().length()); saveSearchHistory(event.getMsg()); } /** * 键盘搜索按钮 */ public void onEvent(SearchEvent event) { //去重 //List<String> list = CacheManager.getInstance().getSearchHistory(); //Iterator<String> iterator = list.iterator(); //boolean flag = false; //while (iterator.hasNext()) { // String item = iterator.next(); // if (TextUtils.equals(event.getMsg(), item)) { // flag = true; // } //} //if (flag == false) { // addText(flHistory, event.getMsg()); //} saveSearchHistory(event.getMsg()); } @OnClick({ R.id.tv_search_back, R.id.iv_del_history }) public void onClick(View view) { switch (view.getId()) { case R.id.tv_search_back: //Intent intent = new Intent(DuTextSearchActivity.this, MainActivity.class); //intent.putExtra("currentTab", fragmentTab); //startActivity(intent); ActivityManager.getInstance().finishActivity(DuTextSearchActivity.class); break; //删除搜索历史 case R.id.iv_del_history: dialog = new ConfirmDialog(DuTextSearchActivity.this); dialog.setOnDeepConfirmListener(new ConfirmDialog.DeepConfirmListener() { @Override public void onSelectCancel() { dialog.dismiss(); } @Override public void onSelectEnsure() { clearSearchHistory(); flHistory.removeAllViews(); dialog.dismiss(); } }); dialog.show(); break; } } @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } /** * 该方法回调时机为,Activity回退栈内Fragment的数量 小于等于1 时,默认finish Activity * 请尽量复写该方法,避免复写onBackPress(),以保证SupportFragment内的onBackPressedSupport()回退事件正常执行 */ @Override public void onBackPressedSupport() { super.onBackPressedSupport(); } }
/** * Copyright (C) 2006-2021 Talend Inc. - www.talend.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.talend.test; import java.io.Serializable; import javax.json.JsonBuilderFactory; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import org.talend.sdk.component.api.processor.ElementListener; import org.talend.sdk.component.api.processor.Input; import org.talend.sdk.component.api.processor.Output; import org.talend.sdk.component.api.processor.OutputEmitter; import org.talend.sdk.component.api.processor.Processor; @Processor(family = "processor", name = "concat") public class ConcatProcessor implements Serializable { private final JsonBuilderFactory factory; public ConcatProcessor(JsonBuilderFactory factory) { this.factory = factory; } @ElementListener public void cat(@Input("str1") final JsonObject str1, @Input("str2") final JsonObject str2, @Output final OutputEmitter<JsonObject> concat) { if (str1 == null && str2 == null) { return; } final JsonObjectBuilder builder = factory.createObjectBuilder(); if (str1 != null) { str1.keySet().forEach(k -> builder.add(k, str1.get(k))); } if (str2 != null) { str2.keySet().forEach(k -> builder.add(k, str2.get(k))); } concat.emit(builder.build()); } }
/** * Copyright 2014 PubNative GmbH * * 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.pubnative.interstitials.widget; import static org.droidparts.util.ui.ViewUtils.setGone; import net.pubnative.interstitials.R; import net.pubnative.interstitials.util.ScreenUtil; import android.content.Context; import android.content.res.Configuration; import android.util.AttributeSet; import android.view.View; import android.widget.LinearLayout; public class InterstitialView extends LinearLayout { private View descriptionView; public InterstitialView(Context ctx) { super(ctx); init(); } public InterstitialView(Context ctx, AttributeSet attrs) { super(ctx, attrs); init(); } public InterstitialView(Context ctx, AttributeSet attrs, int defStyle) { super(ctx, attrs, defStyle); init(); } private void init() { inflate(getContext(), R.layout.pn_view_interstitial, this); descriptionView = findViewById(R.id.view_description); setBackgroundColor(getResources().getColor(android.R.color.white)); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); applyOrientation(); } @Override protected void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); applyOrientation(); } private void applyOrientation() { boolean isPortrait = ScreenUtil.isPortrait(getContext()); setGone(!isPortrait, descriptionView); } }
/** * Copyright 2014 * SMEdit https://github.com/StarMade/SMEdit * SMTools https://github.com/StarMade/SMTools * * 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 jo.sm.plugins.planet.gen; import jo.sm.data.BlockTypes; import jo.sm.ui.act.plugin.Description; /** * @Auther Jo Jaquinta for SMEdit Classic - version 1.0 **/ @Description(displayName = "Giant's Causeway", shortDescription = "Create a hexagonal slab like surface.") public class UndulatingParameters { @Description(displayName = "", shortDescription = "Planetary radius") private int mPlanetRadius; @Description(displayName = "", shortDescription = "Tallest point above baseline (-ve for below)") private int mPlanetHeight; @Description(displayName = "", shortDescription = "Block type to fill with") private short mFillWith; public UndulatingParameters() { mPlanetRadius = 250; mPlanetHeight = 32; mFillWith = BlockTypes.TERRAIN_ROCK_ID; } public int getPlanetRadius() { return mPlanetRadius; } public void setPlanetRadius(int planetRadius) { mPlanetRadius = planetRadius; } public int getPlanetHeight() { return mPlanetHeight; } public void setPlanetHeight(int planetHeight) { mPlanetHeight = planetHeight; } public short getFillWith() { return mFillWith; } public void setFillWith(short fillWith) { mFillWith = fillWith; } }
package com.microsoft.kiota.serialization; import javax.annotation.Nonnull; /** Defines the contract for a factory that creates SerializationWriter instances. */ public interface SerializationWriterFactory { /** * Gets the content type this factory creates serialization writers for. * @return the content type this factory creates serialization writers for. */ @Nonnull String getValidContentType(); /** * Creates a new SerializationWriter instance for the given content type. * @param contentType the content type to create a serialization writer for. * @return a new SerializationWriter instance for the given content type. */ @Nonnull SerializationWriter getSerializationWriter(@Nonnull final String contentType); }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math3.util; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.exception.OutOfRangeException; import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.junit.Assert; import org.junit.Test; /** * */ public class MultidimensionalCounterTest { @Test public void testPreconditions() { MultidimensionalCounter c; try { c = new MultidimensionalCounter(0, 1); Assert.fail("NotStrictlyPositiveException expected"); } catch (NotStrictlyPositiveException e) { // Expected. } try { c = new MultidimensionalCounter(2, 0); Assert.fail("NotStrictlyPositiveException expected"); } catch (NotStrictlyPositiveException e) { // Expected. } try { c = new MultidimensionalCounter(-1, 1); Assert.fail("NotStrictlyPositiveException expected"); } catch (NotStrictlyPositiveException e) { // Expected. } c = new MultidimensionalCounter(2, 3); try { c.getCount(1, 1, 1); Assert.fail("DimensionMismatchException expected"); } catch (DimensionMismatchException e) { // Expected. } try { c.getCount(3, 1); Assert.fail("OutOfRangeException expected"); } catch (OutOfRangeException e) { // Expected. } try { c.getCount(0, -1); Assert.fail("OutOfRangeException expected"); } catch (OutOfRangeException e) { // Expected. } try { c.getCounts(-1); Assert.fail("OutOfRangeException expected"); } catch (OutOfRangeException e) { // Expected. } try { c.getCounts(6); Assert.fail("OutOfRangeException expected"); } catch (OutOfRangeException e) { // Expected. } } @Test public void testIteratorPreconditions() { MultidimensionalCounter.Iterator iter = (new MultidimensionalCounter(2, 3)).iterator(); try { iter.getCount(-1); Assert.fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) { // Expected. } try { iter.getCount(2); Assert.fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) { // Expected. } } @Test public void testMulti2UniConversion() { final MultidimensionalCounter c = new MultidimensionalCounter(2, 4, 5); Assert.assertEquals(c.getCount(1, 2, 3), 33); } @Test public void testAccessors() { final int[] originalSize = new int[] {2, 6, 5}; final MultidimensionalCounter c = new MultidimensionalCounter(originalSize); final int nDim = c.getDimension(); Assert.assertEquals(nDim, originalSize.length); final int[] size = c.getSizes(); for (int i = 0; i < nDim; i++) { Assert.assertEquals(originalSize[i], size[i]); } } @Test public void testIterationConsistency() { final MultidimensionalCounter c = new MultidimensionalCounter(2, 3, 4); final int[][] expected = new int[][] { { 0, 0, 0 }, { 0, 0, 1 }, { 0, 0, 2 }, { 0, 0, 3 }, { 0, 1, 0 }, { 0, 1, 1 }, { 0, 1, 2 }, { 0, 1, 3 }, { 0, 2, 0 }, { 0, 2, 1 }, { 0, 2, 2 }, { 0, 2, 3 }, { 1, 0, 0 }, { 1, 0, 1 }, { 1, 0, 2 }, { 1, 0, 3 }, { 1, 1, 0 }, { 1, 1, 1 }, { 1, 1, 2 }, { 1, 1, 3 }, { 1, 2, 0 }, { 1, 2, 1 }, { 1, 2, 2 }, { 1, 2, 3 } }; final int totalSize = c.getSize(); final int nDim = c.getDimension(); final MultidimensionalCounter.Iterator iter = c.iterator(); for (int i = 0; i < totalSize; i++) { if (!iter.hasNext()) { Assert.fail("Too short"); } final int uniDimIndex = iter.next().intValue(); Assert.assertEquals("Wrong iteration at " + i, i, uniDimIndex); for (int dimIndex = 0; dimIndex < nDim; dimIndex++) { Assert.assertEquals("Wrong multidimensional index for [" + i + "][" + dimIndex + "]", expected[i][dimIndex], iter.getCount(dimIndex)); } Assert.assertEquals("Wrong unidimensional index for [" + i + "]", c.getCount(expected[i]), uniDimIndex); final int[] indices = c.getCounts(uniDimIndex); for (int dimIndex = 0; dimIndex < nDim; dimIndex++) { Assert.assertEquals("Wrong multidimensional index for [" + i + "][" + dimIndex + "]", expected[i][dimIndex], indices[dimIndex]); } } if (iter.hasNext()) { Assert.fail("Too long"); } } }
package com.tomaschlapek.portfolio; import android.app.Application; import com.squareup.leakcanary.LeakCanary; import timber.log.Timber; import timber.log.Timber.DebugTree; public class AndroidApplication extends Application { @Override public void onCreate() { super.onCreate(); // initiate Timber Timber.plant(new DebugTree()); LeakCanary.install(this); } }
package game.item; import util.BmpRes; import game.entity.Entity; public class DefendBullet extends Bullet{ private static final long serialVersionUID=1844677L; static BmpRes bmp=new BmpRes("Item/DefendBullet"); public BmpRes getBmp(){return bmp;} public int maxAmount(){return 999;} @Override public double attackValue(){return 2;} @Override public double mass(){return 0.05;} @Override public double RPG_ExplodeProb(){return 0.1;} };
/* * Copyright 2002-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 com.phoenixnap.oss.ramlplugin.raml2code.raml; import java.util.List; import java.util.Map; import org.raml.v2.api.model.v10.declarations.AnnotationRef; /** * Abstract Representation of a Raml Action * * @author armin.weisser * @since 0.8.1 */ public interface RamlAction { RamlActionType getType(); Map<String, RamlQueryParameter> getQueryParameters(); Map<String, RamlResponse> getResponses(); RamlResource getResource(); Map<String, RamlHeader> getHeaders(); Map<String, RamlMimeType> getBody(); boolean hasBody(); String getDescription(); String getDisplayName(); List<RamlSecurityReference> getSecuredBy(); List<AnnotationRef> getAnnotations(); }
package enginecrafter77.survivalinc.season; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.world.DimensionType; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeEnd; import net.minecraft.world.biome.BiomeHell; import net.minecraft.world.biome.BiomeOcean; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.EntityJoinWorldEvent; import net.minecraftforge.event.world.WorldEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import java.util.function.Predicate; import enginecrafter77.survivalinc.SurvivalInc; public class SeasonController { private static final Predicate<Integer> isDimOverworld = (Integer dimID) -> dimID == DimensionType.OVERWORLD.getId(); private static final Predicate<World> isOverworld = (World world) -> isDimOverworld.test(world.provider.getDimension()); /** The length of one full minecraft day/night cycle */ public static final int minecraftDayLength = 24000; /** The season controller singleton */ public static final SeasonController instance = new SeasonController(); /** The biome temperature controller instance */ public BiomeTempController biomeTemp; public SeasonCalendar calendar; private SeasonController() { try { this.calendar = new SeasonCalendar(); this.biomeTemp = new BiomeTempController(); this.biomeTemp.excluded.add(BiomeOcean.class); this.biomeTemp.excluded.add(BiomeHell.class); this.biomeTemp.excluded.add(BiomeEnd.class); } catch(NoSuchFieldException exc) { RuntimeException nexc = new RuntimeException(); nexc.initCause(exc); throw nexc; } } @SideOnly(Side.CLIENT) public static IMessage onSyncDelivered(SeasonSyncMessage message, MessageContext ctx) { WorldClient world = Minecraft.getMinecraft().world; if(world == null) SurvivalInc.logger.error("Minecraft remote world tracking instance is null. This is NOT a good thing. Season sync packet dropped..."); else if(SeasonController.isOverworld.negate().test(world)) throw new RuntimeException("Received a stat update message from outside overworld."); else { SurvivalInc.logger.info("Updating client's world season data to {}...", message.data.toString()); world.setData(SeasonData.datakey, message.data); MinecraftForge.EVENT_BUS.post(new SeasonChangedEvent(world, message.data.getCurrentDate())); SurvivalInc.logger.info("Client-side season update to {} completed.", message.data.toString()); } return null; } public static SeasonSyncMessage onSyncRequest(SeasonSyncRequest message, MessageContext ctx) { EntityPlayerMP player = ctx.getServerHandler().player; SeasonData data = SeasonData.load(player.world); SurvivalInc.logger.info("Sending season data ({}) to player \"{}\" entering overworld.", data.toString(), player.getDisplayNameString()); return new SeasonSyncMessage(data); } /** * Sends the season data to new players in overworld * @param event The player logged in event */ @SubscribeEvent public void onPlayerJoined(EntityJoinWorldEvent event) { World world = event.getWorld(); Entity ent = event.getEntity(); if(ent instanceof EntityPlayer && world.isRemote && isOverworld.test(world)) { SurvivalInc.logger.info("Requesting season data from server..."); SurvivalInc.proxy.net.sendToServer(new SeasonSyncRequest()); } } /** * Load the season data from disk on server side. * @param event The world load event */ @SubscribeEvent public void loadSeasonData(WorldEvent.Load event) { World world = event.getWorld(); if(!world.isRemote && SeasonController.isOverworld.test(world)) MinecraftForge.EVENT_BUS.post(new SeasonChangedEvent(world)); } /** * Updates the season data on server. Unfortunately, * this method won't work for clients. * @param event The world tick event */ @SubscribeEvent public void onUpdate(TickEvent.WorldTickEvent event) { if(event.side == Side.SERVER && event.phase == TickEvent.Phase.START && SeasonController.isOverworld.test(event.world)) { // Is it early morning? Also, before the player really joins, some time passes. Give the player some time to actually receive the update. if(event.world.getWorldTime() % SeasonController.minecraftDayLength == 1200) { SurvivalInc.logger.info("Season update triggered on {}", event.side.name()); SeasonData data = SeasonData.load(event.world); data.getCurrentDate().advance(1); data.markDirty(); SurvivalInc.proxy.net.sendToDimension(new SeasonSyncMessage(data), DimensionType.OVERWORLD.getId()); // Synchronize the data with clients, so they begin processing on their side MinecraftForge.EVENT_BUS.post(new SeasonChangedEvent(event.world, data.getCurrentDate())); // Broadcast and process the event on server side } } } /** * Capture the season update event and apply biome temperatures * @param event The season changed event */ @SubscribeEvent public void applySeasonData(SeasonChangedEvent event) { event.date.getCalendarEntry().getSeason().applySeason(event.getWorld(), event.date.getDay()); this.biomeTemp.applySeason(event.date); SurvivalInc.logger.info("Applied biome temperatures for season {}", event.date.toString()); } /* * Determines the color of the grass in the said biome * @param event The grass color event * @SubscribeEvent @SideOnly(Side.CLIENT) public void biomeGrass(BiomeEvent.GetGrassColor event) { Range<Float> temperature_range = this.calendar.getTemperatureRange(); float deftemp = event.getBiome().getDefaultTemperature(); // If the current biome is permafrost if((deftemp + temperature_range.upperEndpoint()) < 0F) event.setNewColor(0x5BAE92); else if((deftemp + temperature_range.lowerEndpoint()) > 1F) event.setNewColor(0xCAE24E); }*/ /* * Make nothing grow in winter, and let crops grow faster in summer * @param event * @SubscribeEvent public void affectGrowth(BlockEvent.CropGrowEvent.Pre event) { World world = event.getWorld(); if(world.isRemote) return; // We don't want to check client side SeasonData data = SeasonData.load(world); Event.Result result = Event.Result.DEFAULT; if(!data.getCurrentDate().getCalendarEntry().getSeason().allowCropGrowth()) result = Event.Result.DENY; event.setResult(result); }*/ }
package io.mercury.transport.zmq.exception; public final class ZmqBindException extends RuntimeException { /** * */ private static final long serialVersionUID = -4110788670578471831L; public ZmqBindException(String addr) { super("Unable to bind -> " + addr); } }
// // Decompiled by Procyon v0.5.36 // package pro.streem.ar.schemas.sceneform; import pro.streem.flatbuffers.FlatBufferBuilder; import java.nio.ByteOrder; import java.nio.ByteBuffer; import pro.streem.flatbuffers.Table; public final class MaterialDef extends Table { public static MaterialDef getRootAsMaterialDef(final ByteBuffer _bb) { return getRootAsMaterialDef(_bb, new MaterialDef()); } public static MaterialDef getRootAsMaterialDef(final ByteBuffer _bb, final MaterialDef obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb); } public void __init(final int _i, final ByteBuffer _bb) { this.bb_pos = _i; this.bb = _bb; this.vtable_start = this.bb_pos - this.bb.getInt(this.bb_pos); this.vtable_size = this.bb.getShort(this.vtable_start); } public MaterialDef __assign(final int _i, final ByteBuffer _bb) { this.__init(_i, _bb); return this; } public ParameterDef parameters(final int j) { return this.parameters(new ParameterDef(), j); } public ParameterDef parameters(final ParameterDef obj, final int j) { final int o = this.__offset(4); return (o != 0) ? obj.__assign(this.__indirect(this.__vector(o) + j * 4), this.bb) : null; } public int parametersLength() { final int o = this.__offset(4); return (o != 0) ? this.__vector_len(o) : 0; } public int compiledIndex() { final int o = this.__offset(6); return (o != 0) ? (this.bb.get(o + this.bb_pos) & 0xFF) : 0; } public String name() { final int o = this.__offset(8); return (o != 0) ? this.__string(o + this.bb_pos) : null; } public ByteBuffer nameAsByteBuffer() { return this.__vector_as_bytebuffer(8, 1); } public ByteBuffer nameInByteBuffer(final ByteBuffer _bb) { return this.__vector_in_bytebuffer(_bb, 8, 1); } public static int createMaterialDef(final FlatBufferBuilder builder, final int parametersOffset, final int compiled_index, final int nameOffset) { builder.startObject(3); addName(builder, nameOffset); addParameters(builder, parametersOffset); addCompiledIndex(builder, compiled_index); return endMaterialDef(builder); } public static void startMaterialDef(final FlatBufferBuilder builder) { builder.startObject(3); } public static void addParameters(final FlatBufferBuilder builder, final int parametersOffset) { builder.addOffset(0, parametersOffset, 0); } public static int createParametersVector(final FlatBufferBuilder builder, final int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; --i) { builder.addOffset(data[i]); } return builder.endVector(); } public static void startParametersVector(final FlatBufferBuilder builder, final int numElems) { builder.startVector(4, numElems, 4); } public static void addCompiledIndex(final FlatBufferBuilder builder, final int compiledIndex) { builder.addByte(1, (byte)compiledIndex, 0); } public static void addName(final FlatBufferBuilder builder, final int nameOffset) { builder.addOffset(2, nameOffset, 0); } public static int endMaterialDef(final FlatBufferBuilder builder) { final int o = builder.endObject(); return o; } }
/* * This source file is part of Cube. * * The MIT License (MIT) * * Copyright (c) 2020-2021 Shixin Cube Team. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package cube.common.entity; import cell.util.Utils; import cube.common.Domain; import cube.util.FileType; import cube.util.FileUtils; import org.json.JSONObject; /** * 文件标签。 */ public class FileLabel extends Entity { /** * 文件所有人 ID 。 */ private Long ownerId; /** * 文件名。 */ private String fileName; /** * 文件大小。 */ private long fileSize; /** * 文件最后修改时间。 */ private long lastModified; /** * 文件的完成时间。 */ private long completedTime; /** * 文件的到期时间。 */ private long expiryTime; /** * 文件访问码。 */ private String fileCode; /** * 文件类型。 */ private FileType fileType = FileType.UNKNOWN; /** * 文件 MD5 码。 */ private String md5Code; /** * 文件 SHA1 码。 */ private String sha1Code; /** * 访问文件的 HTTP URL 。 */ private String fileURL; /** * 访问文件的 HTTPS URL 。 */ private String fileSecureURL; /** * 内部服务的直接访问 URL 。 */ private String directURL; /** * 构造函数。 * * @param domainName 域名称。 * @param fileCode 文件码。 * @param ownerId 文件所有人 ID 。 * @param fileName 文件名。 * @param fileSize 文件大小。 * @param lastModified 文件最后修改时间。 * @param completedTime 文件进入系统的时间。 * @param expiryTime 文件的到期时间。 */ public FileLabel(String domainName, String fileCode, Long ownerId, String fileName, long fileSize, long lastModified, long completedTime, long expiryTime) { super(Utils.generateSerialNumber(), domainName); this.uniqueKey = fileCode; // Unique Key 设置为文件码 this.fileCode = fileCode; this.ownerId = ownerId; this.fileName = fileName; this.fileSize = fileSize; this.lastModified = lastModified; this.completedTime = completedTime; this.expiryTime = expiryTime; } /** * 构造函数。 * * @param id 文件标签 ID 。 * @param domainName 域名称。 * @param fileCode 文件码。 * @param ownerId 文件所有人 ID 。 * @param fileName 文件名。 * @param fileSize 文件大小。 * @param completedTime 文件进入系统的时间。 * @param expiryTime 文件的到期时间。 */ public FileLabel(Long id, String domainName, String fileCode, Long ownerId, String fileName, long fileSize, long lastModified, long completedTime, long expiryTime) { super(id, domainName); this.uniqueKey = fileCode; // Unique Key 设置为文件码 this.fileCode = fileCode; this.ownerId = ownerId; this.fileName = fileName; this.fileSize = fileSize; this.lastModified = lastModified; this.completedTime = completedTime; this.expiryTime = expiryTime; } /** * 构造函数。 * * @param json 文件标签的 JSON 格式。 */ public FileLabel(JSONObject json) { super(); this.id = json.getLong("id"); this.domain = new Domain(json.getString("domain")); this.fileCode = json.getString("fileCode"); this.ownerId = json.getLong("ownerId"); this.fileName = json.getString("fileName"); this.fileSize = json.getLong("fileSize"); this.completedTime = json.getLong("completed"); this.lastModified = json.has("lastModified") ? json.getLong("lastModified") : this.completedTime; this.expiryTime = json.getLong("expiry"); this.fileType = FileType.matchExtension(json.getString("fileType")); if (json.has("md5")) { this.md5Code = json.getString("md5"); } if (json.has("sha1")) { this.sha1Code = json.getString("sha1"); } if (json.has("fileURL")) { this.fileURL = json.getString("fileURL"); } if (json.has("fileSecureURL")) { this.fileSecureURL = json.getString("fileSecureURL"); } if (json.has("directURL")) { this.directURL = json.getString("directURL"); } this.uniqueKey = this.fileCode; } /** * 获取所有人 ID 。 * * @return 所有人 ID 。 */ public Long getOwnerId() { return this.ownerId; } /** * 获取文件名。 * * @return 返回文件名。 */ public String getFileName() { return this.fileName; } /** * 获取文件大小。 * * @return 返回文件大小。 */ public long getFileSize() { return this.fileSize; } /** * 获取文件最后一次修改时间。 * * @return 返回文件最后一次修改时间。 */ public long getLastModified() { return this.lastModified; } /** * 获取文件完成存储的时间。 * * @return 返回文件完成存储的时间。 */ public long getCompletedTime() { return this.completedTime; } /** * 设置有效期。 * * @param expiryTime 指定有效期。 */ public void setExpiryTime(long expiryTime) { this.expiryTime = expiryTime; } /** * 获取有效期。 * * @return 返回有效期。 */ public long getExpiryTime() { return this.expiryTime; } /** * 获取文件码。 * * @return 返回文件码。 */ public String getFileCode() { return this.fileCode; } /** * 设置文件类型。 * * @param fileType 文件类型。 */ public void setFileType(FileType fileType) { this.fileType = fileType; } /** * 获取文件类型。 * * @return 返回文件类型。 */ public FileType getFileType() { return this.fileType; } /** * 返回文件扩展名。 * * @return 返回文件扩展名。 */ public String getFileExtension() { return FileUtils.extractFileExtension(this.fileName); } /** * 设置 MD5 码。 * * @param md5Code 指定 MD5 码。 */ public void setMD5Code(String md5Code) { this.md5Code = md5Code; } /** * 获取 MD5 码。 * * @return 返回 MD5 码。 */ public String getMD5Code() { return this.md5Code; } /** * 设置 SHA1 码。 * * @param sha1Code 指定 SHA1 码。 */ public void setSHA1Code(String sha1Code) { this.sha1Code = sha1Code; } /** * 获取 SHA1 码。 * * @return 返回 SHA1 码。 */ public String getSHA1Code() { return this.sha1Code; } /** * 设置文件的 URL 访问地址。 * * @param fileURL 指定文件的 URL 访问地址。 * @param fileSecureURL 指定文件的安全 URL 访问地址。 */ public void setFileURLs(String fileURL, String fileSecureURL) { this.fileURL = fileURL; this.fileSecureURL = fileSecureURL; } /** * 获取文件的 URL 访问地址。 * * @return 返回文件的 URL 访问地址。 */ public String getFileURL() { return this.fileURL; } /** * 获取文件的安全 URL 访问地址。 * * @return 返回文件的安全 URL 访问地址。 */ public String getFileSecureURL() { return this.fileSecureURL; } /** * 设置文件的直接 URL 地址。 * * @param url 指定 URL 。 */ public void setDirectURL(String url) { this.directURL = url; } /** * 获取文件的直接 URL 地址。 * * @return 返回文件的直接 URL 地址。 */ public String getDirectURL() { return this.directURL; } @Override public boolean equals(Object object) { if (null != object && object instanceof FileLabel) { FileLabel other = (FileLabel) object; if (other.fileCode.equals(this.fileCode)) { return true; } } return false; } /** * {@inheritDoc} */ @Override public JSONObject toJSON() { JSONObject json = new JSONObject(); json.put("id", this.id); json.put("domain", this.domain.getName()); json.put("fileCode", this.fileCode); json.put("ownerId", this.ownerId); json.put("fileName", this.fileName); json.put("fileSize", this.fileSize); json.put("lastModified", this.lastModified); json.put("completed", this.completedTime); json.put("expiry", this.expiryTime); json.put("fileType", this.fileType.getPreferredExtension()); if (null != this.md5Code) { json.put("md5", this.md5Code); } if (null != this.sha1Code) { json.put("sha1", this.sha1Code); } if (null != this.fileURL) { json.put("fileURL", this.fileURL); } if (null != this.fileSecureURL) { json.put("fileSecureURL", this.fileSecureURL); } if (null != this.directURL) { json.put("directURL", this.directURL); } return json; } /** * {@inheritDoc} */ @Override public JSONObject toCompactJSON() { JSONObject json = this.toJSON(); if (json.has("directURL")) { json.remove("directURL"); } return json; } }
/* * Copyright 2017-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.yang.runtime.impl.serializerhelper; import org.junit.Test; import org.onosproject.yang.model.DataNode; import org.onosproject.yang.model.InnerNode; import org.onosproject.yang.model.KeyLeaf; import org.onosproject.yang.model.ListKey; import org.onosproject.yang.model.NodeKey; import org.onosproject.yang.model.ResourceId; import org.onosproject.yang.runtime.HelperContext; import org.onosproject.yang.runtime.impl.TestYangSerializerContext; import java.io.IOException; import java.util.Iterator; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.onosproject.yang.model.DataNode.Type.MULTI_INSTANCE_LEAF_VALUE_NODE; import static org.onosproject.yang.model.DataNode.Type.MULTI_INSTANCE_NODE; import static org.onosproject.yang.model.DataNode.Type.SINGLE_INSTANCE_LEAF_VALUE_NODE; import static org.onosproject.yang.model.DataNode.Type.SINGLE_INSTANCE_NODE; import static org.onosproject.yang.runtime.SerializerHelper.addDataNode; import static org.onosproject.yang.runtime.SerializerHelper.exitDataNode; import static org.onosproject.yang.runtime.SerializerHelper.getModuleNameFromNameSpace; import static org.onosproject.yang.runtime.SerializerHelper.getResourceId; import static org.onosproject.yang.runtime.SerializerHelper.initializeDataNode; import static org.onosproject.yang.runtime.impl.TestUtils.LNS; import static org.onosproject.yang.runtime.impl.TestUtils.L_NAME; import static org.onosproject.yang.runtime.impl.TestUtils.validateDataNode; import static org.onosproject.yang.runtime.impl.TestUtils.validateLeafDataNode; import static org.onosproject.yang.runtime.impl.TestUtils.validateResourceId; import static org.onosproject.yang.runtime.impl.TestUtils.walkINTree; /** * Tests the serializer helper methods. */ public class AddToDataNodeListTest { TestYangSerializerContext context = new TestYangSerializerContext(); /* * Reference for data node info. */ HelperContext info; /* * Reference for data node builder. */ DataNode.Builder dBlr; /* * Reference for resource id. */ ResourceId id; /* * Reference for the value. */ String value; /* * Reference for string array to used for resource id testing. */ String[] nA; String[] nsA; String[] valA; private static final String[] EXPECTED = { "Entry Node is /.", "Entry Node is l1.", "Entry Node is k1.", "Exit Node is k1.", "Entry Node is k2.", "Exit Node is k2.", "Entry Node is c1.", "Entry Node is leaf_c1.", "Exit Node is leaf_c1.", "Exit Node is c1.", "Entry Node is k3.", "Exit Node is k3.", "Exit Node is l1.", "Entry Node is leaf1.", "Exit Node is leaf1.", "Entry Node is leaf1.", "Exit Node is leaf1.", "Entry Node is leaf1.", "Exit Node is leaf1.", "Entry Node is leaf1.", "Exit Node is leaf1.", "Exit Node is /." }; /** * Test get module name from namespace. */ @Test public void getModuleNameTest() { String ns = getModuleNameFromNameSpace(context, LNS); assertEquals(ns, "list"); } /** * Test add to data node builder. */ @Test public void addToDataListTest() throws IOException { ResourceId id; dBlr = initializeDataNode(context); dBlr = addDataNode(dBlr, "l1", L_NAME, value, null); value = "1"; dBlr = addDataNode(dBlr, "k1", null, value, null); dBlr = exitDataNode(dBlr); value = "2"; dBlr = addDataNode(dBlr, "k2", null, value, null); dBlr = exitDataNode(dBlr); value = null; dBlr = addDataNode(dBlr, "c1", null, value, null); value = "0"; dBlr = addDataNode(dBlr, "leaf_c1", null, value, null); info = (HelperContext) dBlr.appInfo(); id = getResourceId(dBlr); dBlr = exitDataNode(dBlr); ResourceId id1 = getResourceId(dBlr); dBlr = exitDataNode(dBlr); value = "3"; dBlr = addDataNode(dBlr, "k3", null, value, null); info = (HelperContext) dBlr.appInfo(); ResourceId id2 = getResourceId(dBlr); dBlr = exitDataNode(dBlr); dBlr = exitDataNode(dBlr); // Checking leaf list value = "1"; dBlr = addDataNode(dBlr, "leaf1", L_NAME, value, null); dBlr = exitDataNode(dBlr); value = "2"; dBlr = addDataNode(dBlr, "leaf1", L_NAME, value, null); dBlr = exitDataNode(dBlr); value = "3"; dBlr = addDataNode(dBlr, "leaf1", L_NAME, value, null); dBlr = exitDataNode(dBlr); value = null; dBlr = addDataNode(dBlr, "leaf1", L_NAME, value, null); ResourceId id3 = getResourceId(dBlr); dBlr = exitDataNode(dBlr); //Tree validation nA = new String[]{"/", "l1", "k1", "k2", "c1", "leaf_c1"}; nsA = new String[]{null, LNS, LNS, LNS, LNS, LNS}; valA = new String[]{"1", "2", null, "0"}; validateResourceId(nA, nsA, valA, id); nA = new String[]{"/", "l1", "k1", "k2", "c1"}; nsA = new String[]{null, LNS, LNS, LNS, LNS}; valA = new String[]{"1", "2", null}; validateResourceId(nA, nsA, valA, id1); nA = new String[]{"/", "l1", "k1", "k2", "k3"}; nsA = new String[]{null, LNS, LNS, LNS, LNS}; valA = new String[]{"1", "2", "3"}; validateResourceId(nA, nsA, valA, id2); nA = new String[]{"/", "leaf1"}; nsA = new String[]{null, LNS}; valA = new String[]{null}; validateResourceId(nA, nsA, valA, id3); // Validating the data node. DataNode node = dBlr.build(); validateDataNode(node, "/", null, SINGLE_INSTANCE_NODE, true, null); Map<NodeKey, DataNode> childMap = ((InnerNode) node).childNodes(); Iterator<Map.Entry<NodeKey, DataNode>> it = childMap.entrySet().iterator(); Map.Entry<NodeKey, DataNode> n = it.next(); validateDataNode(n.getValue(), "l1", LNS, MULTI_INSTANCE_NODE, true, null); Iterator<KeyLeaf> keyIt = ((ListKey) n.getKey()).keyLeafs().iterator(); validateLeafDataNode(keyIt.next(), "k1", LNS, "1"); validateLeafDataNode(keyIt.next(), "k2", LNS, "2"); validateLeafDataNode(keyIt.next(), "k3", LNS, "3"); Iterator<Map.Entry<NodeKey, DataNode>> it1; it1 = ((InnerNode) n.getValue()).childNodes().entrySet().iterator(); validateDataNode(it1.next().getValue(), "k1", LNS, SINGLE_INSTANCE_LEAF_VALUE_NODE, false, "1"); validateDataNode(it1.next().getValue(), "k2", LNS, SINGLE_INSTANCE_LEAF_VALUE_NODE, false, "2"); DataNode n1 = it1.next().getValue(); validateDataNode(n1, "c1", LNS, SINGLE_INSTANCE_NODE, true, null); validateDataNode(it1.next().getValue(), "k3", LNS, SINGLE_INSTANCE_LEAF_VALUE_NODE, false, "3"); Iterator<Map.Entry<NodeKey, DataNode>> it2; it2 = ((InnerNode) n1).childNodes().entrySet().iterator(); validateDataNode(it2.next().getValue(), "leaf_c1", LNS, SINGLE_INSTANCE_LEAF_VALUE_NODE, false, "0"); validateDataNode(it.next().getValue(), "leaf1", LNS, MULTI_INSTANCE_LEAF_VALUE_NODE, false, "1"); validateDataNode(it.next().getValue(), "leaf1", LNS, MULTI_INSTANCE_LEAF_VALUE_NODE, false, "2"); validateDataNode(it.next().getValue(), "leaf1", LNS, MULTI_INSTANCE_LEAF_VALUE_NODE, false, "3"); validateDataNode(it.next().getValue(), "leaf1", LNS, MULTI_INSTANCE_LEAF_VALUE_NODE, false, null); walkINTree(dBlr.build(), EXPECTED); } }
package eosio.java; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import client.EosApiClientFactory; import client.EosApiRestClient; import client.domain.common.transaction.PackedTransaction; import client.domain.common.transaction.SignedPackedTransaction; import client.domain.common.transaction.TransactionAction; import client.domain.common.transaction.TransactionAuthorization; import client.domain.response.chain.Block; import client.domain.response.chain.ChainInfo; import client.domain.response.chain.transaction.PushedTransaction; /** * Hello world! * */ public class App { public static String walletBaseUrl = "http://127.0.0.1:8899"; public static String chainBaseUrl = "http://127.0.0.1:8888"; public static String historyBaseUrl = "http://127.0.0.1:8888"; /* Create the rest client */ public static EosApiRestClient eosApiRestClient = EosApiClientFactory .newInstance(walletBaseUrl, chainBaseUrl, historyBaseUrl).newRestClient(); /* Get the head block */ public static ChainInfo chainInfo = eosApiRestClient.getChainInfo(); public static Block block = eosApiRestClient.getBlock(eosApiRestClient.getChainInfo().getHeadBlockId()); public static void main(final String[] args) { System.out.println("hello, world"); // readtransaction("236e90f1a1e365c8d7132f7995f27e67a2df23d633c83c9b830b0ef42cdb5503"); // pushtransaction(); } public static void readtransaction(String hash) { String rpc_url = "http://localhost:8888/v1/chain/get_table_rows"; String payload = // "{\"code\": \"hello\",\"table\": \"kvmng\",\"scope\": \"hello\",\"index_position\": \"1\",\"key_type\": \"string\",\"encode_type\": \"string\",\"upper_bound\": \"string\",\"lower_bound\": \"string\"}"; "{\"json\": true,\"code\": \"hello\",\"table\": \"kvmng\",\"scope\": \"hello\",\"index_position\": \"secondary\",\"key_type\": \"sha256\",\"upper_bound\":" + hash + ",\"lower_bound\":" + hash + "}"; try { URL url = new URL(rpc_url); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type","application/json"); con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(payload); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); System.out.println("Response Code : " + responseCode); BufferedReader iny = new BufferedReader(new InputStreamReader(con.getInputStream())); String output; StringBuffer response = new StringBuffer(); while ((output = iny.readLine()) != null) { response.append(output); } iny.close(); //printing result from response //System.out.println(response.toString()); JSONParser parser = new JSONParser(); Object obj = parser.parse( response.toString() ); JSONObject jsonObj = (JSONObject) obj; JSONArray rows = (JSONArray) jsonObj.get("rows"); JSONObject row = (JSONObject) rows.get(0); String value = (String) row.get("value"); //printing value from row System.out.println("value: " + value); } catch(Exception e) { e.printStackTrace(); } } public static void pushtransaction() { /* Create the json array of arguments */ // Map<String, String> map = new HashMap<>(4); // map.put("from", "eosio"); // map.put("to", "jckim"); // map.put("quantity", "1.0000 SYS"); // map.put("memo", ""); // AbiJsonToBin data = eosApiRestClient.abiJsonToBin("eosio.token", "transfer", // map); /* Create Transaction Action Authorization */ final TransactionAuthorization transactionAuthorization = new TransactionAuthorization(); transactionAuthorization.setActor("hello"); transactionAuthorization.setPermission("active"); /* Create Transaction Action */ final TransactionAction transactionAction1 = new TransactionAction(); transactionAction1.setAccount("eosio"); transactionAction1.setName("setcode"); transactionAction1.setData( "00000000001aa36a0000f8070061736d0100000001370b6000017f60027f7f0060037f7f7f017f60027f7f017f60017f0060017e0060027f7e0060000060037e7e7e0060017f017f60027e7e00028e010803656e7610616374696f6e5f646174615f73697a65000003656e760c656f73696f5f617373657274000103656e76066d656d736574000203656e7610726561645f616374696f6e5f64617461000303656e76066d656d637079000203656e76067072696e7473000403656e76067072696e746e000503656e7611656f73696f5f6173736572745f636f6465000603080707080907040a0a0405017001010105030100010616037f014180c0000b7f0041bdc0000b7f0041bdc0000b070901056170706c7900090a9c05070400100b0b9201001008200020015104404280808080808080c0eb00200251044020002001100d054280808080808080c2eb00200251044020002001100e052000428080808080c0ba98d500520440410042808080d9d3b3ed82ef0010070b0b0b05428080808080c0ba98d50020015104404280808080aefadeeaa47f2002510440410042818080d9d3b3ed82ef0010070b0b0b4100100c0b800101037f02400240024002402000450d004100410028028c40200041107622016a220236028c404100410028028440220320006a41076a417871220036028440200241107420004d0d0120014000417f460d020c030b41000f0b4100200241016a36028c40200141016a4000417f470d010b41004190c000100120030f0b20030b3601017f230041106b2200410036020c4100200028020c28020041076a417871220036028440410020003602804041003f0036028c400b02000ba10102047f017e230041106b22022103200224000240024002400240024010002204450d002004418004490d012004100a21020c020b2003420037030841002102200341086a21050c020b20022004410f6a4170716b220224000b2002200410031a20034200370308200341086a2105200441074b0d010b410041b8c00010010b20052002410810041a2003290308210641a9c000100520061006200341106a24000ba10102047f017e230041106b22022103200224000240024002400240024010002204450d002004418004490d012004100a21020c020b2003420037030841002102200341086a21050c020b20022004410f6a4170716b220224000b2002200410031a20034200370308200341086a2105200441074b0d010b410041b8c00010010b20052002410810041a2003290308210641b1c000100520061006200341106a24000b0b4c04004190c0000b216661696c656420746f20616c6c6f636174652070616765730068656c6c6f2c20000041b1c0000b0768656c6c6f32000041b8c0000b0572656164000041000b0440200000"); // transactionAction1.setData(data.getBinargs()); transactionAction1.setAuthorization(Collections.singletonList(transactionAuthorization)); final TransactionAction transactionAction2 = new TransactionAction(); transactionAction2.setAccount("eosio"); transactionAction2.setName("setabi"); transactionAction2.setData( "00000000001aa36a4f0e656f73696f3a3a6162692f312e31000202686900010475736572046e616d650368693200010475736572046e616d6502000000000000806b02686900000000000000846b03686932000000000000"); // transactionAction2.setData(data.getBinargs()); transactionAction2.setAuthorization(Collections.singletonList(transactionAuthorization)); final String expiration = ZonedDateTime.now(ZoneId.of("GMT")).plusMinutes(3).truncatedTo(ChronoUnit.SECONDS) .format(DateTimeFormatter.ISO_LOCAL_DATE_TIME); /* Create a transaction */ final PackedTransaction packedTransaction = new PackedTransaction(); packedTransaction.setExpiration(expiration); packedTransaction.setRefBlockNum(block.getBlockNum().toString()); packedTransaction.setRefBlockPrefix(block.getRefBlockPrefix().toString()); packedTransaction.setMax_net_usage_words("0"); packedTransaction.setRegion("0"); // packedTransaction.setActions(Collections.singletonList(transactionAction)); final List<TransactionAction> actions = new ArrayList<TransactionAction>(); actions.add(transactionAction1); actions.add(transactionAction2); packedTransaction.setActions(actions); /* Sign the Transaction */ final SignedPackedTransaction signedPackedTransaction = eosApiRestClient.signTransaction(packedTransaction, Collections.singletonList("EOS6MRyAjQq8ud7hVNYcfnVPJqcVpscN5So8BhtHuGYqET5GDW5CV"), chainInfo.getChainId()); /* Push the transaction */ final PushedTransaction pushedTransaction = eosApiRestClient.pushTransaction("none", signedPackedTransaction); System.out.println(pushedTransaction.toString()); } }
/** * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. * */ package org.waveprotocol.wave.client.scroll; import com.google.common.annotations.VisibleForTesting; /** * A target-based scroller that tries to be smart by making aesthetically * pleasing viewport movements. * * @param <M> type of target entities to which this scroller can move */ public final class SmartScroller<M> implements TargetScroller<M> { /** * Defines how to move the viewport between two extents. */ enum ScrollStrategy { SMART { @Override double move(Extent from, Extent target, Extent viewport) { // Constraints: // 0. The target top must end up in the viewport. // 1. The target region must be maximally within the viewport (no // viewport shift could include more of the target). // 2. If the target is already enclosed by the viewport, there is no // movement. // 3. If it is a valid location by the other constraints, the target // must appear at the viewport location of the previously focused // target. // Otherwise, the viewport should be moved minimally to bring the target // to a valid location. // Constraint 0 determines an initial range. double minStart = target.getEnd() - viewport.getSize(); double maxStart = target.getStart(); // Target too big? if (minStart >= maxStart) { // Constraint 1 determines the answer. return maxStart; } // Already valid? if (minStart <= viewport.getStart() && viewport.getStart() <= maxStart) { // Contraint 2 determines the answer. return viewport.getStart(); } // Is previous location good? if (from != null) { double stableStart = viewport.getStart() + target.getStart() - from.getStart(); if (minStart <= stableStart && stableStart <= maxStart) { // Constraint 3 determines the answer. return stableStart; } } // Pick minimal movement. We know current viewport start is either // before the min or after the max. if (viewport.getStart() < minStart) { return minStart; } else { assert viewport.getStart() > maxStart; return maxStart; } } }, // Other strategies may turn up over time. ; /** * @param from location of the previously focused target, or {@code null} * @param target location of the new target (never {@code null}) * @param viewport location of the viewport (never {@code null}) * @return the new viewport location for a shift from previously focused * {@code from} to new target {@code to}, with current viewport * location of {@code viewport}. */ abstract double move(Extent from, Extent target, Extent viewport); } private final ScrollPanel<? super M> scroller; /** Last element brought in to view. Used for smart scrolling. */ private M previousTarget; @VisibleForTesting SmartScroller(ScrollPanel<? super M> scroller) { this.scroller = scroller; } /** * Creates a smart scroller for a scroll panel. */ public static <M> SmartScroller<M> create(ScrollPanel<? super M> panel) { return new SmartScroller<M>(panel); } @Override public void moveTo(M target) { ScrollStrategy style = ScrollStrategy.SMART; Extent from = previousTarget != null ? scroller.extentOf(previousTarget) : null; Extent to = scroller.extentOf(target); Extent viewport = scroller.getViewport(); scroller.moveTo(style.move(from, to, viewport)); previousTarget = target; } }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.test.rest.spec; import com.google.common.collect.Maps; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Represents an elasticsearch REST endpoint (api) */ public class RestApi { private final String name; private List<String> methods = new ArrayList<>(); private List<String> paths = new ArrayList<>(); private List<String> pathParts = new ArrayList<>(); private List<String> params = new ArrayList<>(); private BODY body = BODY.NOT_SUPPORTED; public static enum BODY { NOT_SUPPORTED, OPTIONAL, REQUIRED } RestApi(String name) { this.name = name; } public String getName() { return name; } public List<String> getMethods() { return methods; } /** * Returns the supported http methods given the rest parameters provided */ public List<String> getSupportedMethods(Set<String> restParams) { //we try to avoid hardcoded mappings but the index api is the exception if ("index".equals(name) || "create".equals(name)) { List<String> indexMethods = new ArrayList<>(); for (String method : methods) { if (restParams.contains("id")) { //PUT when the id is provided if (HttpPut.METHOD_NAME.equals(method)) { indexMethods.add(method); } } else { //POST without id if (HttpPost.METHOD_NAME.equals(method)) { indexMethods.add(method); } } } return indexMethods; } return methods; } void addMethod(String method) { this.methods.add(method); } public List<String> getPaths() { return paths; } void addPath(String path) { this.paths.add(path); } public List<String> getPathParts() { return pathParts; } void addPathPart(String pathPart) { this.pathParts.add(pathPart); } public List<String> getParams() { return params; } void addParam(String param) { this.params.add(param); } void setBodyOptional() { this.body = BODY.OPTIONAL; } void setBodyRequired() { this.body = BODY.REQUIRED; } public boolean isBodySupported() { return body != BODY.NOT_SUPPORTED; } public boolean isBodyRequired() { return body == BODY.REQUIRED; } /** * Finds the best matching rest path given the current parameters and replaces * placeholders with their corresponding values received as arguments */ public String[] getFinalPaths(Map<String, String> pathParams) { List<RestPath> matchingRestPaths = findMatchingRestPaths(pathParams.keySet()); if (matchingRestPaths == null || matchingRestPaths.isEmpty()) { throw new IllegalArgumentException("unable to find matching rest path for api [" + name + "] and path params " + pathParams); } String[] paths = new String[matchingRestPaths.size()]; for (int i = 0; i < matchingRestPaths.size(); i++) { RestPath restPath = matchingRestPaths.get(i); String path = restPath.path; for (Map.Entry<String, String> paramEntry : restPath.parts.entrySet()) { // replace path placeholders with actual values String value = pathParams.get(paramEntry.getValue()); if (value == null) { throw new IllegalArgumentException("parameter [" + paramEntry.getValue() + "] missing"); } path = path.replace(paramEntry.getKey(), value); } paths[i] = path; } return paths; } /** * Finds the matching rest paths out of the available ones with the current api (based on REST spec). * * The best path is the one that has exactly the same number of placeholders to replace * (e.g. /{index}/{type}/{id} when the path params are exactly index, type and id). */ private List<RestPath> findMatchingRestPaths(Set<String> restParams) { List<RestPath> matchingRestPaths = new ArrayList<>(); RestPath[] restPaths = buildRestPaths(); for (RestPath restPath : restPaths) { if (restPath.parts.size() == restParams.size()) { if (restPath.parts.values().containsAll(restParams)) { matchingRestPaths.add(restPath); } } } return matchingRestPaths; } private RestPath[] buildRestPaths() { RestPath[] restPaths = new RestPath[paths.size()]; for (int i = 0; i < restPaths.length; i++) { restPaths[i] = new RestPath(paths.get(i)); } return restPaths; } private static class RestPath { private static final Pattern PLACEHOLDERS_PATTERN = Pattern.compile("(\\{(.*?)})"); final String path; //contains param to replace (e.g. {index}) and param key to use for lookup in the current values map (e.g. index) final Map<String, String> parts; RestPath(String path) { this.path = path; this.parts = extractParts(path); } private static Map<String,String> extractParts(String input) { Map<String, String> parts = Maps.newHashMap(); Matcher matcher = PLACEHOLDERS_PATTERN.matcher(input); while (matcher.find()) { //key is e.g. {index} String key = input.substring(matcher.start(), matcher.end()); if (matcher.groupCount() != 2) { throw new IllegalArgumentException("no lookup key found for param [" + key + "]"); } //to be replaced with current value found with key e.g. index String value = matcher.group(2); parts.put(key, value); } return parts; } } }
package com.cryptobuddy.ryanbridges.cryptobuddy; import android.view.View; /** * Created by Ryan on 8/13/2017. */ public interface CustomItemClickListener { void onItemClick(int position, View v); }
package me.piebridge.brevent.ui; import android.content.Intent; import android.content.pm.PackageManager; import android.os.AsyncTask; /** * Created by thom on 2017/1/25. */ public class AppsIconTask extends AsyncTask<Object, Void, AppsItemViewHolder> { @Override protected AppsItemViewHolder doInBackground(Object... params) { PackageManager packageManager = (PackageManager) params[0]; AppsItemViewHolder holder = (AppsItemViewHolder) params[1]; try { Intent launchIntent = packageManager.getLaunchIntentForPackage(holder.packageName); if (launchIntent == null) { holder.icon = packageManager.getApplicationIcon(holder.packageName); } else { holder.icon = packageManager.resolveActivity(launchIntent, 0).activityInfo .loadIcon(packageManager); } } catch (PackageManager.NameNotFoundException e) { // NOSONAR // do nothing } return holder; } @Override protected void onPostExecute(AppsItemViewHolder holder) { if (holder.icon != null) { holder.iconView.setImageDrawable(holder.icon); holder.icon = null; } } }
package demo; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class) public class ApplicationTests { @Test public void contextLoads() { } }
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.guxuede.gm.gdx.actions; import com.badlogic.gdx.utils.Pool; /** An action that runs a {@link Runnable}. Alternatively, the {@link #run()} method can be overridden instead of setting a * runnable. * @author Nathan Sweet */ public class RunnableAction extends Action { private Runnable runnable; private boolean ran; public boolean act (float delta) { if (!ran) { ran = true; run(); } return true; } /** Called to run the runnable. */ public void run () { Pool pool = getPool(); setPool(null); // Ensure this action can't be returned to the pool inside the runnable. try { runnable.run(); } finally { setPool(pool); } } public void restart () { ran = false; } public void reset () { super.reset(); runnable = null; } public Runnable getRunnable () { return runnable; } public void setRunnable (Runnable runnable) { this.runnable = runnable; } }
/* * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.core.client; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.testng.Assert.fail; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.function.Predicate; import java.util.function.Supplier; import org.junit.Before; import org.junit.Test; import org.mockito.stubbing.Answer; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.async.EmptyPublisher; import software.amazon.awssdk.core.client.config.SdkAdvancedAsyncClientOption; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.client.handler.ClientExecutionParams; import software.amazon.awssdk.core.client.handler.SdkAsyncClientHandler; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.protocol.VoidSdkResponse; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.core.runtime.transform.Marshaller; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler; import utils.HttpTestUtils; import utils.ValidSdkObjects; /** * Tests to verify that when exceptions are thrown during various stages of * execution within the handler, they are reported through the returned {@link * java.util.concurrent.CompletableFuture}. * * @see AsyncClientHandlerInterceptorExceptionTest */ public class AsyncClientHandlerExceptionTest { private final SdkRequest request = mock(SdkRequest.class); private final SdkAsyncHttpClient asyncHttpClient = mock(SdkAsyncHttpClient.class); private final Marshaller<SdkRequest> marshaller = mock(Marshaller.class); private final HttpResponseHandler<SdkResponse> responseHandler = mock(HttpResponseHandler.class); private final HttpResponseHandler<SdkServiceException> errorResponseHandler = mock(HttpResponseHandler.class); private SdkAsyncClientHandler clientHandler; private ClientExecutionParams<SdkRequest, SdkResponse> executionParams; @Before public void methodSetup() throws Exception { executionParams = new ClientExecutionParams<SdkRequest, SdkResponse>() .withInput(request) .withMarshaller(marshaller) .withResponseHandler(responseHandler) .withErrorResponseHandler(errorResponseHandler); SdkClientConfiguration config = HttpTestUtils.testClientConfiguration().toBuilder() .option(SdkClientOption.ASYNC_HTTP_CLIENT, asyncHttpClient) .option(SdkClientOption.RETRY_POLICY, RetryPolicy.none()) .option(SdkAdvancedAsyncClientOption.FUTURE_COMPLETION_EXECUTOR, Runnable::run) .build(); clientHandler = new SdkAsyncClientHandler(config); when(request.overrideConfiguration()).thenReturn(Optional.empty()); when(marshaller.marshall(eq(request))).thenReturn(ValidSdkObjects.sdkHttpFullRequest().build()); when(responseHandler.handle(any(SdkHttpFullResponse.class), any(ExecutionAttributes.class))) .thenReturn(VoidSdkResponse.builder().build()); when(asyncHttpClient.execute(any(AsyncExecuteRequest.class))).thenAnswer((Answer<CompletableFuture<Void>>) invocationOnMock -> { SdkAsyncHttpResponseHandler handler = invocationOnMock.getArgumentAt(0, AsyncExecuteRequest.class).responseHandler(); handler.onHeaders(SdkHttpFullResponse.builder() .statusCode(200) .build()); handler.onStream(new EmptyPublisher<>()); return CompletableFuture.completedFuture(null); }); } @Test public void marshallerThrowsReportedThroughFuture() throws ExecutionException, InterruptedException { final SdkClientException e = SdkClientException.create("Could not marshall"); when(marshaller.marshall(any(SdkRequest.class))).thenThrow(e); doVerify(() -> clientHandler.execute(executionParams), e); } @Test public void responseHandlerThrowsReportedThroughFuture() throws Exception { final SdkClientException e = SdkClientException.create("Could not handle response"); when(responseHandler.handle(any(SdkHttpFullResponse.class), any(ExecutionAttributes.class))).thenThrow(e); doVerify(() -> clientHandler.execute(executionParams), e); } @Test public void streamingRequest_marshallingException_shouldInvokeExceptionOccurred() throws Exception { AsyncResponseTransformer asyncResponseTransformer = mock(AsyncResponseTransformer.class); CompletableFuture<?> future = new CompletableFuture<>(); when(asyncResponseTransformer.prepare()).thenReturn(future); SdkClientException exception = SdkClientException.create("Could not handle response"); when(marshaller.marshall(any(SdkRequest.class))).thenThrow(exception); doVerify(() -> clientHandler.execute(executionParams, asyncResponseTransformer), exception); verify(asyncResponseTransformer, times(1)).prepare(); verify(asyncResponseTransformer, times(1)).exceptionOccurred(exception); } private void doVerify(Supplier<CompletableFuture<?>> s, final Throwable expectedException) { doVerify(s, (thrown) -> thrown.getCause() == expectedException); } private void doVerify(Supplier<CompletableFuture<?>> s, Predicate<Throwable> assertFn) { CompletableFuture<?> cf = s.get(); try { cf.get(); fail("get() method did not fail as expected."); } catch (Throwable t) { assertTrue(assertFn.test(t)); } } }
import java.util.Scanner; public class Subsequences_Iteratively { public static void main(String[] args) { Scanner s= new Scanner(System.in); String str=s.next(); System.out.println(str); for(int i=0;i<str.length();i++) { for(int j=i+1;j<=str.length();j++) { System.out.println(str.substring(i, j)); } } } }
/** * Copyright © 2019 Apache IoTDB(incubating) (dev@iotdb.apache.org) * * 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.iotdb.tsfile.read.reader; import java.io.IOException; import java.nio.ByteBuffer; import org.apache.iotdb.tsfile.encoding.common.EndianType; import org.apache.iotdb.tsfile.encoding.decoder.Decoder; import org.apache.iotdb.tsfile.encoding.decoder.DeltaBinaryDecoder; import org.apache.iotdb.tsfile.encoding.decoder.DoublePrecisionDecoder; import org.apache.iotdb.tsfile.encoding.decoder.IntRleDecoder; import org.apache.iotdb.tsfile.encoding.decoder.LongRleDecoder; import org.apache.iotdb.tsfile.encoding.decoder.PlainDecoder; import org.apache.iotdb.tsfile.encoding.decoder.SinglePrecisionDecoder; import org.apache.iotdb.tsfile.encoding.encoder.DeltaBinaryEncoder; import org.apache.iotdb.tsfile.encoding.encoder.DoublePrecisionEncoder; import org.apache.iotdb.tsfile.encoding.encoder.Encoder; import org.apache.iotdb.tsfile.encoding.encoder.IntRleEncoder; import org.apache.iotdb.tsfile.encoding.encoder.LongRleEncoder; import org.apache.iotdb.tsfile.encoding.encoder.PlainEncoder; import org.apache.iotdb.tsfile.encoding.encoder.SinglePrecisionEncoder; import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType; import org.apache.iotdb.tsfile.read.common.BatchData; import org.apache.iotdb.tsfile.read.reader.page.PageReader; import org.apache.iotdb.tsfile.utils.Binary; import org.apache.iotdb.tsfile.write.page.PageWriter; import org.junit.Assert; import org.junit.Test; public class PageReaderTest { private static final int POINTS_COUNT_IN_ONE_PAGE = 1000000; @Test public void testLong() { LoopWriteReadTest test = new LoopWriteReadTest("Test INT64", new LongRleEncoder(EndianType.BIG_ENDIAN), new LongRleDecoder(EndianType.BIG_ENDIAN), TSDataType.INT64, POINTS_COUNT_IN_ONE_PAGE) { @Override public Object generateValueByIndex(int i) { return Long.valueOf(Long.MAX_VALUE - i); } }; test.test(); } @Test public void testBoolean() { LoopWriteReadTest test = new LoopWriteReadTest("Test Boolean", new IntRleEncoder(EndianType.BIG_ENDIAN), new IntRleDecoder(EndianType.BIG_ENDIAN), TSDataType.BOOLEAN, POINTS_COUNT_IN_ONE_PAGE) { @Override public Object generateValueByIndex(int i) { return i % 3 == 0 ? true : false; } }; test.test(); } @Test public void testInt() { LoopWriteReadTest test = new LoopWriteReadTest("Test INT32", new IntRleEncoder(EndianType.BIG_ENDIAN), new IntRleDecoder(EndianType.BIG_ENDIAN), TSDataType.INT32, POINTS_COUNT_IN_ONE_PAGE) { @Override public Object generateValueByIndex(int i) { return Integer.valueOf(i); } }; test.test(); } @Test public void testFloat() { LoopWriteReadTest test = new LoopWriteReadTest("Test FLOAT", new SinglePrecisionEncoder(), new SinglePrecisionDecoder(), TSDataType.FLOAT, POINTS_COUNT_IN_ONE_PAGE) { @Override public Object generateValueByIndex(int i) { return Float.valueOf(i) / 10 - Float.valueOf(i) / 100; } }; test.test(); LoopWriteReadTest test2 = new LoopWriteReadTest("Test FLOAT", new SinglePrecisionEncoder(), new SinglePrecisionDecoder(), TSDataType.FLOAT, POINTS_COUNT_IN_ONE_PAGE) { @Override public Object generateValueByIndex(int i) { return Float.valueOf(i) / 100 - Float.valueOf(i) / 10; } }; test2.test(); } @Test public void testDouble() { LoopWriteReadTest test = new LoopWriteReadTest("Test Double", new DoublePrecisionEncoder(), new DoublePrecisionDecoder(), TSDataType.DOUBLE, POINTS_COUNT_IN_ONE_PAGE) { @Override public Object generateValueByIndex(int i) { return Double.valueOf(i) / 10 - Double.valueOf(i) / 100; } }; test.test(); LoopWriteReadTest test2 = new LoopWriteReadTest("Test Double", new DoublePrecisionEncoder(), new DoublePrecisionDecoder(), TSDataType.DOUBLE, POINTS_COUNT_IN_ONE_PAGE) { @Override public Object generateValueByIndex(int i) { return Double.valueOf(i) / 1000 - Double.valueOf(i) / 100; } }; test2.test(); } @Test public void testBinary() { LoopWriteReadTest test = new LoopWriteReadTest("Test Double", new PlainEncoder(EndianType.LITTLE_ENDIAN, TSDataType.TEXT, 1000), new PlainDecoder(EndianType.LITTLE_ENDIAN), TSDataType.TEXT, POINTS_COUNT_IN_ONE_PAGE) { @Override public Object generateValueByIndex(int i) { return new Binary(new StringBuilder("TEST TEXT").append(i).toString()); } }; test.test(); } private abstract static class LoopWriteReadTest { private Encoder encoder; private Decoder decoder; private TSDataType dataType; private PageWriter pageWriter; private String name; private int count; public LoopWriteReadTest(String name, Encoder encoder, Decoder decoder, TSDataType dataType, int count) { this.name = name; this.encoder = encoder; this.decoder = decoder; this.dataType = dataType; this.count = count; } public void test() { try { pageWriter = new PageWriter(); pageWriter.setTimeEncoder(new DeltaBinaryEncoder.LongDeltaEncoder()); pageWriter.setValueEncoder(this.encoder); writeData(); ByteBuffer page = ByteBuffer.wrap(pageWriter.getUncompressedBytes().array()); PageReader pageReader = new PageReader(page, dataType, decoder, new DeltaBinaryDecoder.LongDeltaDecoder()); int index = 0; long startTimestamp = System.currentTimeMillis(); BatchData data = null; if (pageReader.hasNextBatch()) { data = pageReader.nextBatch(); } assert data != null; while (data.hasNext()) { Assert.assertEquals(Long.valueOf(index), (Long) data.currentTime()); Assert.assertEquals(generateValueByIndex(index), data.currentValue()); data.next(); index++; } long endTimestamp = System.currentTimeMillis(); System.out .println("TestName: [" + name + "]\n\tTSDataType: " + dataType + "\tRead-Count:" + count + "\tTime-used:" + (endTimestamp - startTimestamp) + "ms"); Assert.assertEquals(count, index); } catch (IOException e) { e.printStackTrace(); Assert.fail("Fail when executing test: [" + name + "]"); } } private void writeData() throws IOException { for (int i = 0; i < count; i++) { switch (dataType) { case BOOLEAN: pageWriter.write(Long.valueOf(i), (Boolean) generateValueByIndex(i)); break; case INT32: pageWriter.write(Long.valueOf(i), (Integer) generateValueByIndex(i)); break; case INT64: pageWriter.write(Long.valueOf(i), (Long) generateValueByIndex(i)); break; case FLOAT: pageWriter.write(Long.valueOf(i), (Float) generateValueByIndex(i)); break; case DOUBLE: pageWriter.write(Long.valueOf(i), (Double) generateValueByIndex(i)); break; case TEXT: pageWriter.write(Long.valueOf(i), (Binary) generateValueByIndex(i)); break; } } } public abstract Object generateValueByIndex(int i); } }
package com.codepath.apps.restclienttemplate.models; import androidx.room.Embedded; import java.util.ArrayList; import java.util.List; public class TweetWithUser { @Embedded User user; @Embedded(prefix = "tweet_") Tweet tweet; public static List<Tweet> getTweetList(List<TweetWithUser> tweetWithUsers) { List<Tweet> tweets = new ArrayList<>(); for (int i = 0; i < tweetWithUsers.size(); i++) { Tweet tweet = tweetWithUsers.get(i).tweet; tweet.user = tweetWithUsers.get(i).user; tweets.add(tweet); } return tweets; } }
package mekanism.common.recipe.serializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSyntaxException; import javax.annotation.Nonnull; import mekanism.api.JsonConstants; import mekanism.api.SerializerHelper; import mekanism.api.chemical.gas.GasStack; import mekanism.api.recipes.RotaryRecipe; import mekanism.api.recipes.inputs.FluidStackIngredient; import mekanism.api.recipes.inputs.chemical.GasStackIngredient; import mekanism.common.Mekanism; import net.minecraft.network.PacketByteBuf; import net.minecraft.recipe.RecipeSerializer; import net.minecraft.util.Identifier; import net.minecraft.util.JsonHelper; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.registries.ForgeRegistryEntry; public class RotaryRecipeSerializer<RECIPE extends RotaryRecipe> extends ForgeRegistryEntry<RecipeSerializer<?>> implements RecipeSerializer<RECIPE> { private final IFactory<RECIPE> factory; public RotaryRecipeSerializer(IFactory<RECIPE> factory) { this.factory = factory; } @Nonnull @Override public RECIPE read(@Nonnull Identifier recipeId, @Nonnull JsonObject json) { FluidStackIngredient fluidInputIngredient = null; GasStackIngredient gasInputIngredient = null; GasStack gasOutput = null; FluidStack fluidOutput = null; boolean hasFluidToGas = false; boolean hasGasToFluid = false; if (json.has(JsonConstants.FLUID_INPUT) || json.has(JsonConstants.GAS_OUTPUT)) { JsonElement fluidInput = JsonHelper.hasArray(json, JsonConstants.FLUID_INPUT) ? JsonHelper.getArray(json, JsonConstants.FLUID_INPUT) : JsonHelper.getObject(json, JsonConstants.FLUID_INPUT); fluidInputIngredient = FluidStackIngredient.deserialize(fluidInput); gasOutput = SerializerHelper.getGasStack(json, JsonConstants.GAS_OUTPUT); hasFluidToGas = true; if (gasOutput.isEmpty()) { throw new JsonSyntaxException("Rotary recipe gas output cannot be empty if it is defined."); } } if (json.has(JsonConstants.GAS_INPUT) || json.has(JsonConstants.FLUID_OUTPUT)) { JsonElement gasInput = JsonHelper.hasArray(json, JsonConstants.GAS_INPUT) ? JsonHelper.getArray(json, JsonConstants.GAS_INPUT) : JsonHelper.getObject(json, JsonConstants.GAS_INPUT); gasInputIngredient = GasStackIngredient.deserialize(gasInput); fluidOutput = SerializerHelper.getFluidStack(json, JsonConstants.FLUID_OUTPUT); hasGasToFluid = true; if (fluidOutput.isEmpty()) { throw new JsonSyntaxException("Rotary recipe fluid output cannot be empty if it is defined."); } } if (hasFluidToGas && hasGasToFluid) { return this.factory.create(recipeId, fluidInputIngredient, gasInputIngredient, gasOutput, fluidOutput); } else if (hasFluidToGas) { return this.factory.create(recipeId, fluidInputIngredient, gasOutput); } else if (hasGasToFluid) { return this.factory.create(recipeId, gasInputIngredient, fluidOutput); } throw new JsonSyntaxException("Rotary recipes require at least a gas to fluid or fluid to gas conversion."); } @Override public RECIPE read(@Nonnull Identifier recipeId, @Nonnull PacketByteBuf buffer) { try { FluidStackIngredient fluidInputIngredient = null; GasStackIngredient gasInputIngredient = null; GasStack gasOutput = null; FluidStack fluidOutput = null; boolean hasFluidToGas = buffer.readBoolean(); if (hasFluidToGas) { fluidInputIngredient = FluidStackIngredient.read(buffer); gasOutput = GasStack.readFromPacket(buffer); } boolean hasGasToFluid = buffer.readBoolean(); if (hasGasToFluid) { gasInputIngredient = GasStackIngredient.read(buffer); fluidOutput = FluidStack.readFromPacket(buffer); } if (hasFluidToGas && hasGasToFluid) { return this.factory.create(recipeId, fluidInputIngredient, gasInputIngredient, gasOutput, fluidOutput); } else if (hasFluidToGas) { return this.factory.create(recipeId, fluidInputIngredient, gasOutput); } else if (hasGasToFluid) { return this.factory.create(recipeId, gasInputIngredient, fluidOutput); } //Should never happen, but if we somehow get here log it Mekanism.logger.error("Error reading rotary recipe from packet. A recipe got sent with no conversion in either direction."); return null; } catch (Exception e) { Mekanism.logger.error("Error reading rotary recipe from packet.", e); throw e; } } @Override public void write(@Nonnull PacketByteBuf buffer, @Nonnull RECIPE recipe) { if (recipe.hasFluidToGas() || recipe.hasGasToFluid()) { try { recipe.write(buffer); } catch (Exception e) { Mekanism.logger.error("Error writing rotary recipe to packet.", e); throw e; } } else { Mekanism.logger.error("Error writing rotary recipe to packet. {} has no conversion in either direction, so was not sent.", recipe); } } public interface IFactory<RECIPE extends RotaryRecipe> { RECIPE create(Identifier id, FluidStackIngredient fluidInput, GasStack gasOutput); RECIPE create(Identifier id, GasStackIngredient gasInput, FluidStack fluidOutput); RECIPE create(Identifier id, FluidStackIngredient fluidInput, GasStackIngredient gasInput, GasStack gasOutput, FluidStack fluidOutput); } }
package de.lukweb.timetablebot.telegram.communication; import de.lukweb.timetablebot.BotModule; import de.lukweb.timetablebot.telegram.callbacks.CallbackQueryHandler; import de.lukweb.timetablebot.telegram.commands.TelegramCommand; import java.util.Arrays; import java.util.Collections; import java.util.List; public class CommunicationModule extends BotModule { public CommunicationModule() { name = "communication"; } @Override public List<TelegramCommand> commands() { return Arrays.asList( new BroadcastC(), new MessageUserC(), new NewSchoolYearC() ); } @Override public List<CallbackQueryHandler> queryHandlers() { return Collections.singletonList( new MessageUserCallback() ); } }
package com.plushnode.atlacore.command; import com.plushnode.atlacore.game.Game; import com.plushnode.atlacore.game.ability.AbilityDescription; import com.plushnode.atlacore.platform.Player; import com.plushnode.atlacore.util.ChatColor; public class PresetCommand implements CoreCommand { private String[] aliases = { "preset", "p" }; @Override public boolean execute(CommandSender sender, String[] args) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + "Only players can execute this command."); return true; } if (args.length < 2) { sender.sendMessage(ChatColor.GREEN + "/bending preset [bind/create/delete/list]"); return true; } String action = args[1]; Player player = (Player)sender; switch (action.charAt(0)) { case 'c': case 'C': { if (args.length < 3) { sender.sendMessage(ChatColor.GREEN + "/bending preset create [presetName]"); return true; } String presetName = args[2]; Game.getPresetService().createPreset(player, presetName, (preset) -> { sender.sendMessage(ChatColor.GREEN + "Successfully created preset with the name '" + preset.getName() + "'."); }); } break; case 'l': case 'L': { Game.getPresetService().getPresetNames(player, (presetNames) -> { if (!presetNames.isEmpty()) { String presets = String.join(", ", presetNames); sender.sendMessage(ChatColor.GOLD + presets); } else { sender.sendMessage(ChatColor.RED + "No presets found."); } }); } break; case 'd': case 'D': { if (args.length < 3) { sender.sendMessage(ChatColor.GREEN + "/bending preset delete [presetName]"); return true; } String presetName = args[2]; Game.getPresetService().deletePreset(player, presetName, (success) -> { if (success) { sender.sendMessage(ChatColor.GREEN + "Successfully deleted preset '" + presetName + "'."); } else { sender.sendMessage(ChatColor.RED + "Failed to delete preset '" + presetName + "'."); } }); } break; case 'b': case 'B': { if (args.length < 3) { sender.sendMessage(ChatColor.GREEN + "/bending preset bind [presetName]"); return true; } String presetName = args[2]; Game.getPresetService().loadPreset(player, presetName, (preset) -> { if (preset == null) { sender.sendMessage(ChatColor.RED + "No preset found with the name '" + presetName + "'."); return; } int count = 0; int total = 0; for (int i = 0; i < preset.getAbilities().size(); ++i) { AbilityDescription desc = preset.getAbilities().get(i); if (desc != null) { ++total; if (player.canBind(desc)) { player.setSlotAbility(i + 1, desc); ++count; } else { player.setSlotAbility(i + 1, null); } } else { player.setSlotAbility(i + 1, null); } } if (count > 0 || total == 0) { sender.sendMessage(ChatColor.GREEN + "Successfully bound " + count + "/" + total + " abilities."); } else { sender.sendMessage(ChatColor.RED + "No abilities could be bound from the preset."); } Game.getPlayerService().saveSlots(player); }); } break; } return true; } @Override public String getDescription() { return "Manage presets."; } @Override public String getPermission() { return "atla.command.preset"; } @Override public String[] getAliases() { return aliases; } }
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class Challenge2Test { @Test void filterByPrimeNumbers_given_an_empty_array() { Integer[] given = new Integer[0]; Integer[] shouldReturn = new Integer[0]; Integer[] result = Challenge2.filterByPrimeNumbers(given); assertArrayEquals(result, shouldReturn); } @Test void filterByPrimeNumbers_given_all_prime() { Integer[] given = new Integer[]{5, 3, 7}; Integer[] shouldReturn = new Integer[]{5, 3, 7}; Integer[] result = Challenge2.filterByPrimeNumbers(given); assertArrayEquals(result, shouldReturn); } @Test void filterByPrimeNumbers_given_all_not_prime() { Integer[] given = new Integer[]{8, 6, 10}; Integer[] shouldReturn = new Integer[0]; Integer[] result = Challenge2.filterByPrimeNumbers(given); assertArrayEquals(result, shouldReturn); } @Test void filterByPrimeNumbers_given_mixed_types() { Integer[] given = new Integer[]{2, 8, 1, 6, 7, 10}; Integer[] shouldReturn = new Integer[]{2, 7}; Integer[] result = Challenge2.filterByPrimeNumbers(given); assertArrayEquals(result, shouldReturn); } @Test void isPrime() { Integer[] someOfPrimeNumbers = new Integer[]{2, 3, 5, 7, 11, 13, 17, 19, 23, 29}; Integer[] someOfNotPrimeNumbers = new Integer[]{0, 1, 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20}; for (int shouldBePrime : someOfPrimeNumbers) { assertTrue(Challenge2.isPrime(shouldBePrime), String.format("The number \"%d\" should be prime", shouldBePrime)); } for (int shouldNotBePrime : someOfNotPrimeNumbers) { assertFalse(Challenge2.isPrime(shouldNotBePrime), String.format("The number \"%d\" shouldn't be prime", shouldNotBePrime)); } } }
/* * Copyright (c) 2014 Kevin Sawicki <kevinsawicki@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ package com.github.kevinsawicki.http; import static java.net.HttpURLConnection.HTTP_BAD_REQUEST; import static java.net.HttpURLConnection.HTTP_CREATED; import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR; import static java.net.HttpURLConnection.HTTP_NO_CONTENT; import static java.net.HttpURLConnection.HTTP_NOT_FOUND; import static java.net.HttpURLConnection.HTTP_NOT_MODIFIED; import static java.net.HttpURLConnection.HTTP_OK; import static java.net.Proxy.Type.HTTP; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.Flushable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.MalformedURLException; import java.net.Proxy; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLEncoder; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.security.AccessController; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.PrivilegedAction; import java.security.SecureRandom; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.zip.GZIPInputStream; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; /** * A fluid interface for making HTTP requests using an underlying * {@link HttpURLConnection} (or sub-class). * <p> * Each instance supports making a single request and cannot be reused for * further requests. */ public class HttpRequest { /** * 'UTF-8' charset name */ public static final String CHARSET_UTF8 = "UTF-8"; /** * 'application/x-www-form-urlencoded' content type header value */ public static final String CONTENT_TYPE_FORM = "application/x-www-form-urlencoded"; /** * 'application/json' content type header value */ public static final String CONTENT_TYPE_JSON = "application/json"; /** * 'gzip' encoding header value */ public static final String ENCODING_GZIP = "gzip"; /** * 'Accept' header name */ public static final String HEADER_ACCEPT = "Accept"; /** * 'Accept-Charset' header name */ public static final String HEADER_ACCEPT_CHARSET = "Accept-Charset"; /** * 'Accept-Encoding' header name */ public static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding"; /** * 'Authorization' header name */ public static final String HEADER_AUTHORIZATION = "Authorization"; /** * 'Cache-Control' header name */ public static final String HEADER_CACHE_CONTROL = "Cache-Control"; /** * 'Content-Encoding' header name */ public static final String HEADER_CONTENT_ENCODING = "Content-Encoding"; /** * 'Content-Length' header name */ public static final String HEADER_CONTENT_LENGTH = "Content-Length"; /** * 'Content-Type' header name */ public static final String HEADER_CONTENT_TYPE = "Content-Type"; /** * 'Date' header name */ public static final String HEADER_DATE = "Date"; /** * 'ETag' header name */ public static final String HEADER_ETAG = "ETag"; /** * 'Expires' header name */ public static final String HEADER_EXPIRES = "Expires"; /** * 'If-None-Match' header name */ public static final String HEADER_IF_NONE_MATCH = "If-None-Match"; /** * 'Last-Modified' header name */ public static final String HEADER_LAST_MODIFIED = "Last-Modified"; /** * 'Location' header name */ public static final String HEADER_LOCATION = "Location"; /** * 'Proxy-Authorization' header name */ public static final String HEADER_PROXY_AUTHORIZATION = "Proxy-Authorization"; /** * 'Referer' header name */ public static final String HEADER_REFERER = "Referer"; /** * 'Server' header name */ public static final String HEADER_SERVER = "Server"; /** * 'User-Agent' header name */ public static final String HEADER_USER_AGENT = "User-Agent"; /** * 'DELETE' request method */ public static final String METHOD_DELETE = "DELETE"; /** * 'GET' request method */ public static final String METHOD_GET = "GET"; /** * 'HEAD' request method */ public static final String METHOD_HEAD = "HEAD"; /** * 'OPTIONS' options method */ public static final String METHOD_OPTIONS = "OPTIONS"; /** * 'POST' request method */ public static final String METHOD_POST = "POST"; /** * 'PATCH' request method */ public static final String METHOD_PATCH = "PATCH"; /** * 'PUT' request method */ public static final String METHOD_PUT = "PUT"; /** * 'TRACE' request method */ public static final String METHOD_TRACE = "TRACE"; /** * 'charset' header value parameter */ public static final String PARAM_CHARSET = "charset"; private static final String BOUNDARY = "00content0boundary00"; private static final String CONTENT_TYPE_MULTIPART = "multipart/form-data; boundary=" + BOUNDARY; private static final String CRLF = "\r\n"; private static final String[] EMPTY_STRINGS = new String[0]; private static SSLSocketFactory PINNED_FACTORY; private static SSLSocketFactory TRUSTED_FACTORY; private static ArrayList<Certificate> PINNED_CERTS; private static HostnameVerifier TRUSTED_VERIFIER; private static String getValidCharset(final String charset) { if (charset != null && charset.length() > 0) return charset; else return CHARSET_UTF8; } private static SSLSocketFactory getPinnedFactory() throws HttpRequestException { if (PINNED_FACTORY != null) { return PINNED_FACTORY; } else { IOException e = new IOException("You must add at least 1 certificate in order to pin to certificates"); throw new HttpRequestException(e); } } private static SSLSocketFactory getTrustedFactory() throws HttpRequestException { if (TRUSTED_FACTORY == null) { final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } public void checkClientTrusted(X509Certificate[] chain, String authType) { // Intentionally left blank } public void checkServerTrusted(X509Certificate[] chain, String authType) { // Intentionally left blank } } }; try { SSLContext context = SSLContext.getInstance("TLS"); context.init(null, trustAllCerts, new SecureRandom()); if (android.os.Build.VERSION.SDK_INT < 20) { TRUSTED_FACTORY = new TLSSocketFactory(context); } else { TRUSTED_FACTORY = context.getSocketFactory(); } } catch (GeneralSecurityException e) { IOException ioException = new IOException( "Security exception configuring SSL context"); ioException.initCause(e); throw new HttpRequestException(ioException); } } return TRUSTED_FACTORY; } private static HostnameVerifier getTrustedVerifier() { if (TRUSTED_VERIFIER == null) TRUSTED_VERIFIER = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; return TRUSTED_VERIFIER; } private static StringBuilder addPathSeparator(final String baseUrl, final StringBuilder result) { // Add trailing slash if the base URL doesn't have any path segments. // // The following test is checking for the last slash not being part of // the protocol to host separator: '://'. if (baseUrl.indexOf(':') + 2 == baseUrl.lastIndexOf('/')) result.append('/'); return result; } private static StringBuilder addParamPrefix(final String baseUrl, final StringBuilder result) { // Add '?' if missing and add '&' if params already exist in base url final int queryStart = baseUrl.indexOf('?'); final int lastChar = result.length() - 1; if (queryStart == -1) result.append('?'); else if (queryStart < lastChar && baseUrl.charAt(lastChar) != '&') result.append('&'); return result; } private static StringBuilder addParam(final Object key, Object value, final StringBuilder result) { if (value != null && value.getClass().isArray()) value = arrayToList(value); if (value instanceof Iterable<?>) { Iterator<?> iterator = ((Iterable<?>) value).iterator(); while (iterator.hasNext()) { result.append(key); result.append("[]="); Object element = iterator.next(); if (element != null) result.append(element); if (iterator.hasNext()) result.append("&"); } } else { result.append(key); result.append("="); if (value != null) result.append(value); } return result; } /** * Creates {@link HttpURLConnection HTTP connections} for * {@link URL urls}. */ public interface ConnectionFactory { /** * Open an {@link HttpURLConnection} for the specified {@link URL}. * * @throws IOException */ HttpURLConnection create(URL url) throws IOException; /** * Open an {@link HttpURLConnection} for the specified {@link URL} * and {@link Proxy}. * * @throws IOException */ HttpURLConnection create(URL url, Proxy proxy) throws IOException; /** * A {@link ConnectionFactory} which uses the built-in * {@link URL#openConnection()} */ ConnectionFactory DEFAULT = new ConnectionFactory() { public HttpURLConnection create(URL url) throws IOException { return (HttpURLConnection) url.openConnection(); } public HttpURLConnection create(URL url, Proxy proxy) throws IOException { return (HttpURLConnection) url.openConnection(proxy); } }; } private static ConnectionFactory CONNECTION_FACTORY = ConnectionFactory.DEFAULT; /** * Specify the {@link ConnectionFactory} used to create new requests. */ public static void setConnectionFactory(final ConnectionFactory connectionFactory) { if (connectionFactory == null) CONNECTION_FACTORY = ConnectionFactory.DEFAULT; else CONNECTION_FACTORY = connectionFactory; } /** * Add a certificate to test against when using ssl pinning. * * @param ca * The Certificate to add * @throws GeneralSecurityException * @throws IOException */ public static void addCert(Certificate ca) throws GeneralSecurityException, IOException { if (PINNED_CERTS == null) { PINNED_CERTS = new ArrayList<Certificate>(); } PINNED_CERTS.add(ca); String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); for (int i = 0; i < PINNED_CERTS.size(); i++) { keyStore.setCertificateEntry("CA" + i, PINNED_CERTS.get(i)); } // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tmf.getTrustManagers(), null); if (android.os.Build.VERSION.SDK_INT < 20) { PINNED_FACTORY = new TLSSocketFactory(sslContext); } else { PINNED_FACTORY = sslContext.getSocketFactory(); } } /** * Add a certificate to test against when using ssl pinning. * * @param in * An InputStream to read a certificate from * @throws GeneralSecurityException * @throws IOException */ public static void addCert(InputStream in) throws GeneralSecurityException, IOException { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca; try { ca = cf.generateCertificate(in); addCert(ca); } finally { in.close(); } } /** * Callback interface for reporting upload progress for a request. */ public interface UploadProgress { /** * Callback invoked as data is uploaded by the request. * * @param uploaded The number of bytes already uploaded * @param total The total number of bytes that will be uploaded or -1 if * the length is unknown. */ void onUpload(long uploaded, long total); UploadProgress DEFAULT = new UploadProgress() { public void onUpload(long uploaded, long total) { } }; } /** * <p> * Encodes and decodes to and from Base64 notation. * </p> * <p> * I am placing this code in the Public Domain. Do with it as you will. This * software comes with no guarantees or warranties but with plenty of * well-wishing instead! Please visit <a * href="http://iharder.net/base64">http://iharder.net/base64</a> periodically * to check for updates or to contribute improvements. * </p> * * @author Robert Harder * @author rob@iharder.net * @version 2.3.7 */ public static class Base64 { /** The equals sign (=) as a byte. */ private final static byte EQUALS_SIGN = (byte) '='; /** Preferred encoding. */ private final static String PREFERRED_ENCODING = "US-ASCII"; /** The 64 valid Base64 values. */ private final static byte[] _STANDARD_ALPHABET = { (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '+', (byte) '/' }; /** Defeats instantiation. */ private Base64() { } /** * <p> * Encodes up to three bytes of the array <var>source</var> and writes the * resulting four Base64 bytes to <var>destination</var>. The source and * destination arrays can be manipulated anywhere along their length by * specifying <var>srcOffset</var> and <var>destOffset</var>. This method * does not check to make sure your arrays are large enough to accomodate * <var>srcOffset</var> + 3 for the <var>source</var> array or * <var>destOffset</var> + 4 for the <var>destination</var> array. The * actual number of significant bytes in your array is given by * <var>numSigBytes</var>. * </p> * <p> * This is the lowest level of the encoding methods with all possible * parameters. * </p> * * @param source * the array to convert * @param srcOffset * the index where conversion begins * @param numSigBytes * the number of significant bytes in your array * @param destination * the array to hold the conversion * @param destOffset * the index where output will be put * @return the <var>destination</var> array * @since 1.3 */ private static byte[] encode3to4(byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset) { byte[] ALPHABET = _STANDARD_ALPHABET; int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0) | (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0) | (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0); switch (numSigBytes) { case 3: destination[destOffset] = ALPHABET[(inBuff >>> 18)]; destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f]; destination[destOffset + 3] = ALPHABET[(inBuff) & 0x3f]; return destination; case 2: destination[destOffset] = ALPHABET[(inBuff >>> 18)]; destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f]; destination[destOffset + 3] = EQUALS_SIGN; return destination; case 1: destination[destOffset] = ALPHABET[(inBuff >>> 18)]; destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = EQUALS_SIGN; destination[destOffset + 3] = EQUALS_SIGN; return destination; default: return destination; } } /** * Encode string as a byte array in Base64 annotation. * * @param string * @return The Base64-encoded data as a string */ public static String encode(String string) { byte[] bytes; try { bytes = string.getBytes(PREFERRED_ENCODING); } catch (UnsupportedEncodingException e) { bytes = string.getBytes(); } return encodeBytes(bytes); } /** * Encodes a byte array into Base64 notation. * * @param source * The data to convert * @return The Base64-encoded data as a String * @throws NullPointerException * if source array is null * @throws IllegalArgumentException * if source array, offset, or length are invalid * @since 2.0 */ public static String encodeBytes(byte[] source) { return encodeBytes(source, 0, source.length); } /** * Encodes a byte array into Base64 notation. * * @param source * The data to convert * @param off * Offset in array where conversion should begin * @param len * Length of data to convert * @return The Base64-encoded data as a String * @throws NullPointerException * if source array is null * @throws IllegalArgumentException * if source array, offset, or length are invalid * @since 2.0 */ public static String encodeBytes(byte[] source, int off, int len) { byte[] encoded = encodeBytesToBytes(source, off, len); try { return new String(encoded, PREFERRED_ENCODING); } catch (UnsupportedEncodingException uue) { return new String(encoded); } } /** * Similar to {@link #encodeBytes(byte[], int, int)} but returns a byte * array instead of instantiating a String. This is more efficient if you're * working with I/O streams and have large data sets to encode. * * * @param source * The data to convert * @param off * Offset in array where conversion should begin * @param len * Length of data to convert * @return The Base64-encoded data as a String if there is an error * @throws NullPointerException * if source array is null * @throws IllegalArgumentException * if source array, offset, or length are invalid * @since 2.3.1 */ public static byte[] encodeBytesToBytes(byte[] source, int off, int len) { if (source == null) throw new NullPointerException("Cannot serialize a null array."); if (off < 0) throw new IllegalArgumentException("Cannot have negative offset: " + off); if (len < 0) throw new IllegalArgumentException("Cannot have length offset: " + len); if (off + len > source.length) throw new IllegalArgumentException( String .format( "Cannot have offset of %d and length of %d with array of length %d", off, len, source.length)); // Bytes needed for actual encoding int encLen = (len / 3) * 4 + (len % 3 > 0 ? 4 : 0); byte[] outBuff = new byte[encLen]; int d = 0; int e = 0; int len2 = len - 2; for (; d < len2; d += 3, e += 4) encode3to4(source, d + off, 3, outBuff, e); if (d < len) { encode3to4(source, d + off, len - d, outBuff, e); e += 4; } if (e <= outBuff.length - 1) { byte[] finalOut = new byte[e]; System.arraycopy(outBuff, 0, finalOut, 0, e); return finalOut; } else return outBuff; } } /** * HTTP request exception whose cause is always an {@link IOException} */ public static class HttpRequestException extends RuntimeException { private static final long serialVersionUID = -1170466989781746231L; /** * Create a new HttpRequestException with the given cause * * @param cause */ public HttpRequestException(final IOException cause) { super(cause); } /** * Get {@link IOException} that triggered this request exception * * @return {@link IOException} cause */ @Override public IOException getCause() { return (IOException) super.getCause(); } } /** * Operation that handles executing a callback once complete and handling * nested exceptions * * @param <V> */ protected static abstract class Operation<V> implements Callable<V> { /** * Run operation * * @return result * @throws HttpRequestException * @throws IOException */ protected abstract V run() throws HttpRequestException, IOException; /** * Operation complete callback * * @throws IOException */ protected abstract void done() throws IOException; public V call() throws HttpRequestException { boolean thrown = false; try { return run(); } catch (HttpRequestException e) { thrown = true; throw e; } catch (IOException e) { thrown = true; throw new HttpRequestException(e); } finally { try { done(); } catch (IOException e) { if (!thrown) throw new HttpRequestException(e); } } } } /** * Class that ensures a {@link Closeable} gets closed with proper exception * handling. * * @param <V> */ protected static abstract class CloseOperation<V> extends Operation<V> { private final Closeable closeable; private final boolean ignoreCloseExceptions; /** * Create closer for operation * * @param closeable * @param ignoreCloseExceptions */ protected CloseOperation(final Closeable closeable, final boolean ignoreCloseExceptions) { this.closeable = closeable; this.ignoreCloseExceptions = ignoreCloseExceptions; } @Override protected void done() throws IOException { if (closeable instanceof Flushable) ((Flushable) closeable).flush(); if (ignoreCloseExceptions) try { closeable.close(); } catch (IOException e) { // Ignored } else closeable.close(); } } /** * Class that and ensures a {@link Flushable} gets flushed with proper * exception handling. * * @param <V> */ protected static abstract class FlushOperation<V> extends Operation<V> { private final Flushable flushable; /** * Create flush operation * * @param flushable */ protected FlushOperation(final Flushable flushable) { this.flushable = flushable; } @Override protected void done() throws IOException { flushable.flush(); } } /** * Request output stream */ public static class RequestOutputStream extends BufferedOutputStream { private final CharsetEncoder encoder; /** * Create request output stream * * @param stream * @param charset * @param bufferSize */ public RequestOutputStream(final OutputStream stream, final String charset, final int bufferSize) { super(stream, bufferSize); encoder = Charset.forName(getValidCharset(charset)).newEncoder(); } /** * Write string to stream * * @param value * @return this stream * @throws IOException */ public RequestOutputStream write(final String value) throws IOException { final ByteBuffer bytes = encoder.encode(CharBuffer.wrap(value)); super.write(bytes.array(), 0, bytes.limit()); return this; } } /** * Represents array of any type as list of objects so we can easily iterate over it * @param array of elements * @return list with the same elements */ private static List<Object> arrayToList(final Object array) { if (array instanceof Object[]) return Arrays.asList((Object[]) array); List<Object> result = new ArrayList<Object>(); // Arrays of the primitive types can't be cast to array of Object, so this: if (array instanceof int[]) for (int value : (int[]) array) result.add(value); else if (array instanceof boolean[]) for (boolean value : (boolean[]) array) result.add(value); else if (array instanceof long[]) for (long value : (long[]) array) result.add(value); else if (array instanceof float[]) for (float value : (float[]) array) result.add(value); else if (array instanceof double[]) for (double value : (double[]) array) result.add(value); else if (array instanceof short[]) for (short value : (short[]) array) result.add(value); else if (array instanceof byte[]) for (byte value : (byte[]) array) result.add(value); else if (array instanceof char[]) for (char value : (char[]) array) result.add(value); return result; } /** * Encode the given URL as an ASCII {@link String} * <p> * This method ensures the path and query segments of the URL are properly * encoded such as ' ' characters being encoded to '%20' or any UTF-8 * characters that are non-ASCII. No encoding of URLs is done by default by * the {@link HttpRequest} constructors and so if URL encoding is needed this * method should be called before calling the {@link HttpRequest} constructor. * * @param url * @return encoded URL * @throws HttpRequestException */ public static String encode(final CharSequence url) throws HttpRequestException { URL parsed; try { parsed = new URL(url.toString()); } catch (IOException e) { throw new HttpRequestException(e); } String host = parsed.getHost(); int port = parsed.getPort(); if (port != -1) host = host + ':' + Integer.toString(port); try { String encoded = new URI(parsed.getProtocol(), host, parsed.getPath(), parsed.getQuery(), null).toASCIIString(); int paramsStart = encoded.indexOf('?'); if (paramsStart > 0 && paramsStart + 1 < encoded.length()) encoded = encoded.substring(0, paramsStart + 1) + encoded.substring(paramsStart + 1).replace("+", "%2B"); return encoded; } catch (URISyntaxException e) { IOException io = new IOException("Parsing URI failed"); io.initCause(e); throw new HttpRequestException(io); } } /** * Append given map as query parameters to the base URL * <p> * Each map entry's key will be a parameter name and the value's * {@link Object#toString()} will be the parameter value. * * @param url * @param params * @return URL with appended query params */ public static String append(final CharSequence url, final Map<?, ?> params) { final String baseUrl = url.toString(); if (params == null || params.isEmpty()) return baseUrl; final StringBuilder result = new StringBuilder(baseUrl); addPathSeparator(baseUrl, result); addParamPrefix(baseUrl, result); Entry<?, ?> entry; Iterator<?> iterator = params.entrySet().iterator(); entry = (Entry<?, ?>) iterator.next(); addParam(entry.getKey().toString(), entry.getValue(), result); while (iterator.hasNext()) { result.append('&'); entry = (Entry<?, ?>) iterator.next(); addParam(entry.getKey().toString(), entry.getValue(), result); } return result.toString(); } /** * Append given name/value pairs as query parameters to the base URL * <p> * The params argument is interpreted as a sequence of name/value pairs so the * given number of params must be divisible by 2. * * @param url * @param params * name/value pairs * @return URL with appended query params */ public static String append(final CharSequence url, final Object... params) { final String baseUrl = url.toString(); if (params == null || params.length == 0) return baseUrl; if (params.length % 2 != 0) throw new IllegalArgumentException( "Must specify an even number of parameter names/values"); final StringBuilder result = new StringBuilder(baseUrl); addPathSeparator(baseUrl, result); addParamPrefix(baseUrl, result); addParam(params[0], params[1], result); for (int i = 2; i < params.length; i += 2) { result.append('&'); addParam(params[i], params[i + 1], result); } return result.toString(); } /** * Start a 'GET' request to the given URL * * @param url * @return request * @throws HttpRequestException */ public static HttpRequest get(final CharSequence url) throws HttpRequestException { return new HttpRequest(url, METHOD_GET); } /** * Start a 'GET' request to the given URL * * @param url * @return request * @throws HttpRequestException */ public static HttpRequest get(final URL url) throws HttpRequestException { return new HttpRequest(url, METHOD_GET); } /** * Start a 'GET' request to the given URL along with the query params * * @param baseUrl * @param params * The query parameters to include as part of the baseUrl * @param encode * true to encode the full URL * * @see #append(CharSequence, Map) * @see #encode(CharSequence) * * @return request */ public static HttpRequest get(final CharSequence baseUrl, final Map<?, ?> params, final boolean encode) { String url = append(baseUrl, params); return get(encode ? encode(url) : url); } /** * Start a 'GET' request to the given URL along with the query params * * @param baseUrl * @param encode * true to encode the full URL * @param params * the name/value query parameter pairs to include as part of the * baseUrl * * @see #append(CharSequence, Object...) * @see #encode(CharSequence) * * @return request */ public static HttpRequest get(final CharSequence baseUrl, final boolean encode, final Object... params) { String url = append(baseUrl, params); return get(encode ? encode(url) : url); } /** * Start a 'POST' request to the given URL * * @param url * @return request * @throws HttpRequestException */ public static HttpRequest post(final CharSequence url) throws HttpRequestException { return new HttpRequest(url, METHOD_POST); } /** * Start a 'POST' request to the given URL * * @param url * @return request * @throws HttpRequestException */ public static HttpRequest post(final URL url) throws HttpRequestException { return new HttpRequest(url, METHOD_POST); } /** * Start a 'POST' request to the given URL along with the query params * * @param baseUrl * @param params * the query parameters to include as part of the baseUrl * @param encode * true to encode the full URL * * @see #append(CharSequence, Map) * @see #encode(CharSequence) * * @return request */ public static HttpRequest post(final CharSequence baseUrl, final Map<?, ?> params, final boolean encode) { String url = append(baseUrl, params); return post(encode ? encode(url) : url); } /** * Start a 'POST' request to the given URL along with the query params * * @param baseUrl * @param encode * true to encode the full URL * @param params * the name/value query parameter pairs to include as part of the * baseUrl * * @see #append(CharSequence, Object...) * @see #encode(CharSequence) * * @return request */ public static HttpRequest post(final CharSequence baseUrl, final boolean encode, final Object... params) { String url = append(baseUrl, params); return post(encode ? encode(url) : url); } /** * Start a 'PATCH' request to the given URL * * @param url * @return request * @throws HttpRequestException */ public static HttpRequest patch(final CharSequence url) throws HttpRequestException { return new HttpRequest(url, METHOD_PATCH); } /** * Start a 'PATCH' request to the given URL * * @param url * @return request * @throws HttpRequestException */ public static HttpRequest patch(final URL url) throws HttpRequestException { return new HttpRequest(url, METHOD_PATCH); } /** * Start a 'PATCH' request to the given URL along with the query params * * @param baseUrl * @param params * the query parameters to include as part of the baseUrl * @param encode * true to encode the full URL * * @see #append(CharSequence, Map) * @see #encode(CharSequence) * * @return request */ public static HttpRequest patch(final CharSequence baseUrl, final Map<?, ?> params, final boolean encode) { String url = append(baseUrl, params); return patch(encode ? encode(url) : url); } /** * Start a 'PATCH' request to the given URL along with the query params * * @param baseUrl * @param encode * true to encode the full URL * @param params * the name/value query parameter pairs to include as part of the * baseUrl * * @see #append(CharSequence, Object...) * @see #encode(CharSequence) * * @return request */ public static HttpRequest patch(final CharSequence baseUrl, final boolean encode, final Object... params) { String url = append(baseUrl, params); return patch(encode ? encode(url) : url); } /** * Start a 'PUT' request to the given URL * * @param url * @return request * @throws HttpRequestException */ public static HttpRequest put(final CharSequence url) throws HttpRequestException { return new HttpRequest(url, METHOD_PUT); } /** * Start a 'PUT' request to the given URL * * @param url * @return request * @throws HttpRequestException */ public static HttpRequest put(final URL url) throws HttpRequestException { return new HttpRequest(url, METHOD_PUT); } /** * Start a 'PUT' request to the given URL along with the query params * * @param baseUrl * @param params * the query parameters to include as part of the baseUrl * @param encode * true to encode the full URL * * @see #append(CharSequence, Map) * @see #encode(CharSequence) * * @return request */ public static HttpRequest put(final CharSequence baseUrl, final Map<?, ?> params, final boolean encode) { String url = append(baseUrl, params); return put(encode ? encode(url) : url); } /** * Start a 'PUT' request to the given URL along with the query params * * @param baseUrl * @param encode * true to encode the full URL * @param params * the name/value query parameter pairs to include as part of the * baseUrl * * @see #append(CharSequence, Object...) * @see #encode(CharSequence) * * @return request */ public static HttpRequest put(final CharSequence baseUrl, final boolean encode, final Object... params) { String url = append(baseUrl, params); return put(encode ? encode(url) : url); } /** * Start a 'DELETE' request to the given URL * * @param url * @return request * @throws HttpRequestException */ public static HttpRequest delete(final CharSequence url) throws HttpRequestException { return new HttpRequest(url, METHOD_DELETE); } /** * Start a 'DELETE' request to the given URL * * @param url * @return request * @throws HttpRequestException */ public static HttpRequest delete(final URL url) throws HttpRequestException { return new HttpRequest(url, METHOD_DELETE); } /** * Start a 'DELETE' request to the given URL along with the query params * * @param baseUrl * @param params * The query parameters to include as part of the baseUrl * @param encode * true to encode the full URL * * @see #append(CharSequence, Map) * @see #encode(CharSequence) * * @return request */ public static HttpRequest delete(final CharSequence baseUrl, final Map<?, ?> params, final boolean encode) { String url = append(baseUrl, params); return delete(encode ? encode(url) : url); } /** * Start a 'DELETE' request to the given URL along with the query params * * @param baseUrl * @param encode * true to encode the full URL * @param params * the name/value query parameter pairs to include as part of the * baseUrl * * @see #append(CharSequence, Object...) * @see #encode(CharSequence) * * @return request */ public static HttpRequest delete(final CharSequence baseUrl, final boolean encode, final Object... params) { String url = append(baseUrl, params); return delete(encode ? encode(url) : url); } /** * Start a 'HEAD' request to the given URL * * @param url * @return request * @throws HttpRequestException */ public static HttpRequest head(final CharSequence url) throws HttpRequestException { return new HttpRequest(url, METHOD_HEAD); } /** * Start a 'HEAD' request to the given URL * * @param url * @return request * @throws HttpRequestException */ public static HttpRequest head(final URL url) throws HttpRequestException { return new HttpRequest(url, METHOD_HEAD); } /** * Start a 'HEAD' request to the given URL along with the query params * * @param baseUrl * @param params * The query parameters to include as part of the baseUrl * @param encode * true to encode the full URL * * @see #append(CharSequence, Map) * @see #encode(CharSequence) * * @return request */ public static HttpRequest head(final CharSequence baseUrl, final Map<?, ?> params, final boolean encode) { String url = append(baseUrl, params); return head(encode ? encode(url) : url); } /** * Start a 'GET' request to the given URL along with the query params * * @param baseUrl * @param encode * true to encode the full URL * @param params * the name/value query parameter pairs to include as part of the * baseUrl * * @see #append(CharSequence, Object...) * @see #encode(CharSequence) * * @return request */ public static HttpRequest head(final CharSequence baseUrl, final boolean encode, final Object... params) { String url = append(baseUrl, params); return head(encode ? encode(url) : url); } /** * Start an 'OPTIONS' request to the given URL * * @param url * @return request * @throws HttpRequestException */ public static HttpRequest options(final CharSequence url) throws HttpRequestException { return new HttpRequest(url, METHOD_OPTIONS); } /** * Start an 'OPTIONS' request to the given URL * * @param url * @return request * @throws HttpRequestException */ public static HttpRequest options(final URL url) throws HttpRequestException { return new HttpRequest(url, METHOD_OPTIONS); } /** * Start a 'TRACE' request to the given URL * * @param url * @return request * @throws HttpRequestException */ public static HttpRequest trace(final CharSequence url) throws HttpRequestException { return new HttpRequest(url, METHOD_TRACE); } /** * Start a 'TRACE' request to the given URL * * @param url * @return request * @throws HttpRequestException */ public static HttpRequest trace(final URL url) throws HttpRequestException { return new HttpRequest(url, METHOD_TRACE); } /** * Set the 'http.keepAlive' property to the given value. * <p> * This setting will apply to all requests. * * @param keepAlive */ public static void keepAlive(final boolean keepAlive) { setProperty("http.keepAlive", Boolean.toString(keepAlive)); } /** * Set the 'http.maxConnections' property to the given value. * <p> * This setting will apply to all requests. * * @param maxConnections */ public static void maxConnections(final int maxConnections) { setProperty("http.maxConnections", Integer.toString(maxConnections)); } /** * Set the 'http.proxyHost' and 'https.proxyHost' properties to the given host * value. * <p> * This setting will apply to all requests. * * @param host */ public static void proxyHost(final String host) { setProperty("http.proxyHost", host); setProperty("https.proxyHost", host); } /** * Set the 'http.proxyPort' and 'https.proxyPort' properties to the given port * number. * <p> * This setting will apply to all requests. * * @param port */ public static void proxyPort(final int port) { final String portValue = Integer.toString(port); setProperty("http.proxyPort", portValue); setProperty("https.proxyPort", portValue); } /** * Set the 'http.nonProxyHosts' property to the given host values. * <p> * Hosts will be separated by a '|' character. * <p> * This setting will apply to all requests. * * @param hosts */ public static void nonProxyHosts(final String... hosts) { if (hosts != null && hosts.length > 0) { StringBuilder separated = new StringBuilder(); int last = hosts.length - 1; for (int i = 0; i < last; i++) separated.append(hosts[i]).append('|'); separated.append(hosts[last]); setProperty("http.nonProxyHosts", separated.toString()); } else setProperty("http.nonProxyHosts", null); } /** * Set property to given value. * <p> * Specifying a null value will cause the property to be cleared * * @param name * @param value * @return previous value */ private static String setProperty(final String name, final String value) { final PrivilegedAction<String> action; if (value != null) action = new PrivilegedAction<String>() { public String run() { return System.setProperty(name, value); } }; else action = new PrivilegedAction<String>() { public String run() { return System.clearProperty(name); } }; return AccessController.doPrivileged(action); } private HttpURLConnection connection = null; private final URL url; private final String requestMethod; private RequestOutputStream output; private boolean multipart; private boolean form; private boolean ignoreCloseExceptions = true; private boolean uncompress = false; private int bufferSize = 8192; private long totalSize = -1; private long totalWritten = 0; private String httpProxyHost; private int httpProxyPort; private UploadProgress progress = UploadProgress.DEFAULT; /** * Create HTTP connection wrapper * * @param url Remote resource URL. * @param method HTTP request method (e.g., "GET", "POST"). * @throws HttpRequestException */ public HttpRequest(final CharSequence url, final String method) throws HttpRequestException { try { this.url = new URL(url.toString()); } catch (MalformedURLException e) { throw new HttpRequestException(e); } this.requestMethod = method; } /** * Create HTTP connection wrapper * * @param url Remote resource URL. * @param method HTTP request method (e.g., "GET", "POST"). * @throws HttpRequestException */ public HttpRequest(final URL url, final String method) throws HttpRequestException { this.url = url; this.requestMethod = method; } private Proxy createProxy() { return new Proxy(HTTP, new InetSocketAddress(httpProxyHost, httpProxyPort)); } private HttpURLConnection createConnection() { try { final HttpURLConnection connection; if (httpProxyHost != null) connection = CONNECTION_FACTORY.create(url, createProxy()); else connection = CONNECTION_FACTORY.create(url); connection.setRequestMethod(requestMethod); return connection; } catch (IOException e) { throw new HttpRequestException(e); } } @Override public String toString() { return method() + ' ' + url(); } /** * Get underlying connection * * @return connection */ public HttpURLConnection getConnection() { if (connection == null) connection = createConnection(); return connection; } /** * Set whether or not to ignore exceptions that occur from calling * {@link Closeable#close()} * <p> * The default value of this setting is <code>true</code> * * @param ignore * @return this request */ public HttpRequest ignoreCloseExceptions(final boolean ignore) { ignoreCloseExceptions = ignore; return this; } /** * Get whether or not exceptions thrown by {@link Closeable#close()} are * ignored * * @return true if ignoring, false if throwing */ public boolean ignoreCloseExceptions() { return ignoreCloseExceptions; } /** * Get the status code of the response * * @return the response code * @throws HttpRequestException */ public int code() throws HttpRequestException { try { closeOutput(); return getConnection().getResponseCode(); } catch (IOException e) { throw new HttpRequestException(e); } } /** * Set the value of the given {@link AtomicInteger} to the status code of the * response * * @param output * @return this request * @throws HttpRequestException */ public HttpRequest code(final AtomicInteger output) throws HttpRequestException { output.set(code()); return this; } /** * Is the response code a 200 OK? * * @return true if 200, false otherwise * @throws HttpRequestException */ public boolean ok() throws HttpRequestException { return HTTP_OK == code(); } /** * Is the response code a 201 Created? * * @return true if 201, false otherwise * @throws HttpRequestException */ public boolean created() throws HttpRequestException { return HTTP_CREATED == code(); } /** * Is the response code a 204 No Content? * * @return true if 204, false otherwise * @throws HttpRequestException */ public boolean noContent() throws HttpRequestException { return HTTP_NO_CONTENT == code(); } /** * Is the response code a 500 Internal Server Error? * * @return true if 500, false otherwise * @throws HttpRequestException */ public boolean serverError() throws HttpRequestException { return HTTP_INTERNAL_ERROR == code(); } /** * Is the response code a 400 Bad Request? * * @return true if 400, false otherwise * @throws HttpRequestException */ public boolean badRequest() throws HttpRequestException { return HTTP_BAD_REQUEST == code(); } /** * Is the response code a 404 Not Found? * * @return true if 404, false otherwise * @throws HttpRequestException */ public boolean notFound() throws HttpRequestException { return HTTP_NOT_FOUND == code(); } /** * Is the response code a 304 Not Modified? * * @return true if 304, false otherwise * @throws HttpRequestException */ public boolean notModified() throws HttpRequestException { return HTTP_NOT_MODIFIED == code(); } /** * Get status message of the response * * @return message * @throws HttpRequestException */ public String message() throws HttpRequestException { try { closeOutput(); return getConnection().getResponseMessage(); } catch (IOException e) { throw new HttpRequestException(e); } } /** * Disconnect the connection * * @return this request */ public HttpRequest disconnect() { getConnection().disconnect(); return this; } /** * Set chunked streaming mode to the given size * * @param size * @return this request */ public HttpRequest chunk(final int size) { getConnection().setChunkedStreamingMode(size); return this; } /** * Set the size used when buffering and copying between streams * <p> * This size is also used for send and receive buffers created for both char * and byte arrays * <p> * The default buffer size is 8,192 bytes * * @param size * @return this request */ public HttpRequest bufferSize(final int size) { if (size < 1) throw new IllegalArgumentException("Size must be greater than zero"); bufferSize = size; return this; } /** * Get the configured buffer size * <p> * The default buffer size is 8,192 bytes * * @return buffer size */ public int bufferSize() { return bufferSize; } /** * Set whether or not the response body should be automatically uncompressed * when read from. * <p> * This will only affect requests that have the 'Content-Encoding' response * header set to 'gzip'. * <p> * This causes all receive methods to use a {@link GZIPInputStream} when * applicable so that higher level streams and readers can read the data * uncompressed. * <p> * Setting this option does not cause any request headers to be set * automatically so {@link #acceptGzipEncoding()} should be used in * conjunction with this setting to tell the server to gzip the response. * * @param uncompress * @return this request */ public HttpRequest uncompress(final boolean uncompress) { this.uncompress = uncompress; return this; } /** * Create byte array output stream * * @return stream */ protected ByteArrayOutputStream byteStream() { final int size = contentLength(); if (size > 0) return new ByteArrayOutputStream(size); else return new ByteArrayOutputStream(); } /** * Get response as {@link String} in given character set * <p> * This will fall back to using the UTF-8 character set if the given charset * is null * * @param charset * @return string * @throws HttpRequestException */ public String body(final String charset) throws HttpRequestException { final ByteArrayOutputStream output = byteStream(); try { copy(buffer(), output); return output.toString(getValidCharset(charset)); } catch (IOException e) { throw new HttpRequestException(e); } } /** * Get response as {@link String} using character set returned from * {@link #charset()} * * @return string * @throws HttpRequestException */ public String body() throws HttpRequestException { return body(charset()); } /** * Get the response body as a {@link String} and set it as the value of the * given reference. * * @param output * @return this request * @throws HttpRequestException */ public HttpRequest body(final AtomicReference<String> output) throws HttpRequestException { output.set(body()); return this; } /** * Get the response body as a {@link String} and set it as the value of the * given reference. * * @param output * @param charset * @return this request * @throws HttpRequestException */ public HttpRequest body(final AtomicReference<String> output, final String charset) throws HttpRequestException { output.set(body(charset)); return this; } /** * Is the response body empty? * * @return true if the Content-Length response header is 0, false otherwise * @throws HttpRequestException */ public boolean isBodyEmpty() throws HttpRequestException { return contentLength() == 0; } /** * Get response as byte array * * @return byte array * @throws HttpRequestException */ public byte[] bytes() throws HttpRequestException { final ByteArrayOutputStream output = byteStream(); try { copy(buffer(), output); } catch (IOException e) { throw new HttpRequestException(e); } return output.toByteArray(); } /** * Get response in a buffered stream * * @see #bufferSize(int) * @return stream * @throws HttpRequestException */ public BufferedInputStream buffer() throws HttpRequestException { return new BufferedInputStream(stream(), bufferSize); } /** * Get stream to response body * * @return stream * @throws HttpRequestException */ public InputStream stream() throws HttpRequestException { InputStream stream; if (code() < HTTP_BAD_REQUEST) try { stream = getConnection().getInputStream(); } catch (IOException e) { throw new HttpRequestException(e); } else { stream = getConnection().getErrorStream(); if (stream == null) try { stream = getConnection().getInputStream(); } catch (IOException e) { if (contentLength() > 0) throw new HttpRequestException(e); else stream = new ByteArrayInputStream(new byte[0]); } } if (!uncompress || !ENCODING_GZIP.equals(contentEncoding())) return stream; else try { return new GZIPInputStream(stream); } catch (IOException e) { throw new HttpRequestException(e); } } /** * Get reader to response body using given character set. * <p> * This will fall back to using the UTF-8 character set if the given charset * is null * * @param charset * @return reader * @throws HttpRequestException */ public InputStreamReader reader(final String charset) throws HttpRequestException { try { return new InputStreamReader(stream(), getValidCharset(charset)); } catch (UnsupportedEncodingException e) { throw new HttpRequestException(e); } } /** * Get reader to response body using the character set returned from * {@link #charset()} * * @return reader * @throws HttpRequestException */ public InputStreamReader reader() throws HttpRequestException { return reader(charset()); } /** * Get buffered reader to response body using the given character set r and * the configured buffer size * * * @see #bufferSize(int) * @param charset * @return reader * @throws HttpRequestException */ public BufferedReader bufferedReader(final String charset) throws HttpRequestException { return new BufferedReader(reader(charset), bufferSize); } /** * Get buffered reader to response body using the character set returned from * {@link #charset()} and the configured buffer size * * @see #bufferSize(int) * @return reader * @throws HttpRequestException */ public BufferedReader bufferedReader() throws HttpRequestException { return bufferedReader(charset()); } /** * Stream response body to file * * @param file * @return this request * @throws HttpRequestException */ public HttpRequest receive(final File file) throws HttpRequestException { final OutputStream output; try { output = new BufferedOutputStream(new FileOutputStream(file), bufferSize); } catch (FileNotFoundException e) { throw new HttpRequestException(e); } return new CloseOperation<HttpRequest>(output, ignoreCloseExceptions) { @Override protected HttpRequest run() throws HttpRequestException, IOException { return receive(output); } }.call(); } /** * Stream response to given output stream * * @param output * @return this request * @throws HttpRequestException */ public HttpRequest receive(final OutputStream output) throws HttpRequestException { try { return copy(buffer(), output); } catch (IOException e) { throw new HttpRequestException(e); } } /** * Stream response to given print stream * * @param output * @return this request * @throws HttpRequestException */ public HttpRequest receive(final PrintStream output) throws HttpRequestException { return receive((OutputStream) output); } /** * Receive response into the given appendable * * @param appendable * @return this request * @throws HttpRequestException */ public HttpRequest receive(final Appendable appendable) throws HttpRequestException { final BufferedReader reader = bufferedReader(); return new CloseOperation<HttpRequest>(reader, ignoreCloseExceptions) { @Override public HttpRequest run() throws IOException { final CharBuffer buffer = CharBuffer.allocate(bufferSize); int read; while ((read = reader.read(buffer)) != -1) { buffer.rewind(); appendable.append(buffer, 0, read); buffer.rewind(); } return HttpRequest.this; } }.call(); } /** * Receive response into the given writer * * @param writer * @return this request * @throws HttpRequestException */ public HttpRequest receive(final Writer writer) throws HttpRequestException { final BufferedReader reader = bufferedReader(); return new CloseOperation<HttpRequest>(reader, ignoreCloseExceptions) { @Override public HttpRequest run() throws IOException { return copy(reader, writer); } }.call(); } /** * Set read timeout on connection to given value * * @param timeout * @return this request */ public HttpRequest readTimeout(final int timeout) { getConnection().setReadTimeout(timeout); return this; } /** * Set connect timeout on connection to given value * * @param timeout * @return this request */ public HttpRequest connectTimeout(final int timeout) { getConnection().setConnectTimeout(timeout); return this; } /** * Set header name to given value * * @param name * @param value * @return this request */ public HttpRequest header(final String name, final String value) { getConnection().setRequestProperty(name, value); return this; } /** * Set header name to given value * * @param name * @param value * @return this request */ public HttpRequest header(final String name, final Number value) { return header(name, value != null ? value.toString() : null); } /** * Set all headers found in given map where the keys are the header names and * the values are the header values * * @param headers * @return this request */ public HttpRequest headers(final Map<String, String> headers) { if (!headers.isEmpty()) for (Entry<String, String> header : headers.entrySet()) header(header); return this; } /** * Set header to have given entry's key as the name and value as the value * * @param header * @return this request */ public HttpRequest header(final Entry<String, String> header) { return header(header.getKey(), header.getValue()); } /** * Get a response header * * @param name * @return response header * @throws HttpRequestException */ public String header(final String name) throws HttpRequestException { closeOutputQuietly(); return getConnection().getHeaderField(name); } /** * Get all the response headers * * @return map of response header names to their value(s) * @throws HttpRequestException */ public Map<String, List<String>> headers() throws HttpRequestException { closeOutputQuietly(); return getConnection().getHeaderFields(); } /** * Get a date header from the response falling back to returning -1 if the * header is missing or parsing fails * * @param name * @return date, -1 on failures * @throws HttpRequestException */ public long dateHeader(final String name) throws HttpRequestException { return dateHeader(name, -1L); } /** * Get a date header from the response falling back to returning the given * default value if the header is missing or parsing fails * * @param name * @param defaultValue * @return date, default value on failures * @throws HttpRequestException */ public long dateHeader(final String name, final long defaultValue) throws HttpRequestException { closeOutputQuietly(); return getConnection().getHeaderFieldDate(name, defaultValue); } /** * Get an integer header from the response falling back to returning -1 if the * header is missing or parsing fails * * @param name * @return header value as an integer, -1 when missing or parsing fails * @throws HttpRequestException */ public int intHeader(final String name) throws HttpRequestException { return intHeader(name, -1); } /** * Get an integer header value from the response falling back to the given * default value if the header is missing or if parsing fails * * @param name * @param defaultValue * @return header value as an integer, default value when missing or parsing * fails * @throws HttpRequestException */ public int intHeader(final String name, final int defaultValue) throws HttpRequestException { closeOutputQuietly(); return getConnection().getHeaderFieldInt(name, defaultValue); } /** * Get all values of the given header from the response * * @param name * @return non-null but possibly empty array of {@link String} header values */ public String[] headers(final String name) { final Map<String, List<String>> headers = headers(); if (headers == null || headers.isEmpty()) return EMPTY_STRINGS; final List<String> values = headers.get(name); if (values != null && !values.isEmpty()) return values.toArray(new String[values.size()]); else return EMPTY_STRINGS; } /** * Get parameter with given name from header value in response * * @param headerName * @param paramName * @return parameter value or null if missing */ public String parameter(final String headerName, final String paramName) { return getParam(header(headerName), paramName); } /** * Get all parameters from header value in response * <p> * This will be all key=value pairs after the first ';' that are separated by * a ';' * * @param headerName * @return non-null but possibly empty map of parameter headers */ public Map<String, String> parameters(final String headerName) { return getParams(header(headerName)); } /** * Get parameter values from header value * * @param header * @return parameter value or null if none */ protected Map<String, String> getParams(final String header) { if (header == null || header.length() == 0) return Collections.emptyMap(); final int headerLength = header.length(); int start = header.indexOf(';') + 1; if (start == 0 || start == headerLength) return Collections.emptyMap(); int end = header.indexOf(';', start); if (end == -1) end = headerLength; Map<String, String> params = new LinkedHashMap<String, String>(); while (start < end) { int nameEnd = header.indexOf('=', start); if (nameEnd != -1 && nameEnd < end) { String name = header.substring(start, nameEnd).trim(); if (name.length() > 0) { String value = header.substring(nameEnd + 1, end).trim(); int length = value.length(); if (length != 0) if (length > 2 && '"' == value.charAt(0) && '"' == value.charAt(length - 1)) params.put(name, value.substring(1, length - 1)); else params.put(name, value); } } start = end + 1; end = header.indexOf(';', start); if (end == -1) end = headerLength; } return params; } /** * Get parameter value from header value * * @param value * @param paramName * @return parameter value or null if none */ protected String getParam(final String value, final String paramName) { if (value == null || value.length() == 0) return null; final int length = value.length(); int start = value.indexOf(';') + 1; if (start == 0 || start == length) return null; int end = value.indexOf(';', start); if (end == -1) end = length; while (start < end) { int nameEnd = value.indexOf('=', start); if (nameEnd != -1 && nameEnd < end && paramName.equals(value.substring(start, nameEnd).trim())) { String paramValue = value.substring(nameEnd + 1, end).trim(); int valueLength = paramValue.length(); if (valueLength != 0) if (valueLength > 2 && '"' == paramValue.charAt(0) && '"' == paramValue.charAt(valueLength - 1)) return paramValue.substring(1, valueLength - 1); else return paramValue; } start = end + 1; end = value.indexOf(';', start); if (end == -1) end = length; } return null; } /** * Get 'charset' parameter from 'Content-Type' response header * * @return charset or null if none */ public String charset() { return parameter(HEADER_CONTENT_TYPE, PARAM_CHARSET); } /** * Set the 'User-Agent' header to given value * * @param userAgent * @return this request */ public HttpRequest userAgent(final String userAgent) { return header(HEADER_USER_AGENT, userAgent); } /** * Set the 'Referer' header to given value * * @param referer * @return this request */ public HttpRequest referer(final String referer) { return header(HEADER_REFERER, referer); } /** * Set value of {@link HttpURLConnection#setUseCaches(boolean)} * * @param useCaches * @return this request */ public HttpRequest useCaches(final boolean useCaches) { getConnection().setUseCaches(useCaches); return this; } /** * Set the 'Accept-Encoding' header to given value * * @param acceptEncoding * @return this request */ public HttpRequest acceptEncoding(final String acceptEncoding) { return header(HEADER_ACCEPT_ENCODING, acceptEncoding); } /** * Set the 'Accept-Encoding' header to 'gzip' * * @see #uncompress(boolean) * @return this request */ public HttpRequest acceptGzipEncoding() { return acceptEncoding(ENCODING_GZIP); } /** * Set the 'Accept-Charset' header to given value * * @param acceptCharset * @return this request */ public HttpRequest acceptCharset(final String acceptCharset) { return header(HEADER_ACCEPT_CHARSET, acceptCharset); } /** * Get the 'Content-Encoding' header from the response * * @return this request */ public String contentEncoding() { return header(HEADER_CONTENT_ENCODING); } /** * Get the 'Server' header from the response * * @return server */ public String server() { return header(HEADER_SERVER); } /** * Get the 'Date' header from the response * * @return date value, -1 on failures */ public long date() { return dateHeader(HEADER_DATE); } /** * Get the 'Cache-Control' header from the response * * @return cache control */ public String cacheControl() { return header(HEADER_CACHE_CONTROL); } /** * Get the 'ETag' header from the response * * @return entity tag */ public String eTag() { return header(HEADER_ETAG); } /** * Get the 'Expires' header from the response * * @return expires value, -1 on failures */ public long expires() { return dateHeader(HEADER_EXPIRES); } /** * Get the 'Last-Modified' header from the response * * @return last modified value, -1 on failures */ public long lastModified() { return dateHeader(HEADER_LAST_MODIFIED); } /** * Get the 'Location' header from the response * * @return location */ public String location() { return header(HEADER_LOCATION); } /** * Set the 'Authorization' header to given value * * @param authorization * @return this request */ public HttpRequest authorization(final String authorization) { return header(HEADER_AUTHORIZATION, authorization); } /** * Set the 'Proxy-Authorization' header to given value * * @param proxyAuthorization * @return this request */ public HttpRequest proxyAuthorization(final String proxyAuthorization) { return header(HEADER_PROXY_AUTHORIZATION, proxyAuthorization); } /** * Set the 'Authorization' header to given values in Basic authentication * format * * @param name * @param password * @return this request */ public HttpRequest basic(final String name, final String password) { return authorization("Basic " + Base64.encode(name + ':' + password)); } /** * Set the 'Proxy-Authorization' header to given values in Basic authentication * format * * @param name * @param password * @return this request */ public HttpRequest proxyBasic(final String name, final String password) { return proxyAuthorization("Basic " + Base64.encode(name + ':' + password)); } /** * Set the 'If-Modified-Since' request header to the given value * * @param ifModifiedSince * @return this request */ public HttpRequest ifModifiedSince(final long ifModifiedSince) { getConnection().setIfModifiedSince(ifModifiedSince); return this; } /** * Set the 'If-None-Match' request header to the given value * * @param ifNoneMatch * @return this request */ public HttpRequest ifNoneMatch(final String ifNoneMatch) { return header(HEADER_IF_NONE_MATCH, ifNoneMatch); } /** * Set the 'Content-Type' request header to the given value * * @param contentType * @return this request */ public HttpRequest contentType(final String contentType) { return contentType(contentType, null); } /** * Set the 'Content-Type' request header to the given value and charset * * @param contentType * @param charset * @return this request */ public HttpRequest contentType(final String contentType, final String charset) { if (charset != null && charset.length() > 0) { final String separator = ";" + PARAM_CHARSET + '='; // return header(HEADER_CONTENT_TYPE, contentType + separator + charset); return header(HEADER_CONTENT_TYPE, contentType); } else return header(HEADER_CONTENT_TYPE, contentType); } /** * Get the 'Content-Type' header from the response * * @return response header value */ public String contentType() { return header(HEADER_CONTENT_TYPE); } /** * Get the 'Content-Length' header from the response * * @return response header value */ public int contentLength() { return intHeader(HEADER_CONTENT_LENGTH); } /** * Set the 'Content-Length' request header to the given value * * @param contentLength * @return this request */ public HttpRequest contentLength(final String contentLength) { return contentLength(Integer.parseInt(contentLength)); } /** * Set the 'Content-Length' request header to the given value * * @param contentLength * @return this request */ public HttpRequest contentLength(final int contentLength) { getConnection().setFixedLengthStreamingMode(contentLength); return this; } /** * Set the 'Accept' header to given value * * @param accept * @return this request */ public HttpRequest accept(final String accept) { return header(HEADER_ACCEPT, accept); } /** * Set the 'Accept' header to 'application/json' * * @return this request */ public HttpRequest acceptJson() { return accept(CONTENT_TYPE_JSON); } /** * Copy from input stream to output stream * * @param input * @param output * @return this request * @throws IOException */ protected HttpRequest copy(final InputStream input, final OutputStream output) throws IOException { return new CloseOperation<HttpRequest>(input, ignoreCloseExceptions) { @Override public HttpRequest run() throws IOException { final byte[] buffer = new byte[bufferSize]; int read; while ((read = input.read(buffer)) != -1) { output.write(buffer, 0, read); totalWritten += read; progress.onUpload(totalWritten, totalSize); } return HttpRequest.this; } }.call(); } /** * Copy from reader to writer * * @param input * @param output * @return this request * @throws IOException */ protected HttpRequest copy(final Reader input, final Writer output) throws IOException { return new CloseOperation<HttpRequest>(input, ignoreCloseExceptions) { @Override public HttpRequest run() throws IOException { final char[] buffer = new char[bufferSize]; int read; while ((read = input.read(buffer)) != -1) { output.write(buffer, 0, read); totalWritten += read; progress.onUpload(totalWritten, -1); } return HttpRequest.this; } }.call(); } /** * Set the UploadProgress callback for this request * * @param callback * @return this request */ public HttpRequest progress(final UploadProgress callback) { if (callback == null) progress = UploadProgress.DEFAULT; else progress = callback; return this; } private HttpRequest incrementTotalSize(final long size) { if (totalSize == -1) totalSize = 0; totalSize += size; return this; } /** * Close output stream * * @return this request * @throws HttpRequestException * @throws IOException */ protected HttpRequest closeOutput() throws IOException { progress(null); if (output == null) return this; if (multipart) output.write(CRLF + "--" + BOUNDARY + "--" + CRLF); if (ignoreCloseExceptions) try { output.close(); } catch (IOException ignored) { // Ignored } else output.close(); output = null; return this; } /** * Call {@link #closeOutput()} and re-throw a caught {@link IOException}s as * an {@link HttpRequestException} * * @return this request * @throws HttpRequestException */ protected HttpRequest closeOutputQuietly() throws HttpRequestException { try { return closeOutput(); } catch (IOException e) { throw new HttpRequestException(e); } } /** * Open output stream * * @return this request * @throws IOException */ protected HttpRequest openOutput() throws IOException { if (output != null) return this; getConnection().setDoOutput(true); final String charset = getParam( getConnection().getRequestProperty(HEADER_CONTENT_TYPE), PARAM_CHARSET); output = new RequestOutputStream(getConnection().getOutputStream(), charset, bufferSize); return this; } /** * Start part of a multipart * * @return this request * @throws IOException */ protected HttpRequest startPart() throws IOException { if (!multipart) { multipart = true; contentType(CONTENT_TYPE_MULTIPART).openOutput(); output.write("--" + BOUNDARY + CRLF); } else output.write(CRLF + "--" + BOUNDARY + CRLF); return this; } /** * Write part header * * @param name * @param filename * @return this request * @throws IOException */ protected HttpRequest writePartHeader(final String name, final String filename) throws IOException { return writePartHeader(name, filename, null); } /** * Write part header * * @param name * @param filename * @param contentType * @return this request * @throws IOException */ protected HttpRequest writePartHeader(final String name, final String filename, final String contentType) throws IOException { final StringBuilder partBuffer = new StringBuilder(); partBuffer.append("form-data; name=\"").append(name); if (filename != null) partBuffer.append("\"; filename=\"").append(filename); partBuffer.append('"'); partHeader("Content-Disposition", partBuffer.toString()); if (contentType != null) partHeader(HEADER_CONTENT_TYPE, contentType); return send(CRLF); } /** * Write part of a multipart request to the request body * * @param name * @param part * @return this request */ public HttpRequest part(final String name, final String part) { return part(name, null, part); } /** * Write part of a multipart request to the request body * * @param name * @param filename * @param part * @return this request * @throws HttpRequestException */ public HttpRequest part(final String name, final String filename, final String part) throws HttpRequestException { return part(name, filename, null, part); } /** * Write part of a multipart request to the request body * * @param name * @param filename * @param contentType * value of the Content-Type part header * @param part * @return this request * @throws HttpRequestException */ public HttpRequest part(final String name, final String filename, final String contentType, final String part) throws HttpRequestException { try { startPart(); writePartHeader(name, filename, contentType); output.write(part); } catch (IOException e) { throw new HttpRequestException(e); } return this; } /** * Write part of a multipart request to the request body * * @param name * @param part * @return this request * @throws HttpRequestException */ public HttpRequest part(final String name, final Number part) throws HttpRequestException { return part(name, null, part); } /** * Write part of a multipart request to the request body * * @param name * @param filename * @param part * @return this request * @throws HttpRequestException */ public HttpRequest part(final String name, final String filename, final Number part) throws HttpRequestException { return part(name, filename, part != null ? part.toString() : null); } /** * Write part of a multipart request to the request body * * @param name * @param part * @return this request * @throws HttpRequestException */ public HttpRequest part(final String name, final File part) throws HttpRequestException { return part(name, null, part); } /** * Write part of a multipart request to the request body * * @param name * @param filename * @param part * @return this request * @throws HttpRequestException */ public HttpRequest part(final String name, final String filename, final File part) throws HttpRequestException { return part(name, filename, null, part); } /** * Write part of a multipart request to the request body * * @param name * @param filename * @param contentType * value of the Content-Type part header * @param part * @return this request * @throws HttpRequestException */ public HttpRequest part(final String name, final String filename, final String contentType, final File part) throws HttpRequestException { final InputStream stream; try { stream = new BufferedInputStream(new FileInputStream(part)); incrementTotalSize(part.length()); } catch (IOException e) { throw new HttpRequestException(e); } return part(name, filename, contentType, stream); } /** * Write part of a multipart request to the request body * * @param name * @param part * @return this request * @throws HttpRequestException */ public HttpRequest part(final String name, final InputStream part) throws HttpRequestException { return part(name, null, null, part); } /** * Write part of a multipart request to the request body * * @param name * @param filename * @param contentType * value of the Content-Type part header * @param part * @return this request * @throws HttpRequestException */ public HttpRequest part(final String name, final String filename, final String contentType, final InputStream part) throws HttpRequestException { try { startPart(); writePartHeader(name, filename, contentType); copy(part, output); } catch (IOException e) { throw new HttpRequestException(e); } return this; } /** * Write a multipart header to the response body * * @param name * @param value * @return this request * @throws HttpRequestException */ public HttpRequest partHeader(final String name, final String value) throws HttpRequestException { return send(name).send(": ").send(value).send(CRLF); } /** * Write contents of file to request body * * @param input * @return this request * @throws HttpRequestException */ public HttpRequest send(final File input) throws HttpRequestException { final InputStream stream; try { stream = new BufferedInputStream(new FileInputStream(input)); incrementTotalSize(input.length()); } catch (FileNotFoundException e) { throw new HttpRequestException(e); } return send(stream); } /** * Write byte array to request body * * @param input * @return this request * @throws HttpRequestException */ public HttpRequest send(final byte[] input) throws HttpRequestException { if (input != null) incrementTotalSize(input.length); return send(new ByteArrayInputStream(input)); } /** * Write stream to request body * <p> * The given stream will be closed once sending completes * * @param input * @return this request * @throws HttpRequestException */ public HttpRequest send(final InputStream input) throws HttpRequestException { try { openOutput(); copy(input, output); } catch (IOException e) { throw new HttpRequestException(e); } return this; } /** * Write reader to request body * <p> * The given reader will be closed once sending completes * * @param input * @return this request * @throws HttpRequestException */ public HttpRequest send(final Reader input) throws HttpRequestException { try { openOutput(); } catch (IOException e) { throw new HttpRequestException(e); } final Writer writer = new OutputStreamWriter(output, output.encoder.charset()); return new FlushOperation<HttpRequest>(writer) { @Override protected HttpRequest run() throws IOException { return copy(input, writer); } }.call(); } /** * Write char sequence to request body * <p> * The charset configured via {@link #contentType(String)} will be used and * UTF-8 will be used if it is unset. * * @param value * @return this request * @throws HttpRequestException */ public HttpRequest send(final CharSequence value) throws HttpRequestException { try { openOutput(); output.write(value.toString()); } catch (IOException e) { throw new HttpRequestException(e); } return this; } /** * Create writer to request output stream * * @return writer * @throws HttpRequestException */ public OutputStreamWriter writer() throws HttpRequestException { try { openOutput(); return new OutputStreamWriter(output, output.encoder.charset()); } catch (IOException e) { throw new HttpRequestException(e); } } /** * Write the values in the map as form data to the request body * <p> * The pairs specified will be URL-encoded in UTF-8 and sent with the * 'application/x-www-form-urlencoded' content-type * * @param values * @return this request * @throws HttpRequestException */ public HttpRequest form(final Map<?, ?> values) throws HttpRequestException { return form(values, CHARSET_UTF8); } /** * Write the key and value in the entry as form data to the request body * <p> * The pair specified will be URL-encoded in UTF-8 and sent with the * 'application/x-www-form-urlencoded' content-type * * @param entry * @return this request * @throws HttpRequestException */ public HttpRequest form(final Entry<?, ?> entry) throws HttpRequestException { return form(entry, CHARSET_UTF8); } /** * Write the key and value in the entry as form data to the request body * <p> * The pair specified will be URL-encoded and sent with the * 'application/x-www-form-urlencoded' content-type * * @param entry * @param charset * @return this request * @throws HttpRequestException */ public HttpRequest form(final Entry<?, ?> entry, final String charset) throws HttpRequestException { return form(entry.getKey(), entry.getValue(), charset); } /** * Write the name/value pair as form data to the request body * <p> * The pair specified will be URL-encoded in UTF-8 and sent with the * 'application/x-www-form-urlencoded' content-type * * @param name * @param value * @return this request * @throws HttpRequestException */ public HttpRequest form(final Object name, final Object value) throws HttpRequestException { return form(name, value, CHARSET_UTF8); } /** * Write the name/value pair as form data to the request body * <p> * The values specified will be URL-encoded and sent with the * 'application/x-www-form-urlencoded' content-type * * @param name * @param value * @param charset * @return this request * @throws HttpRequestException */ public HttpRequest form(final Object name, final Object value, String charset) throws HttpRequestException { final boolean first = !form; if (first) { contentType(CONTENT_TYPE_FORM, charset); form = true; } charset = getValidCharset(charset); try { openOutput(); if (!first) output.write('&'); output.write(URLEncoder.encode(name.toString(), charset)); output.write('='); if (value != null) output.write(URLEncoder.encode(value.toString(), charset)); } catch (IOException e) { throw new HttpRequestException(e); } return this; } /** * Write the values in the map as encoded form data to the request body * * @param values * @param charset * @return this request * @throws HttpRequestException */ public HttpRequest form(final Map<?, ?> values, final String charset) throws HttpRequestException { if (!values.isEmpty()) for (Entry<?, ?> entry : values.entrySet()) form(entry, charset); return this; } /** * Configure HTTPS connection to trust only certain certificates * <p> * This method throws an exception if the current request is not a HTTPS request * * @return this request * @throws HttpRequestException */ public HttpRequest pinToCerts() throws HttpRequestException { final HttpURLConnection connection = getConnection(); if (connection instanceof HttpsURLConnection) { ((HttpsURLConnection) connection).setSSLSocketFactory(getPinnedFactory()); } else { IOException e = new IOException("You must use a https url to use ssl pinning"); throw new HttpRequestException(e); } return this; } /** * Configure HTTPS connection to trust all certificates * <p> * This method does nothing if the current request is not a HTTPS request * * @return this request * @throws HttpRequestException */ public HttpRequest trustAllCerts() throws HttpRequestException { final HttpURLConnection connection = getConnection(); if (connection instanceof HttpsURLConnection) ((HttpsURLConnection) connection) .setSSLSocketFactory(getTrustedFactory()); return this; } /** * Configure HTTPS connection to trust all hosts using a custom * {@link HostnameVerifier} that always returns <code>true</code> for each * host verified * <p> * This method does nothing if the current request is not a HTTPS request * * @return this request */ public HttpRequest trustAllHosts() { final HttpURLConnection connection = getConnection(); if (connection instanceof HttpsURLConnection) ((HttpsURLConnection) connection) .setHostnameVerifier(getTrustedVerifier()); return this; } /** * Get the {@link URL} of this request's connection * * @return request URL */ public URL url() { return getConnection().getURL(); } /** * Get the HTTP method of this request * * @return method */ public String method() { return getConnection().getRequestMethod(); } /** * Configure an HTTP proxy on this connection. Use {{@link #proxyBasic(String, String)} if * this proxy requires basic authentication. * * @param proxyHost * @param proxyPort * @return this request */ public HttpRequest useProxy(final String proxyHost, final int proxyPort) { if (connection != null) throw new IllegalStateException("The connection has already been created. This method must be called before reading or writing to the request."); this.httpProxyHost = proxyHost; this.httpProxyPort = proxyPort; return this; } /** * Set whether or not the underlying connection should follow redirects in * the response. * * @param followRedirects - true fo follow redirects, false to not. * @return this request */ public HttpRequest followRedirects(final boolean followRedirects) { getConnection().setInstanceFollowRedirects(followRedirects); return this; } }
package com.atguigu.gulimall.ware.service; import com.baomidou.mybatisplus.extension.service.IService; import com.atguigu.common.utils.PageUtils; import com.atguigu.gulimall.ware.entity.UndoLogEntity; import java.util.Map; /** * * * @author hh * @email 55333@qq.com * @date 2022-04-08 20:19:11 */ public interface UndoLogService extends IService<UndoLogEntity> { PageUtils queryPage(Map<String, Object> params); }
package com.learning.spring.workshop.boot.mvc; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class WebMVCRequestMappingApplication { public static void main(String[] args) { SpringApplication.run(WebMVCRequestMappingApplication.class, args); } }
package stroom.config.global.impl; import com.google.inject.AbstractModule; import stroom.config.global.api.FetchGlobalConfigAction; import stroom.config.global.api.ListGlobalConfigAction; import stroom.config.global.api.UpdateGlobalConfigAction; import stroom.task.api.TaskHandlerBinder; public class GlobalConfigModule extends AbstractModule { @Override protected void configure() { bind(ConfigMapper.class).toProvider(ConfigMapper.ConfigMapperFactory.class); bind(ConfigInitialiser.class).asEagerSingleton(); TaskHandlerBinder.create(binder()) .bind(ListGlobalConfigAction.class, ListGlobalConfigHandler.class) .bind(FetchGlobalConfigAction.class, FetchGlobalConfigHandler.class) .bind(UpdateGlobalConfigAction.class, UpdateGlobalConfigHandler.class); } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; return true; } @Override public int hashCode() { return 0; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.security; import com.azure.core.util.Context; /** Samples for RegulatoryComplianceStandards Get. */ public final class RegulatoryComplianceStandardsGetSamples { /** * Sample code: Get selected regulatory compliance standard details and state. * * @param securityManager Entry point to SecurityManager. API spec for Microsoft.Security (Azure Security Center) * resource provider. */ public static void getSelectedRegulatoryComplianceStandardDetailsAndState( com.azure.resourcemanager.security.SecurityManager securityManager) { securityManager.regulatoryComplianceStandards().getWithResponse("PCI-DSS-3.2", Context.NONE); } }
package org.pudding.listeners; import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent; import net.dv8tion.jda.api.hooks.ListenerAdapter; import javax.annotation.Nonnull; public class PrivateMessageReceived extends ListenerAdapter { @Override public void onPrivateMessageReceived(@Nonnull PrivateMessageReceivedEvent e) { } }
/** * 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.activemq.security; import org.apache.activemq.broker.Broker; import org.apache.activemq.broker.BrokerFilter; import org.apache.activemq.broker.ConnectionContext; import org.apache.activemq.broker.Connector; import org.apache.activemq.broker.EmptyBroker; import org.apache.activemq.broker.TransportConnector; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ConnectionInfo; import org.apache.activemq.transport.tcp.SslTransportServer; /** * A JAAS Authentication Broker that uses different JAAS domain configurations * depending if the connection is over an SSL enabled Connector or not. * * This allows you to, for instance, do DN based authentication for SSL connections * and use a mixture of username/passwords and simple guest authentication for * non-SSL connections. * <p> * An example <code>login.config</code> to do do this is: * <pre> * activemq-domain { * org.apache.activemq.jaas.PropertiesLoginModule sufficient * debug=true * org.apache.activemq.jaas.properties.user="users.properties" * org.apache.activemq.jaas.properties.group="groups.properties"; * org.apache.activemq.jaas.GuestLoginModule sufficient * debug=true * org.apache.activemq.jaas.guest.user="guest" * org.apache.activemq.jaas.guest.group="guests"; * }; * * activemq-ssl-domain { * org.apache.activemq.jaas.TextFileCertificateLoginModule required * debug=true * org.apache.activemq.jaas.textfiledn.user="dns.properties" * org.apache.activemq.jaas.textfiledn.group="groups.properties"; * }; * </pre> */ public class JaasDualAuthenticationBroker extends BrokerFilter { private final JaasCertificateAuthenticationBroker sslBroker; private final JaasAuthenticationBroker nonSslBroker; /*** Simple constructor. Leaves everything to superclass. * * @param next The Broker that does the actual work for this Filter. * @param jaasConfiguration The JAAS domain configuration name for * non-SSL connections (refer to JAAS documentation). * @param jaasSslConfiguration The JAAS domain configuration name for * SSL connections (refer to JAAS documentation). */ public JaasDualAuthenticationBroker(Broker next, String jaasConfiguration, String jaasSslConfiguration) { super(next); this.nonSslBroker = new JaasAuthenticationBroker(new EmptyBroker(), jaasConfiguration); this.sslBroker = new JaasCertificateAuthenticationBroker(new EmptyBroker(), jaasSslConfiguration); } /** * Overridden to allow for authentication using different Jaas * configurations depending on if the connection is SSL or not. * * @param context The context for the incoming Connection. * @param info The ConnectionInfo Command representing the incoming * connection. */ @Override public void addConnection(ConnectionContext context, ConnectionInfo info) throws Exception { if (context.getSecurityContext() == null) { boolean isSSL; Connector connector = context.getConnector(); if (connector instanceof TransportConnector) { TransportConnector transportConnector = (TransportConnector) connector; isSSL = transportConnector.getServer().isSslServer(); } else { isSSL = false; } if (isSSL) { this.sslBroker.addConnection(context, info); } else { this.nonSslBroker.addConnection(context, info); } super.addConnection(context, info); } } /** * Overriding removeConnection to make sure the security context is cleaned. */ @Override public void removeConnection(ConnectionContext context, ConnectionInfo info, Throwable error) throws Exception { boolean isSSL; Connector connector = context.getConnector(); if (connector instanceof TransportConnector) { TransportConnector transportConnector = (TransportConnector) connector; isSSL = (transportConnector.getServer() instanceof SslTransportServer); } else { isSSL = false; } super.removeConnection(context, info, error); if (isSSL) { this.sslBroker.removeConnection(context, info, error); } else { this.nonSslBroker.removeConnection(context, info, error); } } @Override public void removeDestination(ConnectionContext context, ActiveMQDestination destination, long timeout) throws Exception { // Give both a chance to clear out their contexts this.sslBroker.removeDestination(context, destination, timeout); this.nonSslBroker.removeDestination(context, destination, timeout); super.removeDestination(context, destination, timeout); } }
package com.camunda.ui.TaskList; import org.apache.ibatis.logging.LogFactory; import org.camunda.bpm.engine.runtime.ProcessInstance; import org.camunda.bpm.engine.test.ProcessEngineRule; import org.camunda.bpm.extension.process_test_coverage.junit.rules.TestCoverageProcessEngineRuleBuilder; import org.camunda.bpm.engine.test.Deployment; import org.junit.Before; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.*; import static org.junit.Assert.*; /** * Test case starting an in-memory database-backed Process Engine. */ public class InMemoryH2Test { @ClassRule @Rule public static ProcessEngineRule rule = TestCoverageProcessEngineRuleBuilder.create().build(); private static final String PROCESS_DEFINITION_KEY = "TaskList"; static { LogFactory.useSlf4jLogging(); // MyBatis } @Before public void setup() { init(rule.getProcessEngine()); } /** * Just tests if the process definition is deployable. */ @Test @Deployment(resources = "process.bpmn") public void testParsingAndDeployment() { // nothing is done here, as we just want to check for exceptions during deployment } @Test @Deployment(resources = "process.bpmn") public void testHappyPath() { //ProcessInstance processInstance = processEngine().getRuntimeService().startProcessInstanceByKey(PROCESS_DEFINITION_KEY); // Now: Drive the process by API and assert correct behavior by camunda-bpm-assert } }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.admanager.jaxws.v201805; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * * Gets a {@link ContactPage} of {@link Contact} objects that satisfy the given * {@link Statement#query}. The following fields are supported for filtering: * * <table> * <tr> * <th scope="col">PQL Property</th> <th scope="col">Object Property</th> * </tr> * <tr> * <td>{@code name}</td> * <td>{@link Contact#name}</td> * </tr> * <tr> * <td>{@code email}</td> * <td>{@link Contact#email}</td> * </tr> * <tr> * <td>{@code id}</td> * <td>{@link Contact#id}</td> * </tr> * <tr> * <td>{@code comment}</td> * <td>{@link Contact#comment}</td> * </tr> * <tr> * <td>{@code companyId}</td> * <td>{@link Contact#companyId}</td> * </tr> * <tr> * <td>{@code title}</td> * <td>{@link Contact#title}</td> * </tr> * <tr> * <td>{@code cellPhone}</td> * <td>{@link Contact#cellPhone}</td> * </tr> * <tr> * <td>{@code workPhone}</td> * <td>{@link Contact#workPhone}</td> * </tr> * <tr> * <td>{@code faxPhone}</td> * <td>{@link Contact#faxPhone}</td> * </tr> * <tr> * <td>{@code status}</td> * <td>{@link Contact#status}</td> * </tr> * </table> * * @param filterStatement a Publisher Query Language statement used to filter * a set of contacts * @return the contacts that match the given filter * * * <p>Java class for getContactsByStatement element declaration. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;element name="getContactsByStatement"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="statement" type="{https://www.google.com/apis/ads/publisher/v201805}Statement" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "statement" }) @XmlRootElement(name = "getContactsByStatement") public class ContactServiceInterfacegetContactsByStatement { protected Statement statement; /** * Gets the value of the statement property. * * @return * possible object is * {@link Statement } * */ public Statement getStatement() { return statement; } /** * Sets the value of the statement property. * * @param value * allowed object is * {@link Statement } * */ public void setStatement(Statement value) { this.statement = value; } }
package com.liquidlabs.vso; import static org.junit.Assert.*; import java.util.concurrent.Executors; import com.liquidlabs.common.NetworkUtils; import org.jmock.Expectations; import org.jmock.Mockery; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.liquidlabs.orm.Id; import com.liquidlabs.orm.ORMapperFactory; import com.liquidlabs.transport.proxy.AddressUpdater; import com.liquidlabs.vso.lookup.LookupSpace; import com.liquidlabs.vso.lookup.ServiceInfo; public class SpaceServicePeerTest { Mockery mockery = new Mockery(); private LookupSpace lookup; private ORMapperFactory mapperOne; private SpaceServiceImpl spaceOne; private SpaceServiceImpl spaceTwo; private ORMapperFactory mapperTwo; @Before public void setUp() throws Exception { try { com.liquidlabs.common.concurrent.ExecutorService.setTestMode(); lookup = mockery.mock(LookupSpace.class); mockery.checking(new Expectations() { { atLeast(1).of(lookup).registerService(with(any(ServiceInfo.class)), with(any(Long.class))); atLeast(1).of(lookup).registerUpdateListener(with(any(String.class)), with(any(AddressUpdater.class)), with(any(String.class)), with(any(String.class)), with(any(String.class)), with(any(String.class)), with(any(Boolean.class))); atLeast(1).of(lookup).unregisterService(with(any(ServiceInfo.class))); } }); final int p1 = NetworkUtils.determinePort(10204); this.mapperOne = new ORMapperFactory(p1, "SERVICE", p1); spaceOne = new SpaceServiceImpl(lookup, mapperOne, "SERVICE", Executors.newScheduledThreadPool(10), true, false, true); spaceOne.start(); spaceOne.start(this, "test-1.0"); final int p2 = NetworkUtils.determinePort(11024); this.mapperTwo = new ORMapperFactory(p2, "SERVICE", p2); spaceTwo = new SpaceServiceImpl(lookup, mapperTwo, "SERVICE", Executors.newScheduledThreadPool(10), true, false, true); spaceTwo.start(); spaceTwo.start(this, "test-1.0"); spaceOne.addPeer(spaceTwo.getReplicationURI()); spaceTwo.addPeer(spaceOne.getReplicationURI()); Thread.sleep(3 * 1000); } catch (Throwable t) { t.printStackTrace(); } } @After public void tearDown() throws Exception { spaceOne.stop(); spaceTwo.stop(); } public int count = 0; @Test public void testShouldWriteInOneAndReadInTheOther() throws Exception { System.out.println("Writting Hello:::::::::::::::::::::"); spaceOne.store(new Stuff("hello"), 7); Thread.sleep(500); mapperOne.stop(); System.out.println("Reading Hello:::::::::::::::::::::"); Stuff findById = spaceTwo.findById(Stuff.class, "hello"); assertNotNull("Should have found Stuff instance 'hello'",findById); Thread.sleep(10 * 1000); Stuff findById2 = spaceTwo.findById(Stuff.class, "hello"); assertNull("Should have Expired",findById2); } public static class Stuff { public Stuff() { } public Stuff(String string) { id = string; } @Id String id; } }
package de.dosmike.sponge.lockette; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Base64; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; import java.util.UUID; import org.spongepowered.api.Sponge; import org.spongepowered.api.world.Location; import org.spongepowered.api.world.World; import com.google.common.reflect.TypeToken; import ninja.leaping.configurate.ConfigurationNode; import ninja.leaping.configurate.objectmapping.ObjectMappingException; import ninja.leaping.configurate.objectmapping.serialize.TypeSerializer; public class LockSerializer implements TypeSerializer<PluginLock> { /** convert any serializable into a string */ private static String serser(Serializable o) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(o); oos.close(); return Base64.getEncoder().encodeToString(baos.toByteArray()); } /** convert serialized string data into a class object */ private static Object serdes(String s) throws IOException, ClassNotFoundException { byte[] bdata = Base64.getDecoder().decode(s); ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bdata)); Object o = ois.readObject(); ois.close(); return o; } static Location<World> str2loc (String s) { String[] p = s.split("/"); return Sponge.getServer().getWorld(p[0]).get().getLocation(Double.parseDouble(p[1]), Double.parseDouble(p[2]), Double.parseDouble(p[3])); } static String loc2str (Location<World> l) { return l.getExtent().getName() + "/" + l.getX() + "/" + l.getY() + "/" + l.getZ(); } TypeToken<List<UUID>> tokenListUUID = new TypeToken<List<UUID>>() { private static final long serialVersionUID = 1217193667806512560L; }; @Override public PluginLock deserialize(TypeToken<?> type, ConfigurationNode cfg) throws ObjectMappingException { PluginLock lock = new PluginLock(); String tmp = cfg.getNode("owner").getString(); lock.owner = tmp==null?null:UUID.fromString(tmp); lock.active = cfg.getNode("active").getBoolean(); lock.permission = cfg.getNode("permission").getString(); lock.permitted = (List<UUID>)cfg.getNode("permitted").getValue(tokenListUUID); lock.pluginID = cfg.getNode("pluginID").getString(); lock.data = new HashMap<>(); cfg.getNode("data").getChildrenMap().forEach((Object t, ConfigurationNode u)-> { try { lock.data.put((String)t, (Serializable)serdes(u.getString())); } catch (Exception e) { e.printStackTrace(); } }); return lock; } @Override public void serialize(TypeToken<?> type, PluginLock obj, ConfigurationNode cfg) throws ObjectMappingException { cfg.getNode("active").setValue(obj.active); cfg.getNode("owner").setValue(obj.owner.toString()); cfg.getNode("permission").setValue(obj.permission); cfg.getNode("permitted").setValue(tokenListUUID, obj.permitted); cfg.getNode("pluginID").setValue(obj.pluginID); cfg = cfg.getNode("data"); for (Entry<String, Serializable> d : obj.data.entrySet()) { try { cfg.getNode(d.getKey()).setValue(serser(d.getValue())); } catch (Exception e1) { throw new ObjectMappingException("Failed to save custom plugin lock data", e1); } } } }
package com.sodino.titlebar.fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.sodino.titlebar.R; import com.sodino.titlebar.activity.BaseActivity; /** * Created by Administrator on 2017/4/6. */ public class ContactFragment extends BaseFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.frag_contact, container, false); return v; } @Override protected boolean isFixTransparentStatusBar(){ return true; } @Override protected void fixTransparentStatusBar(View view) { BaseActivity.addTransparentStatusBarBgView(mActivity, view); } }
package algorithm; import com.jme3.math.Quaternion; import javafx.geometry.Point3D; import org.apache.commons.math3.stat.descriptive.rank.Percentile; import java.util.Collections; import java.util.List; /** * This class provides the methods for processing the measurements. */ public class DataProcessor { /** * This method computes the distance of two average points. Then the * expected distance is subtracted from the distance of the points. * * @param expectedDistance - value of type double * @param firstAverangeMeasurement - value of type AverageMeasurement * @param secondAverangeMeasurement - value of type AverageMeasurement * @return accurate - the distance */ public double getAccuracy(double expectedDistance, AverageMeasurement firstAverangeMeasurement, AverageMeasurement secondAverangeMeasurement) { /** * calculates the distance between the points of * firstAverangeMeasurement and secondAverangeMeasurement */ double accurate = getDistance(firstAverangeMeasurement.getPoint(), secondAverangeMeasurement.getPoint()) - expectedDistance; return accurate; } /** * This method gets a quaternion (four double values) and two * measurements. With the method getRotation the quaternion of * firstMeasurement is fetched. From this value, the second * quaternion is subtracted from the second measurement. * Then the expected quaternion is subtracted. * * @param expectedRotation - of type quaternion * @param firstMeasurement - of type Measurement * @param secondMeasurement - of type Measurement * @return result - of type quaternion */ public Quaternion getAccuracyRotation(Quaternion expectedRotation, Measurement firstMeasurement, Measurement secondMeasurement) { Quaternion result = secondMeasurement.getRotation() .subtract(firstMeasurement.getRotation()) .subtract(expectedRotation); return result; } /** * This method calculates the values for a boxplot. The values are sorted by * using the sort method of the Collections class. After that, an array is * created from the ArrayList using the method toDoubleArray, because the * Percentile class can only count on arrays. The values are calculated using * the available methods in these two classes. * * @param values - a list with values * @return boxPlot - of type boxPlot with results */ public BoxPlot getBoxPlot(List<Double> values) { BoxPlot boxPlot = new BoxPlot(); /* * The values are sorted by using the method sort of the class Collections. */ Collections.sort(values); /* Create an array. */ Percentile percentile = new Percentile(); percentile.setData(toDoubleArray(values)); /* Calculation of the values. */ boxPlot.setMax(Collections.max(values)); boxPlot.setMin(Collections.min(values)); boxPlot.setQ1(percentile.evaluate(25)); boxPlot.setMedian(percentile.evaluate(50)); boxPlot.setQ3(percentile.evaluate(75)); return boxPlot; } /* toDoubleArray converts a list into an array */ double[] toDoubleArray(List<Double> list) { double[] ret = new double[list.size()]; int i = 0; for (Double e : list) { ret[i++] = e.intValue(); } return ret; } /** * This method calculates the distance of two points and uses the method * distance from the class Point3D * * @param firstPoint - of type Point3D * @param secondPoint - of type Point3D * @return distance - of type double */ private double getDistance(Point3D firstPoint, Point3D secondPoint) { double distance = firstPoint.distance(secondPoint); return distance; } }
package com.server.session; import java.nio.ByteBuffer; public interface BasicSession { void init(int bufferSize, long timeout, int port); boolean hasData(); void writeWithFlip(ByteBuffer buffer); String getBufferAsString(); void flashTo(ByteBuffer target); int getPort(); }
/* * Copyright (c) 1997, 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 com.sun.xml.ws.policy.config; import com.sun.istack.logging.Logger; import com.sun.xml.ws.config.metro.dev.FeatureReader; import com.sun.xml.ws.config.metro.util.ParserUtil; import com.sun.xml.ws.policy.PolicyException; import com.sun.xml.ws.policy.sourcemodel.PolicyModelUnmarshaller; import com.sun.xml.ws.policy.sourcemodel.PolicySourceModel; import javax.xml.stream.XMLEventReader; import jakarta.xml.ws.WebServiceException; /** * * @author Fabian Ritzmann */ public class PolicyFeatureReader implements FeatureReader { private static final Logger LOGGER = Logger.getLogger(PolicyFeatureReader.class); // TODO implement public PolicyFeature parse(XMLEventReader reader) throws WebServiceException { try{ final PolicyModelUnmarshaller unmarshaller = PolicyModelUnmarshaller.getXmlUnmarshaller(); final PolicySourceModel model = unmarshaller.unmarshalModel(reader); return new PolicyFeature(null); } catch (PolicyException e) { // TODO logging message throw LOGGER.logSevereException(new WebServiceException("Failed to unmarshal policy expression", e)); } } }
package module0514_public.a; import java.awt.datatransfer.*; import java.beans.beancontext.*; import java.io.*; /** * Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut * labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. * Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. * * @see java.awt.datatransfer.DataFlavor * @see java.beans.beancontext.BeanContext * @see java.io.File */ @SuppressWarnings("all") public abstract class Foo0<U> implements module0514_public.a.IFoo0<U> { java.rmi.Remote f0 = null; java.nio.file.FileStore f1 = null; java.sql.Array f2 = null; public U element; public static Foo0 instance; public static Foo0 getInstance() { return instance; } public static <T> T create(java.util.List<T> input) { return null; } public String getName() { return element.toString(); } public void setName(String string) { return; } public U get() { return element; } public void set(Object element) { this.element = (U)element; } public U call() throws Exception { return (U)getInstance().call(); } }
package com.java110.web.smo.app.impl; import com.alibaba.fastjson.JSONObject; import com.java110.common.constant.PrivilegeCodeConstant; import com.java110.common.constant.ServiceConstant; import com.java110.common.util.Assert; import org.springframework.web.client.RestTemplate; import com.java110.core.context.IPageData; import com.java110.web.core.AbstractComponentSMO; import com.java110.web.smo.app.IDeleteAppSMO; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; /** * 添加小区服务实现类 * delete by wuxw 2019-06-30 */ @Service("deleteAppSMOImpl") public class DeleteAppSMOImpl extends AbstractComponentSMO implements IDeleteAppSMO { @Autowired private RestTemplate restTemplate; @Override protected void validate(IPageData pd, JSONObject paramIn) { //super.validatePageInfo(pd); //Assert.hasKeyAndValue(paramIn, "xxx", "xxx"); Assert.hasKeyAndValue(paramIn, "appId", "应用Id不能为空"); super.checkUserHasPrivilege(pd, restTemplate, PrivilegeCodeConstant.AGENT_HAS_LIST_APP); } @Override protected ResponseEntity<String> doBusinessProcess(IPageData pd, JSONObject paramIn) { ResponseEntity<String> responseEntity = null; super.validateStoreStaffCommunityRelationship(pd, restTemplate); responseEntity = this.callCenterService(restTemplate, pd, paramIn.toJSONString(), ServiceConstant.SERVICE_API_URL + "/api/app.deleteApp", HttpMethod.POST); return responseEntity; } @Override public ResponseEntity<String> deleteApp(IPageData pd) { return super.businessProcess(pd); } public RestTemplate getRestTemplate() { return restTemplate; } public void setRestTemplate(RestTemplate restTemplate) { this.restTemplate = restTemplate; } }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.firebase.database.tubesock; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.WritableByteChannel; import java.util.Random; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; /** * This class handles blocking write operations to the websocket. Given an opcode and some bytes, it * frames a message and sends it over the wire. The actual sending happens in a separate thread. */ class WebSocketWriter { private BlockingQueue<ByteBuffer> pendingBuffers; private final Random random = new Random(); private volatile boolean stop = false; private boolean closeSent = false; private WebSocket websocket; private WritableByteChannel channel; private final Thread innerThread; WebSocketWriter(WebSocket websocket, String threadBaseName, int clientId) { innerThread = WebSocket.getThreadFactory() .newThread( new Runnable() { @Override public void run() { runWriter(); } }); WebSocket.getIntializer().setName(getInnerThread(), threadBaseName + "Writer-" + clientId); this.websocket = websocket; pendingBuffers = new LinkedBlockingQueue<ByteBuffer>(); } void setOutput(OutputStream output) { channel = Channels.newChannel(output); } private ByteBuffer frameInBuffer(byte opcode, boolean masking, byte[] data) throws IOException { int headerLength = 2; // This is just an assumed headerLength, as we use a ByteArrayOutputStream if (masking) { headerLength += 4; } int length = data.length; if (length < 126) { // nothing add to header length } else if (length <= 65535) { headerLength += 2; } else { headerLength += 8; } ByteBuffer frame = ByteBuffer.allocate(data.length + headerLength); byte fin = (byte) 0x80; byte startByte = (byte) (fin | opcode); frame.put(startByte); int length_field; if (length < 126) { if (masking) { length = 0x80 | length; } frame.put((byte) length); } else if (length <= 65535) { length_field = 126; if (masking) { length_field = 0x80 | length_field; } frame.put((byte) length_field); // We check the size above, so we know we aren't losing anything with the cast frame.putShort((short) length); } else { length_field = 127; if (masking) { length_field = 0x80 | length_field; } frame.put((byte) length_field); // Since an integer occupies just 4 bytes we fill the 4 leading length bytes with zero frame.putInt(0); frame.putInt(length); } byte[] mask; if (masking) { mask = generateMask(); frame.put(mask); for (int i = 0; i < data.length; i++) { frame.put((byte) (data[i] ^ mask[i % 4])); } } frame.flip(); return frame; } private byte[] generateMask() { final byte[] mask = new byte[4]; random.nextBytes(mask); return mask; } synchronized void send(byte opcode, boolean masking, byte[] data) throws IOException { ByteBuffer frame = frameInBuffer(opcode, masking, data); if (stop && (closeSent || opcode != WebSocket.OPCODE_CLOSE)) { throw new WebSocketException("Shouldn't be sending"); } if (opcode == WebSocket.OPCODE_CLOSE) { closeSent = true; } pendingBuffers.add(frame); } private void writeMessage() throws InterruptedException, IOException { ByteBuffer msg = pendingBuffers.take(); channel.write(msg); } void stopIt() { stop = true; } private void handleError(WebSocketException e) { websocket.handleReceiverError(e); } private void runWriter() { try { while (!stop && !Thread.interrupted()) { writeMessage(); } // We're stopping, clear any remaining messages for (int i = 0; i < pendingBuffers.size(); ++i) { writeMessage(); } } catch (IOException e) { handleError(new WebSocketException("IO Exception", e)); } catch (InterruptedException e) { // this thread is regularly terminated via an interrupt // e.printStackTrace(); } } Thread getInnerThread() { return innerThread; } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. package com.microsoft.graph.generated; import com.microsoft.graph.concurrency.*; import com.microsoft.graph.core.*; import com.microsoft.graph.extensions.*; import com.microsoft.graph.http.*; import com.microsoft.graph.generated.*; import com.microsoft.graph.options.*; import com.microsoft.graph.serializer.*; import java.util.Arrays; import java.util.EnumSet; import com.google.gson.JsonObject; import com.google.gson.annotations.*; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Base Workbook Table Row Collection Page. */ public class BaseWorkbookTableRowCollectionPage extends BaseCollectionPage<WorkbookTableRow, IWorkbookTableRowCollectionRequestBuilder> implements IBaseWorkbookTableRowCollectionPage { /** * A collection page for WorkbookTableRow. * * @param response The serialized BaseWorkbookTableRowCollectionResponse from the service * @param builder The request builder for the next collection page */ public BaseWorkbookTableRowCollectionPage(final BaseWorkbookTableRowCollectionResponse response, final IWorkbookTableRowCollectionRequestBuilder builder) { super(response.value, builder); } }
/* * Copyright 2012 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.workbench.common.widgets.configresource.client.widget.unbound; import javax.inject.Inject; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.Widget; import org.guvnor.common.services.project.model.ProjectImports; import static org.uberfire.commons.validation.PortablePreconditions.*; public class ImportsWidgetPresenter implements ImportsWidgetView.Presenter, IsWidget { private ImportsWidgetView view; public ImportsWidgetPresenter() { } @Inject public ImportsWidgetPresenter( final ImportsWidgetView view ) { this.view = view; view.init( this ); } @Override public void setContent( final ProjectImports importTypes, final boolean isReadOnly ) { checkNotNull( "importTypes", importTypes ); view.setContent( importTypes.getImports().getImports(), isReadOnly ); } @Override public Widget asWidget() { return view.asWidget(); } }
/* * Copyright (C) 2018 AlexMofer * * 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 am.util.font; import org.xmlpull.v1.XmlPullParser; /** * API 28 * 版本增加到23 * font标签增加fallbackFor字段 * Created by Alex on 2018/8/30. */ @SuppressWarnings("WeakerAccess") class FontsReaderApi28 extends FontsReaderApi26 { protected static final String ATTR_FALLBACKFOR = "fallbackFor"; @Override protected void startFont(XmlPullParser parser) { super.startFont(parser); if (mFont != null) mFont.setFallbackFor(parser.getAttributeValue(null, ATTR_FALLBACKFOR)); } }
// Write a method to replace all spaces in a string with a "%20" import java.io.*; import java.util.*; public class Solution { public static String replaceString(String input) { String edited = input.replaceAll(" ","%20"); return edited; } public static void main(String[] args) { input = "Hi there" String output = replaceString(input); System.out.println(output); } }
package com.plaid.client.response.paymentinitiation; import com.plaid.client.model.paymentinitiation.Amount; import com.plaid.client.model.paymentinitiation.Bacs; import com.plaid.client.model.paymentinitiation.RefundDetails; import com.plaid.client.model.paymentinitiation.Schedule; import com.plaid.client.response.BaseResponse; public class PaymentGetResponse extends BaseResponse { private String paymentId; private String reference; private Amount amount; private Schedule schedule; private String status; private String lastStatusUpdate; private String recipientId; private RefundDetails refundDetails; private Bacs bacs; private String iban; public String getPaymentId() { return paymentId; } public String getReference() { return reference; } public Amount getAmount() { return amount; } public Schedule getSchedule() { return schedule; } public String getStatus() { return status; } public String getLastStatusUpdate() { return lastStatusUpdate; } public String getRecipientId() { return recipientId; } public RefundDetails getRefundDetails() { return refundDetails; } public Bacs getBacs() { return bacs; } public String getIban() { return iban; } }
/* * Copyright 2014 NAVER Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.navercorp.pinpoint.collector.handler; import com.navercorp.pinpoint.io.request.ServerRequest; import com.navercorp.pinpoint.io.request.UnSupportedServerRequestTypeException; import com.navercorp.pinpoint.thrift.dto.ThriftRequest; import org.apache.thrift.TBase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.navercorp.pinpoint.collector.dao.AgentInfoDao; import com.navercorp.pinpoint.collector.dao.ApplicationIndexDao; import com.navercorp.pinpoint.thrift.dto.TAgentInfo; import com.navercorp.pinpoint.thrift.dto.TResult; /** * @author emeroad * @author koo.taejin */ @Service("agentInfoHandler") public class AgentInfoHandler implements SimpleHandler, RequestResponseHandler { private final Logger logger = LoggerFactory.getLogger(AgentInfoHandler.class.getName()); @Autowired private AgentInfoDao agentInfoDao; @Autowired private ApplicationIndexDao applicationIndexDao; @Override public void handleSimple(ServerRequest serverRequest) { if (serverRequest instanceof ThriftRequest) { handleSimple(((ThriftRequest)serverRequest).getData()); } else { throw new UnSupportedServerRequestTypeException(serverRequest.getClass() + "is not support type : " + serverRequest); } } public void handleSimple(TBase<?, ?> tbase) { handleRequest(tbase); } @Override public TBase<?, ?> handleRequest(TBase<?, ?> tbase) { if (!(tbase instanceof TAgentInfo)) { logger.warn("invalid tbase:{}", tbase); // it happens to return null not only at this BO(Business Object) but also at other BOs. return null; } try { TAgentInfo agentInfo = (TAgentInfo) tbase; logger.debug("Received AgentInfo={}", agentInfo); // agent info agentInfoDao.insert(agentInfo); // for querying agentid using applicationname applicationIndexDao.insert(agentInfo); return new TResult(true); } catch (Exception e) { logger.warn("AgentInfo handle error. Caused:{}", e.getMessage(), e); TResult result = new TResult(false); result.setMessage(e.getMessage()); return result; } } }
package com.carson.commands.main.tic; public class Tac { //0 is blank //1 is user //2 is AI private Board b = new Board(); public Tac() { } public String start(int turn) { if(turn == -1) { move(); } return b.printBoard(); } public String moveNext(int turn) { if(b.set(turn, 2)) { move(); if(b.boardWin() == 2) { return b.printBoard() + "\n You Won!!!!!! please contact the dev, this shouldn't happen lol"; }else { return b.printBoard(); } }else { move(); return "Not a valued option. It's the bot's turn\n" + b.printBoard(); } } private void move() { b.set(choseNext(b), 1); } private double testLayout(Board b,int player, double value) { double score = 0; for(int i = 0;i<9;i++) { Board bTest = b.copy(); if(bTest.set(i, player)) { if(bTest.boardWin() == 1) { if(value == 1) { score += 10000; }else { //score++; } }else if(bTest.boardWin() == 2) { if(value == 1) { score -= 1000; }else { score--; } }else if(bTest.boardWin() == 0) { if(player == 1) { score+= testLayout(bTest,2,2) ; }else { score+= testLayout(bTest,1,2); } } } } return score; } private int choseNext(Board b) { if(b.get(0) == 2 && b.get(1) == 0 && b.get(2) == 0 && b.get(3) == 0 && b.get(4) == 1 && b.get(5) == 0 && b.get(6) == 0 && b.get(7) == 0 && b.get(8) == 2 ) { System.out.println("EVENT: hardcode tictactoe one ran"); return 3; } if(b.get(0) == 0 && b.get(1) == 0 && b.get(2) == 2 && b.get(3) == 0 && b.get(4) == 1 && b.get(5) == 0 && b.get(6) == 2 && b.get(7) == 0 && b.get(8) == 0 ) { System.out.println("EVENT: hardcode tictactoe two ran"); return 3; } double[] scores = new double[9]; for(int i = 0;i<9;i++) { Board bTest = b.copy(); if(bTest.set(i, 1)){ scores[i] = testLayout(bTest, 2,1); }else { scores[i] = -1000000; } } int best = 0; for(int i = 0;i<9;i++) { if(scores[i] > scores[best]) { best = i; } } // System.out.println("scores"); boolean allTenK = true; for(int q = 0;q<9;q++) { double i = scores[q]; if(i != -1000000 || i!=0) { allTenK = false; }else{ } // System.out.println(q+")" + i); } if(allTenK) { // System.out.println("\nI've calculated that there is no way for anyone to win. "); } // System.out.println("best move found:" + best); return best; } public int checkWin() { return b.boardWin(); } }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.12.16 at 12:47:21 PM EST // package xml.us.patent.application.v40_041202; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlValue; /** * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) @XmlRootElement(name = "isbn") public class Isbn { @XmlValue protected String value; /** * Gets the value of the value property. * * @return * possible object is * {@link String } * */ public String getvalue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link String } * */ public void setvalue(String value) { this.value = value; } }
package sqltoregex.controller; import org.jgrapht.graph.DefaultWeightedEdge; import org.jgrapht.graph.SimpleGraph; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.xml.sax.SAXException; import sqltoregex.settings.SettingsManager; import sqltoregex.settings.SettingsOption; import sqltoregex.settings.SettingsType; import sqltoregex.settings.regexgenerator.synonymgenerator.StringSynonymGenerator; import sqltoregex.settings.regexgenerator.synonymgenerator.SynonymGenerator; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPathExpressionException; import java.io.IOException; import java.net.URISyntaxException; import java.util.Map; import java.util.Set; class GraphPreProcessorTest { private final SettingsManager settingsManager = new SettingsManager(); GraphPreProcessorTest() throws XPathExpressionException, ParserConfigurationException, IOException, SAXException, URISyntaxException { } @Test void getSynonymMap() { Map<String, Set<String>> map = GraphPreProcessor.getSynonymMap(settingsManager.getSettingBySettingsOption( SettingsOption.AGGREGATEFUNCTIONLANG, StringSynonymGenerator.class, SettingsType.ALL) .map(SynonymGenerator::getGraph) .orElse(new SimpleGraph<>( DefaultWeightedEdge.class))); Assertions.assertTrue(map.containsKey("AVG")); Assertions.assertTrue(map.containsKey("SUM")); Assertions.assertTrue(map.containsKey("COUNT")); Assertions.assertEquals(3, map.size()); } }
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.flowable.engine.test.cfg; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.flowable.common.engine.api.FlowableException; import org.flowable.common.engine.api.FlowableOptimisticLockingException; import org.flowable.common.engine.impl.interceptor.Command; import org.flowable.common.engine.impl.interceptor.CommandContext; import org.flowable.common.engine.impl.interceptor.CommandInterceptor; import org.flowable.common.engine.impl.interceptor.RetryInterceptor; import org.flowable.engine.ProcessEngine; import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl; import org.flowable.engine.impl.cfg.StandaloneInMemProcessEngineConfiguration; import org.junit.Assert; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * @author Daniel Meyer * @author Joram Barrez */ public class RetryInterceptorTest { protected ProcessEngine processEngine; protected RetryInterceptor retryInterceptor; @BeforeEach public void setupProcessEngine() { ProcessEngineConfigurationImpl processEngineConfiguration = (ProcessEngineConfigurationImpl) new StandaloneInMemProcessEngineConfiguration(); processEngineConfiguration.setJdbcUrl("jdbc:h2:mem:retryInterceptorTest"); List<CommandInterceptor> interceptors = new ArrayList<>(); retryInterceptor = new RetryInterceptor(); interceptors.add(retryInterceptor); processEngineConfiguration.setCustomPreCommandInterceptors(interceptors); processEngine = processEngineConfiguration.buildProcessEngine(); } @AfterEach public void shutdownProcessEngine() { processEngine.close(); } @Test public void testRetryInterceptor() { try { processEngine.getManagementService().executeCommand(new CommandThrowingOptimisticLockingException()); Assert.fail("ActivitiException expected."); } catch (FlowableException e) { Assert.assertTrue(e.getMessage().contains(retryInterceptor.getNumOfRetries() + " retries failed")); } Assert.assertEquals(retryInterceptor.getNumOfRetries() + 1, counter.get()); // +1, we retry 3 times, so one extra for the regular execution } public static AtomicInteger counter = new AtomicInteger(); protected class CommandThrowingOptimisticLockingException implements Command<Void> { @Override public Void execute(CommandContext commandContext) { counter.incrementAndGet(); throw new FlowableOptimisticLockingException(""); } } }
package com.blockvader.wtimprovements.init; import com.blockvader.wtimprovements.WTImprovements; import net.minecraft.potion.EffectInstance; import net.minecraft.potion.Effects; import net.minecraft.potion.Potion; import net.minecraft.util.ResourceLocation; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.ModList; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.registries.ForgeRegistries; @EventBusSubscriber(modid = WTImprovements.MOD_ID, bus = EventBusSubscriber.Bus.MOD) public class InitPotionTypes { //Vanilla public static Potion MIGHTY_NIGHT_VISION; public static Potion MIGHTY_INVISIBILITY; public static Potion MIGHTY_LEAPING; public static Potion MIGHTY_FIRE_RESISTANCE; public static Potion MIGHTY_SWIFTNESS; public static Potion MIGHTY_TURTLE_MASTER; public static Potion MIGHTY_WATER_BREATHING; public static Potion MIGHTY_HEALING; public static Potion MIGHTY_REGENERATION; public static Potion MIGHTY_STRENGTH; public static Potion MIGHTY_SLOW_FALLING; //Quark public static Potion MIGHTY_FORTITUDE; public static Potion MIGHTY_DANFER_SIGHT; public static Potion MIGHTY_STABILITY; //Atmospheric public static Potion MIGHTY_RELIEF; //Buzzier bees public static Potion MIGHTY_LUCK; //Upgrade aquatic public static Potion MIGHTY_RESTFULNESS; public static Potion MIGHTY_REPELLENCE; public static Potion MIGHTY_VIBING; public static boolean fortitudeCreated; public static boolean dangerSightCreated; public static boolean stabilityCreated; public static boolean reliefCreated; public static boolean luckCreated; public static boolean restfulnessCreated; public static boolean repellenceCreated; public static boolean vibingCreated; @SubscribeEvent public static void onPotionTypeRegistry(RegistryEvent.Register<Potion> event) { MIGHTY_NIGHT_VISION = new Potion("mighty_night_vision", new EffectInstance(Effects.NIGHT_VISION, 24000)).setRegistryName("mighty_night_vision"); event.getRegistry().register(MIGHTY_NIGHT_VISION); MIGHTY_INVISIBILITY = new Potion("mighty_invisibility", new EffectInstance(Effects.INVISIBILITY, 24000)).setRegistryName("mighty_invisibility"); event.getRegistry().register(MIGHTY_INVISIBILITY); MIGHTY_LEAPING = new Potion("mighty_leaping", new EffectInstance(Effects.JUMP_BOOST, 4800, 1)).setRegistryName("mighty_leaping"); event.getRegistry().register(MIGHTY_LEAPING); MIGHTY_FIRE_RESISTANCE = new Potion("mighty_fire_resistance", new EffectInstance(Effects.FIRE_RESISTANCE, 24000)).setRegistryName("mighty_fire_resistance"); event.getRegistry().register(MIGHTY_FIRE_RESISTANCE); MIGHTY_SWIFTNESS = new Potion("mighty_swiftness", new EffectInstance(Effects.SPEED, 4800, 1)).setRegistryName("mighty_swiftness"); event.getRegistry().register(MIGHTY_SWIFTNESS); MIGHTY_TURTLE_MASTER = new Potion("mighty_turtle_master", new EffectInstance(Effects.SLOWNESS, 1060, 5), new EffectInstance(Effects.RESISTANCE, 1060, 3)).setRegistryName("mighty_turtle_master"); event.getRegistry().register(MIGHTY_TURTLE_MASTER); MIGHTY_WATER_BREATHING = new Potion("mighty_water_breathing", new EffectInstance(Effects.INVISIBILITY, 24000)).setRegistryName("mighty_water_breathing"); event.getRegistry().register(MIGHTY_WATER_BREATHING); MIGHTY_HEALING = new Potion("mighty_healing", new EffectInstance(Effects.INSTANT_HEALTH, 1, 2)).setRegistryName("mighty_healing"); event.getRegistry().register(MIGHTY_HEALING); MIGHTY_REGENERATION = new Potion("mighty_regeneration", new EffectInstance(Effects.REGENERATION, 1200, 1)).setRegistryName("mighty_regeneration"); event.getRegistry().register(MIGHTY_REGENERATION); MIGHTY_STRENGTH = new Potion("mighty_strength", new EffectInstance(Effects.STRENGTH, 4800, 1)).setRegistryName("mighty_strength"); event.getRegistry().register(MIGHTY_STRENGTH); MIGHTY_SLOW_FALLING = new Potion("mighty_slow_falling", new EffectInstance(Effects.SLOW_FALLING, 12000)).setRegistryName("mighty_slow_falling"); event.getRegistry().register(MIGHTY_SLOW_FALLING); if (ModList.get().isLoaded(WTImprovements.QUARK_ID)) { ResourceLocation dangerSight = new ResourceLocation(WTImprovements.QUARK_ID, "danger_sight"); if (ForgeRegistries.POTIONS.containsKey(dangerSight)) { MIGHTY_DANFER_SIGHT = new Potion(new EffectInstance(ForgeRegistries.POTIONS.getValue(dangerSight), 24000)).setRegistryName("mighty_danger_sight"); event.getRegistry().register(MIGHTY_DANFER_SIGHT); dangerSightCreated = true; } ResourceLocation resilience = new ResourceLocation(WTImprovements.QUARK_ID, "resilience"); if (ForgeRegistries.POTIONS.containsKey(resilience)) { MIGHTY_STABILITY = new Potion(new EffectInstance(ForgeRegistries.POTIONS.getValue(resilience), 4800, 1)).setRegistryName("mighty_stability"); event.getRegistry().register(MIGHTY_STABILITY); stabilityCreated = true; } MIGHTY_FORTITUDE = new Potion(new EffectInstance(Effects.RESISTANCE, 4800, 1)).setRegistryName("mighty_fortitude"); event.getRegistry().register(MIGHTY_FORTITUDE); fortitudeCreated = true; } if (ModList.get().isLoaded(WTImprovements.ATMOSPHERIC_ID)) { ResourceLocation relief = new ResourceLocation(WTImprovements.ATMOSPHERIC_ID, "relief"); if (ForgeRegistries.POTIONS.containsKey(relief)) { MIGHTY_RELIEF = new Potion(new EffectInstance(ForgeRegistries.POTIONS.getValue(relief), 24000)).setRegistryName("mighty_relief"); event.getRegistry().register(MIGHTY_RELIEF); reliefCreated = true; } } if (ModList.get().isLoaded(WTImprovements.UPGRADE_AQUATIC_ID)) { ResourceLocation restfulness = new ResourceLocation(WTImprovements.UPGRADE_AQUATIC_ID, "restfulness"); if (ForgeRegistries.POTIONS.containsKey(restfulness)) { MIGHTY_RESTFULNESS = new Potion(new EffectInstance(ForgeRegistries.POTIONS.getValue(restfulness), 1, 2)).setRegistryName("mighty_restfulness"); event.getRegistry().register(MIGHTY_RESTFULNESS); restfulnessCreated = true; } ResourceLocation repellence = new ResourceLocation(WTImprovements.UPGRADE_AQUATIC_ID, "repellence"); if (ForgeRegistries.POTIONS.containsKey(repellence)) { MIGHTY_REPELLENCE = new Potion(new EffectInstance(ForgeRegistries.POTIONS.getValue(repellence), 4800, 1)).setRegistryName("mighty_repellence"); event.getRegistry().register(MIGHTY_REPELLENCE); repellenceCreated = true; } ResourceLocation vibing = new ResourceLocation(WTImprovements.UPGRADE_AQUATIC_ID, "vibing"); if (ForgeRegistries.POTIONS.containsKey(vibing)) { MIGHTY_VIBING = new Potion(new EffectInstance(ForgeRegistries.POTIONS.getValue(vibing), 4800, 1)).setRegistryName("mighty_vibing"); event.getRegistry().register(MIGHTY_VIBING); vibingCreated = true; } } if (ModList.get().isLoaded(WTImprovements.BUZZIER_BEES_ID)) { MIGHTY_LUCK = new Potion(new EffectInstance(Effects.LUCK, 9600, 1)).setRegistryName("mighty_luck"); event.getRegistry().register(MIGHTY_LUCK); luckCreated = true; } } }