text
stringlengths
7
1.01M
package uk.co.victoriajanedavis.shopify_challenge.ui; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import uk.co.victoriajanedavis.shopify_challenge.R; import uk.co.victoriajanedavis.shopify_challenge.ui.base.BaseActivity; import uk.co.victoriajanedavis.shopify_challenge.ui.tags.TagsFragment; public class MainActivity extends BaseActivity { private static final String TAG = "MainActivity"; @Override protected void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FragmentManager fm = getSupportFragmentManager(); Fragment fragment = fm.findFragmentById (R.id.activity_fragment_container); if (fragment == null) { fragment = TagsFragment.newInstance(); fm.beginTransaction() .add(R.id.activity_fragment_container, fragment, TagsFragment.TAG) .commit(); } } }
/* * Copyright 2018 Amazon.com, Inc. 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 com.netflix.spinnaker.clouddriver.lambda.provider.agent; import com.amazonaws.services.lambda.AWSLambda; import com.amazonaws.services.lambda.model.AliasConfiguration; import com.amazonaws.services.lambda.model.EventSourceMappingConfiguration; import com.amazonaws.services.lambda.model.FunctionConfiguration; import com.amazonaws.services.lambda.model.ListAliasesRequest; import com.amazonaws.services.lambda.model.ListAliasesResult; import com.amazonaws.services.lambda.model.ListEventSourceMappingsRequest; import com.amazonaws.services.lambda.model.ListEventSourceMappingsResult; import com.amazonaws.services.lambda.model.ListFunctionsRequest; import com.amazonaws.services.lambda.model.ListFunctionsResult; import com.amazonaws.services.lambda.model.ListVersionsByFunctionRequest; import com.amazonaws.services.lambda.model.ListVersionsByFunctionResult; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.netflix.spinnaker.cats.agent.AccountAware; import com.netflix.spinnaker.cats.agent.AgentDataType; import com.netflix.spinnaker.cats.agent.CacheResult; import com.netflix.spinnaker.cats.agent.CachingAgent; import com.netflix.spinnaker.cats.agent.DefaultCacheResult; import com.netflix.spinnaker.cats.cache.CacheData; import com.netflix.spinnaker.cats.cache.DefaultCacheData; import com.netflix.spinnaker.cats.provider.ProviderCache; import com.netflix.spinnaker.clouddriver.aws.provider.AwsInfrastructureProvider; import com.netflix.spinnaker.clouddriver.aws.provider.AwsProvider; import com.netflix.spinnaker.clouddriver.aws.security.AmazonClientProvider; import com.netflix.spinnaker.clouddriver.aws.security.NetflixAmazonCredentials; import com.netflix.spinnaker.clouddriver.lambda.cache.Keys; import lombok.extern.slf4j.Slf4j; import java.util.*; import static com.netflix.spinnaker.cats.agent.AgentDataType.Authority.AUTHORITATIVE; import static com.netflix.spinnaker.clouddriver.lambda.cache.Keys.Namespace.LAMBDA_FUNCTIONS; @Slf4j public class LambdaCachingAgent implements CachingAgent, AccountAware { private static final TypeReference<Map<String, Object>> ATTRIBUTES = new TypeReference<Map<String, Object>>() { }; private static final Set<AgentDataType> types = new HashSet<AgentDataType>() {{ add(AUTHORITATIVE.forType(LAMBDA_FUNCTIONS.ns)); }}; private final ObjectMapper objectMapper; private final AmazonClientProvider amazonClientProvider; private final NetflixAmazonCredentials account; private final String region; LambdaCachingAgent(ObjectMapper objectMapper, AmazonClientProvider amazonClientProvider, NetflixAmazonCredentials account, String region) { this.objectMapper = objectMapper; this.amazonClientProvider = amazonClientProvider; this.account = account; this.region = region; } @Override public String getProviderName() { return AwsProvider.PROVIDER_NAME; } @Override public String getAgentType() { return account.getName() + "/" + region + "/" + LambdaCachingAgent.class.getSimpleName(); } @Override public String getAccountName() { return account.getName(); } @Override public Collection<AgentDataType> getProvidedDataTypes() { return types; } @Override public CacheResult loadData(ProviderCache providerCache) { log.info("Describing items in {}", getAgentType()); AWSLambda lambda = amazonClientProvider.getAmazonLambda(account, region); String nextMarker = null; List<FunctionConfiguration> lstFunction = new ArrayList<FunctionConfiguration>(); do { ListFunctionsRequest listFunctionsRequest = new ListFunctionsRequest(); if (nextMarker != null) { listFunctionsRequest.setMarker(nextMarker); } ListFunctionsResult listFunctionsResult = lambda.listFunctions(listFunctionsRequest); lstFunction.addAll(listFunctionsResult.getFunctions()); nextMarker = listFunctionsResult.getNextMarker(); } while (nextMarker != null && nextMarker.length() != 0); Collection<CacheData> data = new LinkedList<>(); for (FunctionConfiguration x : lstFunction) { Map<String, Object> attributes = objectMapper.convertValue(x, ATTRIBUTES); attributes.put("account", account.getName()); attributes.put("region", region); attributes.put("revisions", listFunctionRevisions(x.getFunctionArn())); attributes.put("aliasConfiguration", listAliasConfiguration(x.getFunctionArn())); attributes.put("eventSourceMappings", listEventSourceMappingConfiguration(x.getFunctionArn())); data.add( new DefaultCacheData( Keys.getLambdaFunctionKey(account.getName(), region, x.getFunctionName()), attributes, Collections.emptyMap() ) ); } log.info("Caching {} items in {}", String.valueOf(data.size()), getAgentType()); return new DefaultCacheResult(Collections.singletonMap(LAMBDA_FUNCTIONS.ns, data)); } private Map<String, String> listFunctionRevisions(String functionArn) { AWSLambda lambda = amazonClientProvider.getAmazonLambda(account, region); String nextMarker = null; Map<String, String> listRevionIds = new HashMap<String, String>(); do { ListVersionsByFunctionRequest listVersionsByFunctionRequest = new ListVersionsByFunctionRequest(); listVersionsByFunctionRequest.setFunctionName(functionArn); if (nextMarker != null) { listVersionsByFunctionRequest.setMarker(nextMarker); } ListVersionsByFunctionResult listVersionsByFunctionResult = lambda.listVersionsByFunction(listVersionsByFunctionRequest); for (FunctionConfiguration x : listVersionsByFunctionResult.getVersions()) { listRevionIds.put(x.getRevisionId(), x.getVersion()); } nextMarker = listVersionsByFunctionResult.getNextMarker(); } while (nextMarker != null && nextMarker.length() != 0); return listRevionIds; } private List<AliasConfiguration> listAliasConfiguration(String functionArn) { AWSLambda lambda = amazonClientProvider.getAmazonLambda(account, region); String nextMarker = null; List<AliasConfiguration> aliasConfigurations = new ArrayList<>(); do { ListAliasesRequest listAliasesRequest = new ListAliasesRequest(); listAliasesRequest.setFunctionName(functionArn); if (nextMarker != null) { listAliasesRequest.setMarker(nextMarker); } ListAliasesResult listAliasesResult = lambda.listAliases(listAliasesRequest); for (AliasConfiguration x : listAliasesResult.getAliases()) { aliasConfigurations.add(x); } nextMarker = listAliasesResult.getNextMarker(); } while (nextMarker != null && nextMarker.length() != 0); return aliasConfigurations; } private final List<EventSourceMappingConfiguration> listEventSourceMappingConfiguration(String functionArn) { List<EventSourceMappingConfiguration> eventSourceMappingConfigurations = new ArrayList<>(); AWSLambda lambda = amazonClientProvider.getAmazonLambda(account, region); String nextMarker = null; do { ListEventSourceMappingsRequest listEventSourceMappingsRequest = new ListEventSourceMappingsRequest(); listEventSourceMappingsRequest.setFunctionName(functionArn); if (nextMarker != null) { listEventSourceMappingsRequest.setMarker(nextMarker); } ListEventSourceMappingsResult listEventSourceMappingsResult = lambda.listEventSourceMappings( listEventSourceMappingsRequest ); for (EventSourceMappingConfiguration x : listEventSourceMappingsResult.getEventSourceMappings()) { eventSourceMappingConfigurations.add(x); } nextMarker = listEventSourceMappingsResult.getNextMarker(); } while (nextMarker != null && nextMarker.length() != 0); return eventSourceMappingConfigurations; } }
package com.demo; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @org.springframework.web.bind.annotation.RestController public class RestController { @RequestMapping(value = "/hello", method = RequestMethod.GET) public String helloWorld() { return "Hello World"; } }
/* * code https://github.com/jittagornp/excel-object-mapping */ package com.blogspot.na5cent.exom.util; import java.lang.reflect.Field; /** * @author redcrow */ public interface EachFieldCallback { void each(Field field, String name) throws Throwable; }
/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * 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.sweble.wikitext.parser.nodes; import org.sweble.wikitext.parser.nodes.WtContentNode.WtContentNodeImpl; public class WtParagraph extends WtContentNodeImpl { private static final long serialVersionUID = 1L; // ========================================================================= protected WtParagraph() { } protected WtParagraph(WtNodeList content) { super(content); } @Override public int getNodeType() { return NT_PARAGRAPH; } }
package com.lsh.fillette.AppManaging; import android.app.Application; import android.content.Context; import android.util.Log; import com.google.firebase.FirebaseApp; import com.kakao.auth.IApplicationConfig; import com.kakao.auth.KakaoAdapter; import com.kakao.auth.KakaoSDK; /** * Created by lsh on 2018. 3. 27.. * <p> * Set up kakao login. */ public class KakaoLoginApplication extends Application { private static KakaoLoginApplication self; public static final String TAG = KakaoLoginApplication.class.getName(); @Override public void onCreate() { super.onCreate(); self = this; Log.d(TAG, "Entered kakao login"); FirebaseApp.initializeApp(this); KakaoSDK.init(new KakaoAdapter() { @Override public IApplicationConfig getApplicationConfig() { return new IApplicationConfig() { @Override public Context getApplicationContext() { return self; } }; } }); } }
/* * JBoss, Home of Professional Open Source * * Copyright 2013 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.picketlink.test.idm.other.shane.model.scenario1.entity; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; /** * Lookup table containing countries * * @author Shane Bryzak */ @Entity public class Country implements Serializable { private static final long serialVersionUID = -8291183691785718272L; @Id @GeneratedValue private Long countryId; private String name; public Long getCountryId() { return countryId; } public void setCountryId(Long countryId) { this.countryId = countryId; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.log; import org.apache.yetus.audience.InterfaceAudience; import org.slf4j.Marker; import org.slf4j.MarkerFactory; @InterfaceAudience.Private public class HBaseMarkers { public static final Marker FATAL = MarkerFactory.getMarker("FATAL"); private HBaseMarkers() { } }
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =======================================================================*/ // This class has been generated, DO NOT EDIT! package org.tensorflow.op.io; import java.util.Arrays; import java.util.Iterator; import java.util.List; import org.tensorflow.DataType; import org.tensorflow.Operand; import org.tensorflow.Operation; import org.tensorflow.OperationBuilder; import org.tensorflow.Output; import org.tensorflow.op.RawOp; import org.tensorflow.op.Scope; import org.tensorflow.op.annotation.Endpoint; import org.tensorflow.op.annotation.Operator; import org.tensorflow.types.TInt32; import org.tensorflow.types.family.TType; /** * Dequeues `n` tuples of one or more tensors from the given queue. * <p> * If the queue is closed and there are fewer than `n` elements, then an * OutOfRange error is returned. * <p> * This operation concatenates queue-element component tensors along the * 0th dimension to make a single component tensor. All of the components * in the dequeued tuple will have size `n` in the 0th dimension. * <p> * This operation has `k` outputs, where `k` is the number of components in * the tuples stored in the given queue, and output `i` is the ith * component of the dequeued tuple. * <p> * N.B. If the queue is empty, this operation will block until `n` elements * have been dequeued (or 'timeout_ms' elapses, if specified). */ @Operator(group = "io") public final class QueueDequeueMany extends RawOp implements Iterable<Operand<TType>> { /** * Optional attributes for {@link org.tensorflow.op.io.QueueDequeueMany} */ public static class Options { /** * @param timeoutMs If the queue has fewer than n elements, this operation * will block for up to timeout_ms milliseconds. * Note: This option is not supported yet. */ public Options timeoutMs(Long timeoutMs) { this.timeoutMs = timeoutMs; return this; } private Long timeoutMs; private Options() { } } /** * Factory method to create a class wrapping a new QueueDequeueMany operation. * * @param scope current scope * @param handle The handle to a queue. * @param n The number of tuples to dequeue. * @param componentTypes The type of each component in a tuple. * @param options carries optional attributes values * @return a new instance of QueueDequeueMany */ @Endpoint(describeByClass = true) public static QueueDequeueMany create(Scope scope, Operand<?> handle, Operand<TInt32> n, List<DataType<?>> componentTypes, Options... options) { OperationBuilder opBuilder = scope.env().opBuilder("QueueDequeueManyV2", scope.makeOpName("QueueDequeueMany")); opBuilder.addInput(handle.asOutput()); opBuilder.addInput(n.asOutput()); opBuilder = scope.applyControlDependencies(opBuilder); DataType[] componentTypesArray = new DataType[componentTypes.size()]; for (int i = 0; i < componentTypesArray.length; ++i) { componentTypesArray[i] = componentTypes.get(i); } opBuilder.setAttr("component_types", componentTypesArray); if (options != null) { for (Options opts : options) { if (opts.timeoutMs != null) { opBuilder.setAttr("timeout_ms", opts.timeoutMs); } } } return new QueueDequeueMany(opBuilder.build()); } /** * @param timeoutMs If the queue has fewer than n elements, this operation * will block for up to timeout_ms milliseconds. * Note: This option is not supported yet. */ public static Options timeoutMs(Long timeoutMs) { return new Options().timeoutMs(timeoutMs); } /** * One or more tensors that were dequeued as a tuple. */ public List<Output<?>> components() { return components; } @Override @SuppressWarnings({"rawtypes", "unchecked"}) public Iterator<Operand<TType>> iterator() { return (Iterator) components.iterator(); } private List<Output<?>> components; private QueueDequeueMany(Operation operation) { super(operation); int outputIdx = 0; int componentsLength = operation.outputListLength("components"); components = Arrays.asList(operation.outputList(outputIdx, componentsLength)); outputIdx += componentsLength; } }
package com.fasterxml.jackson.module.jaxb.types; import java.util.*; import javax.xml.bind.annotation.*; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.module.jaxb.BaseJaxbTest; /** * Tests for handling of type-related JAXB annotations */ public class TestJaxbTypes extends BaseJaxbTest { static class AbstractWrapper { @XmlElement(type=BeanImpl.class) public AbstractBean wrapped; public AbstractWrapper() { this(null); } public AbstractWrapper(AbstractBean bean) { wrapped = bean; } } interface AbstractBean { } @JsonPropertyOrder({ "a", "b" }) static class BeanImpl implements AbstractBean { public int a; protected String b; public BeanImpl() { this(0, null); } public BeanImpl(int a, String b) { this.a = a; this.b = b; } public String getB() { return b; } public void setB(String b) { this.b = b; } } static class ListBean { /* Note: here we rely on implicit linking between the field * and accessors. */ @XmlElement(type=BeanImpl.class) protected List<AbstractBean> beans; public ListBean() { } public ListBean(AbstractBean ... beans) { this.beans = Arrays.asList(beans); } public ListBean(List<AbstractBean> beans) { this.beans = beans; } public List<AbstractBean> getBeans() { return beans; } public void setBeans(List<AbstractBean> b) { beans = b; } public int size() { return beans.size(); } public BeanImpl get(int index) { return (BeanImpl) beans.get(index); } } /* And then mix'n match, to try end-to-end */ static class ComboBean { protected AbstractBean bean; public ListBean beans; public ComboBean() { } public ComboBean(AbstractBean bean, ListBean beans) { this.bean = bean; this.beans = beans; } @XmlElement(type=BeanImpl.class) public AbstractBean getBean() { return bean; } public void setBean(AbstractBean bean) { this.bean = bean; } } /** * Unit test for [JACKSON-250] */ @JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include= JsonTypeInfo.As.PROPERTY) @JsonTypeName("Name") @XmlType static class P2 { String id; public P2(String id) { this.id = id; } public P2() { } @XmlID @XmlAttribute(name="id") public String getId() { return id; } public void setId(String id) { this.id = id; } } /* /********************************************************** /* Unit tests /********************************************************** */ public void testXmlElementTypeDeser() throws Exception { ObjectMapper mapper = getJaxbMapper(); AbstractWrapper wrapper = mapper.readValue("{\"wrapped\":{\"a\":13,\"b\":\"...\"}}", AbstractWrapper.class); assertNotNull(wrapper); BeanImpl bean = (BeanImpl) wrapper.wrapped; assertEquals(13, bean.a); assertEquals("...", bean.b); } public void testXmlElementTypeSer() throws Exception { ObjectMapper mapper = getJaxbAndJacksonMapper(); AbstractWrapper wrapper = new AbstractWrapper(new BeanImpl(-3, "c")); assertEquals("{\"wrapped\":{\"a\":-3,\"b\":\"c\"}}", mapper.writeValueAsString(wrapper)); } public void testXmlElementListTypeDeser() throws Exception { ObjectMapper mapper = getJaxbMapper(); ListBean listBean = mapper.readValue ("{\"beans\": [{\"a\":1,\"b\":\"a\"}, {\"a\":7,\"b\":\"b\" }]}", ListBean.class); assertNotNull(listBean); List<AbstractBean> beans = listBean.beans; assertNotNull(beans); assertEquals(2, beans.size()); assertNotNull(beans.get(0)); assertNotNull(beans.get(1)); BeanImpl bean = (BeanImpl) beans.get(0); assertEquals(1, bean.a); assertEquals("a", bean.b); bean = (BeanImpl) beans.get(1); assertEquals(7, bean.a); assertEquals("b", bean.b); } public void testXmlElementListArrayDeser() throws Exception { ObjectMapper mapper = getJaxbMapper(); ListBean[] listBeans = mapper.readValue ("[{\"beans\": [{\"a\":1,\"b\":\"a\"}, {\"a\":7,\"b\":\"b\" }]}]", ListBean[].class); assertNotNull(listBeans); assertEquals(1, listBeans.length); List<AbstractBean> beans = listBeans[0].beans; assertNotNull(beans); assertEquals(2, beans.size()); BeanImpl bean = (BeanImpl) beans.get(0); assertEquals(1, bean.a); assertEquals("a", bean.b); bean = (BeanImpl) beans.get(1); assertEquals(7, bean.a); assertEquals("b", bean.b); } public void testXmlElementListTypeSer() throws Exception { // important: Jackson mapper so we can force ordering ObjectMapper mapper = getJaxbAndJacksonMapper(); ListBean bean = new ListBean(); List<AbstractBean> beans = new ArrayList<AbstractBean>(); beans.add(new BeanImpl(1, "a")); beans.add(new BeanImpl(2, "b")); bean.beans = beans; assertEquals("{\"beans\":[{\"a\":1,\"b\":\"a\"},{\"a\":2,\"b\":\"b\"}]}", mapper.writeValueAsString(bean)); } public void testRoundTrip() throws Exception { ComboBean input = new ComboBean(new BeanImpl(3, "abc"), new ListBean(new BeanImpl(1, "a"), new BeanImpl(2, "b"), new BeanImpl(3, "c"))); ObjectMapper mapper = getJaxbMapper(); String str = mapper.writeValueAsString(input); ComboBean result = mapper.readValue(str, ComboBean.class); assertEquals(3, ((BeanImpl)result.bean).a); assertEquals("abc", ((BeanImpl)result.bean).b); assertEquals(3, result.beans.size()); assertEquals(1, (result.beans.get(0)).a); assertEquals("a", (result.beans.get(0)).b); assertEquals(2, (result.beans.get(1)).a); assertEquals("b", (result.beans.get(1)).b); assertEquals(3, (result.beans.get(2)).a); assertEquals("c", (result.beans.get(2)).b); } public void testListWithDefaultTyping() throws Exception { Object input = new ListBean(new BeanImpl(1, "a")); ObjectMapper mapper = getJaxbMapperBuilder() .enableDefaultTyping() .build(); String str = mapper.writeValueAsString(input); ListBean listBean = mapper.readValue(str, ListBean.class); assertNotNull(listBean); List<AbstractBean> beans = listBean.beans; assertNotNull(beans); assertEquals(1, beans.size()); assertNotNull(beans.get(0)); BeanImpl bean = (BeanImpl) beans.get(0); assertEquals(1, bean.a); assertEquals("a", bean.b); } public void testIssue250() throws Exception { ObjectMapper mapper = getJaxbAndJacksonMapper(); P2 bean = new P2("myId"); String str = mapper.writeValueAsString(bean); assertEquals("{\"@type\":\"Name\",\"id\":\"myId\"}", str); } }
package Utils; import org.junit.Test; import static org.junit.Assert.*; public class UploadTest { @Test public void getImage() { } @Test public void getAudio() { } }
/* * Copyright (c) 2020 Applica.ai All Rights Reserved * * Copyright (c) 2020 Temporal Technologies, Inc. All Rights Reserved * * Copyright 2012-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Modifications copyright (C) 2017 Uber Technologies, Inc. * * 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 ai.applica.spring.boot.starter.temporal.samples; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import ai.applica.spring.boot.starter.temporal.HelloRemoteWorkflowImpl; import ai.applica.spring.boot.starter.temporal.HelloWorkflow; import ai.applica.spring.boot.starter.temporal.RemoteActivities; import ai.applica.spring.boot.starter.temporal.WorkflowFactory; import ai.applica.spring.boot.starter.temporal.config.TemporalProperties; import ai.applica.spring.boot.starter.temporal.extensions.TemporalTestWatcher; import ai.applica.spring.boot.starter.temporal.samples.apps.RemoteActivity; import io.temporal.testing.TestWorkflowEnvironment; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.springframework.beans.factory.annotation.Autowired; /** * Unit test for {@link RemoteActivity}. Creates mock activities and verifies that stub * configuration is taken from the YAML file ({@code spring.temporal.activityStubs}) when absent * from {@link @ActivityStub} annotation. */ class RemoteActivityTest extends BaseTest { @Autowired TemporalProperties temporalProperties; @Autowired WorkflowFactory fact; @RegisterExtension TemporalTestWatcher temporalTestWatcher = new TemporalTestWatcher(); private TestWorkflowEnvironment testEnv; @BeforeEach public void setUp() { testEnv = TestWorkflowEnvironment.newInstance(); temporalTestWatcher.setEnvironment(testEnv); } @AfterEach public void tearDown() { testEnv.close(); } @Test void testRemoteActivityConfiguration() { String phrase = "Hello remote!"; RemoteActivities remoteActivity = mock(RemoteActivities.class); when(remoteActivity.echo(phrase)).thenReturn(phrase); createWorkerForRemoteActivity(remoteActivity); createWorkerForLocalWorkflow(HelloRemoteWorkflowImpl.class); HelloWorkflow workflowStub = fact.makeStub( HelloWorkflow.class, HelloRemoteWorkflowImpl.class, testEnv.getWorkflowClient()); testEnv.start(); String echoResult = workflowStub.process(); assertEquals(phrase, echoResult); } private void createWorkerForLocalWorkflow(Class clazz) { fact.makeWorker(testEnv, clazz); } private void createWorkerForRemoteActivity(RemoteActivities remoteActivity) { String remoteTaskQueue = temporalProperties .getActivityStubs() .get(RemoteActivities.class.getSimpleName()) .getTaskQueue(); testEnv.newWorker(remoteTaskQueue).registerActivitiesImplementations(remoteActivity); } }
/* Alloy Analyzer 4 -- Copyright (c) 2006-2009, Felix Chang * * 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 edu.mit.csail.sdg.translator; import static edu.mit.csail.sdg.ast.Sig.NONE; import static edu.mit.csail.sdg.ast.Sig.SEQIDX; import static edu.mit.csail.sdg.ast.Sig.SIGINT; import static edu.mit.csail.sdg.ast.Sig.STRING; import static edu.mit.csail.sdg.ast.Sig.UNIV; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import edu.mit.csail.sdg.alloy4.Err; import edu.mit.csail.sdg.alloy4.ErrorFatal; import edu.mit.csail.sdg.alloy4.ErrorSyntax; import edu.mit.csail.sdg.alloy4.Pos; import edu.mit.csail.sdg.alloy4.Util; import edu.mit.csail.sdg.alloy4.XMLNode; import edu.mit.csail.sdg.ast.Attr; import edu.mit.csail.sdg.ast.Expr; import edu.mit.csail.sdg.ast.ExprVar; import edu.mit.csail.sdg.ast.Sig; import edu.mit.csail.sdg.ast.Sig.Field; import edu.mit.csail.sdg.ast.Sig.PrimSig; import edu.mit.csail.sdg.ast.Sig.SubsetSig; import kodkod.ast.Relation; import kodkod.instance.Tuple; import kodkod.instance.TupleFactory; import kodkod.instance.TupleSet; /** * This helper class contains helper routines for reading an A4Solution object * from an XML file. * * @modified [electrum] incrementally builds a solution by iteratively reading * states from the XML; must start by collecting all used atoms, since * univ varies from state to state */ public final class A4SolutionReader { /** The resulting A4Solution object. */ private A4Solution sol; /** The provided choices of existing Sig and Field. */ private final LinkedHashSet<Expr> choices = new LinkedHashSet<Expr>(); /** Stores the set of atoms. */ private final TreeSet<String> atoms = new TreeSet<String>(); /** Stores the set of STRING atoms. */ private final TreeSet<String> strings = new TreeSet<String>(); /** Maps each Sig/Field/Skolem id to an XMLNode. */ private final Map<String,XMLNode> nmap = new LinkedHashMap<String,XMLNode>(); /** Maps each Sig id to a Sig. */ private final Map<String,Sig> id2sig = new LinkedHashMap<String,Sig>(); /** Stores the set of all sigs. */ private final Set<Sig> allsigs = Util.asSet((Sig) UNIV, SIGINT, SEQIDX, STRING, NONE); /** Mapes each expression we've seen to its TupleSet. */ private final Map<Expr,TupleSet> expr2ts = new LinkedHashMap<Expr,TupleSet>(); /** The Kodkod tupleset factory. */ private TupleFactory factory; /** * Helper method that returns true if the given attribute value in the given XML * node is equal to "yes" */ private static boolean yes(XMLNode node, String attr) { return node.getAttribute(attr).equals("yes"); } /** * Helper method that returns an XML node's "label" attribute. */ private static String label(XMLNode node) { return node.getAttribute("label"); } /** * Helper method that returns true if the two iterables contain the same * elements (though possibly in different order) */ private static boolean sameset(Iterable<Sig> a, Iterable<Sig> b) { ArrayList<Sig> tmp = new ArrayList<Sig>(); for (Sig x : b) tmp.add(x); for (Sig x : a) if (tmp.contains(x)) tmp.remove(x); else return false; return tmp.isEmpty(); } /** Parse tuple. */ private Tuple parseTuple(XMLNode tuple, int arity) throws Err { Tuple ans = null; try { for (XMLNode sub : tuple) if (sub.is("atom")) { Tuple x = factory.tuple(sub.getAttribute("label")); if (ans == null) ans = x; else ans = ans.product(x); } if (ans == null) throw new ErrorFatal("Expecting: <tuple> <atom label=\"..\"/> .. </tuple>"); if (ans.arity() != arity) throw new ErrorFatal("Expecting: tuple of arity " + arity + " but got tuple of arity " + ans.arity()); return ans; } catch (Throwable ex) { throw new ErrorFatal("Expecting: <tuple> <atom label=\"..\"/> .. </tuple>", ex); } } /** Parse tuples. */ private TupleSet parseTuples(XMLNode tuples, int arity) throws Err { TupleSet ans = factory.noneOf(arity); for (XMLNode sub : tuples) if (sub.is("tuple")) ans.add(parseTuple(sub, arity)); return ans; } /** Parse sig/set. */ private Sig parseSig(String id, int depth) throws IOException, Err { Sig ans = id2sig.get(id); // [electrum] identify that has not been processed in this step (ans may be != null from previous steps) if (ans != null && expr2ts.get(ans) != null) return ans; XMLNode node = nmap.get(id); if (node == null) throw new IOException("Unknown SigID " + id + " encountered."); if (!node.is("sig")) throw new IOException("ID " + id + " is not a sig."); String label = label(node); Attr isAbstract = yes(node, "abstract") ? Attr.ABSTRACT : null; Attr isOne = yes(node, "one") ? Attr.ONE : null; Attr isLone = yes(node, "lone") ? Attr.LONE : null; Attr isSome = yes(node, "some") ? Attr.SOME : null; Attr isPrivate = yes(node, "private") ? Attr.PRIVATE : null; Attr isMeta = yes(node, "meta") ? Attr.META : null; Attr isEnum = yes(node, "enum") ? Attr.ENUM : null; Attr isExact = yes(node, "exact") ? Attr.EXACT : null; Attr isVar = yes(node, "var") ? Attr.VARIABLE : null; if (yes(node, "builtin")) { if (label.equals(UNIV.label)) { id2sig.put(id, UNIV); return UNIV; } if (label.equals(SIGINT.label)) { id2sig.put(id, SIGINT); return SIGINT; } if (label.equals(SEQIDX.label)) { id2sig.put(id, SEQIDX); return SEQIDX; } if (label.equals(STRING.label)) { id2sig.put(id, STRING); return STRING; } throw new IOException("Unknown builtin sig: " + label + " (id=" + id + ")"); } if (depth > nmap.size()) throw new IOException("Sig " + label + " (id=" + id + ") is in a cyclic inheritance relationship."); List<Sig> parents = null; TupleSet ts = factory.noneOf(1); for (XMLNode sub : node) { if (sub.is("atom")) { ts.add(factory.tuple(sub.getAttribute("label"))); continue; } if (!sub.is("type")) continue; Sig parent = parseSig(sub.getAttribute("ID"), depth + 1); if (parents == null) parents = new ArrayList<Sig>(); parents.add(parent); } if (parents == null) { String parentID = node.getAttribute("parentID"); Sig parent = parseSig(parentID, depth + 1); if (!(parent instanceof PrimSig)) throw new IOException("Parent of sig " + label + " (id=" + id + ") must not be a subset sig."); for (Expr choice : choices) if (choice instanceof PrimSig && parent == ((PrimSig) choice).parent && ((Sig) choice).label.equals(label)) { ans = (Sig) choice; choices.remove(choice); break; } if (ans == null) { ans = new PrimSig(label, (PrimSig) parent, isAbstract, isLone, isOne, isSome, isPrivate, isMeta, isEnum, isVar); allsigs.add(ans); } } else { for (Expr choice : choices) if (choice instanceof SubsetSig && ((Sig) choice).label.equals(label) && sameset(parents, ((SubsetSig) choice).parents)) { ans = (Sig) choice; choices.remove(choice); break; } if (ans == null) { ans = new SubsetSig(label, parents, isExact, isLone, isOne, isSome, isPrivate, isMeta, isVar); allsigs.add(ans); } } id2sig.put(id, ans); expr2ts.put(ans, ts); if (ans instanceof PrimSig) { // Add the atoms in this SIG into all parent sigs for (PrimSig ans2 = ((PrimSig) ans).parent; ans2 != null && !ans2.builtin; ans2 = ans2.parent) { TupleSet ts2 = expr2ts.get(ans2); if (ts2 == null) ts2 = ts.clone(); else { ts2 = ts2.clone(); ts2.addAll(ts); } expr2ts.put(ans2, ts2); } } return ans; } /** Parse type. */ private Expr parseType(XMLNode node) throws IOException, Err { Expr expr = null; if (!node.is("types")) throw new IOException("<types>...</type> expected"); for (XMLNode n : node) if (n.is("type")) { Sig sig = parseSig(n.getAttribute("ID"), 0); if (expr == null) expr = sig; else expr = expr.product(sig); } if (expr == null) throw new IOException("<type ID=../> expected"); return expr; } /** Parse field. */ private Field parseField(String id) throws IOException, Err { final XMLNode node = nmap.get(id); if (node == null) throw new IOException("Unknown FieldID " + id + " encountered."); if (!node.is("field")) throw new IOException("ID " + id + " is not a field."); String label = label(node); Pos isPrivate = yes(node, "private") ? Pos.UNKNOWN : null; Pos isMeta = yes(node, "meta") ? Pos.UNKNOWN : null; Pos isVar = yes(node, "var") ? Pos.UNKNOWN : null; Expr type = null; for (XMLNode sub : node) if (sub.is("types")) { Expr t = parseType(sub); if (type == null) type = t; else type = type.plus(t); } int arity; if (type == null || (arity = type.type().arity()) < 2) throw new IOException("Field " + label + " is maltyped."); String parentID = node.getAttribute("parentID"); Sig parent = id2sig.get(parentID); if (parent == null) throw new IOException("ID " + parentID + " is not a sig."); Field field = null; for (Field f : parent.getFields()) if (f.label.equals(label) && f.type().arity() == arity && choices.contains(f)) { field = f; choices.remove(f); break; } if (field == null) field = parent.addTrickyField(Pos.UNKNOWN, isPrivate, null, null, isMeta, isVar, new String[] { label }, UNIV.join(type))[0]; TupleSet ts = parseTuples(node, arity); expr2ts.put(field, ts); return field; } /** Parse skolem. */ private ExprVar parseSkolem(String id) throws IOException, Err { final XMLNode node = nmap.get(id); if (node == null) throw new IOException("Unknown ID " + id + " encountered."); if (!node.is("skolem")) throw new IOException("ID " + id + " is not a skolem."); String label = label(node); Expr type = null; for (XMLNode sub : node) if (sub.is("types")) { Expr t = parseType(sub); if (type == null) type = t; else type = type.plus(t); } int arity; if (type == null || (arity = type.type().arity()) < 1) throw new IOException("Skolem " + label + " is maltyped."); // [electrum] try to use previously created expr for skolem, not registered anywhere ExprVar var = null; for (Expr exp : expr2ts.keySet()) if (exp instanceof ExprVar && ((ExprVar) exp).label.equals(label)) var = (ExprVar) exp; if (var == null) var = ExprVar.make(Pos.UNKNOWN, label, type.type()); TupleSet ts = parseTuples(node, arity); expr2ts.put(var, ts); return var; } /** Parse everything. */ // [electrum] heavily modified to support sequences of <instance> nodes, A4Solutions are built incrementally private A4SolutionReader(Iterable<Sig> sigs, XMLNode xml) throws IOException, Err { // find <instance>..</instance> if (!xml.is("alloy")) throw new ErrorSyntax("The XML file's root node must be <alloy> or <instance>."); XMLNode inst = null; A4Solution prev = null; for (XMLNode sub : xml) if (sub.is("instance")) { inst = sub; break; } if (inst == null) throw new ErrorSyntax("The XML file must contain an <instance> element."); // set up the basic values of the A4Solution object final int bitwidth = Integer.parseInt(inst.getAttribute("bitwidth")); final int maxseq = Integer.parseInt(inst.getAttribute("maxseq")); final int tracelength; final int backloop; final int maxtrace; final int mintrace; try { mintrace = Integer.parseInt(inst.getAttribute("mintrace")); maxtrace = Integer.parseInt(inst.getAttribute("maxtrace")); tracelength = Integer.parseInt(inst.getAttribute("tracelength")); backloop = Integer.parseInt(inst.getAttribute("backloop")); } catch (Exception ex) { throw new ErrorSyntax("Missing trace attributes."); } final int max = Util.max(bitwidth), min = Util.min(bitwidth); if (bitwidth >= 1 && bitwidth <= 30) for (int i = min; i <= max; i++) { atoms.add(Integer.toString(i)); } // [electrum] get all atoms of the universe, must traverse all states for (XMLNode sub : xml) if (sub.is("instance")) { inst = sub; for (XMLNode x : inst) { if (x.is("sig")) { boolean isString = STRING.label.equals(label(x)) && yes(x, "builtin"); for (XMLNode y : x) if (y.is("atom")) { String attr = y.getAttribute("label"); atoms.add(attr); if (isString) strings.add(attr); } } } } for (XMLNode sub : xml) if (sub.is("instance")) { inst = sub; // [electrum] if not first step, retrieve already created sigs prev = sol; if (prev != null) sigs = prev.getAllReachableSigs(); for (Sig s : sigs) if (!s.builtin) { allsigs.add(s); choices.add(s); for (Field f : s.getFields()) choices.add(f); } nmap.clear(); expr2ts.clear(); for (XMLNode x : inst) { String id = x.getAttribute("ID"); if (id.length() > 0 && (x.is("field") || x.is("skolem") || x.is("sig"))) { if (nmap.put(id, x) != null) throw new IOException("ID " + id + " is repeated."); } } // create the A4Solution object A4Options opt = new A4Options(); opt.originalFilename = inst.getAttribute("filename"); // [electrum] do not use actual max trace, solution would identify unbounded solving but no unbounded solver sol = new A4Solution(inst.getAttribute("command"), bitwidth, mintrace, tracelength, maxseq, strings, atoms, null, opt, 1); factory = sol.getFactory(); // parse all the sigs, fields, and skolems for (Map.Entry<String,XMLNode> e : nmap.entrySet()) if (e.getValue().is("sig")) parseSig(e.getKey(), 0); for (Map.Entry<String,XMLNode> e : nmap.entrySet()) if (e.getValue().is("field")) parseField(e.getKey()); for (Map.Entry<String,XMLNode> e : nmap.entrySet()) if (e.getValue().is("skolem")) parseSkolem(e.getKey()); for (Sig s : allsigs) if (!s.builtin) { TupleSet ts = expr2ts.remove(s); if (ts == null) ts = factory.noneOf(1); // If the sig was NOT mentioned in the XML file... Relation r; // [electrum] if first state create the relation if (prev == null) r = sol.addRel(s.label, ts, ts, s.isVariable != null); // [electrum] otherwise use previously created else { r = (Relation) prev.a2k(s); sol.addPreRel(s.label, ts, ts, r); } sol.addSig(s, r); for (Field f : s.getFields()) { ts = expr2ts.remove(f); if (ts == null) ts = factory.noneOf(f.type().arity()); // If the field was NOT mentioned in the XML file... // [electrum] if first state create the relation if (prev == null) r = sol.addRel(s.label + "." + f.label, ts, ts, f.isVariable != null); // [electrum] otherwise use previously created else { r = (Relation) prev.a2k(f); sol.addPreRel(s.label + "." + f.label, ts, ts, r); } sol.addField(f, r); } } for (Map.Entry<Expr,TupleSet> e : expr2ts.entrySet()) { ExprVar v = (ExprVar) (e.getKey()); TupleSet ts = e.getValue(); Relation r = null; if (prev == null) r = sol.addRel(v.label, ts, ts, true); else { // [electrum] search for skolem relation, not registered anywhere, but skolems always present in all instances for (Expr exp : prev.a2k().keySet()) if (exp instanceof ExprVar && ((Relation) prev.a2k(exp)).name().equals(v.label)) { r = (Relation) prev.a2k(exp); break; } sol.addPreRel(v.label, ts, ts, r); } sol.kr2type(r, v.type()); } // Done! sol.solve(null, prev, backloop); // [electrum] merge current solution with previous, if any } } /** * Parse the XML element into an AlloyInstance. * <p> * The list of sigs, if not null, will be used as the sigs (and their fields) * that we expect to exist; <br> * if there's a sig or field X in the list but not in the XML, then X's tupleset * will be regarded as empty; <br> * if there's a sig or field X in the XML but not in the list, then X (and its * value in XML file) is added to the solution. */ public static A4Solution read(Iterable<Sig> sigs, XMLNode xml) throws Err { try { if (sigs == null) sigs = new ArrayList<Sig>(); A4SolutionReader x = new A4SolutionReader(sigs, xml); return x.sol; } catch (Throwable ex) { if (ex instanceof Err) throw ((Err) ex); else throw new ErrorFatal("Fatal error occured: " + ex, ex); } } }
package org.kyojo.schemaorg.m3n3.doma.core.container; import java.math.BigDecimal; import org.seasar.doma.ExternalDomain; import org.seasar.doma.jdbc.domain.DomainConverter; import org.kyojo.schemaorg.m3n3.core.impl.ANNUAL_PERCENTAGE_RATE; import org.kyojo.schemaorg.m3n3.core.Container.AnnualPercentageRate; @ExternalDomain public class AnnualPercentageRateConverter implements DomainConverter<AnnualPercentageRate, BigDecimal> { @Override public BigDecimal fromDomainToValue(AnnualPercentageRate domain) { return domain.getNativeValue(); } @Override public AnnualPercentageRate fromValueToDomain(BigDecimal value) { return new ANNUAL_PERCENTAGE_RATE(value); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.iceberg; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import java.io.IOException; import java.util.Collection; import org.apache.iceberg.avro.Avro; import org.apache.iceberg.exceptions.RuntimeIOException; import org.apache.iceberg.expressions.Expression; import org.apache.iceberg.expressions.ResidualEvaluator; import org.apache.iceberg.io.CloseableIterable; import org.apache.iceberg.io.FileIO; import org.apache.iceberg.types.Types; /** * A {@link Table} implementation that exposes a table's valid manifest files as rows. * <p> * A valid manifest file is one that is referenced from any snapshot currently tracked by the table. * <p> * This table may return duplicate rows. */ public class AllManifestsTable extends BaseMetadataTable { private static final Schema MANIFEST_FILE_SCHEMA = new Schema( Types.NestedField.required(1, "path", Types.StringType.get()), Types.NestedField.required(2, "length", Types.LongType.get()), Types.NestedField.optional(3, "partition_spec_id", Types.IntegerType.get()), Types.NestedField.optional(4, "added_snapshot_id", Types.LongType.get()), Types.NestedField.optional(5, "added_data_files_count", Types.IntegerType.get()), Types.NestedField.optional(6, "existing_data_files_count", Types.IntegerType.get()), Types.NestedField.optional(7, "deleted_data_files_count", Types.IntegerType.get()), Types.NestedField.optional(8, "partition_summaries", Types.ListType.ofRequired(9, Types.StructType.of( Types.NestedField.required(10, "contains_null", Types.BooleanType.get()), Types.NestedField.optional(11, "lower_bound", Types.StringType.get()), Types.NestedField.optional(12, "upper_bound", Types.StringType.get()) ))) ); private final TableOperations ops; private final Table table; public AllManifestsTable(TableOperations ops, Table table) { this.ops = ops; this.table = table; } @Override Table table() { return table; } @Override String metadataTableName() { return "all_manifests"; } @Override public TableScan newScan() { return new AllManifestsTableScan(ops, table, MANIFEST_FILE_SCHEMA); } @Override public Schema schema() { return MANIFEST_FILE_SCHEMA; } public static class AllManifestsTableScan extends BaseTableScan { AllManifestsTableScan(TableOperations ops, Table table, Schema fileSchema) { super(ops, table, fileSchema); } private AllManifestsTableScan( TableOperations ops, Table table, Long snapshotId, Schema schema, Expression rowFilter, boolean caseSensitive, boolean colStats, Collection<String> selectedColumns, ImmutableMap<String, String> options) { super(ops, table, snapshotId, schema, rowFilter, caseSensitive, colStats, selectedColumns, options); } @Override protected TableScan newRefinedScan( TableOperations ops, Table table, Long snapshotId, Schema schema, Expression rowFilter, boolean caseSensitive, boolean colStats, Collection<String> selectedColumns, ImmutableMap<String, String> options) { return new AllManifestsTableScan( ops, table, snapshotId, schema, rowFilter, caseSensitive, colStats, selectedColumns, options); } @Override public TableScan useSnapshot(long scanSnapshotId) { throw new UnsupportedOperationException("Cannot select snapshot: all_manifests is for all snapshots"); } @Override public TableScan asOfTime(long timestampMillis) { throw new UnsupportedOperationException("Cannot select snapshot: all_manifests is for all snapshots"); } @Override protected long targetSplitSize(TableOperations ops) { return ops.current().propertyAsLong( TableProperties.METADATA_SPLIT_SIZE, TableProperties.METADATA_SPLIT_SIZE_DEFAULT); } @Override protected CloseableIterable<FileScanTask> planFiles( TableOperations ops, Snapshot snapshot, Expression rowFilter, boolean caseSensitive, boolean colStats) { String schemaString = SchemaParser.toJson(schema()); String specString = PartitionSpecParser.toJson(PartitionSpec.unpartitioned()); // Data tasks produce the table schema, not the projection schema and projection is done by processing engines. return CloseableIterable.withNoopClose(Iterables.transform(ops.current().snapshots(), snap -> { if (snap.manifestListLocation() != null) { return new ManifestListReadTask(ops.io(), table().spec(), new BaseFileScanTask( DataFiles.fromManifestList(ops.io().newInputFile(snap.manifestListLocation())), schemaString, specString, ResidualEvaluator.unpartitioned(rowFilter))); } else { return StaticDataTask.of( ops.io().newInputFile(ops.current().file().location()), snap.manifests(), manifest -> ManifestsTable.manifestFileToRow(table().spec(), manifest)); } })); } } static class ManifestListReadTask implements DataTask { private final FileIO io; private final PartitionSpec spec; private final FileScanTask manifestListTask; ManifestListReadTask(FileIO io, PartitionSpec spec, FileScanTask manifestListTask) { this.io = io; this.spec = spec; this.manifestListTask = manifestListTask; } @Override public CloseableIterable<StructLike> rows() { try (CloseableIterable<ManifestFile> manifests = Avro .read(io.newInputFile(manifestListTask.file().path().toString())) .rename("manifest_file", GenericManifestFile.class.getName()) .rename("partitions", GenericPartitionFieldSummary.class.getName()) .rename("r508", GenericPartitionFieldSummary.class.getName()) .project(ManifestFile.schema()) .classLoader(GenericManifestFile.class.getClassLoader()) .reuseContainers(false) .build()) { return CloseableIterable.transform(manifests, manifest -> ManifestsTable.manifestFileToRow(spec, manifest)); } catch (IOException e) { throw new RuntimeIOException(e, "Cannot read manifest list file: %s", manifestListTask.file().path()); } } @Override public DataFile file() { return manifestListTask.file(); } @Override public PartitionSpec spec() { return manifestListTask.spec(); } @Override public long start() { return 0; } @Override public long length() { return manifestListTask.length(); } @Override public Expression residual() { return manifestListTask.residual(); } @Override public Iterable<FileScanTask> split(long splitSize) { return ImmutableList.of(this); // don't split } } }
package com.atlands.assistant.db; import org.litepal.crud.LitePalSupport; public class Contentlist extends LitePalSupport { private int id; private String name; private String link; private int tid; private int cid; private int oid; private int wid; public int getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public int getTid() { return tid; } public void setTid(int tid) { this.tid = tid; } public int getCid() { return cid; } public void setCid(int cid) { this.cid = cid; } public int getOid() { return oid; } public void setOid(int oid) { this.oid = oid; } public int getWid() { return wid; } public void setWid(int wid) { this.wid = wid; } }
package mcjty.rftools.api.storage; import net.minecraft.item.ItemStack; import javax.annotation.Nullable; import java.util.function.Predicate; /** * This interface is implemented by the RFTools Storage Scanner tile entity */ public interface IStorageScanner { /** * Request an itemstack from the storage scanner * Returns null/EMPTY if not possible. The returned itemstack will have at most * 'amount' items in it. It will try to extract as much as possible. * The given amount is automatically capped to the stack limit of the item * This can also return null (or EMPTY on 1.11) if there is insufficient energy * for the request */ ItemStack requestItem(ItemStack match, int amount, boolean routable, boolean oredict); /** * Request an itemstack from the storage scanner * Returns null/EMPTY if not possible. * The returned item will have at most 'amount' items in it (capped to max stacksize) * This can also return null (or EMPTY on 1.11) if there is insufficient energy * for the request */ ItemStack requestItem(Predicate<ItemStack> matcher, boolean simulate, int amount, boolean routable); /** * Count the number of items that match in this storage scanner. This counts all the * items available in the system so the returned number can exceed the maximum * stacksize of the item * @return */ int countItems(ItemStack match, boolean routable, boolean oredict); /** * Count the number of items that match in this storage scanner. This counts all the * items available in the system so the returned number can exceed the maximum * stacksize of the item * @return */ int countItems(ItemStack match, boolean routable, boolean oredict, @Nullable Integer maxneeded); /** * Count items matching a certain predicate. * If 'maxneeded' is given then the count will stop as soon as we have reached that number */ int countItems(Predicate<ItemStack> matcher, boolean routable, @Nullable Integer maxneeded); /** * Push the given items into the system (routable inventories only). * Returns the stack that could not be inserted. * @param stack */ ItemStack insertItem(ItemStack stack, boolean simulate); /** * Push the given items into the system (routable inventories only). * Returns the number of items that could not be inserted. * @param stack */ int insertItem(ItemStack stack); }
/* * Copyright 2012-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.autoconfigure.hazelcast; import java.io.IOException; import com.hazelcast.config.Config; import com.hazelcast.core.Hazelcast; import com.hazelcast.core.HazelcastInstance; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.Resource; /** * Configuration for Hazelcast server. * * @author Stephane Nicoll * @author Vedran Pavic */ @Configuration @ConditionalOnMissingBean(HazelcastInstance.class) class HazelcastServerConfiguration { static final String CONFIG_SYSTEM_PROPERTY = "hazelcast.config"; @Configuration @ConditionalOnMissingBean(Config.class) @Conditional(ConfigAvailableCondition.class) static class HazelcastServerConfigFileConfiguration { @Bean public HazelcastInstance hazelcastInstance(HazelcastProperties properties) throws IOException { Resource config = properties.resolveConfigLocation(); if (config != null) { return new HazelcastInstanceFactory(config).getHazelcastInstance(); } return Hazelcast.newHazelcastInstance(); } } @Configuration @ConditionalOnSingleCandidate(Config.class) static class HazelcastServerConfigConfiguration { @Bean public HazelcastInstance hazelcastInstance(Config config) { return new HazelcastInstanceFactory(config).getHazelcastInstance(); } } /** * {@link HazelcastConfigResourceCondition} that checks if the * {@code spring.hazelcast.config} configuration key is defined. */ static class ConfigAvailableCondition extends HazelcastConfigResourceCondition { ConfigAvailableCondition() { super(CONFIG_SYSTEM_PROPERTY, "file:./hazelcast.xml", "classpath:/hazelcast.xml"); } } }
package com.contoso.helpers; public class MockHelper { }
// *************************************************************************************************************************** // * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * // * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * // * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance * // * with the License. You may obtain a copy of the License at * // * * // * http://www.apache.org/licenses/LICENSE-2.0 * // * * // * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an * // * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * // * specific language governing permissions and limitations under the License. * // *************************************************************************************************************************** package org.apache.juneau.assertions; import static org.apache.juneau.assertions.Assertions.*; import static org.junit.runners.MethodSorters.*; import java.io.*; import java.time.*; import java.util.*; import org.apache.juneau.collections.*; import org.junit.*; @FixMethodOrder(NAME_ASCENDING) public class Assertions_Test { @Test public void a01_basic() throws Exception { assertDate(new Date()).isAfter(new Date(0)); assertInteger(2).isGt(1); assertLong(2l).isGt(1l); assertObject("foo").asJson().is("'foo'"); assertString("foo").is("foo"); assertThrowable(null).doesNotExist(); assertArray(new String[0]).isEmpty(); assertCollection(AList.create()).isEmpty(); assertList(AList.create()).isEmpty(); assertStream(new ByteArrayInputStream("foo".getBytes())).asString().is("foo"); assertStream((InputStream)null).asString().doesNotExist(); assertStream(Optional.of(new ByteArrayInputStream("foo".getBytes()))).asString().is("foo"); assertStream(Optional.empty()).asString().doesNotExist(); assertBytes("foo".getBytes()).asString().is("foo"); assertBytes((byte[])null).asString().doesNotExist(); assertBytes(Optional.of("foo".getBytes())).asString().is("foo"); assertBytes(Optional.empty()).asString().doesNotExist(); assertReader(new StringReader("foo")).is("foo"); assertReader((Reader)null).doesNotExist(); assertReader(Optional.of(new StringReader("foo"))).is("foo"); assertReader(Optional.empty()).doesNotExist(); assertThrown(()->{throw new RuntimeException("foo");}).is("foo"); assertThrown(()->{}).doesNotExist(); assertZonedDateTime(ZonedDateTime.now()).exists(); assertZonedDateTime(Optional.of(ZonedDateTime.now())).exists(); assertBean("123").exists(); assertBean(Optional.of("123")).exists(); assertBoolean(true).isTrue(); assertBoolean(Optional.of(true)).isTrue(); new Assertions(); } @Test public void a02_stdout_stderr() throws Exception { assertThrown(()->assertObject(null).msg("Test message").stdout().exists()).exists(); assertObject(assertObject("foo").silent().error("test {0}", "message").getMessage()).is("test message"); } }
package org.smoothbuild.util.io; import java.io.IOException; import okio.BufferedSource; @FunctionalInterface public interface DataReader<T> { public T readFrom(BufferedSource source) throws IOException; }
/* * 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.onsmqtt.transform.v20191211; import com.aliyuncs.onsmqtt.model.v20191211.QuerySessionByClientIdResponse; import com.aliyuncs.transform.UnmarshallerContext; public class QuerySessionByClientIdResponseUnmarshaller { public static QuerySessionByClientIdResponse unmarshall(QuerySessionByClientIdResponse querySessionByClientIdResponse, UnmarshallerContext _ctx) { querySessionByClientIdResponse.setRequestId(_ctx.stringValue("QuerySessionByClientIdResponse.RequestId")); querySessionByClientIdResponse.setOnlineStatus(_ctx.booleanValue("QuerySessionByClientIdResponse.OnlineStatus")); return querySessionByClientIdResponse; } }
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.cdi.tck.tests.interceptors.invocation; import java.io.Serializable; import jakarta.annotation.PostConstruct; import jakarta.annotation.Priority; import jakarta.interceptor.AroundInvoke; import jakarta.interceptor.AroundTimeout; import jakarta.interceptor.Interceptor; import jakarta.interceptor.InvocationContext; @SuppressWarnings("serial") @Interceptor @AlmightyBinding @Priority(0) public class AlmightyInterceptor implements Serializable { public static boolean methodIntercepted = false; public static boolean timeoutIntercepted = false; public static boolean lifecycleCallbackIntercepted = false; @AroundInvoke public Object alwaysReturnThis(InvocationContext ctx) throws Exception { methodIntercepted = true; return ctx.proceed(); } @AroundTimeout public Object interceptTimeout(InvocationContext ctx) throws Exception { timeoutIntercepted = true; return ctx.proceed(); } @PostConstruct public void postConstruct(InvocationContext ctx) { lifecycleCallbackIntercepted = true; } public static void reset() { methodIntercepted = false; lifecycleCallbackIntercepted = false; } }
package com.redis_cache.redis_sentinel.controller; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value="/simpleController") public class SimpleController { @RequestMapping( value="/helloFriends", method= RequestMethod.GET, produces = "text/plain") public ResponseEntity<String> helloFriendsMethod() { return ResponseEntity.ok().body("hello friends"); } }
package ru.job4j.array; import java.util.Arrays; /** * @author tumen.garmazhapov (gtb-85@yandex.ru) * @since 11.2018*/ public class ArrayDuplicate { /** * метод удалаяет дубликаты из массива * @param array массив строк * @return array массив без дубликатов*/ public String[] remove(String[] array) { int unique = array.length; for (int out = 0; out < unique; out++) { for (int in = out + 1; in < unique; in++) { if (array[out].equals(array[in])) { array[in] = array[unique - 1]; unique--; in--; } } } return Arrays.copyOf(array, unique); } }
package net.launchers.mod.network.packet; import io.netty.buffer.Unpooled; import net.fabricmc.fabric.api.network.PacketContext; import net.fabricmc.fabric.api.network.ServerSidePacketRegistry; import net.launchers.mod.loader.LMLoader; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.Identifier; import net.minecraft.util.PacketByteBuf; public abstract class CustomPacket { public static Identifier PACKET_ID = new Identifier(LMLoader.MOD_ID, "cp"); public CustomPacket() { } public void sendTo(PlayerEntity player) { PacketByteBuf buf = new PacketByteBuf(Unpooled.buffer()); write(buf); ServerSidePacketRegistry.INSTANCE.sendToPlayer(player, PACKET_ID, buf); } protected abstract void onReceive(PacketContext ctx); public abstract void write(PacketByteBuf buf); }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.data.confidentialledger; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceClient; import com.azure.core.annotation.ServiceMethod; import com.azure.core.experimental.http.DynamicRequest; import com.azure.core.http.HttpMethod; import com.azure.core.http.HttpPipeline; import com.azure.core.util.serializer.ObjectSerializer; import java.net.URL; /** Initializes a new instance of the ConfidentialLedgerIdentityServiceBaseClient type. */ @ServiceClient(builder = ConfidentialLedgerClientBuilder.class) public final class ConfidentialLedgerIdentityServiceBaseClient { private final URL ledgerUri; private final String apiVersion; private final URL identityServiceUri; private final HttpPipeline httpPipeline; private final ObjectSerializer serializer; /** * Initializes an instance of ConfidentialLedgerIdentityServiceBaseClient client. * * @param ledgerUri The Confidential Ledger URL, for example https://contoso.confidentialledger.azure.com. * @param apiVersion Api Version. * @param identityServiceUri The Identity Service URL, for example https://identity.accledger.azure.com. * @param httpPipeline The HTTP pipeline to send requests through. * @param serializer The serializer to serialize an object into a string. */ ConfidentialLedgerIdentityServiceBaseClient( URL ledgerUri, String apiVersion, URL identityServiceUri, HttpPipeline httpPipeline, ObjectSerializer serializer) { this.ledgerUri = ledgerUri; this.apiVersion = apiVersion; this.identityServiceUri = identityServiceUri; this.httpPipeline = httpPipeline; this.serializer = serializer; } /** * Gets identity information for a Confidential Ledger instance. * * <p><strong>Response Body Schema</strong> * * <pre>{@code * { * ledgerId: String * ledgerTlsCertificate: String * } * }</pre> * * @param ledgerId Id of the Confidential Ledger instance to get information for. * @return a DynamicRequest where customizations can be made before sent to the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public DynamicRequest getLedgerIdentity(String ledgerId) { return new DynamicRequest(serializer, httpPipeline) .setUrl("{identityServiceUri}/ledgerIdentity/{ledgerId}") .setPathParam("identityServiceUri", identityServiceUri.toString()) .setPathParam("ledgerId", ledgerId) .addQueryParam("api-version", apiVersion) .addHeader("Accept", "application/json") .addHeader("Content-Type", "application/json") .setHttpMethod(HttpMethod.GET); } /** * Create an empty DynamicRequest with the serializer and pipeline initialized for this client. * * @return a DynamicRequest where customizations can be made before sent to the service. */ @ServiceMethod(returns = ReturnType.SINGLE) public DynamicRequest invoke() { return new DynamicRequest(serializer, httpPipeline); } }
package app.entitties; import javax.persistence.*; @Entity @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) public abstract class Person extends BaseEntity{ private String firstName; private String lastName; private String phoneNumber; public Person() { } @Column(name = "first_name") public String getFirstName() { return this.firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @Column(name = "last_name") public String getLastName() { return this.lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Column(name = "phone_number") public String getPhoneNumber() { return this.phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } }
package net.menthor.editor.v2.ui.table; /** * ============================================================================================ * Menthor Editor -- Copyright (c) 2015 * * This file is part of Menthor Editor. Menthor Editor is based on TinyUML and as so it is * distributed under the same license terms. * * Menthor Editor is free software; you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * Menthor Editor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with Menthor Editor; * if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, * MA 02110-1301 USA * ============================================================================================ */ import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.DefaultCellEditor; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextPane; import javax.swing.KeyStroke; import javax.swing.ScrollPaneConstants; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.border.EmptyBorder; import javax.swing.border.EtchedBorder; import javax.swing.event.ChangeEvent; import javax.swing.table.TableCellEditor; import net.menthor.editor.v2.ui.color.ColorMap; import net.menthor.editor.v2.ui.color.ColorType; import net.menthor.editor.v2.ui.icon.IconMap; import net.menthor.editor.v2.ui.icon.IconType; import RefOntoUML.parser.OntoUMLParser; import javax.swing.ListSelectionModel; public class MappingTablePane extends JPanel { private static final long serialVersionUID = -7587547341203464118L; protected MappingTableModel tableModel; protected JScrollPane scrollpane = new JScrollPane(); protected JTable table; protected JPanel headerPane = new JPanel(); protected JButton btnAdd; protected JButton btnDelete; protected JTextPane textPane = new JTextPane(); private JPanel panel; public MappingTableModel getTableModel(){ return tableModel; } public JPanel getHeaderPane() { return headerPane; } public void setText(String text) { textPane.setText(text); } public MappingTablePane(String sourceColumnTitle, OntoUMLParser refparser, String targetColumnTitle, String choiceColumnTitle){ tableModel = new MappingChoiceTableModel(sourceColumnTitle, targetColumnTitle, choiceColumnTitle); buildUI(refparser); } /** @wbp.parser.constructor */ public MappingTablePane(String sourceColumnTitle, OntoUMLParser refparser, String targetColumnTitle){ tableModel = new MappingTableModel(sourceColumnTitle, targetColumnTitle); buildUI(refparser); } public void addMapping(ActionEvent evt){ tableModel.addEmptyEntry(); } public void refreshData(){ tableModel.fireTableDataChanged(); } public void deleteMapping(ActionEvent evt){ for(int i = table.getSelectedRows().length-1; i >= 0; i--){ int selectedRow = table.getSelectedRows()[i]; table.editingStopped(new ChangeEvent(table)); if (selectedRow >= 0 && selectedRow < tableModel.getRowCount()){ tableModel.removeEntryAt(selectedRow); } } } public void deleteSingleMapping(ActionEvent evt){ int selectedRow = table.getSelectedRow(); table.editingStopped(new ChangeEvent(table)); if (selectedRow >= 0 && selectedRow < tableModel.getRowCount()){ tableModel.removeEntryAt(selectedRow); } } private void buildUI(OntoUMLParser refparser){ scrollpane.setMinimumSize(new Dimension(0, 0)); scrollpane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); scrollpane.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null)); table = new JTable(tableModel); table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); scrollpane.setViewportView(table); table.setBorder(new EmptyBorder(0, 0, 0, 0)); table.setFillsViewportHeight(true); table.setGridColor(Color.LIGHT_GRAY); table.setSelectionBackground(ColorMap.getInstance().getColor(ColorType.MENTHOR_BLUE)); table.setSelectionForeground(Color.BLACK); table.setFocusable(false); table.setRowHeight(23); headerPane.setPreferredSize(new Dimension(10, 60)); setLayout(new BorderLayout(0,0)); add(headerPane, BorderLayout.NORTH); textPane.setEditable(false); textPane.setMargin(new Insets(10, 10, 5, 3)); textPane.setPreferredSize(new Dimension(6, 50)); textPane.setBackground(UIManager.getColor("Panel.background")); panel = new JPanel(); FlowLayout flowLayout = (FlowLayout) panel.getLayout(); flowLayout.setAlignment(FlowLayout.RIGHT); btnAdd = new JButton(); panel.add(btnAdd); btnAdd.setPreferredSize(new Dimension(33, 30)); btnAdd.setFocusable(false); btnAdd.setToolTipText("Add new mapping"); btnAdd.setIcon(IconMap.getInstance().getIcon(IconType.MENTHOR_ADD)); btnDelete = new JButton(); panel.add(btnDelete); btnDelete.setPreferredSize(new Dimension(33, 30)); btnDelete.setFocusable(false); btnDelete.setToolTipText("Delete selected mapping"); btnDelete.setIcon(IconMap.getInstance().getIcon(IconType.MENTHOR_DELETE)); btnDelete.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { deleteMapping(arg0); } }); btnAdd.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { if(!tableModel.hasNullEntry()) addMapping(arg0); else{ JOptionPane.showMessageDialog(null,"Please, fill the <no value> cells before moving on.", "Invalid Entry", JOptionPane.ERROR_MESSAGE); } } }); headerPane.setLayout(new BorderLayout(0, 0)); headerPane.add(panel, BorderLayout.EAST); headerPane.add(textPane, BorderLayout.CENTER); add(scrollpane, BorderLayout.CENTER); } protected TableCellEditor createEditor(Object[] objects, boolean isEditable) { @SuppressWarnings({ "rawtypes", "unchecked" }) JComboBox combo = new JComboBox(objects) { private static final long serialVersionUID = 1L; @Override protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed){ boolean retValue = super.processKeyBinding(ks, e, condition,pressed); if (!retValue && isStartingCellEdit() && editor != null) { editor.setItem(String.valueOf(ks.getKeyChar())); } return retValue; } private boolean isStartingCellEdit(){ JTable table = (JTable) SwingUtilities.getAncestorOfClass(JTable.class, this); return table != null && table.isFocusOwner() && !Boolean.FALSE.equals((Boolean)table.getClientProperty("JTable.autoStartsEdit")); } }; combo.setEditable(isEditable); return new DefaultCellEditor(combo); } protected JButton addButton(String toolTipText, IconType iconType) { JButton newBtn = new JButton(); panel.add(newBtn); newBtn.setPreferredSize(new Dimension(33, 30)); newBtn.setFocusable(false); newBtn.setToolTipText(toolTipText); newBtn.setIcon(IconMap.getInstance().getIcon(iconType)); return newBtn; } }
package def.dom; @jsweet.lang.Interface public abstract class StoreSiteSpecificExceptionsInformation extends StoreExceptionsInformation { @jsweet.lang.Optional public String[] arrayOfDomainStrings; }
package com.goayo.debtify.model; /** * @author Oscar Sanner and Olof Sjögren * @date 2020-10-07 * <p> * Interface for event handlers who wish to subscribe to the EventBus and it's events. * <p> * 2020-10-13 Modified by Olof Sjögren: removed event parameter from method. Is now only a notification. */ public interface IEventHandler { /** * Notification method used to update the handler when a corresponding event it is listening to is fired. */ void onModelEvent(); }
package com.xceptance.xlt.nocoding.parser.csv; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; import org.apache.commons.csv.CSVParser; import com.xceptance.xlt.nocoding.command.Command; import com.xceptance.xlt.nocoding.command.action.Action; import com.xceptance.xlt.nocoding.command.action.subrequest.StaticSubrequest; import com.xceptance.xlt.nocoding.parser.Parser; import com.xceptance.xlt.nocoding.parser.csv.command.ActionParser; import com.xceptance.xlt.nocoding.parser.csv.command.StaticSubrequestParser; import com.xceptance.xlt.nocoding.parser.csv.command.XhrSubrequestParser; /** * Reads a CSV file, and generates a list filled with {@link Command}s out of the CSV file. * * @author ckeiner */ public class CsvParser implements Parser { /** * Parses the content of the Reader <code>reader</code> to a list of {@link Command}s * * @param reader * The Reader that contains {@link Command}s in a parser dependent format * @return A list of {@link Command}s * @throws IOException * if an I/O error occurs during creating the reader, parsing the file or closing the parser */ @Override public List<Command> parse(final Reader reader) throws IOException { // Initialize variables final List<Command> scriptItems = new ArrayList<>(); final ActionWrapper lastAction = new ActionWrapper(); final StaticSubrequestWrapper lastStatic = new StaticSubrequestWrapper(); // Create a CSVParser based on the Reader final CSVParser parser = new CSVParser(reader, CsvConstants.CSV_FORMAT.withFirstRecordAsHeader()); try { validateHeader(parser.getHeaderMap().keySet()); parser.forEach(record -> { // If the record is consistent, which means that all headers have a value if (record.isConsistent()) { // Get the type of the record String type = CsvConstants.TYPE_DEFAULT; if (record.isMapped(CsvConstants.TYPE)) { type = record.get(CsvConstants.TYPE); } // Differentiate between Action, Static and Xhr Requests switch (type) { case CsvConstants.TYPE_ACTION: // Reset the last static subrequest lastStatic.setStaticSubrequest(null); // Set the new action as last action lastAction.setAction(new ActionParser().parse(record)); // And add it to the scriptItems scriptItems.add(lastAction.getAction()); break; case CsvConstants.TYPE_STATIC: // If there was no lastAction, throw an exception if (lastAction.getAction() == null) { throw new IllegalArgumentException("Static Type must be defined after an Action Type"); } // If there wasn't a last static request if (lastStatic.getStaticSubrequest() == null) { // Read the static request and assign it to lastStatic lastStatic.setStaticSubrequest(new StaticSubrequestParser().parse(record)); // Assign last static as actionItem of the lastAction lastAction.getAction().getActionItems().add(lastStatic.getStaticSubrequest()); } // If there was a last static request else { // Simply add the url of the current static request to the lastStatic request, so they // can // be executed parallel lastStatic.getStaticSubrequest().getUrls().addAll(new StaticSubrequestParser().parse(record).getUrls()); } break; case CsvConstants.TYPE_XHR_ACTION: // Reset the last static subrequest lastStatic.setStaticSubrequest(null); // If there was no lastAction, throw an exception if (lastAction.getAction() == null) { throw new IllegalArgumentException("Xhr Action Type must be defined after an Action Type"); } // Add the Xhr Subrequest to the action items of the lastAction lastAction.getAction().getActionItems().add(new XhrSubrequestParser().parse(record)); break; default: // If the type is unknown, throw an error throw new IllegalArgumentException("The record has an unknown type: " + type); } } else { throw new IllegalStateException("The record does not contain an entry for each header!"); } }); } catch (final Throwable e) { throw new IllegalStateException("CSV Parsing failed in line " + parser.getCurrentLineNumber() + ": " + e.getMessage(), e); } finally { parser.close(); } // Return the scriptItems return scriptItems; } /** * Validates the headers are permitted * * @param headers */ private void validateHeader(final Set<String> headers) { // for each header for (final String header : headers) { // If the header is not in the permitted list if (!CsvConstants.isPermittedHeaderField(header)) { // Verify the header either starts with the Regexp or Xpath getter prefix if (!(header.startsWith(CsvConstants.REGEXP_GETTER_PREFIX) || header.startsWith(CsvConstants.XPATH_GETTER_PREFIX))) { throw new IllegalArgumentException(header + "isn't an allowed header!"); } } } } @Override public List<String> getExtensions() { return Arrays.asList("csv"); } public class ActionWrapper { public Action getAction() { return action; } public void setAction(final Action action) { this.action = action; } Action action; } public class StaticSubrequestWrapper { public StaticSubrequest getStaticSubrequest() { return staticSubrequest; } public void setStaticSubrequest(final StaticSubrequest staticSubrequest) { this.staticSubrequest = staticSubrequest; } StaticSubrequest staticSubrequest; } }
package org.jetlinks.community.rule.engine.entity; import com.alibaba.fastjson.JSONObject; import lombok.Getter; import lombok.Setter; import org.hswebframework.web.bean.FastBeanCopier; import org.jetlinks.core.event.TopicPayload; import java.util.Map; /** * @author bsetfeng * @since 1.0 **/ @Getter @Setter public class RuleEngineExecuteEventInfo { private String id; private String event; private long createTime = System.currentTimeMillis(); private String instanceId; private String nodeId; private String ruleData; private String contextId; public static RuleEngineExecuteEventInfo of(TopicPayload message) { Map<String, String> vars = message.getTopicVars("/rule-engine/{instanceId}/{nodeId}/event/{event}"); RuleEngineExecuteEventInfo info = FastBeanCopier.copy(vars, new RuleEngineExecuteEventInfo()); JSONObject json = message.bodyToJson(); info.id=json.getString("id"); info.contextId=json.getString("contextId"); info.setRuleData(json.toJSONString()); return info; } }
package ru.faulab.javaee.design.patterns.sample.project.platform.expection; public class GenericUserException extends SimpleProjectException { private final int errorCode; public GenericUserException(int errorCode, String message) { super(message); this.errorCode = errorCode; } @Override public ErrorValueObject toErrorValueObject() { return ErrorValueObject.builder().errorCode(errorCode).userMessage(getLocalizedMessage()).build(); } }
/* * MIT License * * Copyright (c) 2010 - 2021 The OSHI Project Contributors: https://github.com/oshi/oshi/graphs/contributors * * 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 oshi.hardware.platform.windows; import java.util.ArrayList; import java.util.List; import com.sun.jna.platform.win32.Advapi32Util; // NOSONAR squid:S1191 import com.sun.jna.platform.win32.Win32Exception; import com.sun.jna.platform.win32.WinError; import com.sun.jna.platform.win32.WinReg; import oshi.annotation.concurrent.Immutable; import oshi.hardware.SoundCard; import oshi.hardware.common.AbstractSoundCard; /** * Sound Card data obtained from registry */ @Immutable final class WindowsSoundCard extends AbstractSoundCard { private static final String REGISTRY_SOUNDCARDS = "SYSTEM\\CurrentControlSet\\Control\\Class\\{4d36e96c-e325-11ce-bfc1-08002be10318}\\"; /** * Constructor for WindowsSoundCard. * * @param kernelVersion * The version * @param name * The name * @param codec * The codec */ WindowsSoundCard(String kernelVersion, String name, String codec) { super(kernelVersion, name, codec); } /** * Returns Windows audio device driver information, which represents the closest * proxy we have to sound cards. * <p> * NOTE : The reason why the codec name is same as the card name is because * windows does not provide the name of the codec chip but sometimes the name of * the card returned is infact the name of the codec chip also. Example : * Realtek ALC887 HD Audio Device * * @return List of sound cards */ public static List<SoundCard> getSoundCards() { List<SoundCard> soundCards = new ArrayList<>(); String[] keys = Advapi32Util.registryGetKeys(WinReg.HKEY_LOCAL_MACHINE, REGISTRY_SOUNDCARDS); for (String key : keys) { String fullKey = REGISTRY_SOUNDCARDS + key; try { if (Advapi32Util.registryValueExists(WinReg.HKEY_LOCAL_MACHINE, fullKey, "Driver")) { soundCards.add(new WindowsSoundCard( Advapi32Util.registryGetStringValue(WinReg.HKEY_LOCAL_MACHINE, fullKey, "Driver") + " " + Advapi32Util.registryGetStringValue(WinReg.HKEY_LOCAL_MACHINE, fullKey, "DriverVersion"), Advapi32Util.registryGetStringValue(WinReg.HKEY_LOCAL_MACHINE, fullKey, "ProviderName") + " " + Advapi32Util.registryGetStringValue(WinReg.HKEY_LOCAL_MACHINE, fullKey, "DriverDesc"), Advapi32Util.registryGetStringValue(WinReg.HKEY_LOCAL_MACHINE, fullKey, "DriverDesc"))); } } catch (Win32Exception e) { if (e.getErrorCode() != WinError.ERROR_ACCESS_DENIED) { // Ignore access denied errors, re-throw others throw e; } } } return soundCards; } }
/* * Copyright 2013-2018 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.support.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * Details about AWS resources that were analyzed in a call to Trusted Advisor * <a>DescribeTrustedAdvisorCheckSummaries</a>. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/support-2013-04-15/TrustedAdvisorResourcesSummary" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class TrustedAdvisorResourcesSummary implements Serializable, Cloneable, StructuredPojo { /** * <p> * The number of AWS resources that were analyzed by the Trusted Advisor check. * </p> */ private Long resourcesProcessed; /** * <p> * The number of AWS resources that were flagged (listed) by the Trusted Advisor check. * </p> */ private Long resourcesFlagged; /** * <p> * The number of AWS resources ignored by Trusted Advisor because information was unavailable. * </p> */ private Long resourcesIgnored; /** * <p> * The number of AWS resources ignored by Trusted Advisor because they were marked as suppressed by the user. * </p> */ private Long resourcesSuppressed; /** * <p> * The number of AWS resources that were analyzed by the Trusted Advisor check. * </p> * * @param resourcesProcessed * The number of AWS resources that were analyzed by the Trusted Advisor check. */ public void setResourcesProcessed(Long resourcesProcessed) { this.resourcesProcessed = resourcesProcessed; } /** * <p> * The number of AWS resources that were analyzed by the Trusted Advisor check. * </p> * * @return The number of AWS resources that were analyzed by the Trusted Advisor check. */ public Long getResourcesProcessed() { return this.resourcesProcessed; } /** * <p> * The number of AWS resources that were analyzed by the Trusted Advisor check. * </p> * * @param resourcesProcessed * The number of AWS resources that were analyzed by the Trusted Advisor check. * @return Returns a reference to this object so that method calls can be chained together. */ public TrustedAdvisorResourcesSummary withResourcesProcessed(Long resourcesProcessed) { setResourcesProcessed(resourcesProcessed); return this; } /** * <p> * The number of AWS resources that were flagged (listed) by the Trusted Advisor check. * </p> * * @param resourcesFlagged * The number of AWS resources that were flagged (listed) by the Trusted Advisor check. */ public void setResourcesFlagged(Long resourcesFlagged) { this.resourcesFlagged = resourcesFlagged; } /** * <p> * The number of AWS resources that were flagged (listed) by the Trusted Advisor check. * </p> * * @return The number of AWS resources that were flagged (listed) by the Trusted Advisor check. */ public Long getResourcesFlagged() { return this.resourcesFlagged; } /** * <p> * The number of AWS resources that were flagged (listed) by the Trusted Advisor check. * </p> * * @param resourcesFlagged * The number of AWS resources that were flagged (listed) by the Trusted Advisor check. * @return Returns a reference to this object so that method calls can be chained together. */ public TrustedAdvisorResourcesSummary withResourcesFlagged(Long resourcesFlagged) { setResourcesFlagged(resourcesFlagged); return this; } /** * <p> * The number of AWS resources ignored by Trusted Advisor because information was unavailable. * </p> * * @param resourcesIgnored * The number of AWS resources ignored by Trusted Advisor because information was unavailable. */ public void setResourcesIgnored(Long resourcesIgnored) { this.resourcesIgnored = resourcesIgnored; } /** * <p> * The number of AWS resources ignored by Trusted Advisor because information was unavailable. * </p> * * @return The number of AWS resources ignored by Trusted Advisor because information was unavailable. */ public Long getResourcesIgnored() { return this.resourcesIgnored; } /** * <p> * The number of AWS resources ignored by Trusted Advisor because information was unavailable. * </p> * * @param resourcesIgnored * The number of AWS resources ignored by Trusted Advisor because information was unavailable. * @return Returns a reference to this object so that method calls can be chained together. */ public TrustedAdvisorResourcesSummary withResourcesIgnored(Long resourcesIgnored) { setResourcesIgnored(resourcesIgnored); return this; } /** * <p> * The number of AWS resources ignored by Trusted Advisor because they were marked as suppressed by the user. * </p> * * @param resourcesSuppressed * The number of AWS resources ignored by Trusted Advisor because they were marked as suppressed by the user. */ public void setResourcesSuppressed(Long resourcesSuppressed) { this.resourcesSuppressed = resourcesSuppressed; } /** * <p> * The number of AWS resources ignored by Trusted Advisor because they were marked as suppressed by the user. * </p> * * @return The number of AWS resources ignored by Trusted Advisor because they were marked as suppressed by the * user. */ public Long getResourcesSuppressed() { return this.resourcesSuppressed; } /** * <p> * The number of AWS resources ignored by Trusted Advisor because they were marked as suppressed by the user. * </p> * * @param resourcesSuppressed * The number of AWS resources ignored by Trusted Advisor because they were marked as suppressed by the user. * @return Returns a reference to this object so that method calls can be chained together. */ public TrustedAdvisorResourcesSummary withResourcesSuppressed(Long resourcesSuppressed) { setResourcesSuppressed(resourcesSuppressed); return this; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getResourcesProcessed() != null) sb.append("ResourcesProcessed: ").append(getResourcesProcessed()).append(","); if (getResourcesFlagged() != null) sb.append("ResourcesFlagged: ").append(getResourcesFlagged()).append(","); if (getResourcesIgnored() != null) sb.append("ResourcesIgnored: ").append(getResourcesIgnored()).append(","); if (getResourcesSuppressed() != null) sb.append("ResourcesSuppressed: ").append(getResourcesSuppressed()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof TrustedAdvisorResourcesSummary == false) return false; TrustedAdvisorResourcesSummary other = (TrustedAdvisorResourcesSummary) obj; if (other.getResourcesProcessed() == null ^ this.getResourcesProcessed() == null) return false; if (other.getResourcesProcessed() != null && other.getResourcesProcessed().equals(this.getResourcesProcessed()) == false) return false; if (other.getResourcesFlagged() == null ^ this.getResourcesFlagged() == null) return false; if (other.getResourcesFlagged() != null && other.getResourcesFlagged().equals(this.getResourcesFlagged()) == false) return false; if (other.getResourcesIgnored() == null ^ this.getResourcesIgnored() == null) return false; if (other.getResourcesIgnored() != null && other.getResourcesIgnored().equals(this.getResourcesIgnored()) == false) return false; if (other.getResourcesSuppressed() == null ^ this.getResourcesSuppressed() == null) return false; if (other.getResourcesSuppressed() != null && other.getResourcesSuppressed().equals(this.getResourcesSuppressed()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getResourcesProcessed() == null) ? 0 : getResourcesProcessed().hashCode()); hashCode = prime * hashCode + ((getResourcesFlagged() == null) ? 0 : getResourcesFlagged().hashCode()); hashCode = prime * hashCode + ((getResourcesIgnored() == null) ? 0 : getResourcesIgnored().hashCode()); hashCode = prime * hashCode + ((getResourcesSuppressed() == null) ? 0 : getResourcesSuppressed().hashCode()); return hashCode; } @Override public TrustedAdvisorResourcesSummary clone() { try { return (TrustedAdvisorResourcesSummary) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.support.model.transform.TrustedAdvisorResourcesSummaryMarshaller.getInstance().marshall(this, protocolMarshaller); } }
/* * Copyright (c) 2014-2017 Neil Ellis * * 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.sillelien.jas; import com.sillelien.jas.jproxy.JProxy; import com.sillelien.jas.jproxy.JProxyConfig; import com.sillelien.jas.jproxy.JProxyScriptEngine; import com.sillelien.jas.jproxy.JProxyScriptEngineFactory; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.script.Bindings; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.tools.Diagnostic; import javax.tools.JavaFileObject; import java.util.Collections; import java.util.List; public final class Demo { @NotNull private static final Logger log = LoggerFactory.getLogger("Demo"); public static void main(@NotNull String[] ignored) throws Exception { //Initializing and configuring the JSR-223 script engine JProxyConfig jpConfig = JProxy.createJProxyConfig(); jpConfig.setEnabled(true) .setRelProxyOnReloadListener((objOld, objNew, proxy, method, args) -> { //TODO }) // .setInputPath(".") .setScanPeriod(-1) .setClassFolder("./tmp/classes") .setCompilationOptions(Collections.emptyList()) .setJProxyDiagnosticsListener(diagnostics -> { List<Diagnostic<? extends JavaFileObject>> diagnosticList = diagnostics.getDiagnostics(); diagnosticList.stream() .filter(diagnostic -> diagnostic.getKind().equals(Diagnostic.Kind.ERROR)) .forEach(i->log.debug(i.toString())); }); JProxyScriptEngineFactory factory = JProxyScriptEngineFactory.create(); ScriptEngineManager manager = new ScriptEngineManager(); manager.registerEngineName("java", factory); Bindings bindings = manager.getBindings(); bindings.put("in", "World"); ScriptEngine engine = manager.getEngineByName("java"); JProxyScriptEngine scriptEngine = (JProxyScriptEngine) engine; scriptEngine.init(jpConfig); //Your code goes here, e.g. scriptEngine.eval("System.out.println(\"Hello \"+context.getAttribute(\"in\",javax.script.ScriptContext.ENGINE_SCOPE));return null;\n",bindings); } }
package com.epam.edu.htm.controler.mapper; import com.epam.edu.htm.controler.dto.ContactDto; import com.epam.edu.htm.model.Contact; import org.mapstruct.Mapper; import org.mapstruct.factory.Mappers; @Mapper public interface ContactMapper { ContactMapper INSTANCE = Mappers.getMapper(ContactMapper.class); ContactDto contactToDto(Contact contact); Contact dtotoContsct(ContactDto contactDto); }
/* * 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.geronimo.testsuite.v22.ui; import java.io.FileInputStream; import org.apache.geronimo.testsuite.common.selenium.EclipseSelenium; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swt.widgets.Shell; /** * Tutorial5MinuteTest * * @version $Rev$ $Date$ */ public class Tutorial5MinuteTest extends AbstractTestCase { @Override public boolean buildTestCase() { boolean success = createProjects (); if (success == true) { success = copyCode(); } return success; } @Override public boolean runTestCase() { boolean success = serverTasks.publishAllProjects(); if (success == true) { success = webTesting(); } return success; } @Override public boolean cleanupTestCase() { boolean success = serverTasks.removeAllProjects(); if (success == true) { success = projectTasks.deleteProject ("SampleWAR"); } if (success == true) { success = projectTasks.deleteProject ("SampleEJB"); } if (success == true) { success = projectTasks.deleteProject ("SampleEAR"); } return success; } public boolean createProjects() { boolean success = createEARProject (); if (success == true) { success = createEJBProject (); } if (success == true) { success = createWARProject (); } return success; } private boolean createEARProject() { boolean success = true; try { Shell wizardShell = abbotHelper.clickMenuItem (workbenchShell, new String[] {"&File", "&New\tAlt+Shift+N", "&Other..."}, "New"); abbotHelper.clickTreeItem (wizardShell, new String[] {"Java EE", "Enterprise Application Project"}); abbotHelper.clickButton (wizardShell, IDialogConstants.NEXT_LABEL); abbotHelper.setTextField(wizardShell, "", "SampleEAR"); abbotHelper.clickButton (wizardShell, IDialogConstants.NEXT_LABEL); abbotHelper.clickButton (wizardShell, "Generate Deployment Descriptor"); abbotHelper.clickButton (wizardShell, IDialogConstants.NEXT_LABEL); abbotHelper.setTextField(wizardShell, "default", "sampleear"); abbotHelper.setTextField(wizardShell, "", "sample-ear"); abbotHelper.setTextField(wizardShell, "car", "ear"); abbotHelper.clickButton (wizardShell, IDialogConstants.FINISH_LABEL); abbotHelper.waitForDialogDisposal (wizardShell); } catch (Exception e) { e.printStackTrace(); success = false; } return success; } private boolean createEJBProject() { boolean success = true; try { Shell wizardShell = abbotHelper.clickMenuItem (workbenchShell, new String[] {"&File", "&New\tAlt+Shift+N", "&Other..."}, "New"); abbotHelper.clickTreeItem (wizardShell, new String[] {"EJB", "EJB Project"}); abbotHelper.clickButton (wizardShell, IDialogConstants.NEXT_LABEL); abbotHelper.setTextField(wizardShell, "", "SampleEJB"); abbotHelper.clickButton (wizardShell, "Add &project to an EAR"); abbotHelper.clickButton (wizardShell, IDialogConstants.NEXT_LABEL); abbotHelper.clickButton (wizardShell, "Create an EJB Client JAR module to hold the client interfaces and classes."); abbotHelper.clickButton (wizardShell, IDialogConstants.NEXT_LABEL); abbotHelper.setTextField(wizardShell, "default", "sampleear"); abbotHelper.setTextField(wizardShell, "", "sample-ejb"); abbotHelper.setTextField(wizardShell, "car", "ejb"); abbotHelper.clickButton (wizardShell, IDialogConstants.FINISH_LABEL); abbotHelper.waitForDialogDisposal (wizardShell); abbotHelper.doubleClickItem(workbenchShell, "SampleEJB"); abbotHelper.doubleClickItem(workbenchShell, "ejbModule"); abbotHelper.doubleClickItem(workbenchShell, "META-INF"); Shell questionShell = abbotHelper.rightClickItem(workbenchShell, "openejb-jar.xml", new String[] {"&Delete"}, "Delete Resources"); abbotHelper.clickButton (questionShell, IDialogConstants.OK_LABEL); abbotHelper.waitForDialogDisposal (questionShell); } catch (Exception e) { e.printStackTrace(); success = false; } return success; } private boolean createWARProject() { boolean success = true; try { Shell wizardShell = abbotHelper.clickMenuItem (workbenchShell, new String[] {"&File", "&New\tAlt+Shift+N", "&Other..."}, "New"); abbotHelper.clickTreeItem (wizardShell, new String[] {"Web", "Dynamic Web Project"}); abbotHelper.clickButton (wizardShell, IDialogConstants.NEXT_LABEL); abbotHelper.setTextField(wizardShell, "", "SampleWAR"); abbotHelper.clickButton (wizardShell, "Add &project to an EAR"); abbotHelper.clickButton (wizardShell, IDialogConstants.NEXT_LABEL); abbotHelper.clickButton (wizardShell, IDialogConstants.NEXT_LABEL); abbotHelper.setTextField(wizardShell, "default", "sampleear"); abbotHelper.setTextField(wizardShell, "", "sample-war"); abbotHelper.setTextField(wizardShell, "car", "war"); abbotHelper.clickButton (wizardShell, IDialogConstants.FINISH_LABEL); abbotHelper.waitForDialogDisposal (wizardShell); } catch (Exception e) { e.printStackTrace(); success = false; } return success; } private boolean copyCode () { boolean success = true; try { abbotHelper.clickItem (workbenchShell, "SampleWAR"); Shell propShell = abbotHelper.clickMenuItem (workbenchShell, new String[] {"&Project", "&Properties"}, "Properties for SampleWAR"); abbotHelper.clickItem (propShell, "Java EE Module Dependencies"); abbotHelper.clickButton (propShell, "Select &All"); abbotHelper.clickButton (propShell, "&Apply"); abbotHelper.clickButton (propShell, IDialogConstants.OK_LABEL); IWorkspaceRoot aWSRoot = ResourcesPlugin.getWorkspace().getRoot(); IProject aProject = aWSRoot.getProject ("SampleEJB"); IFolder aFolder = aProject.getFolder("ejbModule/sampleear"); aFolder.create (false, true, null); String fileDir = aWSRoot.getLocation().toOSString() + "/src/main/resources/ui-tutorial"; IFile aFile = aProject.getFile("ejbModule/sampleear/RemoteBusinessInterface.java"); aFile.create(new FileInputStream (fileDir + "/RemoteBusinessInterface.java"), true, null); aFile = aProject.getFile("ejbModule/sampleear/MyStatelessSessionBean.java"); aFile.create(new FileInputStream (fileDir + "/MyStatelessSessionBean.java"), true, null); aProject = aWSRoot.getProject ("SampleWAR"); aFolder = aProject.getFolder("src/sampleear"); aFolder.create (false, true, null); aFile = aProject.getFile("WebContent/index.jsp"); aFile.create(new FileInputStream (fileDir + "/index.jsp"), true, null); // have to go through Servlet Creation dialog to make the web.xml correct Shell servletShell = abbotHelper.rightClickItem(workbenchShell, "SampleWAR", new String [] {"&New", "Servlet"}, "Create Servlet"); abbotHelper.setCursorText("MyServlet"); abbotHelper.setTextField(servletShell, "", "sampleear"); abbotHelper.clickButton (servletShell, IDialogConstants.NEXT_LABEL); abbotHelper.clickItem(servletShell, "/MyServlet"); Shell urlShell = abbotHelper.clickEnabledButton (servletShell, "Edit...", "URL Mappings"); abbotHelper.setTextField(urlShell, "/MyServlet", "/sayHello"); abbotHelper.clickButton (urlShell, IDialogConstants.OK_LABEL); abbotHelper.clickButton (servletShell, IDialogConstants.FINISH_LABEL); // copy over the correct contents aFile = aProject.getFile("src/sampleear/MyServlet.java"); aFile.setContents(new FileInputStream (fileDir + "/MyServlet.java"), true, true, null); // close the open file abbotHelper.clickMenuItem (workbenchShell, new String[] {"&File", "&Close"}); } catch (Exception e) { e.printStackTrace(); success = false; } return success; } private boolean webTesting () { boolean success = true; try { EclipseSelenium selenium = new EclipseSelenium(); selenium.start(); selenium.open ("http://localhost:8080/SampleWAR/"); selenium.type ("name", "Tom"); selenium.click ("submit"); selenium.waitForPageToLoad ("3000"); success = (selenium.getHtmlSource().indexOf ("says hello to") > 0); selenium.stop(); } catch (Exception e) { e.printStackTrace(); success = false; } return success; } }
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* * ResultMatrixSignificance.java * Copyright (C) 2005 University of Waikato, Hamilton, New Zealand * */ package weka.experiment; import weka.core.RevisionUtils; /** <!-- globalinfo-start --> * Only outputs the significance indicators. Can be used for spotting patterns. * <p/> <!-- globalinfo-end --> * <!-- options-start --> * Valid options are: <p/> * * <pre> -mean-prec &lt;int&gt; * The number of decimals after the decimal point for the mean. * (default: 2)</pre> * * <pre> -stddev-prec &lt;int&gt; * The number of decimals after the decimal point for the mean. * (default: 2)</pre> * * <pre> -col-name-width &lt;int&gt; * The maximum width for the column names (0 = optimal). * (default: 0)</pre> * * <pre> -row-name-width &lt;int&gt; * The maximum width for the row names (0 = optimal). * (default: 40)</pre> * * <pre> -mean-width &lt;int&gt; * The width of the mean (0 = optimal). * (default: 0)</pre> * * <pre> -stddev-width &lt;int&gt; * The width of the standard deviation (0 = optimal). * (default: 0)</pre> * * <pre> -sig-width &lt;int&gt; * The width of the significance indicator (0 = optimal). * (default: 0)</pre> * * <pre> -count-width &lt;int&gt; * The width of the counts (0 = optimal). * (default: 0)</pre> * * <pre> -show-stddev * Whether to display the standard deviation column. * (default: no)</pre> * * <pre> -show-avg * Whether to show the row with averages. * (default: no)</pre> * * <pre> -remove-filter * Whether to remove the classname package prefixes from the * filter names in datasets. * (default: no)</pre> * * <pre> -print-col-names * Whether to output column names or just numbers representing them. * (default: no)</pre> * * <pre> -print-row-names * Whether to output row names or just numbers representing them. * (default: no)</pre> * * <pre> -enum-col-names * Whether to enumerate the column names (prefixing them with * '(x)', with 'x' being the index). * (default: no)</pre> * * <pre> -enum-row-names * Whether to enumerate the row names (prefixing them with * '(x)', with 'x' being the index). * (default: no)</pre> * <!-- options-end --> * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision: 5346 $ */ public class ResultMatrixSignificance extends ResultMatrix { /** for serialization. */ private static final long serialVersionUID = -1280545644109764206L; /** * initializes the matrix as 1x1 matrix. */ public ResultMatrixSignificance() { this(1, 1); } /** * initializes the matrix with the given dimensions. * * @param cols the number of columns * @param rows the number of rows */ public ResultMatrixSignificance(int cols, int rows) { super(cols, rows); } /** * initializes the matrix with the values from the given matrix. * * @param matrix the matrix to get the values from */ public ResultMatrixSignificance(ResultMatrix matrix) { super(matrix); } /** * Returns a string describing the matrix. * * @return a description suitable for * displaying in the experimenter gui */ public String globalInfo() { return "Only outputs the significance indicators. Can be used for spotting patterns."; } /** * returns the name of the output format. * * @return the display name */ public String getDisplayName() { return "Significance only"; } /** * returns the default of whether column names or numbers instead are printed. * * @return true if names instead of numbers are printed */ public boolean getDefaultPrintColNames() { return false; } /** * returns the default width for the row names. * * @return the width */ public int getDefaultRowNameWidth() { return 40; } /** * returns the default of whether std deviations are displayed or not. * * @return true if the std deviations are displayed */ public boolean getDefaultShowStdDev() { return false; } /** * sets whether to display the std deviations or not - always false! * * @param show ignored */ public void setShowStdDev(boolean show) { // ignore } /** * returns the matrix as plain text. * * @return the matrix */ public String toStringMatrix() { StringBuffer result; String[][] cells; int i; int n; int nameWidth; String line; String colStr; int rows; result = new StringBuffer(); cells = toArray(); // pad names nameWidth = getColSize(cells, 0); for (i = 0; i < cells.length - 1; i++) cells[i][0] = padString(cells[i][0], nameWidth); // determine number of displayed rows rows = cells.length - 1; if (getShowAverage()) rows--; for (i = 0; i < rows; i++) { line = ""; colStr = ""; for (n = 0; n < cells[i].length; n++) { // the header of the column if (isMean(n) || isRowName(n)) colStr = cells[0][n]; if ( (n > 1) && (!isSignificance(n)) ) continue; // padding between cols if (n > 0) line += " "; // padding for "(" below dataset line if ( (i > 0) && (n > 1) ) line += " "; if (i == 0) { line += colStr; } else { if (n == 0) { line += cells[i][n]; } else if (n == 1) { line += colStr.replaceAll(".", " "); // base column has no significance! } else { line += cells[i][n]; // add blanks dep. on length of # line += colStr.replaceAll(".", " ").substring(2); } } } result.append(line + "\n"); // separator line if (i == 0) result.append(line.replaceAll(".", "-") + "\n"); } return result.toString(); } /** * returns the header of the matrix as a string. * * @return the header * @see #m_HeaderKeys * @see #m_HeaderValues */ public String toStringHeader() { return new ResultMatrixPlainText(this).toStringHeader(); } /** * returns returns a key for all the col names, for better readability if * the names got cut off. * * @return the key */ public String toStringKey() { return new ResultMatrixPlainText(this).toStringKey(); } /** * returns the summary as string. * * @return the summary */ public String toStringSummary() { return new ResultMatrixPlainText(this).toStringSummary(); } /** * returns the ranking in a string representation. * * @return the ranking */ public String toStringRanking() { return new ResultMatrixPlainText(this).toStringRanking(); } /** * Returns the revision string. * * @return the revision */ public String getRevision() { return RevisionUtils.extract("$Revision: 5346 $"); } /** * for testing only. * * @param args ignored */ public static void main(String[] args) { ResultMatrix matrix; int i; int n; matrix = new ResultMatrixSignificance(3, 3); // set header matrix.addHeader("header1", "value1"); matrix.addHeader("header2", "value2"); matrix.addHeader("header2", "value3"); // set values for (i = 0; i < matrix.getRowCount(); i++) { for (n = 0; n < matrix.getColCount(); n++) { matrix.setMean(n, i, (i+1)*n); matrix.setStdDev(n, i, ((double) (i+1)*n) / 100); if (i == n) { if (i % 2 == 1) matrix.setSignificance(n, i, SIGNIFICANCE_WIN); else matrix.setSignificance(n, i, SIGNIFICANCE_LOSS); } } } System.out.println("\n\n--> " + matrix.getDisplayName()); System.out.println("\n1. complete\n"); System.out.println(matrix.toStringHeader() + "\n"); System.out.println(matrix.toStringMatrix() + "\n"); System.out.println(matrix.toStringKey()); System.out.println("\n2. complete with std deviations\n"); matrix.setShowStdDev(true); System.out.println(matrix.toStringMatrix()); System.out.println("\n3. cols numbered\n"); matrix.setPrintColNames(false); System.out.println(matrix.toStringMatrix()); System.out.println("\n4. second col missing\n"); matrix.setColHidden(1, true); System.out.println(matrix.toStringMatrix()); System.out.println("\n5. last row missing, rows numbered too\n"); matrix.setRowHidden(2, true); matrix.setPrintRowNames(false); System.out.println(matrix.toStringMatrix()); System.out.println("\n6. mean prec to 3\n"); matrix.setMeanPrec(3); matrix.setPrintRowNames(false); System.out.println(matrix.toStringMatrix()); } }
/* * 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.cache; import java.util.Collection; import org.apache.ignite.cluster.ClusterState; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.failure.StopNodeOrHaltFailureHandler; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; /** * */ public class ClusterReadOnlyModeAbstractTest extends GridCommonAbstractTest { /** */ private static final int SRVS = 3; /** Cache names. */ protected static final Collection<String> CACHE_NAMES = ClusterReadOnlyModeTestUtils.cacheNames(); /** {@inheritDoc} */ @Override protected void beforeTestsStarted() throws Exception { super.beforeTestsStarted(); startGridsMultiThreaded(SRVS); } /** {@inheritDoc} */ @Override protected void afterTest() throws Exception { super.afterTest(); changeClusterReadOnlyMode(false); for (String cacheName : CACHE_NAMES) grid(0).cache(cacheName).removeAll(); } /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName); cfg.setCacheConfiguration(ClusterReadOnlyModeTestUtils.cacheConfigurations()); cfg.setFailureHandler(new StopNodeOrHaltFailureHandler()); return cfg; } /** * Change read only mode on all nodes. * * @param readOnly Read only. */ protected void changeClusterReadOnlyMode(boolean readOnly) { grid(0).cluster().state(readOnly ? ClusterState.ACTIVE_READ_ONLY : ClusterState.ACTIVE); } }
package com.wechat.handler; import me.chanjar.weixin.common.api.WxConsts; import me.chanjar.weixin.common.session.WxSessionManager; import me.chanjar.weixin.mp.api.WxMpService; import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage; import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage; import org.springframework.stereotype.Component; import com.wechat.builder.TextBuilder; import java.util.Map; /** * @author Binary Wang(https://github.com/binarywang) */ @Component public class LocationHandler extends AbstractHandler { @Override public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) { if (wxMessage.getMsgType().equals(WxConsts.XML_MSG_LOCATION)) { //TODO 接收处理用户发送的地理位置消息 try { String content = "感谢反馈,您的的地理位置已收到!"; return new TextBuilder().build(content, wxMessage, null); } catch (Exception e) { this.logger.error("位置消息接收处理失败", e); return null; } } //上报地理位置事件 this.logger.info("\n上报地理位置 。。。 "); this.logger.info("\n纬度 : " + wxMessage.getLatitude()); this.logger.info("\n经度 : " + wxMessage.getLongitude()); this.logger.info("\n精度 : " + String.valueOf(wxMessage.getPrecision())); //TODO 可以将用户地理位置信息保存到本地数据库,以便以后使用 return null; } }
package com.brandon3055.draconicevolution.common.tileentities.energynet; import cofh.api.energy.IEnergyReceiver; import com.brandon3055.draconicevolution.DraconicEvolution; import com.brandon3055.draconicevolution.client.render.particle.ParticleEnergyField; import com.brandon3055.draconicevolution.client.render.particle.Particles; import com.brandon3055.draconicevolution.common.items.tools.Wrench; import com.brandon3055.draconicevolution.common.lib.References; import com.brandon3055.brandonscore.common.utills.Utills; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ChatComponentText; import net.minecraft.util.ChatComponentTranslation; import net.minecraftforge.common.util.ForgeDirection; import java.util.ArrayList; import java.util.List; /** * Created by Brandon on 10/02/2015. */ public class TileWirelessEnergyTransceiver extends TileRemoteEnergyBase { @SideOnly(Side.CLIENT) private ParticleEnergyField ring; public List<LinkedReceiver> receiverList = new ArrayList<LinkedReceiver>(); public TileWirelessEnergyTransceiver() { } public TileWirelessEnergyTransceiver(int powerTier) { this.powerTier = powerTier; this.updateStorage(); } @Override public int getCap() { return 50000 + (powerTier * 4500000); } @Override public int getRec() { return 50000 + (powerTier * 4500000); } @Override public int getExt() { return 50000 + (powerTier * 4500000); } @Override public void updateEntity() { super.updateEntity(); if (worldObj.isRemote) { ring = DraconicEvolution.proxy.energyField(worldObj, xCoord + 0.5, yCoord + 0.5, zCoord + 0.5, 2, powerTier == 1, ring, inView > 0); for (LinkedReceiver receiver : receiverList) { int particleValue = 200; if (receiver.particleEnergyCounter > particleValue) { receiver.particleEnergyCounter -= particleValue; //todo detect box size DraconicEvolution.proxy.spawnParticle(new Particles.TransceiverParticle(worldObj, xCoord + 0.5, yCoord + 0.3 + (worldObj.rand.nextDouble() * 0.4), zCoord + 0.5, receiver.xCoord + worldObj.rand.nextDouble(), receiver.yCoord + worldObj.rand.nextDouble(), receiver.zCoord + worldObj.rand.nextDouble()), 64); } } } else { for (LinkedReceiver receiver : receiverList) { if (!receiver.isStillValid(worldObj) && worldObj.getChunkFromBlockCoords(receiver.xCoord, receiver.zCoord).isChunkLoaded) { receiverList.remove(receiver); worldObj.markBlockForUpdate(xCoord, yCoord, zCoord); break; } int sent = receiver.receiveEnergy(worldObj, storage.extractEnergy(receiver.receiveEnergy(worldObj, powerTier == 0 ? 5000 : 50000, true), false), false); sent = (sent / 20); if (sent > Short.MAX_VALUE) sent = Short.MAX_VALUE; if (sent > 0) sendObjectToClient(References.SHORT_ID, 10 + receiverList.indexOf(receiver), (short) sent); } } } @SideOnly(Side.CLIENT) @Override public void receiveObjectFromServer(int index, Object object) { super.receiveObjectFromServer(index, object); if (index >= 10) { if (receiverList.size() > index - 10 && receiverList.get(index - 10).particleEnergyCounter < 10000) receiverList.get(index - 10).particleEnergyCounter += (Short) object; } } public void linkDevice(int x, int y, int z, int side, EntityPlayer player, String mode) { TileEntity target = worldObj.getTileEntity(x, y, z); if (!(target instanceof IEnergyReceiver)) { player.addChatComponentMessage(new ChatComponentText("Unknown Error occurred [Invalid Tile]")); return; } IEnergyReceiver receiver = (IEnergyReceiver) target; if (!receiver.canConnectEnergy(ForgeDirection.getOrientation(side))) { player.addChatComponentMessage(new ChatComponentTranslation("msg.de.wrongSide.txt")); return; } if (receiverList.size() >= getmaxWirelessConnections()) { player.addChatComponentMessage(new ChatComponentTranslation("msg.de.maxConnections.txt")); return; } if (Utills.getDistanceAtoB(xCoord, yCoord, zCoord, x, y, z) > (powerTier == 0 ? 15 : 30)) { player.addChatComponentMessage(new ChatComponentTranslation("msg.de.outOfRange.txt")); return; } if (mode.equals(Wrench.BIND_MODE)) { LinkedReceiver r = new LinkedReceiver(x, y, z, side); for (LinkedReceiver r2 : receiverList) { if (r.xCoord == r2.xCoord && r.yCoord == r2.yCoord && r.zCoord == r2.zCoord && r.connectionSide == r2.connectionSide) { player.addChatComponentMessage(new ChatComponentTranslation("msg.de.linked.txt")); return; } } receiverList.add(r); player.addChatComponentMessage(new ChatComponentTranslation("msg.de.linked.txt")); worldObj.markBlockForUpdate(xCoord, yCoord, zCoord); } else if (mode.equals(Wrench.UNBIND_MODE)) { for (LinkedReceiver r2 : receiverList) { if (x == r2.xCoord && y == r2.yCoord && z == r2.zCoord && side == r2.connectionSide) { player.addChatComponentMessage(new ChatComponentTranslation("msg.de.unLinked.txt")); receiverList.remove(r2); worldObj.markBlockForUpdate(xCoord, yCoord, zCoord); return; } } } } @Override public void writeToNBT(NBTTagCompound compound) { super.writeToNBT(compound); compound.setInteger("Receiver_Count", receiverList.size()); for (int i = 0; i < receiverList.size(); i++) receiverList.get(i).writeToNBT(compound, String.valueOf(i)); } @Override public void readFromNBT(NBTTagCompound compound) { super.readFromNBT(compound); int count = compound.getInteger("Receiver_Count"); receiverList.clear(); for (int i = 0; i < count; i++) { LinkedReceiver r = new LinkedReceiver(); r.readFromNBT(compound, String.valueOf(i)); receiverList.add(r); } } // @Override // public double getCapacity() { // return ((double) getEnergyStored(ForgeDirection.UNKNOWN) / (double) getMaxEnergyStored(ForgeDirection.UNKNOWN)) * 100D; // } /** * Calculates the energy flow based on the local buffer * and the remote buffer * return double between 0 to 100 */ public double getFlow(double localCap, double remoteCap) { return Math.max(0, Math.min(100, (localCap - remoteCap) * 100D/*Flow Multiplier*/)); } @Override public double getBeamX() { return xCoord + 0.5D; } @Override public double getBeamY() { return yCoord + 0.5D; } @Override public double getBeamZ() { return zCoord + 0.5D; } @Override public int getMaxConnections() { return powerTier == 0 ? 3 : 6; } public int getmaxWirelessConnections() { return powerTier == 0 ? 8 : 16; } }
package org.robovm.bindings.playservices; import java.util.ArrayList; import org.robovm.apple.foundation.NSArray; import org.robovm.apple.foundation.NSData; import org.robovm.apple.foundation.NSError; import org.robovm.apple.foundation.NSNumber; import org.robovm.apple.foundation.NSObject; import org.robovm.apple.foundation.NSString; import org.robovm.apple.foundation.NSURL; import org.robovm.apple.uikit.UIViewController; import org.robovm.bindings.gpgs.GPGAchievement; import org.robovm.bindings.gpgs.GPGAchievementAllMetadataBlock; import org.robovm.bindings.gpgs.GPGAchievementController; import org.robovm.bindings.gpgs.GPGAchievementControllerDelegate; import org.robovm.bindings.gpgs.GPGAchievementDidIncrementBlock; import org.robovm.bindings.gpgs.GPGAchievementDidRevealBlock; import org.robovm.bindings.gpgs.GPGAchievementDidUnlockBlock; import org.robovm.bindings.gpgs.GPGAchievementMetadata; import org.robovm.bindings.gpgs.GPGAchievementState; import org.robovm.bindings.gpgs.GPGAppStateConflictHandler; import org.robovm.bindings.gpgs.GPGAppStateLoadResultHandler; import org.robovm.bindings.gpgs.GPGAppStateModel; import org.robovm.bindings.gpgs.GPGAppStateWriteResultHandler; import org.robovm.bindings.gpgs.GPGAppStateWriteStatus; import org.robovm.bindings.gpgs.GPGLeaderboard; import org.robovm.bindings.gpgs.GPGLeaderboardAllMetadataBlock; import org.robovm.bindings.gpgs.GPGLeaderboardController; import org.robovm.bindings.gpgs.GPGLeaderboardControllerDelegate; import org.robovm.bindings.gpgs.GPGLeaderboardLoadScoresBlock; import org.robovm.bindings.gpgs.GPGLeaderboardMetadata; import org.robovm.bindings.gpgs.GPGLeaderboardTimeScope; import org.robovm.bindings.gpgs.GPGLeaderboardsController; import org.robovm.bindings.gpgs.GPGLeaderboardsControllerDelegate; import org.robovm.bindings.gpgs.GPGManager; import org.robovm.bindings.gpgs.GPGReAuthenticationBlock; import org.robovm.bindings.gpgs.GPGScore; import org.robovm.bindings.gpgs.GPGScoreReport; import org.robovm.bindings.gpgs.GPGScoreReportScoreBlock; import org.robovm.bindings.gpgs.GPGToastPlacement; import org.robovm.bindings.gpp.GPPShare; import org.robovm.bindings.gpp.GPPSignIn; import org.robovm.bindings.gpp.GPPSignInDelegate; import org.robovm.bindings.gt.GTMOAuth2Authentication; import org.robovm.objc.ObjCClass; /** Manager that handles the most common usage of Google Play Game Services. * @author Michael Hadash */ public class PlayServicesManager extends NSObject implements GPPSignInDelegate, GPGAchievementControllerDelegate, GPGLeaderboardControllerDelegate, GPGLeaderboardsControllerDelegate { public static final int TOAST_WELCOME = 0; public static final int TOAST_ACHIEVEMENTS = 1; public static final int TOAST_BOTH = 2; public static final int DATA_NAME = 0; public static final int DATA_AVATAR = 1; public static final int DATA_ID = 2; // identifiers private String clientId; // view controller private UIViewController viewController; // blocks private GPGReAuthenticationBlock gamesAuthBlock; private GPGAchievementDidRevealBlock revealBlock; private GPGAchievementDidIncrementBlock incrementBlock; private GPGAchievementDidUnlockBlock unlockBlock; private GPGAppStateWriteResultHandler cloudCompletionHandler; private GPGScoreReportScoreBlock postScoreCompletionHandler; // options private boolean fetchName = false; private boolean fetchEmail = false; private final boolean fetchId = true; // used to fix a RoboVM bug with NSArray static { ObjCClass.getByType(GPGAchievementMetadata.class); ObjCClass.getByType(GPGLeaderboardMetadata.class); ObjCClass.getByType(GPGScore.class); } /** interface to get a callback when the login finished. */ public interface LoginCallback { public void success (); public void error (NSError error); }; /** interface to get a callback when the scores have loaded. */ public interface ScoresLoaded { public void invoke (ArrayList<GPGScore> scores); }; private final GPGLeaderboardLoadScoresBlock loadScoresBlock = new GPGLeaderboardLoadScoresBlock() { @Override public void invoke (NSArray<GPGScore> scores, NSError error) { if (error != null) { System.out.println("[Error] PlayServicesManager: An error occured while loading the scores: " + error.description()); return; } // convert to an ArrayList ArrayList<GPGScore> list = new ArrayList<GPGScore>(); for (int i = 0; i < scores.size(); i++) { list.add(scores.get(i)); } // invoke the callback scoresLoaded.invoke(list); } }; private LoginCallback loginCallback; private ScoresLoaded scoresLoaded; /** Call this in your app's didFinishLaunching() method. You must specify your clientID and, if you need user data, what data to * load during login before calling this. */ public void didFinishLaunching () { GPPSignIn signIn = GPPSignIn.sharedInstance(); signIn.setClientID(clientId); // set scopes ArrayList<NSString> scopes = new ArrayList<NSString>(); scopes.add(new NSString("https://www.googleapis.com/auth/plus.login")); scopes.add(new NSString("https://www.googleapis.com/auth/games")); scopes.add(new NSString("https://www.googleapis.com/auth/appstate")); signIn.setScopes(new NSArray<NSString>(scopes)); signIn.setDelegate(this); signIn.setShouldFetchGoogleUserID(fetchId); signIn.setShouldFetchGoogleUserEmail(fetchEmail); signIn.setShouldFetchGooglePlusUser(fetchName); // try to sign in silently signIn.trySilentAuthentication(); // define blocks revealBlock = new GPGAchievementDidRevealBlock() { @Override public void invoke (GPGAchievementState state, NSError error) { if (error != null) { System.out.println("Error while revealing achievement!"); } } }; incrementBlock = new GPGAchievementDidIncrementBlock() { @Override public void invoke (boolean newlyUnlocked, int currentSteps, NSError error) { if (error != null) { System.out.println("Error while revealing!"); } } }; unlockBlock = new GPGAchievementDidUnlockBlock() { @Override public void invoke (boolean newlyUnlocked, NSError error) { if (error != null) { System.out.println("Error while unlocking!"); } } }; cloudCompletionHandler = new GPGAppStateWriteResultHandler() { @Override public void invoke (GPGAppStateWriteStatus status, NSError error) { switch (status) { case GPGAppStateWriteStatusSuccess: System.out.println("cloud save succeeded!"); break; case GPGAppStateWriteStatusBadKeyDataOrVersion: System.out.println("cloud save failed: bad key or version"); break; case GPGAppStateWriteStatusConflict: System.out.println("cloud save failed: conflict"); break; case GPGAppStateWriteStatusKeysQuotaExceeded: System.out.println("cloud save failed: keys quota exceeded"); break; case GPGAppStateWriteStatusNotFound: System.out.println("cloud save failed: not found"); break; case GPGAppStateWriteStatusSizeExceeded: System.out.println("cloud save failed: size exceeded"); break; case GPGAppStateWriteStatusUnknownError: System.out.println("cloud save failed: unknown error"); break; } } }; postScoreCompletionHandler = new GPGScoreReportScoreBlock() { @Override public void invoke (GPGScoreReport report, NSError error) { if (error != null) { System.out.println("score posting failed!"); } } }; } @Override public void finishedWithAuth (GTMOAuth2Authentication auth, NSError error) { if (error == null) { // after the google+ sign-in is done, we must continue the sign-in of 'games'. startGoogleGamesSignIn(); // invoke the callback if it is set. if (loginCallback != null) { loginCallback.success(); } } else { // invoke the callback if it is set. if (loginCallback != null) { loginCallback.error(error); } System.out.println("error during login: " + error.description()); } } /** Continues the sign-in process. */ private void startGoogleGamesSignIn () { final GPPSignIn s = GPPSignIn.sharedInstance(); GPGManager m = GPGManager.sharedInstance(); gamesAuthBlock = new GPGReAuthenticationBlock() { @Override public void invoke (boolean requiresKeychainWipe, NSError error) { // If you hit this, auth has failed and you need to authenticate. // Most likely you can refresh behind the scenes if (requiresKeychainWipe) { s.signOut(); } s.authenticate(); } }; // pass the GPPSignIn to the GPGManager. m.signIn(s, gamesAuthBlock); } /** Do not use this. This could not be a private member, but do as if it doesn't exists. */ @Override public void achievementViewControllerDidFinish (GPGAchievementController viewController) { viewController.dismissViewController(true, null); } /** Do not use this. This could not be a private member, but do as if it doesn't exists. */ @Override public void leaderboardViewControllerDidFinish (GPGLeaderboardController viewController) { viewController.dismissViewController(true, null); } /** Do not use this. This could not be a private member, but do as if it doesn't exists. */ @Override public void leaderboardsViewControllerDidFinish (GPGLeaderboardsController viewController) { viewController.dismissViewController(true, null); } /** Logs you in into Google Play Game Services using the 'games' and 'appstate' scopes. Only call this when the user pressed a * designated login button. */ public void login () { GPPSignIn.sharedInstance().authenticate(); } /** Sets a callback that will be invoked when the user is logged in successfully. * @param callback the callback. */ public void setLoginCallback (LoginCallback callback) { loginCallback = callback; } /** Logs you in into Google Play Game Services using the 'games' and 'appstate' scopes. Only call this when the user pressed a * designated login button. */ public void login (LoginCallback callback) { loginCallback = callback; GPPSignIn.sharedInstance().authenticate(); } /** Signs the user out of the services. */ public void logout () { if (isLoggedIn()) { GPPSignIn.sharedInstance().signOut(); GPGManager.sharedInstance().signOut(); } } /** @return whether the user is logged in. */ public boolean isLoggedIn () { if (GPGManager.sharedInstance() == null) { return false; } else { return GPGManager.sharedInstance().hasAuthorizer(); } } /** Call this to pass your client identifier. * @param clientId the identifier. You can find the identifier in the Google Play Developers Console. */ public void setClientId (String clientId) { this.clientId = clientId; } /** Changes the location where toast messages are displayed. * @param toastType the type of toast of which you would like to change the location. Choose from the manager's static fields. * @param placement the placement that you want for the toasts. */ public void setToastLocation (int toastType, GPGToastPlacement placement) { switch (toastType) { case TOAST_ACHIEVEMENTS: GPGManager.sharedInstance().setAchievementUnlockedToastPlacement(placement); break; case TOAST_WELCOME: GPGManager.sharedInstance().setWelcomeBackToastPlacement(placement); break; case TOAST_BOTH: GPGManager.sharedInstance().setAchievementUnlockedToastPlacement(placement); GPGManager.sharedInstance().setWelcomeBackToastPlacement(placement); break; } } /** Select the data that you would like to receive from google about the user. * @param name the full name. * @param email the email address. */ public void setUserDataToRetrieve (boolean name, boolean email) { fetchName = name; fetchEmail = email; } /** Let the manager know of your root view controller. */ public void setViewController (UIViewController viewController) { this.viewController = viewController; } /** Pops the achievements view controller. This displays all the achievements and the user's progress. */ public void showAchievements () { GPGAchievementController achController = new GPGAchievementController(); achController.setAchievementDelegate(this); viewController.presentViewController(achController, true, null); } /** @return an ArrayList containing all data about your achievements and your user's progress. */ public ArrayList<GPGAchievementMetadata> getAchievementsList () { final ArrayList<GPGAchievementMetadata> list = new ArrayList<GPGAchievementMetadata>(); GPGAchievementMetadata.allMetadata(new GPGAchievementAllMetadataBlock() { @Override public void invoke(NSArray metadata, NSError error) { if (error == null){ // Something went wrong. } else { // obtain the data and put it in a list NSArray<GPGAchievementMetadata> dat = metadata; for (int i = 0; i < dat.size(); i++) { GPGAchievementMetadata n = dat.get(i); if (n != null) { list.add(n); } else { System.out.println("[Warning] PlayServicesManager: One of your achievements could not be listed."); } } } } }); // return the list return list; } /** Reveals a hidden achievement. * @param identifier the achievement identifier. */ public void revealAchievement (String identifier) { GPGAchievement a = GPGAchievement.getAchievementWithId(identifier); a.revealAchievementWithCompletionHandler(revealBlock); } /** Reveals a hidden achievement. * @param identifier the achievement identifier. * @param block a block that is invoked when the reveal process ends. Used to check whether it succeeded. Note: make the block * an instance member to be sure it is not garbage collected. */ public void revealAchievement (String identifier, GPGAchievementDidRevealBlock block) { GPGAchievement a = GPGAchievement.getAchievementWithId(identifier); a.revealAchievementWithCompletionHandler(block); } /** Increments an achievement. * @param identifier the achievement identifier. * @param steps number of steps to increment. */ public void incrementAchievement (String identifier, int steps) { GPGAchievement a = GPGAchievement.getAchievementWithId(identifier); a.incrementAchievementNumSteps(steps, incrementBlock); } /** Increments an achievement. * @param identifier the achievement identifier. * @param steps number of steps to increment. * @param block a block that is invoked when the increment process ends. Used to check whether it succeeded. Note: make the * block an instance member to be sure it is not garbage collected. */ public void incrementAchievement (String identifier, int steps, GPGAchievementDidIncrementBlock block) { GPGAchievement a = GPGAchievement.getAchievementWithId(identifier); a.incrementAchievementNumSteps(steps, block); } /** Unlocks an achievement. * @param identifier the achievement identifier. */ public void unlockAchievement (String identifier) { GPGAchievement a = GPGAchievement.getAchievementWithId(identifier); a.unlockAchievementWithCompletionHandler(unlockBlock); } /** Unlocks an achievement. * @param identifier the achievement identifier. * @param block a block that is invoked when the unlock process ends. Used to check whether it succeeded. Note: make the block * an instance member to be sure it is not garbage collected. */ public void unlockAchievement (String identifier, GPGAchievementDidUnlockBlock block) { GPGAchievement a = GPGAchievement.getAchievementWithId(identifier); a.unlockAchievementWithCompletionHandler(block); } /** Posts data (savegame) to google. * @param stateKey your state slot. Can be: 0, 1, 2, 3. * @param data the data that you wish to store. It has a maximum size, which can be found in google's documentation. * @param conflictHandler handler that defines what to do when a conflict occured. It is very important for the user experience * to implement this correctly. */ public void cloudSave (int stateKey, NSData data, GPGAppStateConflictHandler conflictHandler) { // get the model GPGAppStateModel model = GPGManager.sharedInstance().getApplicationModel().getAppState(); // add the data model.setStateData(data, NSNumber.valueOf(stateKey)); // post the data model.update(NSNumber.valueOf(stateKey), cloudCompletionHandler, conflictHandler); } /** Posts data (savegame) to google. * @param stateKey your state slot. Can be: 0, 1, 2, 3. * @param data the data that you wish to store. It has a maximum size, which can be found in google's documentation. * @param conflictHandler handler that defines what to do when a conflict occured. It is very important for the user experience * to implement this correctly. * @param resultHandler handler that is invoked to inform you whether it succeeded or not. */ public void cloudSave (int stateKey, NSData data, GPGAppStateConflictHandler conflictHandler, GPGAppStateWriteResultHandler resultHandler) { // get the model GPGAppStateModel model = GPGManager.sharedInstance().getApplicationModel().getAppState(); // add the data model.setStateData(data, NSNumber.valueOf(stateKey)); // post the data model.update(NSNumber.valueOf(stateKey), resultHandler, conflictHandler); } /** Loads data (savegame) from google. * @param stateKey your state slot. Can be: 0, 1, 2, 3. * @param conflictHandler handler that defines what to do when a conflict occured. It is very important for the user experience * to implement this correctly. * @param resultHandler handler that is invoked to inform you whether it is succeeded or not. If it succeeded, the handler will * also contain the data that you requested. */ public void cloudLoad (int stateKey, GPGAppStateConflictHandler conflictHandler, GPGAppStateLoadResultHandler resultHandler) { // get the model final GPGAppStateModel model = GPGManager.sharedInstance().getApplicationModel().getAppState(); // start the load request model.load(NSNumber.valueOf(stateKey), resultHandler, conflictHandler); } /** Clears data at google. * @param stateKey your state slot. Can be: 0, 1, 2, 3. * @param conflictHandler handler that defines what to do when a conflict occured. It is very important for the user experience * to implement this correctly. * @param resultHandler handler that is invoked to inform you whether it is succeeded or not. If it succeeded, the handler will * also contain the data that you requested. */ public void cloudClear (int stateKey, GPGAppStateConflictHandler conflictHandler, GPGAppStateWriteResultHandler resultHandler) { // get the model final GPGAppStateModel model = GPGManager.sharedInstance().getApplicationModel().getAppState(); // clear the state model.clear(NSNumber.valueOf(stateKey), resultHandler, conflictHandler); } /** Call to display a specific leaderboard. * @param identifier the leaderboard identifier. */ public void showLeaderboard (String identifier) { showLeaderboard(identifier, GPGLeaderboardTimeScope.GPGLeaderboardTimeScopeAllTime); } /** Call to display a specific leaderboard. * @param identifier the leaderboard identifier. * @param timeScope the default time scope to display. */ public void showLeaderboard (String identifier, GPGLeaderboardTimeScope timeScope) { // create the view controller GPGLeaderboardController leadController = new GPGLeaderboardController(identifier); leadController.setLeaderboardDelegate(this); // you can choose the default time scope to display in the view controller. leadController.setTimeScope(timeScope); // present the leaderboard view controller viewController.presentViewController(leadController, true, null); } /** Displays a list of all leaderboards. The user can then select a leaderboard to display any leaderboard they want from your * app. */ public void showLeaderboardsPicker () { // create the view controller GPGLeaderboardsController leadsController = new GPGLeaderboardsController(); leadsController.setLeaderboardsDelegate(this); // present the leaderboard picker view controller viewController.presentViewController(leadsController, true, null); } /** Posts a score to a leaderboard. * @param leaderboardId the identifier of the leaderboard. * @param score the score. */ public void postScore (String leaderboardId, long score) { postScore(leaderboardId, score, postScoreCompletionHandler); } /** Posts a score to a leaderboard. * @param leaderboardId the identifier of the leaderboard. * @param score the score. * @param block a block that is invoked when the posting is completed. It contains data about whether it succeeded and whether * it is a highscore or not (and in which time scopes). It will also contain the actual high score if the posted * score is not the highscore in the particular time scope. */ public void postScore (String leaderboardId, long score, GPGScoreReportScoreBlock block) { // create the score instance GPGScore gpgScore = new GPGScore(leaderboardId); gpgScore.setValue(score); // post the score gpgScore.submitScoreWithCompletionHandler(block); } /** @return an ArrayList containing all data about your leaderboards. */ public ArrayList<GPGLeaderboardMetadata> getLeaderboardsList () { // obtain the data and put it in a list final ArrayList<GPGLeaderboardMetadata> list = new ArrayList<GPGLeaderboardMetadata>(); GPGLeaderboardMetadata.allMetadataWithCompletionHandler(new GPGLeaderboardAllMetadataBlock() { @Override public void invoke(NSArray metadata, NSError error) { NSArray<GPGLeaderboardMetadata> dat = metadata; for (int i = 0; i < dat.size(); i++) { GPGLeaderboardMetadata n = dat.get(i); if (n != null) { list.add(n); } else { System.out.println("[Warning] PlayServicesManager: One of your leaderboards could not be listed."); } } } }); // return the list return list; } /** Loads the scores of a leaderboard. * @param leaderboardId the leaderboard identifier. * @param social whether you want social or global scores. * @param timeScope the time scopes where you want the scores for. * @param callback the completion handler. This is invoked when the scores are received. */ public void getScoresOfLeaderboard (String leaderboardId, boolean social, GPGLeaderboardTimeScope timeScope, ScoresLoaded callback) { // set the callback scoresLoaded = callback; // create the leaderboard class GPGLeaderboard b = GPGLeaderboard.getLeaderboardWithId(leaderboardId); // set options b.setSocial(social); b.setTimeScope(timeScope); // load the scores b.loadScoresWithCompletionHandler(loadScoresBlock); } // share dialog /** the most basic way to open the share dialog */ public void gppShare_openBasicShareDialog () { GPPShare.sharedInstance().shareDialog().open(); } /** Sets the URL resource to be shared. and opens the dialog * * @param the url the user will be directed to when clicking through */ public void gppShare_setURLToShareAndOpen (String urlToShare) { GPPShare.sharedInstance().shareDialog().setURLToShare(new NSURL(urlToShare)).open(); } /** Sets the text to prefill user's comment in the share dialog. and opens the dialog * * @param the prefilled coment that wil be displayd on the google plus wall */ public void gppShare_setPrefillTextAndOpen (String prefillText) { GPPShare.sharedInstance().shareDialog().setPrefillText(new NSString(prefillText)).open(); } /** Sets the title, description, and thumbnail URL of the shared content preview in the share dialog. Only set these fields if * you are sharing with a content deep link and don't have a URL resource. |title| is required. * @param title * @param description * @param thumbnailURL */ public void gppShare_setTitleAndOpen (String title, String description, String thumbnailURL) { GPPShare.sharedInstance().shareDialog().setTitle(new NSString(title), new NSString(description), new NSURL(thumbnailURL)) .open(); } /** Sets the content deep-link ID that takes the user straight to your shared content. Only set this field if you want the * content deep-linking feature. The content deep-link ID can either be a fully qualified URI, or URI path, which can be up to * 512 characters in length. * @param title * @param description * @param thumbnailURL * @param contentDeepLinkID */ public void gppShare_setTitleDeepLinkAndOpen (String title, String description, String thumbnailURL, String contentDeepLinkID) { GPPShare.sharedInstance().shareDialog().setTitle(new NSString(title), new NSString(description), new NSURL(thumbnailURL)) .setContentDeepLinkID(new NSString(contentDeepLinkID)).open(); } /** Sets the call-to-action button of the shared content preview. The call-to-action button consists of a label, URL, and * deep-link ID. The |label| is a string key defined under "data-calltoactionlabel" on * http://developers.google.com/+/web/share/interactive#button_attr_calltoactionlabel that maps to the actual button text. The * |url| is where the user is taken to after tapping on the button. The optional |deepLinkID| is the call-to-action deep-link * ID that takes the user straight to a specific action in your app. It can either be a fully qualified URI, or URI path, which * can be up to 512 characters in length. Note: In order to set the call-to-action button: User must have been authenticated * with scopes including "https://www.googleapis.com/auth/plus.login". * @param label * @param urlToShare * @param contentDeepLinkID */ public void gppShare_setCallToActionButtonWithLabel (String label, String urlToShare, String contentDeepLinkID) { GPPShare.sharedInstance().shareDialog().setURLToShare(new NSURL(urlToShare)) .setCallToActionButtonWithLabel(new NSString(label), new NSURL(urlToShare), new NSString(contentDeepLinkID)).open(); } }
package org.seng302.leftovers.service; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.seng302.leftovers.dto.user.UserRole; import org.seng302.leftovers.entities.Keyword; import org.seng302.leftovers.entities.User; import org.seng302.leftovers.entities.event.KeywordCreatedEvent; import org.seng302.leftovers.persistence.UserRepository; import org.seng302.leftovers.persistence.event.EventRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Class responsible for sending notifications for keyword related events. */ @Service public class KeywordService { private static final Logger logger = LogManager.getLogger(KeywordService.class); private final UserRepository userRepository; private final EventRepository eventRepository; @Autowired public KeywordService(EventRepository eventRepository, UserRepository userRepository) { this.eventRepository = eventRepository; this.userRepository = userRepository; } /** * Sends create keyword event to default global application admin and all other global application admins. * @param keyword The keyword that has been created. */ public void sendNewKeywordEvent(Keyword keyword, User creator) { List<User> adminList = userRepository.findAllByRole(UserRole.DGAA); adminList.addAll(userRepository.findAllByRole(UserRole.GAA)); Set<User> adminSet = new HashSet<>(adminList); logger.info("Sending keyword creation notification for keyword \"{}\" to system administrators", keyword.getName()); for (User admin : adminSet) { KeywordCreatedEvent newKeywordEvent = new KeywordCreatedEvent(admin, creator, keyword); eventRepository.save(newKeywordEvent); } } }
package ml.puredark.hviewer.ui.activities; import android.content.ActivityNotFoundException; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Intent; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.text.method.LinkMovementMethod; import android.text.util.Linkify; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.TextView; import androidx.appcompat.widget.Toolbar; import androidx.coordinatorlayout.widget.CoordinatorLayout; import androidx.documentfile.provider.DocumentFile; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.OrientationHelper; import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.StaggeredGridLayoutManager; import com.github.clans.fab.FloatingActionButton; import com.github.clans.fab.FloatingActionMenu; import com.google.android.material.appbar.AppBarLayout; import com.wuxiaolong.pullloadmorerecyclerview.PullLoadMoreRecyclerView; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import ml.puredark.hviewer.HViewerApplication; import ml.puredark.hviewer.R; import ml.puredark.hviewer.beans.Comment; import ml.puredark.hviewer.beans.DownloadTask; import ml.puredark.hviewer.beans.LocalCollection; import ml.puredark.hviewer.beans.Tag; import ml.puredark.hviewer.beans.Video; import ml.puredark.hviewer.core.HtmlContentParser; import ml.puredark.hviewer.core.RuleParser; import ml.puredark.hviewer.dataholders.FavouriteHolder; import ml.puredark.hviewer.helpers.MDStatusBarCompat; import ml.puredark.hviewer.http.ImageLoader; import ml.puredark.hviewer.ui.adapters.CollectionTagAdapter; import ml.puredark.hviewer.ui.adapters.CommentAdapter; import ml.puredark.hviewer.ui.adapters.PictureVideoAdapter; import ml.puredark.hviewer.ui.adapters.ViewPagerAdapter; import ml.puredark.hviewer.ui.customs.AutoFitStaggeredGridLayoutManager; import ml.puredark.hviewer.ui.customs.ExTabLayout; import ml.puredark.hviewer.ui.customs.ExViewPager; import ml.puredark.hviewer.ui.customs.WrappedGridLayoutManager; import ml.puredark.hviewer.ui.dataproviders.ListDataProvider; import ml.puredark.hviewer.ui.listeners.SwipeBackOnPageChangeListener; import ml.puredark.hviewer.utils.DensityUtil; public class DownloadTaskActivity extends BaseActivity { @BindView(R.id.coordinator_layout) CoordinatorLayout coordinatorLayout; @BindView(R.id.backdrop) ImageView backdrop; @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.tab_layout) ExTabLayout tabLayout; @BindView(R.id.view_pager) ExViewPager viewPager; @BindView(R.id.btn_return) ImageView btnReturn; @BindView(R.id.app_bar) AppBarLayout appBar; @BindView(R.id.fab_menu) FloatingActionMenu fabMenu; @BindView(R.id.fab_download) FloatingActionButton fabDownload; private DownloadTask task; private PullLoadMoreRecyclerView rvIndex; private RecyclerView rvComment; private PictureVideoAdapter pictureVideoAdapter; private CommentAdapter commentAdapter; private CollectionViewHolder holder; private FavouriteHolder favouriteHolder; private int startPage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_collection); ButterKnife.bind(this); MDStatusBarCompat.setCollapsingToolbar(this, coordinatorLayout, appBar, backdrop, toolbar); if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) { FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) toolbar.getLayoutParams(); lp.height = (int) (getResources().getDimension(R.dimen.tool_bar_height)); lp.topMargin = MDStatusBarCompat.getStatusBarHeight(this); toolbar.setLayoutParams(lp); } setContainer(coordinatorLayout); /* 为返回按钮加载图标 */ setReturnButton(btnReturn); setAppBar(appBar); setFabMenu(fabMenu); //获取传递过来的Collection实例 if (HViewerApplication.temp instanceof DownloadTask) task = (DownloadTask) HViewerApplication.temp; //获取失败则结束此界面 if (task == null || task.collection == null) { finish(); return; } favouriteHolder = new FavouriteHolder(this); //解析URL模板 parseUrl(task.collection.site.galleryUrl); toolbar.setTitle(task.collection.title); setSupportActionBar(toolbar); setCover(task.collection); initCover(task.collection.cover); initTabAndViewPager(); refreshDescription(); fabDownload.setVisibility(View.GONE); } private void parseUrl(String url) { String pageStr = RuleParser.parseUrl(url).get("page"); try { if (pageStr == null) { startPage = 0; } else { String[] pageStrs = pageStr.split(":"); if (pageStrs.length > 1) { startPage = Integer.parseInt(pageStrs[0]); } else { startPage = Integer.parseInt(pageStr); } } } catch (NumberFormatException e) { startPage = 0; } } private void initCover(String cover) { if (cover != null) { ImageLoader.loadImageFromUrl(this, backdrop, cover); } } private void setCover(LocalCollection collection) { if (collection == null) return; if (collection.pictures != null) { if (collection.pictures.size() > 0) collection.cover = collection.pictures.get(0).thumbnail; } } private void initTabAndViewPager() { //初始化Tab和ViewPager List<View> views = new ArrayList<>(); List<String> titles = new ArrayList<>(); titles.add("目录"); View viewIndex = getLayoutInflater().inflate(R.layout.view_collection_index, null); views.add(viewIndex); titles.add("详情"); View viewDescription = getLayoutInflater().inflate(R.layout.view_collection_desciption, null); views.add(viewDescription); View viewComment = null; if (commentEnabled()) { titles.add("评论"); viewComment = getLayoutInflater().inflate(R.layout.view_collection_comment, null); views.add(viewComment); } holder = new CollectionViewHolder(viewDescription); ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(views, titles); viewPager.setAdapter(viewPagerAdapter); tabLayout.setupWithViewPager(viewPager); viewPager.addOnPageChangeListener(new SwipeBackOnPageChangeListener(this)); //初始化相册目录 rvIndex = (PullLoadMoreRecyclerView) viewIndex.findViewById(R.id.rv_index); pictureVideoAdapter = new PictureVideoAdapter(this, new ListDataProvider(task.collection.pictures), new ListDataProvider(task.collection.videos)); pictureVideoAdapter.setCookie(task.collection.site.cookie); rvIndex.setAdapter(pictureVideoAdapter); rvIndex.getRecyclerView().addOnScrollListener(new PictureVideoAdapter.ScrollDetector() { @Override public void onScrollUp() { fabMenu.hideMenu(true); } @Override public void onScrollDown() { fabMenu.showMenu(true); } }); rvIndex.getRecyclerView().setClipToPadding(false); rvIndex.getRecyclerView().setPadding( DensityUtil.dp2px(this, 8), DensityUtil.dp2px(this, 16), DensityUtil.dp2px(this, 8), DensityUtil.dp2px(this, 16)); pictureVideoAdapter.setOnItemClickListener((v, position) -> { if (position < pictureVideoAdapter.getPictureSize()) openPictureViewerActivity(position); else openVideoViewerActivity(position); }); //根据item宽度自动设置spanCount GridLayoutManager layoutManager = new WrappedGridLayoutManager(this, 6); rvIndex.getRecyclerView().setLayoutManager(layoutManager); pictureVideoAdapter.setLayoutManager(layoutManager); rvIndex.setPullRefreshEnable(false); rvIndex.setPushRefreshEnable(false); if (viewComment != null) { //初始化评论列表 rvComment = (RecyclerView) viewComment.findViewById(R.id.rv_comment); List<Comment> comments = new ArrayList<>(); commentAdapter = new CommentAdapter(this, new ListDataProvider(comments)); commentAdapter.setCookie(task.collection.site.cookie); rvComment.setAdapter(commentAdapter); //禁用下拉刷新和加载更多(暂时) // rvComment.setPullRefreshEnable(false); // rvComment.setPushRefreshEnable(false); } } private void openPictureViewerActivity(int position) { HViewerApplication.temp = this; HViewerApplication.temp2 = task.collection.site; HViewerApplication.temp3 = task.collection; HViewerApplication.temp4 = task.collection.pictures; Intent intent = new Intent(this, PictureViewerActivity.class); intent.putExtra("position", position); startActivity(intent); } private void openVideoViewerActivity(int position) { Video video = (Video) pictureVideoAdapter.getVideoDataProvider().getItem(position - pictureVideoAdapter.getPictureSize()); if (video.vlink == null) { showSnackBar("视频为空,可能下载失败"); return; } try { Intent intent = new Intent(Intent.ACTION_VIEW); Uri uri = Uri.parse(video.vlink); DocumentFile docFile = DocumentFile.fromSingleUri(this, uri); intent.setDataAndType(docFile.getUri(), "video/mp4"); intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); startActivity(Intent.createChooser(intent, "选择播放器")); } catch (Exception e) { showSnackBar("无法打开,下载路径需要设置为content://协议"); } } private boolean commentEnabled() { if (task.collection.site.galleryRule == null) return false; else return (task.collection.site.galleryRule.commentRule != null && task.collection.site.galleryRule.commentRule.item != null && task.collection.site.galleryRule.commentRule.author != null && task.collection.site.galleryRule.commentRule.content != null) || (task.collection.site.galleryRule.commentItem != null && task.collection.site.galleryRule.commentAuthor != null && task.collection.site.galleryRule.commentContent != null); } private void refreshDescription() { toolbar.setTitle(task.collection.title); holder.tvTitle.setText(task.collection.title); holder.tvUploader.setText(task.collection.uploader); holder.tvCategory.setText(task.collection.category); CollectionTagAdapter adapter = (CollectionTagAdapter) holder.rvTags.getAdapter(); if (task.collection.tags != null) { adapter.getDataProvider().clear(); adapter.getDataProvider().addAll(task.collection.tags); } adapter.setOnItemClickListener((v, position) -> { if (task.collection.tags != null) { Tag tag = adapter.getDataProvider().getItem(position); Intent intent = new Intent(DownloadTaskActivity.this, MainActivity.class); intent.setAction("search"); intent.putExtra("tag", tag); startActivity(intent); this.finish(); } }); adapter.notifyDataSetChanged(); holder.rbRating.setRating(task.collection.rating); holder.tvSubmittime.setText(task.collection.datetime); String url = task.collection.site.getGalleryUrl(task.collection.idCode, 0, task.collection.pictures); if (task.collection.description != null) holder.tvDescription.setText(HtmlContentParser.getClickableHtml(this, task.collection.description, url, source -> new BitmapDrawable())); } @OnClick(R.id.btn_return) void back() { onBackPressed(); } @OnClick(R.id.fab_browser) void fab_browser() { final String url = task.collection.site.getGalleryUrl(task.collection.idCode, startPage, pictureVideoAdapter.getPictureDataProvider().getItems()); Intent intent = new Intent(); intent.setAction("android.intent.action.VIEW"); Uri content_url = Uri.parse(url); intent.setData(content_url); try { startActivity(intent); }catch (ActivityNotFoundException e){ ClipboardManager myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); myClipboard.setPrimaryClip(ClipData.newPlainText("url", url)); showSnackBar("没有可调用的浏览器,网址已复制到剪贴板"); } } @OnClick(R.id.fab_favor) void favor() { int cid = favouriteHolder.addFavourite(task.collection); if(cid>=0) { task.collection.cid = cid; showSnackBar("收藏成功!"); }else{ showSnackBar("图册已收藏!"); } } @Override public void onResume() { super.onResume(); } @Override public void onDestroy() { super.onDestroy(); if (favouriteHolder != null) favouriteHolder.onDestroy(); } public class CollectionViewHolder { @BindView(R.id.tv_title) TextView tvTitle; @BindView(R.id.tv_uploader) TextView tvUploader; @BindView(R.id.tv_category) TextView tvCategory; @BindView(R.id.rv_tags) RecyclerView rvTags; @BindView(R.id.rb_rating) RatingBar rbRating; @BindView(R.id.tv_submittime) TextView tvSubmittime; @BindView(R.id.tv_description) TextView tvDescription; public CollectionViewHolder(View view) { ButterKnife.bind(this, view); rvTags.setAdapter( new CollectionTagAdapter( new ListDataProvider<>( new ArrayList<>() ) ) ); StaggeredGridLayoutManager layoutManager = new AutoFitStaggeredGridLayoutManager(getApplicationContext(), OrientationHelper.HORIZONTAL); rvTags.setLayoutManager(layoutManager); tvDescription.setAutoLinkMask(Linkify.EMAIL_ADDRESSES | Linkify.WEB_URLS); tvDescription.setMovementMethod(LinkMovementMethod.getInstance()); } } }
package org.basex.io.in; import java.io.*; /** * This server-side class wraps an {@link InputStream} filled by a database * client. The incoming bytes are decoded: * <ul> * <li> {@code 0x00} is treated as end of stream, and -1 is returned</li> * <li> {@code 0xFF} is treated as encoding flag and skipped</li> * </ul> * * @author BaseX Team 2005-15, BSD License * @author Christian Gruen */ public final class DecodingInput extends InputStream { /** Input stream. */ private final InputStream input; /** All bytes have been read. */ private boolean more = true; /** * Constructor. * @param input buffer input to be wrapped */ public DecodingInput(final InputStream input) { this.input = input; } @Override public int read() throws IOException { if(more) { final int b = input.read(); if(b != 0) return b == 0xFF ? input.read() : b; more = false; } return -1; } /** * Flushes the remaining client data. * @throws IOException I/O exception */ public void flush() throws IOException { while(read() != -1); } }
package org.openapitools.model; import com.fasterxml.jackson.annotation.JsonTypeName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.File; import java.math.BigDecimal; import java.util.Date; import java.util.UUID; import org.joda.time.LocalDate; import java.io.Serializable; import javax.validation.constraints.*; import javax.validation.Valid; import io.swagger.annotations.*; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("format_test") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class FormatTest implements Serializable { private @Valid Integer integer; private @Valid Integer int32; private @Valid Long int64; private @Valid BigDecimal number; private @Valid Float _float; private @Valid Double _double; private @Valid String string; private @Valid byte[] _byte; private @Valid File binary; private @Valid LocalDate date; private @Valid Date dateTime; private @Valid UUID uuid; private @Valid String password; private @Valid BigDecimal bigDecimal; /** * minimum: 10 * maximum: 100 **/ public FormatTest integer(Integer integer) { this.integer = integer; return this; } @ApiModelProperty(value = "") @JsonProperty("integer") @Min(10) @Max(100) public Integer getInteger() { return integer; } @JsonProperty("integer") public void setInteger(Integer integer) { this.integer = integer; } /** * minimum: 20 * maximum: 200 **/ public FormatTest int32(Integer int32) { this.int32 = int32; return this; } @ApiModelProperty(value = "") @JsonProperty("int32") @Min(20) @Max(200) public Integer getInt32() { return int32; } @JsonProperty("int32") public void setInt32(Integer int32) { this.int32 = int32; } /** **/ public FormatTest int64(Long int64) { this.int64 = int64; return this; } @ApiModelProperty(value = "") @JsonProperty("int64") public Long getInt64() { return int64; } @JsonProperty("int64") public void setInt64(Long int64) { this.int64 = int64; } /** * minimum: 32.1 * maximum: 543.2 **/ public FormatTest number(BigDecimal number) { this.number = number; return this; } @ApiModelProperty(required = true, value = "") @JsonProperty("number") @NotNull @DecimalMin("32.1") @DecimalMax("543.2") public BigDecimal getNumber() { return number; } @JsonProperty("number") public void setNumber(BigDecimal number) { this.number = number; } /** * minimum: 54.3 * maximum: 987.6 **/ public FormatTest _float(Float _float) { this._float = _float; return this; } @ApiModelProperty(value = "") @JsonProperty("float") @DecimalMin("54.3") @DecimalMax("987.6") public Float getFloat() { return _float; } @JsonProperty("float") public void setFloat(Float _float) { this._float = _float; } /** * minimum: 67.8 * maximum: 123.4 **/ public FormatTest _double(Double _double) { this._double = _double; return this; } @ApiModelProperty(value = "") @JsonProperty("double") @DecimalMin("67.8") @DecimalMax("123.4") public Double getDouble() { return _double; } @JsonProperty("double") public void setDouble(Double _double) { this._double = _double; } /** **/ public FormatTest string(String string) { this.string = string; return this; } @ApiModelProperty(value = "") @JsonProperty("string") @Pattern(regexp="/[a-z]/i") public String getString() { return string; } @JsonProperty("string") public void setString(String string) { this.string = string; } /** **/ public FormatTest _byte(byte[] _byte) { this._byte = _byte; return this; } @ApiModelProperty(required = true, value = "") @JsonProperty("byte") @NotNull @Pattern(regexp="^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$") public byte[] getByte() { return _byte; } @JsonProperty("byte") public void setByte(byte[] _byte) { this._byte = _byte; } /** **/ public FormatTest binary(File binary) { this.binary = binary; return this; } @ApiModelProperty(value = "") @JsonProperty("binary") public File getBinary() { return binary; } @JsonProperty("binary") public void setBinary(File binary) { this.binary = binary; } /** **/ public FormatTest date(LocalDate date) { this.date = date; return this; } @ApiModelProperty(required = true, value = "") @JsonProperty("date") @NotNull public LocalDate getDate() { return date; } @JsonProperty("date") public void setDate(LocalDate date) { this.date = date; } /** **/ public FormatTest dateTime(Date dateTime) { this.dateTime = dateTime; return this; } @ApiModelProperty(value = "") @JsonProperty("dateTime") public Date getDateTime() { return dateTime; } @JsonProperty("dateTime") public void setDateTime(Date dateTime) { this.dateTime = dateTime; } /** **/ public FormatTest uuid(UUID uuid) { this.uuid = uuid; return this; } @ApiModelProperty(example = "72f98069-206d-4f12-9f12-3d1e525a8e84", value = "") @JsonProperty("uuid") public UUID getUuid() { return uuid; } @JsonProperty("uuid") public void setUuid(UUID uuid) { this.uuid = uuid; } /** **/ public FormatTest password(String password) { this.password = password; return this; } @ApiModelProperty(required = true, value = "") @JsonProperty("password") @NotNull @Size(min=10,max=64) public String getPassword() { return password; } @JsonProperty("password") public void setPassword(String password) { this.password = password; } /** **/ public FormatTest bigDecimal(BigDecimal bigDecimal) { this.bigDecimal = bigDecimal; return this; } @ApiModelProperty(value = "") @JsonProperty("BigDecimal") public BigDecimal getBigDecimal() { return bigDecimal; } @JsonProperty("BigDecimal") public void setBigDecimal(BigDecimal bigDecimal) { this.bigDecimal = bigDecimal; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FormatTest formatTest = (FormatTest) o; return Objects.equals(this.integer, formatTest.integer) && Objects.equals(this.int32, formatTest.int32) && Objects.equals(this.int64, formatTest.int64) && Objects.equals(this.number, formatTest.number) && Objects.equals(this._float, formatTest._float) && Objects.equals(this._double, formatTest._double) && Objects.equals(this.string, formatTest.string) && Objects.equals(this._byte, formatTest._byte) && Objects.equals(this.binary, formatTest.binary) && Objects.equals(this.date, formatTest.date) && Objects.equals(this.dateTime, formatTest.dateTime) && Objects.equals(this.uuid, formatTest.uuid) && Objects.equals(this.password, formatTest.password) && Objects.equals(this.bigDecimal, formatTest.bigDecimal); } @Override public int hashCode() { return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, uuid, password, bigDecimal); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class FormatTest {\n"); sb.append(" integer: ").append(toIndentedString(integer)).append("\n"); sb.append(" int32: ").append(toIndentedString(int32)).append("\n"); sb.append(" int64: ").append(toIndentedString(int64)).append("\n"); sb.append(" number: ").append(toIndentedString(number)).append("\n"); sb.append(" _float: ").append(toIndentedString(_float)).append("\n"); sb.append(" _double: ").append(toIndentedString(_double)).append("\n"); sb.append(" string: ").append(toIndentedString(string)).append("\n"); sb.append(" _byte: ").append(toIndentedString(_byte)).append("\n"); sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); sb.append(" password: ").append(toIndentedString(password)).append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
package org.devon.parallel.knnclassifier; /** * @author dewen.ye * @date 2019/3/10 09:06 */ public class Sample { double[] example; public double[] getExample() { return example; } public void setExample(double[] example) { this.example = example; } }
package com.revolsys.gis.web.rest.converter; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpInputMessage; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletWebRequest; import com.revolsys.geometry.io.GeometryReader; import com.revolsys.geometry.io.GeometryReaderFactory; import com.revolsys.geometry.model.GeometryFactory; import com.revolsys.io.IoConstants; import com.revolsys.io.IoFactory; import com.revolsys.spring.resource.InputStreamResource; import com.revolsys.ui.web.rest.converter.AbstractHttpMessageConverter; public class GeometryReaderHttpMessageConverter extends AbstractHttpMessageConverter<GeometryReader> { private GeometryFactory geometryFactory; public GeometryReaderHttpMessageConverter() { super(GeometryReader.class, IoFactory.mediaTypes(GeometryReaderFactory.class), null); } public GeometryFactory getGeometryFactory() { return this.geometryFactory; } @Override public GeometryReader read(final Class<? extends GeometryReader> clazz, final HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { try { final HttpHeaders headers = inputMessage.getHeaders(); final MediaType mediaType = headers.getContentType(); Charset charset = mediaType.getCharset(); if (charset == null) { charset = StandardCharsets.UTF_8; } final InputStream body = inputMessage.getBody(); final String mediaTypeString = mediaType.getType() + "/" + mediaType.getSubtype(); final GeometryReaderFactory readerFactory = IoFactory .factoryByMediaType(GeometryReaderFactory.class, mediaTypeString); if (readerFactory == null) { throw new HttpMessageNotReadableException("Cannot read data in format" + mediaType); } else { final InputStreamResource resource = new InputStreamResource("geometryInput", body); final GeometryReader reader = readerFactory.newGeometryReader(resource); GeometryFactory factory = this.geometryFactory; final ServletWebRequest requestAttributes = (ServletWebRequest)RequestContextHolder .getRequestAttributes(); final String srid = requestAttributes.getParameter("srid"); if (srid != null && srid.trim().length() > 0) { factory = GeometryFactory.floating3d(Integer.parseInt(srid)); } reader.setProperty(IoConstants.GEOMETRY_FACTORY, factory); return reader; } } catch (final IOException e) { throw new HttpMessageNotReadableException("Error reading data", e); } } public void setGeometryFactory(final GeometryFactory geometryFactory) { this.geometryFactory = geometryFactory; } }
package com.king.poi.word; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.usermodel.Table; import org.apache.poi.hwpf.usermodel.TableCell; import org.apache.poi.hwpf.usermodel.TableIterator; import org.apache.poi.hwpf.usermodel.TableRow; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFTable; import org.apache.poi.xwpf.usermodel.XWPFTableCell; import org.apache.poi.xwpf.usermodel.XWPFTableRow; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * 核心功能:将文档中表格定义的实体转换成Java实体对象 * <br/> 1. 支持解析doc格式和docx格式的Word文档 * <br/> 2. 支持批量解析Word文档并转换成实体 * <br/> 3. 解析配置支持自定义,详情请查看{@link ParseConfig}相关配置 * <br/> 4. 虽然解析可配置,但因文档内容的不可控,解析转换也具有一定的局限性 * * @author <a href="mailto:jenly1314@gmail.com">Jenly</a> */ public final class WordPOI { private WordPOI(){ throw new AssertionError(); } /** * 通过流得到XWPFDocument (.docx格式的文档) * @param inputStream * @return * @throws IOException */ private static XWPFDocument getXWPFDocument(InputStream inputStream) throws IOException { return new XWPFDocument(inputStream); } /** * 通过流得到HWPFDocument (.doc格式的文档) * @param inputStream * @return * @throws IOException */ private static HWPFDocument getHWPFDocument(InputStream inputStream) throws IOException { return new HWPFDocument(inputStream); } /** * 获取TableIterator * @param inputStream * @return * @throws IOException */ private static TableIterator getTableIterator(InputStream inputStream) throws IOException { return new TableIterator(getHWPFDocument(inputStream).getRange()); } /** * 获取XWPFTable列表 * @param inputStream * @return * @throws IOException */ private static List<XWPFTable> getXWPFTables(InputStream inputStream) throws IOException { return getXWPFDocument(inputStream).getTables(); } /** * Word文档转实体 * @param wordPath 文档路径 * @param outPath 输出路径 * @param packageName 实体类包名 * @param entityNames 实体类名称 * @throws Exception */ public static void wordToEntity(String wordPath,String outPath,String packageName,String... entityNames) throws Exception{ wordToEntity(wordPath,outPath,packageName,new ParseConfig(),entityNames); } /** * Word文档转实体 * @param wordPath 文档路径 * @param outPath 输出路径 * @param packageName 实体类包名 * @param parseConfig 解析配置 * @param entityNames 实体类名称 * @throws Exception */ public static void wordToEntity(String wordPath,String outPath,String packageName,ParseConfig parseConfig,String... entityNames) throws Exception{ if(wordPath!=null){ boolean isDoc = wordPath.endsWith("doc"); wordToEntity(new FileInputStream(wordPath),isDoc,outPath,packageName,parseConfig,entityNames); } } /** * Word文档转实体 * @param inputStream * @param isDoc true 表示是".doc"格式的文件,false 表示是“.docx”格式的文件 * @param outPath 输出路径 * @param packageName 实体类包名 * @param entityNames 实体名称 * @throws IOException */ public static void wordToEntity(InputStream inputStream,boolean isDoc,String outPath,String packageName,String... entityNames) throws IOException{ wordToEntity(inputStream,isDoc,outPath,packageName,new ParseConfig(),entityNames); } /** * Word文档转实体 * @param inputStream 需要解析的文档的流 * @param isDoc true 表示是".doc"格式的文件,false 表示是“.docx”格式的文件 * @param outPath 输出路径 * @param packageName 实体类包名 * @param parseConfig 解析配置 * @param entityNames 实体名称 * @throws IOException */ public static void wordToEntity(InputStream inputStream,boolean isDoc,String outPath,String packageName,ParseConfig parseConfig,String... entityNames) throws IOException{ if(isDoc){ docToEntity(inputStream,outPath,packageName,parseConfig,entityNames); }else{ docxToEntity(inputStream,outPath,packageName,parseConfig,entityNames); } } /** * docx格式的文档转实体 * @param inputStream 需要解析的文档的流 * @param outPath 输出路径 * @param packageName 实体类包名 * @param parseConfig 解析配置 * @param entityNames 实体名称 * @throws IOException */ private static void docxToEntity(InputStream inputStream,String outPath,String packageName,ParseConfig parseConfig,String... entityNames) throws IOException{ boolean isParseEntityName = parseConfig.isParseEntityName(); int length = entityNames.length; if(isParseEntityName || length>0){ List<XWPFTable> xwpfTableList = getXWPFTables(inputStream); int size = xwpfTableList.size(); //遍历文档所有表格 for (int i = parseConfig.getStartTable(); i < size; i++) { if(i > length && !isParseEntityName){ return; } //得到文档当前表格 XWPFTable table = xwpfTableList.get(i); int rows = table.getNumberOfRows(); String entityName; if(isParseEntityName){ entityName = table.getRow(parseConfig.getEntityNameRow()).getCell(parseConfig.getEntityNameColumn()).getText(); }else{ entityName = entityNames[i]; } EntityProperty entityProperty = new EntityProperty(packageName,entityName); Map<String,String> transformations = parseConfig.getTransformations(); boolean isTransfer = transformations != null && !transformations.isEmpty(); List<FieldProperty> filedPropertyList = new ArrayList<>(); //遍历文档当前表格的当前行 for (int j = parseConfig.getStartRow(); j < rows; j++){ XWPFTableRow row = table.getRow(j); List<XWPFTableCell> cells = row.getTableCells(); int cols = cells.size(); FieldProperty filedProperty = new FieldProperty(); //遍历文档当前表格当前行的当前列 for (int k = parseConfig.getStartColumn(); k < cols; k++) { XWPFTableCell cell = cells.get(k); if(k == parseConfig.getFieldNameColumn()){ filedProperty.setName(cell.getText()); }else if(k == parseConfig.getFieldTypeColumn()){ String type = cell.getText(); if(isTransfer && transformations.containsKey(type)){ filedProperty.setType(transformations.get(type)); }else{ filedProperty.setType(type); } }else if(k == parseConfig.getFieldDescColumn()){ filedProperty.setDesc(cell.getText()); } } String name = filedProperty.getName(); //过滤掉为空的字段名称 if(name != null && name.trim().length() > 0){ filedPropertyList.add(filedProperty); } } entityProperty.setFiledPropertyList(filedPropertyList); generateEntity(entityProperty,false,outPath,parseConfig); } } } /** * doc格式的文档转实体 * @param inputStream 需要解析的文档的流 * @param outPath 输出路径 * @param packageName 实体类包名 * @param parseConfig 解析配置 * @param entityNames 实体名称 * @throws IOException */ private static void docToEntity(InputStream inputStream,String outPath,String packageName,ParseConfig parseConfig,String... entityNames) throws IOException{ boolean isParseEntityName = parseConfig.isParseEntityName(); int length = entityNames.length; if(isParseEntityName || length>0){ TableIterator tableIterator = getTableIterator(inputStream); int index = 0; for(int i = 0; i<parseConfig.getStartTable(); i++){ tableIterator.hasNext(); } Map<String,String> transformations = parseConfig.getTransformations(); boolean isTransfer = transformations != null && !transformations.isEmpty(); while (tableIterator.hasNext()){ if(index > length && !isParseEntityName){ return; } Table table = tableIterator.next(); int rows = table.numRows(); String entityName; if(isParseEntityName){ entityName = table.getRow(parseConfig.getEntityNameRow()).getCell(parseConfig.getEntityNameColumn()).text().replace("\u0007",""); }else{ entityName = entityNames[index]; } EntityProperty entityProperty = new EntityProperty(packageName,entityName); List<FieldProperty> filedPropertyList = new ArrayList<>(); //遍历文档当前表格的当前行 for (int j = parseConfig.getStartRow(); j < rows; j++){ TableRow row = table.getRow(j); int cols = row.numCells(); FieldProperty filedProperty = new FieldProperty(); //遍历文档当前表格当前行的当前列 for (int k = parseConfig.getStartColumn(); k < cols; k++) { TableCell cell = row.getCell(k); if(k == parseConfig.getFieldNameColumn()){ filedProperty.setName(cell.getParagraph(0).text().replace("\u0007","")); }else if(k == parseConfig.getFieldTypeColumn()){ String type = cell.getParagraph(0).text().replace("\u0007",""); if(isTransfer && transformations.containsKey(type)){ filedProperty.setType(transformations.get(type)); }else{ filedProperty.setType(type); } }else if(k == parseConfig.getFieldDescColumn()){ filedProperty.setDesc(cell.getParagraph(0).text().replace("\u0007","")); } } String name = filedProperty.getName(); //过滤掉为空的字段名称 if(name != null && name.trim().length() > 0){ filedPropertyList.add(filedProperty); } } entityProperty.setFiledPropertyList(filedPropertyList); generateEntity(entityProperty,true,outPath,parseConfig); index++; } } } /** * 生成实体对象 * @param entityProperty 实体属性 * @param isDoc true 表示是".doc"格式的文件,false 表示是“.docx”格式的文件 * @param outPath 输出路径 * @param parseConfig 解析配置 * @throws IOException */ private static void generateEntity(EntityProperty entityProperty,boolean isDoc,String outPath,ParseConfig parseConfig) throws IOException{ String className = entityProperty.getClassName(); String javaName = className + ".java"; StringBuffer buffer = new StringBuffer(); buffer.append("/* ") .append("<a href=\"https://github.com/jenly1314/WordPOI\">WordPOI</a>") .append(" */\n"); buffer.append("package "+ entityProperty.getPackageName()+";\n\n"); //是否使用Lobmok boolean useLombok = parseConfig.isUseLombok(); //是否生成get和set方法 boolean genGetterAndSetter = parseConfig.isGenGetterAndSetter(); //是否生成toString方法 boolean genToString = parseConfig.isGenToString(); //是否包含泛型 boolean genericity = false; //是否导入List boolean importList = false; //是否导入Set boolean importSet = false; //是否导入Map boolean importMap = false; List<FieldProperty> filedPropertyList = entityProperty.getFiledPropertyList(); if(filedPropertyList !=null ){ StringBuffer bufferField = new StringBuffer(); StringBuffer bufferGetSet = new StringBuffer(); StringBuffer bufferToString = new StringBuffer(); //toString开头 if(genToString && !useLombok){ bufferToString.append("\t@Override\n") .append("\tpublic String toString(){\n") .append("\t\treturn ") .append("\"").append(className).append("{\" + \n"); } int index = 0; int size = filedPropertyList.size(); for(FieldProperty filedProperty : filedPropertyList){ bufferField.append("\t/** " + filedProperty.getDesc() + " */\n"); bufferField.append("\tprivate " + filedProperty.getType() + " " + filedProperty.getName() + ";\n"); String fieldType = filedProperty.getType(); if(fieldType!=null){ //遍历是否包含泛型 if(fieldType.contains("<T>") || fieldType.equals("T")){ genericity = true; } //遍历是否包含集合 if(fieldType.startsWith("List")){ importList = true; }else if(fieldType.startsWith("Set")){ importSet = true; }else if(fieldType.startsWith("Map")){ importMap = true; } } if(!useLombok){//只有当不使用Lombok时,才会根据genGetterAndSetter 和 genToString 来判断是否生成get、set、toString等方法 String fieldName = filedProperty.getName(); //是否生成get和set方法 if(genGetterAndSetter){ String getterName = fieldName.substring(0,1).toUpperCase() + fieldName.substring(1); //Generate getter if("boolean".equalsIgnoreCase(fieldType)){ bufferGetSet.append("\tpublic " + fieldType + " is" + getterName + "(){\n") .append("\t\treturn " + fieldName + ";\n") .append("\t}\n\n"); }else{ bufferGetSet.append("\tpublic " + fieldType + " get" + getterName + "(){\n") .append("\t\treturn " + fieldName + ";\n") .append("\t}\n\n"); } //Generate setter bufferGetSet.append("\tpublic void set" + getterName + "(" + fieldType + " " + filedProperty.getName() + "){\n") .append("\t\tthis." + fieldName + " = " + fieldName + ";\n") .append("\t}\n\n"); } if(genToString){//生成toString方法 bufferToString.append("\t\t\t\t\"").append(fieldName).append("=\" + ") .append(fieldName); if(index < size-1){ bufferToString.append(" + \",\" + \n"); }else{ bufferToString.append(" + \"}\";\n"); } } } index++; } if(parseConfig.isSerializable()){//导入Serializable buffer.append("import java.io.Serializable;\n"); } if(importList){//导入List buffer.append("import java.util.List;\n"); } if(importSet){//导入Set buffer.append("import java.util.Set;\n"); } if(importMap){//导入Map buffer.append("import java.util.Map;\n"); } if(useLombok){//导入Lombok buffer.append("import lombok.Data;\n"); } buffer.append("\n"); //是否显示头部注释说明 if(parseConfig.isShowHeader()){ String header = parseConfig.getHeader(); if(header!=null && header.length()>0){ buffer.append("/**\n"); buffer.append(" * ") .append(header.replace("\n","\n * ")); buffer.append("\n */\n"); } } if(useLombok){//添加Lombok的data注解 buffer.append("@Data\n"); } //拼接类 buffer.append("public class " + className); if(genericity){ buffer.append("<T>"); } //序列化 if(parseConfig.isSerializable()){ buffer.append(" implements Serializable"); } buffer.append(" {\n\n"); //添加字段 buffer.append(bufferField).append("\n"); if(!useLombok){ if(genGetterAndSetter){ buffer.append(bufferGetSet); } if(genToString){ //toString结尾 bufferToString.append("\t}\n\n"); buffer.append(bufferToString); } } } buffer.append("\n}\n\n"); File dirFile = new File(outPath); if(dirFile!=null && !dirFile.exists()){ dirFile.mkdirs(); } //将内容写入到文件 File file = new File(outPath,javaName); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),parseConfig.getCharsetName())); //doc格式的文档解析后会有\u0007字符需统一过滤 writer.write(isDoc ? buffer.toString().replace("\u0007","") : buffer.toString()); writer.flush(); writer.close(); } }
package backtype.storm.hooks; import backtype.storm.hooks.info.BoltAckInfo; import backtype.storm.hooks.info.BoltExecuteInfo; import backtype.storm.hooks.info.SpoutFailInfo; import backtype.storm.hooks.info.SpoutAckInfo; import backtype.storm.hooks.info.EmitInfo; import backtype.storm.hooks.info.BoltFailInfo; import backtype.storm.task.TopologyContext; import java.util.Map; public interface ITaskHook { void prepare(Map conf, TopologyContext context); void cleanup(); void emit(EmitInfo info); void spoutAck(SpoutAckInfo info); void spoutFail(SpoutFailInfo info); void boltExecute(BoltExecuteInfo info); void boltAck(BoltAckInfo info); void boltFail(BoltFailInfo info); }
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2021 DBeaver Corp and others * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.ext.oracle.edit; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.ext.oracle.model.*; import org.jkiss.dbeaver.model.DBPDataSource; import org.jkiss.dbeaver.model.DBPEvaluationContext; import org.jkiss.dbeaver.model.DBPScriptObject; import org.jkiss.dbeaver.model.edit.DBECommandContext; import org.jkiss.dbeaver.model.edit.DBEPersistAction; import org.jkiss.dbeaver.model.exec.DBCExecutionContext; import org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistAction; import org.jkiss.dbeaver.model.impl.sql.edit.SQLObjectEditor; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.runtime.VoidProgressMonitor; import org.jkiss.dbeaver.model.struct.DBSObject; import org.jkiss.dbeaver.model.struct.cache.DBSObjectCache; import org.jkiss.utils.CommonUtils; import java.util.List; import java.util.Map; /** * OraclePackageManager */ public class OraclePackageManager extends SQLObjectEditor<OraclePackage, OracleSchema> { @Nullable @Override public DBSObjectCache<? extends DBSObject, OraclePackage> getObjectsCache(OraclePackage object) { return object.getSchema().packageCache; } @Override protected OraclePackage createDatabaseObject(DBRProgressMonitor monitor, DBECommandContext context, final Object container, Object copyFrom, Map<String, Object> options) { return new OraclePackage( (OracleSchema) container, "NEW_PACKAGE"); } @Override protected void addObjectCreateActions(DBRProgressMonitor monitor, DBCExecutionContext executionContext, List<DBEPersistAction> actions, ObjectCreateCommand objectCreateCommand, Map<String, Object> options) { createOrReplaceProcedureQuery(executionContext, actions, objectCreateCommand.getObject()); } @Override protected void addObjectDeleteActions(DBRProgressMonitor monitor, DBCExecutionContext executionContext, List<DBEPersistAction> actions, ObjectDeleteCommand objectDeleteCommand, Map<String, Object> options) { final OraclePackage object = objectDeleteCommand.getObject(); actions.add( new SQLDatabasePersistAction("Drop package", "DROP PACKAGE " + object.getFullyQualifiedName(DBPEvaluationContext.DDL)) //$NON-NLS-1$ ); } @Override protected void addObjectModifyActions(DBRProgressMonitor monitor, DBCExecutionContext executionContext, List<DBEPersistAction> actionList, ObjectChangeCommand objectChangeCommand, Map<String, Object> options) { createOrReplaceProcedureQuery(executionContext, actionList, objectChangeCommand.getObject()); } @Override public long getMakerOptions(DBPDataSource dataSource) { return FEATURE_EDITOR_ON_CREATE; } private void createOrReplaceProcedureQuery(DBCExecutionContext executionContext, List<DBEPersistAction> actionList, OraclePackage pack) { try { String header = pack.getObjectDefinitionText(new VoidProgressMonitor(), DBPScriptObject.EMPTY_OPTIONS).trim(); if (!header.endsWith(";")) { header += ";"; } if (!CommonUtils.isEmpty(header)) { actionList.add( new OracleObjectValidateAction( pack, OracleObjectType.PACKAGE, "Create package header", header)); //$NON-NLS-1$ } String body = pack.getExtendedDefinitionText(new VoidProgressMonitor()); if (!CommonUtils.isEmpty(body)) { body = body.trim(); if (!body.endsWith(";")) { body += ";"; } actionList.add( new OracleObjectValidateAction( pack, OracleObjectType.PACKAGE_BODY, "Create package body", body)); } else { actionList.add( new SQLDatabasePersistAction( "Drop package header", "DROP PACKAGE BODY " + pack.getFullyQualifiedName(DBPEvaluationContext.DDL), DBEPersistAction.ActionType.OPTIONAL) //$NON-NLS-1$ ); } } catch (DBException e) { log.warn(e); } OracleUtils.addSchemaChangeActions(executionContext, actionList, pack); } }
package br.com.desafiomercadolivre.modelos; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import javax.persistence.*; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Size; import java.time.LocalDateTime; import java.util.Collection; import java.util.Objects; @Entity @Table(name = "tb_usuarios") public class Usuario implements UserDetails { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotBlank(message = "É necessário preencher login.") @Email @Column(unique = true) private String login; @NotBlank(message = "É necessário uma senha.") @Size(min = 6, message = "A senha precisa de 6 caracteres no mínimo.") private String senha; private LocalDateTime dataCadastro; @Deprecated public Usuario(){ } public Usuario(String login, String senha) { this.login = login; this.senha = senha; this.dataCadastro = LocalDateTime.now(); } // método do spring Security @Override public Collection<? extends GrantedAuthority> getAuthorities() { // Configuração de roles (Perfis) return null; } public Long getId() { return id; } @Override public String getPassword() { return this.senha; } @Override public String getUsername() { return this.login; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Usuario usuario = (Usuario) o; return Objects.equals(id, usuario.id); } @Override public int hashCode() { return Objects.hash(id); } }
package org.papaja.adminfly.module.psy.tests.MMPI; import org.papaja.function.Converter; import java.util.Map; public interface AnswersPointsConverterInterface extends Converter<Map<Integer, Answer>, Map<Scale, Integer>> { default Map<Scale, Integer> getPoints(Map<Integer, Answer> answers) { return convert(answers); } }
package com.carporange.ichange.sign_calender; import java.util.Calendar; import java.util.HashSet; import java.util.Set; /** * 月历抽象父类 * 继承该类可以实现自己的日历对象 * <p/> * Abstract class of Calendar * * @author AigeStudio 2015-06-15 */ public abstract class DPCalendar { protected final Calendar c = Calendar.getInstance(); /** * 获取某年某月的节日数组 * <p/> * Build the festival date array of given year and month * * @param year 某年 * @param month 某月 * @return 该月节日数组 */ public abstract String[][] buildMonthFestival(int year, int month); /** * 获取某年某月的假期数组 * <p/> * Build the holiday date array of given year and month * * @param year 某年 * @param month 某月 * @return 该月假期数组 */ public abstract Set<String> buildMonthHoliday(int year, int month); /** * 判断某年是否为闰年 * * @param year ... * @return true表示闰年 */ public boolean isLeapYear(int year) { return (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)); } /** * 判断给定日期是否为今天 * * @param year 某年 * @param month 某月 * @param day 某天 * @return ... */ public boolean isToday(int year, int month, int day) { Calendar c1 = Calendar.getInstance(); Calendar c2 = Calendar.getInstance(); c1.set(year, month - 1, day); return (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR)) && (c1.get(Calendar.MONTH) == (c2.get(Calendar.MONTH))) && (c1.get(Calendar.DAY_OF_MONTH) == c2.get(Calendar.DAY_OF_MONTH)); } /** * 生成某年某月的公历天数数组 * 数组为6x7的二维数组因为一个月的周数永远不会超过六周 * 天数填充对应相应的二维数组下标 * 如果某个数组下标中没有对应天数那么则填充一个空字符串 * * @param year 某年 * @param month 某月 * @return 某年某月的公历天数数组 */ public String[][] buildMonthG(int year, int month) { c.clear(); String tmp[][] = new String[6][7]; c.set(year, month - 1, 1); int daysInMonth = 0; if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month == 4 || month == 6 || month == 9 || month == 11) { daysInMonth = 30; } else if (month == 2) { if (isLeapYear(year)) { daysInMonth = 29; } else { daysInMonth = 28; } } int dayOfWeek = c.get(Calendar.DAY_OF_WEEK) - Calendar.SUNDAY; int day = 1; for (int i = 0; i < 6; i++) { for (int j = 0; j < 7; j++) { tmp[i][j] = ""; if (i == 0 && j >= dayOfWeek) { tmp[i][j] = "" + day; day++; } else if (i > 0 && day <= daysInMonth) { tmp[i][j] = "" + day; day++; } } } return tmp; } /** * 生成某年某月的周末日期集合 * * @param year 某年 * @param month 某月 * @return 某年某月的周末日期集合 */ public Set<String> buildMonthWeekend(int year, int month) { Set<String> set = new HashSet<>(); c.clear(); c.set(year, month - 1, 1); do { int day = c.get(Calendar.DAY_OF_WEEK); if (day == Calendar.SATURDAY || day == Calendar.SUNDAY) { set.add(String.valueOf(c.get(Calendar.DAY_OF_MONTH))); } c.add(Calendar.DAY_OF_YEAR, 1); } while (c.get(Calendar.MONTH) == month - 1); return set; } protected long GToNum(int year, int month, int day) { month = (month + 9) % 12; year = year - month / 10; return 365 * year + year / 4 - year / 100 + year / 400 + (month * 306 + 5) / 10 + (day - 1); } protected int getBitInt(int data, int length, int shift) { return (data & (((1 << length) - 1) << shift)) >> shift; } }
/* * Copyright (c) 2018 Cadenza United Kingdom Limited * * 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.cadenzauk.siesta.ddl.definition.intercept; import com.cadenzauk.siesta.Database; import com.cadenzauk.siesta.ddl.action.Action; import com.cadenzauk.siesta.ddl.action.ActionInterceptor; import com.cadenzauk.siesta.ddl.action.Priority; import com.cadenzauk.siesta.ddl.definition.action.CreateSequenceAction; import com.cadenzauk.siesta.ddl.sql.action.CreateSequenceSql; import com.google.common.reflect.TypeToken; import java.util.stream.Stream; public class CreateSequenceGenerator extends ActionInterceptor<CreateSequenceAction> { @Override public Stream<Action> intercept(Database database, CreateSequenceAction action) { return Stream.of(new CreateSequenceSql(action)); } @Override public TypeToken<CreateSequenceAction> supportedType() { return TypeToken.of(CreateSequenceAction.class); } @Override public int priority() { return Priority.GENERATION; } }
package seedu.savenus.model.info; import seedu.savenus.logic.commands.DislikeCommand; //@@author robytanama /** * Contains information on like command. */ public class DislikeInfo { public static final String COMMAND_WORD = DislikeCommand.COMMAND_WORD; public static final String INFORMATION = "Dislike command allows your to state your preferences.\n" + "Do note that only one field is compulsory but multiple fields can be added\n\n" + "The dislike feature will depend on the following factors:\n" + "Category\n" + "Tags\n" + "Location\n\n"; public static final String USAGE = "dislike c/Chinese t/Cheap t/Healthy l/University Town\n"; public static final String OUTPUT = "The app will store the information that you have disliked Food with:\n" + "Category: Chinese, Tags: Cheap and Healthy, Location: University Town"; }
/* * Copyright 2020 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.kogito.process.bpmn2; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.jbpm.bpmn2.xml.BPMNDISemanticModule; import org.jbpm.bpmn2.xml.BPMNExtensionsSemanticModule; import org.jbpm.bpmn2.xml.BPMNSemanticModule; import org.jbpm.compiler.xml.SemanticModule; import org.jbpm.compiler.xml.XmlProcessReader; import org.jbpm.compiler.xml.core.SemanticModules; import org.jbpm.workflow.core.WorkflowProcess; import org.kie.api.definition.process.Node; import org.kie.api.definition.process.Process; import org.kie.api.io.Resource; import org.kie.kogito.Application; import org.kie.kogito.StaticApplication; import org.kie.kogito.StaticConfig; import org.kie.kogito.process.ProcessConfig; public class BpmnProcessCompiler { private final SemanticModules bpmnSemanticModules; public BpmnProcessCompiler(SemanticModule... modules) { this.bpmnSemanticModules = new SemanticModules(); if (modules.length == 0) { // add default this.bpmnSemanticModules.addSemanticModule(new BPMNSemanticModule()); this.bpmnSemanticModules.addSemanticModule(new BPMNExtensionsSemanticModule()); this.bpmnSemanticModules.addSemanticModule(new BPMNDISemanticModule()); } else { for (SemanticModule module : modules) { this.bpmnSemanticModules.addSemanticModule(module); } } } protected SemanticModules getSemanticModules() { return bpmnSemanticModules; } public List<BpmnProcess> from(ProcessConfig config, Resource... resources) { try { BpmnProcesses bpmnProcesses = new BpmnProcesses(); StaticApplication application = new StaticApplication(new StaticConfig(null, config), bpmnProcesses); List<Process> processes = new ArrayList<>(); XmlProcessReader xmlReader = new XmlProcessReader( getSemanticModules(), Thread.currentThread().getContextClassLoader()); configureProcessReader(xmlReader, config); for (Resource resource : resources) { processes.addAll(xmlReader.read(resource.getReader())); } List<BpmnProcess> bpmnProcessesList = processes.stream() .map(p -> create(p, config, application)) .collect(Collectors.toList()); bpmnProcessesList.forEach(p -> { for (Node node : ((WorkflowProcess) p.get()).getNodesRecursively()) { processNode(node, bpmnProcessesList); } }); return bpmnProcessesList; } catch (Exception e) { throw new BpmnProcessReaderException(e); } } protected void configureProcessReader(XmlProcessReader xmlReader, ProcessConfig config) { } protected BpmnProcess create(Process process, ProcessConfig config, Application application) { return config == null ? new BpmnProcess(process) : new BpmnProcess(process, config, application); } protected void processNode(Node node, List<BpmnProcess> bpmnProcesses) { } }
/* * Copyright (c) 2017. Sunghyouk Bae <sunghyouk.bae@gmail.com> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.hibernate.cache.redis.jpa; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import lombok.extern.slf4j.Slf4j; import org.hibernate.cache.redis.hibernate5.SingletonRedisRegionFactory; import org.hibernate.cache.redis.jpa.models.Account; import org.hibernate.cache.redis.jpa.repository.EventRepository; import org.hibernate.cfg.Environment; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.orm.hibernate5.HibernateExceptionTranslator; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; import java.io.IOException; import java.util.Properties; import static org.springframework.util.StringUtils.arrayToCommaDelimitedString; @Slf4j @Configuration @EnableTransactionManagement(proxyTargetClass = true) @EnableJpaRepositories(basePackageClasses = {EventRepository.class}) public class JpaCacheConfiguration { public String getDatabaseName() { return "hibernate"; } /** * 매핑할 엔티티 클래스가 정의된 package name 의 배열 */ public String[] getMappedPackageNames() { return new String[]{ Account.class.getPackage().getName() }; } /** * JPA 환경 설정 정보 * * @return 설정 정보 */ public Properties jpaProperties() { Properties props = new Properties(); props.put(Environment.FORMAT_SQL, "true"); props.put(Environment.HBM2DDL_AUTO, "create"); props.put(Environment.SHOW_SQL, "true"); props.put(Environment.POOL_SIZE, 30); // Secondary Cache props.put(Environment.USE_SECOND_LEVEL_CACHE, true); props.put(Environment.USE_QUERY_CACHE, true); props.put(Environment.CACHE_REGION_FACTORY, SingletonRedisRegionFactory.class.getName()); props.put(Environment.CACHE_REGION_PREFIX, "hibernate"); props.put(Environment.CACHE_PROVIDER_CONFIG, "conf/hibernate-redis.properties"); props.setProperty(Environment.GENERATE_STATISTICS, "true"); props.setProperty(Environment.USE_STRUCTURED_CACHE, "true"); // NOTE: Don't use TRANSACTION_COORDINATOR_STRATEGY in JPA // props.setProperty(Environment.TRANSACTION_COORDINATOR_STRATEGY, JtaTransactionCoordinatorBuilderImpl.class.getName()); return props; } @Bean(destroyMethod = "close") public DataSource dataSource() { HikariConfig config = new HikariConfig(); config.setDriverClassName("org.h2.Driver"); config.setJdbcUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;MVCC=TRUE;"); config.setUsername("sa"); config.setPassword(""); config.setInitializationFailFast(true); config.setConnectionTestQuery("SELECT 1"); return new HikariDataSource(config); } @Bean public EntityManagerFactory entityManagerFactory() throws IOException { log.info("Create EntityManagerFactory Bean..."); LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean(); String[] packagenames = getMappedPackageNames(); if (packagenames != null && packagenames.length > 0) { log.debug("Scan JPA entities... packages=[{}]", arrayToCommaDelimitedString(packagenames)); factoryBean.setPackagesToScan(packagenames); } factoryBean.setJpaProperties(jpaProperties()); factoryBean.setDataSource(dataSource()); HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter(); adapter.setGenerateDdl(true); factoryBean.setJpaVendorAdapter(adapter); factoryBean.afterPropertiesSet(); log.info("Created EntityManagerFactory Bean"); return factoryBean.getObject(); } @Bean public PlatformTransactionManager transactionManager() throws IOException { return new JpaTransactionManager(entityManagerFactory()); } /** * Hibernate 에외를 변환하는 {@link HibernateExceptionTranslator} 를 Spring 의 ApplicationContext에 등록합니다. */ // NOTE: 이거 꼭 정의해야 합니다. @Bean public HibernateExceptionTranslator hibernateExceptionTranslator() { return new HibernateExceptionTranslator(); } /** * 예외를 변환하는 Processor를 동록합니다. * * @return {@link PersistenceExceptionTranslationPostProcessor} instance. */ @Bean public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { return new PersistenceExceptionTranslationPostProcessor(); } }
/* * Copyright (C) 2019 the original author or authors. * * This file is part of jBB Application Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 */ package org.jbb; import org.jbb.lib.restful.paging.PageDto; import java.util.List; import io.restassured.http.ContentType; import io.restassured.http.Cookies; import io.restassured.mapper.TypeRef; import io.restassured.module.mockmvc.RestAssuredMockMvc; import io.restassured.module.mockmvc.response.MockMvcResponse; import io.restassured.module.mockmvc.specification.MockMvcRequestSpecification; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic; public final class ApiRequestUtils { public static final String ADMINISTRATOR_USERNAME = "administrator"; public static final String ADMINISTRATOR_PSWD = "administrator"; public static MockMvcRequestSpecification noAuthApiRequest() { return RestAssuredMockMvc.given() .accept(ContentType.JSON) .contentType(ContentType.JSON); } public static MockMvcRequestSpecification signInAdminApiRequest() { return signInApiRequest(ADMINISTRATOR_USERNAME, ADMINISTRATOR_PSWD); } public static MockMvcRequestSpecification signInApiRequest(String username, String password) { MockMvcResponse signInResponse = RestAssuredMockMvc.given() .param("username", username) .param("password", password) .contentType(ContentType.URLENC) .post("/api/v1/sign-in"); assertThat(signInResponse.statusCode()).isEqualTo(204); Cookies cookies = signInResponse.detailedCookies(); return RestAssuredMockMvc.given() .accept(ContentType.JSON) .contentType(ContentType.JSON) .cookies(cookies); } public static MockMvcRequestSpecification basicAuthUserApiRequest(String username, String password) { return noAuthApiRequest() .postProcessors(httpBasic(username, password)); } public static MockMvcRequestSpecification basicAuthAdminApiRequest() { return basicAuthUserApiRequest(ADMINISTRATOR_USERNAME, ADMINISTRATOR_PSWD); } public static <T> T responseBodyAs(MockMvcResponse response, Class<T> responseBodyClass) { return response.then().extract().body().as(responseBodyClass); } public static <T> List<T> responseBodyAsListOf(MockMvcResponse response, Class<T> responseBodyClass) { return response.then().extract().body().as(new TypeRef<List<T>>() { }); } public static <T> PageDto<T> responseBodyAsPageOf(MockMvcResponse response, Class<T> responseBodyClass) { return response.then().extract().body().as(new TypeRef<PageDto<T>>() { }); } }
/* * 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.directconnect.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/DeleteDirectConnectGatewayAssociation" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DeleteDirectConnectGatewayAssociationRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The ID of the Direct Connect gateway association. * </p> */ private String associationId; /** * <p> * The ID of the Direct Connect gateway. * </p> */ private String directConnectGatewayId; /** * <p> * The ID of the virtual private gateway. * </p> */ private String virtualGatewayId; /** * <p> * The ID of the Direct Connect gateway association. * </p> * * @param associationId * The ID of the Direct Connect gateway association. */ public void setAssociationId(String associationId) { this.associationId = associationId; } /** * <p> * The ID of the Direct Connect gateway association. * </p> * * @return The ID of the Direct Connect gateway association. */ public String getAssociationId() { return this.associationId; } /** * <p> * The ID of the Direct Connect gateway association. * </p> * * @param associationId * The ID of the Direct Connect gateway association. * @return Returns a reference to this object so that method calls can be chained together. */ public DeleteDirectConnectGatewayAssociationRequest withAssociationId(String associationId) { setAssociationId(associationId); return this; } /** * <p> * The ID of the Direct Connect gateway. * </p> * * @param directConnectGatewayId * The ID of the Direct Connect gateway. */ public void setDirectConnectGatewayId(String directConnectGatewayId) { this.directConnectGatewayId = directConnectGatewayId; } /** * <p> * The ID of the Direct Connect gateway. * </p> * * @return The ID of the Direct Connect gateway. */ public String getDirectConnectGatewayId() { return this.directConnectGatewayId; } /** * <p> * The ID of the Direct Connect gateway. * </p> * * @param directConnectGatewayId * The ID of the Direct Connect gateway. * @return Returns a reference to this object so that method calls can be chained together. */ public DeleteDirectConnectGatewayAssociationRequest withDirectConnectGatewayId(String directConnectGatewayId) { setDirectConnectGatewayId(directConnectGatewayId); return this; } /** * <p> * The ID of the virtual private gateway. * </p> * * @param virtualGatewayId * The ID of the virtual private gateway. */ public void setVirtualGatewayId(String virtualGatewayId) { this.virtualGatewayId = virtualGatewayId; } /** * <p> * The ID of the virtual private gateway. * </p> * * @return The ID of the virtual private gateway. */ public String getVirtualGatewayId() { return this.virtualGatewayId; } /** * <p> * The ID of the virtual private gateway. * </p> * * @param virtualGatewayId * The ID of the virtual private gateway. * @return Returns a reference to this object so that method calls can be chained together. */ public DeleteDirectConnectGatewayAssociationRequest withVirtualGatewayId(String virtualGatewayId) { setVirtualGatewayId(virtualGatewayId); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getAssociationId() != null) sb.append("AssociationId: ").append(getAssociationId()).append(","); if (getDirectConnectGatewayId() != null) sb.append("DirectConnectGatewayId: ").append(getDirectConnectGatewayId()).append(","); if (getVirtualGatewayId() != null) sb.append("VirtualGatewayId: ").append(getVirtualGatewayId()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DeleteDirectConnectGatewayAssociationRequest == false) return false; DeleteDirectConnectGatewayAssociationRequest other = (DeleteDirectConnectGatewayAssociationRequest) obj; if (other.getAssociationId() == null ^ this.getAssociationId() == null) return false; if (other.getAssociationId() != null && other.getAssociationId().equals(this.getAssociationId()) == false) return false; if (other.getDirectConnectGatewayId() == null ^ this.getDirectConnectGatewayId() == null) return false; if (other.getDirectConnectGatewayId() != null && other.getDirectConnectGatewayId().equals(this.getDirectConnectGatewayId()) == false) return false; if (other.getVirtualGatewayId() == null ^ this.getVirtualGatewayId() == null) return false; if (other.getVirtualGatewayId() != null && other.getVirtualGatewayId().equals(this.getVirtualGatewayId()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getAssociationId() == null) ? 0 : getAssociationId().hashCode()); hashCode = prime * hashCode + ((getDirectConnectGatewayId() == null) ? 0 : getDirectConnectGatewayId().hashCode()); hashCode = prime * hashCode + ((getVirtualGatewayId() == null) ? 0 : getVirtualGatewayId().hashCode()); return hashCode; } @Override public DeleteDirectConnectGatewayAssociationRequest clone() { return (DeleteDirectConnectGatewayAssociationRequest) super.clone(); } }
package adinar.annotationsutils.viewinserter; import android.util.Pair; import java.lang.reflect.Method; import adinar.annotationsutils.common.Cache; import adinar.annotationsutils.common.PrimitiveToObjectConverter; public class MethodResolver { private static final String TAG = "MethodResolver"; private MethodResolver() {} private static class MethodEntry { String methodName; Class argumentClass; Class methodClass; public MethodEntry(String methodName, Class argumentClass, Class methodClass) { this.methodName = methodName; this.argumentClass = argumentClass; this.methodClass = methodClass; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MethodEntry that = (MethodEntry) o; if (!methodName.equals(that.methodName)) return false; if (!argumentClass.equals(that.argumentClass)) return false; return methodClass.equals(that.methodClass); } @Override public int hashCode() { int result = methodName.hashCode(); result = 31 * result + argumentClass.hashCode(); result = 31 * result + methodClass.hashCode(); return result; } } private static class MethodRecursiveSearch { private String methodName; private Class argumentClass; private Class orgMethodClass; public MethodRecursiveSearch(String methodName, Class argumentClass, Class methodClass) { this.methodName = methodName; this.argumentClass = argumentClass; this.orgMethodClass = methodClass; } public Method getMethod(final Class methodClass) { if (methodClass == null) { throw new NoSuchMethodExceptionRuntime( String.format("Method %s(%s) was not found in " + "%s and it's superclasses. " + "Ensure method argument type is exactly matching or " + ">>> use asString in annotation. <<< %s", methodName, String.valueOf(argumentClass), String.valueOf(orgMethodClass), argumentClass == CharSequence.class ? "CharSequence is default type, you need to change it." : "")); } MethodEntry entry = new MethodEntry(methodName, argumentClass, methodClass); return Cache.getCached(new Pair<>(MethodResolver.class, entry), new Cache.Supplier<Method>() { @Override public Method get() { Method meth; try { if (argumentClass == void.class) { meth = methodClass.getDeclaredMethod(methodName); } else { meth = methodClass.getDeclaredMethod(methodName, argumentClass); } } catch (NoSuchMethodException e) { meth = checkForMethodWithPrimitiveArgument(methodClass); if (meth == null) meth = getMethod(methodClass.getSuperclass()); } return meth; } }); } private Method checkForMethodWithPrimitiveArgument(Class methodClass) { if (PrimitiveToObjectConverter.hasPrimitive(argumentClass)) { try { return methodClass.getDeclaredMethod(methodName, PrimitiveToObjectConverter.getPrimitiveClass(argumentClass)); } catch (NoSuchMethodException e1) {} } return null; } } public static Method getMethodFor(String methodName, Class argumentClass, Class methodClass) { MethodRecursiveSearch mrs = new MethodRecursiveSearch(methodName, argumentClass, methodClass); return mrs.getMethod(methodClass); } /** Exception thrown when no method with given signature was found. May be caused by * misspell or wrong argument Class (ex. if CharSequence is expected String cannot * be directly passed.) */ public static class NoSuchMethodExceptionRuntime extends RuntimeException { public NoSuchMethodExceptionRuntime(String format) { super(format); } } public static Method getMethodAndCheckHeuristics(String methodName, Class argumentClass, Class methodClass) { Method meth; // @meth is a view method like EditText.getText(), value of item field / method // will be applied to it. try { meth = getMethodFor(methodName, argumentClass, methodClass); } catch (MethodResolver.NoSuchMethodExceptionRuntime e1) { // Heuristic, many Android Views methods that take text // takes CharSequence as argument. if (argumentClass == String.class) { meth = getMethodFor(methodName, CharSequence.class, methodClass); } else { // Another heuristic, because Integer.class != int.class we should check it... Class objectClass = PrimitiveToObjectConverter.getObjectClass(argumentClass); if (objectClass != argumentClass) { meth = getMethodFor(methodName, objectClass, methodClass); } else { throw e1; } } } return meth; } }
/* * 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.myfaces.shared.view; import java.io.IOException; import java.io.OutputStream; import javax.servlet.ServletOutputStream; /** * Delegates the standard OutputStream-methods (close, flush, write) * to the given ServletOutputStream, if the ResponseSwitch is enabled * * @author Werner Punz (latest modification by $Author: lu4242 $) * @author Jakob Korherr * @version $Revision: 1151650 $ $Date: 2011-07-27 17:14:17 -0500 (Wed, 27 Jul 2011) $ */ class SwitchableOutputStream extends ServletOutputStream { OutputStream _delegate = null; ResponseSwitch _responseSwitch = null; public SwitchableOutputStream(ServletOutputStream delegate, ResponseSwitch responseSwitch) { _delegate = delegate; _responseSwitch = responseSwitch; } @Override public void close() throws IOException { if (_responseSwitch.isEnabled()) { _delegate.close(); } } @Override public void flush() throws IOException { if (_responseSwitch.isEnabled()) { _delegate.flush(); } } @Override public void write(byte[] b, int off, int len) throws IOException { if (_responseSwitch.isEnabled()) { _delegate.write(b, off, len); } } @Override public void write(byte[] b) throws IOException { if (_responseSwitch.isEnabled()) { _delegate.write(b); } } @Override public void write(int b) throws IOException { if (_responseSwitch.isEnabled()) { _delegate.write(b); } } }
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package com.cloud.agent.api.routing; import com.cloud.agent.api.to.LoadBalancerTO; import com.cloud.agent.api.to.NicTO; /** * LoadBalancerConfigCommand sends the load balancer configuration */ public class HealthCheckLBConfigCommand extends NetworkElementCommand { LoadBalancerTO[] loadBalancers; protected HealthCheckLBConfigCommand() { } public HealthCheckLBConfigCommand(LoadBalancerTO[] loadBalancers) { this.loadBalancers = loadBalancers; } public LoadBalancerTO[] getLoadBalancers() { return loadBalancers; } }
/* * Copyright 1999-2019 Seata.io 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 io.seata.saga.engine.store; import io.seata.saga.proctrl.ProcessContext; import io.seata.saga.statelang.domain.StateInstance; import io.seata.saga.statelang.domain.StateMachineInstance; import java.util.List; /** * StateMachine engine log store * * @author lorne.cl */ public interface StateLogStore { /** * Record state machine startup events * @param machineInstance */ void recordStateMachineStarted(StateMachineInstance machineInstance, ProcessContext context); /** * Record status end event * @param machineInstance */ void recordStateMachineFinished(StateMachineInstance machineInstance, ProcessContext context); /** * Record state machine restarted * @param machineInstance */ void recordStateMachineRestarted(StateMachineInstance machineInstance, ProcessContext context); /** * Record state start execution event * @param stateInstance */ void recordStateStarted(StateInstance stateInstance, ProcessContext context); /** * Record state execution end event * @param stateInstance */ void recordStateFinished(StateInstance stateInstance, ProcessContext context); /** * Get state machine instance * @param stateMachineInstanceId * @return */ StateMachineInstance getStateMachineInstance(String stateMachineInstanceId); /** * Get state machine instance by businessKey * @param businessKey * @param tenantId * @return */ StateMachineInstance getStateMachineInstanceByBusinessKey(String businessKey, String tenantId); /** * Query the list of state machine instances by parent id * @param parentId * @return */ List<StateMachineInstance> queryStateMachineInstanceByParentId(String parentId); /** * Get state instance * @param stateInstanceId * @param machineInstId * @return */ StateInstance getStateInstance(String stateInstanceId, String machineInstId); /** * Get a list of state instances by state machine instance id * @param stateMachineInstanceId * @return */ List<StateInstance> queryStateInstanceListByMachineInstanceId(String stateMachineInstanceId); }
package fr.inria.spirals.repairnator; import com.martiansoftware.jsap.*; import fr.inria.spirals.repairnator.config.RepairnatorConfig; import fr.inria.spirals.repairnator.serializer.engines.SerializerEngine; import fr.inria.spirals.repairnator.serializer.engines.json.JSONFileSerializerEngine; import fr.inria.spirals.repairnator.serializer.engines.table.CSVSerializerEngine; import fr.inria.spirals.repairnator.states.LauncherMode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.ArrayList; import java.util.List; public class GitRepositoryLauncherUtils { private static final Logger LOGGER = LoggerFactory.getLogger(GitRepositoryLauncherUtils.class); public static void registerGitArgs(JSAP jsap) throws JSAPException { // --gitRepo jsap.registerParameter(GitRepositoryLauncherUtils.defineArgGitRepositoryMode()); // --gitRepoUrl jsap.registerParameter(GitRepositoryLauncherUtils.defineArgGitRepositoryUrl()); // --gitRepoBranch jsap.registerParameter(GitRepositoryLauncherUtils.defineArgGitRepositoryBranch()); // --gitRepoIdCommit jsap.registerParameter(GitRepositoryLauncherUtils.defineArgGitRepositoryIdCommit()); // --gitRepoFirstCommit jsap.registerParameter(GitRepositoryLauncherUtils.defineArgGitRepositoryFirstCommit()); } public static void initGitConfig(RepairnatorConfig config, JSAPResult arguments, JSAP jsap) { if (GitRepositoryLauncherUtils.getArgGitRepositoryMode(arguments)) { config.setLauncherMode(LauncherMode.GIT_REPOSITORY); if (GitRepositoryLauncherUtils.getArgGitRepositoryFirstCommit(arguments)) { config.setGitRepositoryFirstCommit(true); } } else { LOGGER.error("Parameter 'gitrepo' is required in GIT_REPOSITORY launcher mode."); LauncherUtils.printUsage(jsap, LauncherType.PIPELINE); } if (arguments.getString("gitRepositoryUrl") == null) { LOGGER.error("Parameter 'gitrepourl' is required in GIT_REPOSITORY launcher mode."); LauncherUtils.printUsage(jsap, LauncherType.PIPELINE); } if (config.isGitRepositoryFirstCommit() && arguments.getString("gitRepositoryIdCommit") != null) { LOGGER.error("Parameters 'gitrepofirstcommit' and 'gitrepoidcommit' cannot be used at the same time."); LauncherUtils.printUsage(jsap, LauncherType.PIPELINE); } config.setGitRepositoryUrl(GitRepositoryLauncherUtils.getArgGitRepositoryUrl(arguments)); config.setGitRepositoryBranch(GitRepositoryLauncherUtils.getArgGitRepositoryBranch(arguments)); config.setGitRepositoryIdCommit(GitRepositoryLauncherUtils.getArgGitRepositoryIdCommit(arguments)); } public static Switch defineArgGitRepositoryMode() { Switch sw = new Switch("gitRepo"); sw.setLongFlag("gitrepo"); sw.setDefault("false"); sw.setHelp("This mode allows to use Repairnator to analyze bugs present in a Git repository."); return sw; } public static boolean getArgGitRepositoryMode(JSAPResult arguments) { return arguments.getBoolean("gitRepo"); } public static FlaggedOption defineArgGitRepositoryUrl() { FlaggedOption opt = new FlaggedOption("gitRepositoryUrl"); opt.setLongFlag("gitrepourl"); opt.setStringParser(JSAP.STRING_PARSER); opt.setHelp("Specify a Git repository URL (only in GIT_REPOSITORY mode)."); return opt; } public static String getArgGitRepositoryUrl(JSAPResult arguments) { return arguments.getString("gitRepositoryUrl"); } public static FlaggedOption defineArgGitRepositoryBranch() { FlaggedOption opt = new FlaggedOption("gitRepositoryBranch"); opt.setLongFlag("gitrepobranch"); opt.setStringParser(JSAP.STRING_PARSER); opt.setHelp("Specify a branch of the given repository (only in GIT_REPOSITORY mode)"); return opt; } public static String getArgGitRepositoryBranch(JSAPResult arguments) { return arguments.getString("gitRepositoryBranch"); } public static FlaggedOption defineArgGitRepositoryIdCommit() { FlaggedOption opt = new FlaggedOption("gitRepositoryIdCommit"); opt.setLongFlag("gitrepoidcommit"); opt.setStringParser(JSAP.STRING_PARSER); opt.setHelp("Specify the commit id of the given repository (only in GIT_REPOSITORY mode)."); return opt; } public static String getArgGitRepositoryIdCommit(JSAPResult arguments) { return arguments.getString("gitRepositoryIdCommit"); } public static Switch defineArgGitRepositoryFirstCommit() { Switch sw = new Switch("gitRepositoryFirstCommit"); sw.setLongFlag("gitrepofirstcommit"); sw.setDefault("false"); sw.setHelp("Decides whether to clone the first commit of the specified branch (only in GIT_REPOSITORY mode)."); return sw; } public static boolean getArgGitRepositoryFirstCommit(JSAPResult arguments) { return arguments.getBoolean("gitRepositoryFirstCommit"); } public static List<SerializerEngine> initFileSerializerEngines(Logger logger) { List<SerializerEngine> fileSerializerEngines = new ArrayList<>(); RepairnatorConfig config = RepairnatorConfig.getInstance(); if (config.getOutputPath() != null) { logger.info("Initialize file serializer engines."); String path = config.getOutputPath(); if (config.getGitRepositoryId() != null) { path += File.separator + config.getGitRepositoryId(); } fileSerializerEngines.add(new CSVSerializerEngine(path)); fileSerializerEngines.add(new JSONFileSerializerEngine(path)); } else { logger.info("File serializers won't be used."); } return fileSerializerEngines; } }
package com.adahas.tools.jmxeval.model; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.text.StrLookup; import org.apache.commons.lang3.text.StrSubstitutor; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import com.adahas.tools.jmxeval.Context; import com.adahas.tools.jmxeval.exception.JMXEvalException; /** * AbstractElement implementation for configuration elements */ public class Element { /** * References to the child elements */ protected final List<Element> childElements = new ArrayList<>(); /** * Execution context. */ protected final Context context; /** * String substituter. */ private final StrSubstitutor substitutor; /** * Construct with the execution context. * * @param context Execution context */ protected Element(final Context context) { this.context = context; // Initialise string substituter for token replacement in variables this.substitutor = new StrSubstitutor(new StrLookup<String>() { @Override public String lookup(final String key) { final Object value = context.getVar(key); if (value == null) { return null; } else { return String.valueOf(value); } } }); this.substitutor.setEnableSubstitutionInVariables(true); } /** * Process method to be overridden to implement different behaviour, * and defaults to executing child element process() methods * * @throws JMXEvalException When processing fails */ public void process() throws JMXEvalException { for (Element element : childElements) { element.process(); } } /** * Adds a child element * * @param childElement adds a childElement */ protected void addChildElement(final Element childElement) { this.childElements.add(childElement); } /** * Create a Field. * * @param node Node to lookup the attribute on * @param attribute Attribute to look up * @param defaultValue Default value * @return the {@link Field} to get the node attribute */ public Field getNodeAttr(final Node node, final String attribute, final Field defaultValue) { return new NodeField(node, attribute, defaultValue); } /** * Create a Field. * * @param node Node to lookup the attribute on * @param attribute Attribute to look up * @param defaultValue Default value * @return the {@link Field} to get the node attribute */ public Field getNodeAttr(final Node node, final String attribute, final String defaultValue) { return new NodeField(node, attribute, new Literal(defaultValue)); } /** * Create a Field. * * @param node Node to lookup the attribute on * @param attribute Attribute to look up * @param defaultValue Default value * @return the {@link Field} to get the node attribute */ public Field getNodeAttr(final Node node, final String attribute) { return new NodeField(node, attribute, literal(null)); } /** * Create a Literal. * * @param value Literal value * @return the {@link Literal} to get the value */ public static Literal literal(final String value) { return new Literal(value); } /** * Create a Literal. * * @param value Literal value * @return the {@link Literal} to get the value */ public static Literal literalNull() { return new Literal(null); } /** * Value provider interface for {@link Field}. */ public abstract static class Field { /** * Get the field value. */ public abstract String get(); /** * @see java.lang.Object#toString() */ @Override public String toString() { return String.valueOf(get()); } } /** * Field of element where the value is calculated lazily. */ public class NodeField extends Field { private final Node node; private final String attribute; private final Field defaultValue; private NodeField(final Node node, final String attribute, final Field defaultValue) { super(); this.node = node; this.attribute = attribute; this.defaultValue = defaultValue; } /** * @see com.adahas.tools.jmxeval.model.Element.FieldValueProvider#get() */ @Override public String get() { final NamedNodeMap nodeAttributes = node.getAttributes(); final Node attributeNode = nodeAttributes.getNamedItem(attribute); String attributeValue = null; // Get the value of the attribute if (attributeNode != null) { attributeValue = attributeNode.getNodeValue(); } // If the value is null, set the default if (attributeValue == null) { attributeValue = defaultValue.get(); } // Replace any variables if (attributeValue != null) { attributeValue = substitutor.replace(attributeValue); } return attributeValue; } } /** * Literal value field. */ public static class Literal extends Field { private final String value; private Literal(final String value) { super(); this.value = value; } /** * @see com.adahas.tools.jmxeval.model.Element.Field#get() */ @Override public String get() { return value; } } }
package com.example.simpledriverassistant.Beans; import android.util.Log; import androidx.annotation.NonNull; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.SetOptions; public class User { private String email; private String uid; private String name; private Boolean online; private LocationUser locationUser; private int like; private int dislike; private Double rating; private final String TAG = User.class.getSimpleName(); private FirebaseUser user_google_information = FirebaseAuth.getInstance().getCurrentUser(); private FirebaseFirestore db = FirebaseFirestore.getInstance(); private DocumentReference documentReference; public User() { } public User(String email) { this.email = email; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public LocationUser getLocationUser() { return locationUser; } public void setLocationUser(LocationUser locationUser) { this.locationUser = locationUser; } public Boolean getOnline() { return online; } public void setOnline(Boolean online) { this.online = online; } public int getLike() { return like; } public void setLike(int like) { this.like = like; } public int getDislike() { return dislike; } public void setDislike(int unlike) { this.dislike = unlike; } public Double getRating() { return rating; } public void setRating(Double rating) { this.rating = rating; } public void userToString() { Log.d(TAG, "getEmail " + getEmail() + " getName " + getName() + " getUid " + getUid() + " getLike " + getLike() + " getDislike " + getDislike() + " getRating " + getRating() + " getOnline " + getOnline() + getLocationUser()); } public void userUpdate() { db.collection("users").document(getEmail()).set(this, SetOptions.merge()) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Log.d(TAG, "Dane zostały zapisane"); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.d(TAG, "Błąd w zapisnie danych: " + e.toString()); } }); userToString(); } public void userDownloadOnes() { documentReference = db.collection("users").document(getEmail()); documentReference.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() { @Override public void onSuccess(DocumentSnapshot documentSnapshot) { if (documentSnapshot.exists()) { User userDocument = documentSnapshot.toObject(User.class); setLike(userDocument.getLike()); setDislike(userDocument.getDislike()); } Log.d(TAG, "Dane zostały zapisane"); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.d(TAG, "Błąd w zapisnie danych: " + e.toString()); } }); } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.pinot.segment.local.realtime.impl.dictionary; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.apache.pinot.segment.local.io.writer.impl.DirectMemoryManager; import org.apache.pinot.segment.spi.memory.PinotDataBufferMemoryManager; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; public class OffHeapMutableBytesStoreTest { private static final int NUM_VALUES = 100_000; private static final int MAX_NUM_BYTES_PER_VALUE = 512; private static final long RANDOM_SEED = System.currentTimeMillis(); private static final Random RANDOM = new Random(RANDOM_SEED); private final PinotDataBufferMemoryManager _memoryManager = new DirectMemoryManager("testSegment"); private final byte[][] _values = new byte[NUM_VALUES][]; @BeforeClass public void setUp() { System.out.println("Random seed: " + RANDOM_SEED); for (int i = 0; i < NUM_VALUES; i++) { int numBytes = RANDOM.nextInt(MAX_NUM_BYTES_PER_VALUE); byte[] value = new byte[numBytes]; RANDOM.nextBytes(value); _values[i] = value; } } @Test public void testAdd() throws Exception { try (OffHeapMutableBytesStore offHeapMutableBytesStore = new OffHeapMutableBytesStore(_memoryManager, null)) { for (int i = 0; i < NUM_VALUES; i++) { Assert.assertEquals(offHeapMutableBytesStore.add(_values[i]), i); } } } @Test public void testGet() throws Exception { try (OffHeapMutableBytesStore offHeapMutableBytesStore = new OffHeapMutableBytesStore(_memoryManager, null)) { for (int i = 0; i < NUM_VALUES; i++) { offHeapMutableBytesStore.add(_values[i]); } for (int i = 0; i < NUM_VALUES; i++) { int index = RANDOM.nextInt(NUM_VALUES); assertTrue(Arrays.equals(offHeapMutableBytesStore.get(index), _values[index])); } } } @Test public void testEqualsValueAt() throws Exception { try (OffHeapMutableBytesStore offHeapMutableBytesStore = new OffHeapMutableBytesStore(_memoryManager, null)) { for (int i = 0; i < NUM_VALUES; i++) { offHeapMutableBytesStore.add(_values[i]); } for (int i = 0; i < NUM_VALUES; i++) { int index = RANDOM.nextInt(NUM_VALUES); assertTrue(offHeapMutableBytesStore.equalsValueAt(index, _values[index])); if (!Arrays.equals(_values[index], _values[0])) { assertFalse(offHeapMutableBytesStore.equalsValueAt(0, _values[index])); assertFalse(offHeapMutableBytesStore.equalsValueAt(index, _values[0])); } } } } @Test public void concurrentReadWrite() throws Exception { int numReaders = 4; ExecutorService executorService = Executors.newFixedThreadPool(numReaders + 1); List<Future> futures = new ArrayList<>(numReaders + 1); try (OffHeapMutableBytesStore offHeapMutableBytesStore = new OffHeapMutableBytesStore(_memoryManager, null)) { // Write one value before starting the reader threads offHeapMutableBytesStore.add(_values[0]); // Writer thread futures.add(executorService.submit(() -> { for (int i = 1; i < NUM_VALUES; i++) { offHeapMutableBytesStore.add(_values[i]); } })); // Reader threads for (int i = 0; i < numReaders; i++) { futures.add(executorService.submit(() -> { while (true) { int numValues = offHeapMutableBytesStore.getNumValues(); // Read at random index int index = RANDOM.nextInt(numValues); assertTrue(Arrays.equals(offHeapMutableBytesStore.get(index), _values[index])); // Read the last added value assertTrue(Arrays.equals(offHeapMutableBytesStore.get(numValues - 1), _values[numValues - 1])); // Stop after all values are added if (numValues == NUM_VALUES) { return; } } })); } executorService.shutdown(); for (Future future : futures) { future.get(); } } } }
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ package org.deeplearning4j.nn.modelimport.keras.e2e; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.apache.commons.io.FileUtils; import org.deeplearning4j.common.resources.DL4JResources; import org.deeplearning4j.eval.ROCMultiClass; import org.deeplearning4j.gradientcheck.GradientCheckUtil; import org.deeplearning4j.nn.api.Layer; import org.deeplearning4j.nn.api.layers.IOutputLayer; import org.deeplearning4j.nn.conf.ConvolutionMode; import org.deeplearning4j.nn.conf.layers.Convolution1DLayer; import org.deeplearning4j.nn.conf.layers.FeedForwardLayer; import org.deeplearning4j.nn.conf.layers.LossLayer; import org.deeplearning4j.nn.conf.layers.RnnOutputLayer; import org.deeplearning4j.nn.graph.ComputationGraph; import org.deeplearning4j.BaseDL4JTest; import org.deeplearning4j.nn.modelimport.keras.Hdf5Archive; import org.deeplearning4j.nn.modelimport.keras.KerasModel; import org.deeplearning4j.nn.modelimport.keras.KerasSequentialModel; import org.deeplearning4j.nn.modelimport.keras.utils.KerasModelBuilder; import org.deeplearning4j.nn.modelimport.keras.utils.KerasModelUtils; import org.deeplearning4j.nn.multilayer.MultiLayerNetwork; import org.deeplearning4j.nn.transferlearning.FineTuneConfiguration; import org.deeplearning4j.nn.transferlearning.TransferLearning; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.nd4j.linalg.activations.Activation; import org.nd4j.linalg.activations.IActivation; import org.nd4j.linalg.activations.impl.*; import org.nd4j.linalg.api.buffer.DataType; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.factory.Nd4j; import org.nd4j.linalg.function.BiFunction; import org.nd4j.linalg.function.Function; import org.nd4j.linalg.learning.config.NoOp; import org.nd4j.linalg.lossfunctions.LossFunctions; import org.nd4j.linalg.lossfunctions.impl.LossSparseMCXENT; import org.nd4j.resources.Resources; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.*; import static org.junit.Assert.*; /** * Unit tests for end-to-end Keras model import. * * @author dave@skymind.io, Max Pumperla */ @Slf4j public class KerasModelEndToEndTest extends BaseDL4JTest { private static final String GROUP_ATTR_INPUTS = "inputs"; private static final String GROUP_ATTR_OUTPUTS = "outputs"; private static final String GROUP_PREDICTIONS = "predictions"; private static final String GROUP_ACTIVATIONS = "activations"; private static final String TEMP_OUTPUTS_FILENAME = "tempOutputs"; private static final String TEMP_MODEL_FILENAME = "tempModel"; private static final String H5_EXTENSION = ".h5"; private static final double EPS = 1E-5; private static final boolean SKIP_GRAD_CHECKS = true; @Rule public final TemporaryFolder testDir = new TemporaryFolder(); @Override public long getTimeoutMilliseconds() { return 180000L; //Most benchmarks should run very quickly; large timeout is to avoid issues with unusually slow download of test resources } @Test(expected = IllegalStateException.class) public void fileNotFoundEndToEnd() throws Exception { String modelPath = "modelimport/keras/examples/foo/bar.h5"; importEndModelTest(modelPath, null, true, true, false, false); } /** * MNIST MLP tests */ @Test public void importMnistMlpTfKeras1() throws Exception { String modelPath = "modelimport/keras/examples/mnist_mlp/mnist_mlp_tf_keras_1_model.h5"; String inputsOutputPath = "modelimport/keras/examples/mnist_mlp/mnist_mlp_tf_keras_1_inputs_and_outputs.h5"; importEndModelTest(modelPath, inputsOutputPath, true, true, false, false); } @Test public void importMnistMlpThKeras1() throws Exception { String modelPath = "modelimport/keras/examples/mnist_mlp/mnist_mlp_th_keras_1_model.h5"; String inputsOutputPath = "modelimport/keras/examples/mnist_mlp/mnist_mlp_th_keras_1_inputs_and_outputs.h5"; importEndModelTest(modelPath, inputsOutputPath, false, true, false, false); } @Test public void importMnistMlpTfKeras2() throws Exception { String modelPath = "modelimport/keras/examples/mnist_mlp/mnist_mlp_tf_keras_2_model.h5"; String inputsOutputPath = "modelimport/keras/examples/mnist_mlp/mnist_mlp_tf_keras_2_inputs_and_outputs.h5"; importEndModelTest(modelPath, inputsOutputPath, true, true, false, false); } @Test public void importMnistMlpReshapeTfKeras1() throws Exception { String modelPath = "modelimport/keras/examples/mnist_mlp_reshape/mnist_mlp_reshape_tf_keras_1_model.h5"; String inputsOutputPath = "modelimport/keras/examples/mnist_mlp_reshape/mnist_mlp_reshape_tf_keras_1_inputs_and_outputs.h5"; importEndModelTest(modelPath, inputsOutputPath, true, true, true, false); } /** * MNIST CNN tests */ @Test public void importMnistCnnTfKeras1() throws Exception { String modelPath = "modelimport/keras/examples/mnist_cnn/mnist_cnn_tf_keras_1_model.h5"; String inputsOutputPath = "modelimport/keras/examples/mnist_cnn/mnist_cnn_tf_keras_1_inputs_and_outputs.h5"; importEndModelTest(modelPath, inputsOutputPath, true, false, false, false); } @Test public void importMnistCnnThKeras1() throws Exception { String modelPath = "modelimport/keras/examples/mnist_cnn/mnist_cnn_th_keras_1_model.h5"; String inputsOutputPath = "modelimport/keras/examples/mnist_cnn/mnist_cnn_th_keras_1_inputs_and_outputs.h5"; importEndModelTest(modelPath, inputsOutputPath, false, true, true, false); } @Test public void importMnistCnnTfKeras2() throws Exception { String modelPath = "modelimport/keras/examples/mnist_cnn/mnist_cnn_tf_keras_2_model.h5"; String inputsOutputPath = "modelimport/keras/examples/mnist_cnn/mnist_cnn_tf_keras_2_inputs_and_outputs.h5"; importEndModelTest(modelPath, inputsOutputPath, true, true, true, false); } /** * IMDB Embedding and LSTM test */ @Test public void importImdbLstmTfKeras1() throws Exception { String modelPath = "modelimport/keras/examples/imdb_lstm/imdb_lstm_tf_keras_1_model.h5"; String inputsOutputPath = "modelimport/keras/examples/imdb_lstm/imdb_lstm_tf_keras_1_inputs_and_outputs.h5"; importEndModelTest(modelPath, inputsOutputPath, true, true, false, false, true, null, null); } @Test public void importImdbLstmThKeras1() throws Exception { String modelPath = "modelimport/keras/examples/imdb_lstm/imdb_lstm_th_keras_1_model.h5"; String inputsOutputPath = "modelimport/keras/examples/imdb_lstm/imdb_lstm_th_keras_1_inputs_and_outputs.h5"; importEndModelTest(modelPath, inputsOutputPath, true, true, false, false, true, null, null); } @Test public void importImdbLstmTfKeras2() throws Exception { String modelPath = "modelimport/keras/examples/imdb_lstm/imdb_lstm_tf_keras_2_model.h5"; String inputsOutputPath = "modelimport/keras/examples/imdb_lstm/imdb_lstm_tf_keras_2_inputs_and_outputs.h5"; importEndModelTest(modelPath, inputsOutputPath, true, true, false, false, true, null, null); } @Test public void importImdbLstmThKeras2() throws Exception { String modelPath = "modelimport/keras/examples/imdb_lstm/imdb_lstm_th_keras_2_model.h5"; String inputsOutputPath = "modelimport/keras/examples/imdb_lstm/imdb_lstm_th_keras_2_inputs_and_outputs.h5"; importEndModelTest(modelPath, inputsOutputPath, false, true, false, false, true, null, null); } /** * IMDB LSTM fasttext */ // TODO: prediction checks fail due to globalpooling for fasttext, very few grads fail as well @Test public void importImdbFasttextTfKeras1() throws Exception { String modelPath = "modelimport/keras/examples/imdb_fasttext/imdb_fasttext_tf_keras_1_model.h5"; String inputsOutputPath = "modelimport/keras/examples/imdb_fasttext/imdb_fasttext_tf_keras_1_inputs_and_outputs.h5"; importEndModelTest(modelPath, inputsOutputPath, false, false, false, false); } @Test public void importImdbFasttextThKeras1() throws Exception { String modelPath = "modelimport/keras/examples/imdb_fasttext/imdb_fasttext_th_keras_1_model.h5"; String inputsOutputPath = "modelimport/keras/examples/imdb_fasttext/imdb_fasttext_th_keras_1_inputs_and_outputs.h5"; importEndModelTest(modelPath, inputsOutputPath, false, false, false, false); } @Test public void importImdbFasttextTfKeras2() throws Exception { String modelPath = "modelimport/keras/examples/imdb_fasttext/imdb_fasttext_tf_keras_2_model.h5"; String inputsOutputPath = "modelimport/keras/examples/imdb_fasttext/imdb_fasttext_tf_keras_2_inputs_and_outputs.h5"; importEndModelTest(modelPath, inputsOutputPath, true, false, false, false); } /** * Simple LSTM (return sequences = false) into Dense layer test */ @Test public void importSimpleLstmTfKeras1() throws Exception { String modelPath = "modelimport/keras/examples/simple_lstm/simple_lstm_tf_keras_1_model.h5"; String inputsOutputPath = "modelimport/keras/examples/simple_lstm/simple_lstm_tf_keras_1_inputs_and_outputs.h5"; importEndModelTest(modelPath, inputsOutputPath, true, true, false, false); } @Test public void importSimpleLstmThKeras1() throws Exception { String modelPath = "modelimport/keras/examples/simple_lstm/simple_lstm_th_keras_1_model.h5"; String inputsOutputPath = "modelimport/keras/examples/simple_lstm/simple_lstm_th_keras_1_inputs_and_outputs.h5"; importEndModelTest(modelPath, inputsOutputPath, true, true, false, false); } @Test public void importSimpleLstmTfKeras2() throws Exception { String modelPath = "modelimport/keras/examples/simple_lstm/simple_lstm_tf_keras_2_model.h5"; String inputsOutputPath = "modelimport/keras/examples/simple_lstm/simple_lstm_tf_keras_2_inputs_and_outputs.h5"; importEndModelTest(modelPath, inputsOutputPath, true, false, false, false); } /** * Simple LSTM (return sequences = true) into flatten into Dense layer test */ @Test public void importSimpleFlattenLstmTfKeras2() throws Exception { String modelPath = "modelimport/keras/examples/simple_flatten_lstm/simple_flatten_lstm_tf_keras_2_model.h5"; String inputsOutputPath = "modelimport/keras/examples/simple_flatten_lstm/" + "simple_flatten_lstm_tf_keras_2_inputs_and_outputs.h5"; importEndModelTest(modelPath, inputsOutputPath, true, true, false, false); } /** * Simple RNN (return sequences = true) into flatten into Dense layer test */ @Test public void importSimpleFlattenRnnTfKeras2() throws Exception { String modelPath = "modelimport/keras/examples/simple_flatten_rnn/simple_flatten_rnn_tf_keras_2_model.h5"; String inputsOutputPath = "modelimport/keras/examples/simple_flatten_rnn/" + "simple_flatten_rnn_tf_keras_2_inputs_and_outputs.h5"; importEndModelTest(modelPath, inputsOutputPath, true, true, false, false, true, null, null); } /** * Simple RNN (return sequences = false) into Dense layer test */ @Test public void importSimpleRnnTfKeras2() throws Exception { String modelPath = "modelimport/keras/examples/simple_rnn/simple_rnn_tf_keras_2_model.h5"; String inputsOutputPath = "modelimport/keras/examples/simple_rnn/" + "simple_rnn_tf_keras_2_inputs_and_outputs.h5"; importEndModelTest(modelPath, inputsOutputPath, true, true, false, false); } /** * CNN without bias test */ @Test public void importCnnNoBiasTfKeras2() throws Exception { String modelPath = "modelimport/keras/examples/cnn_no_bias/mnist_cnn_no_bias_tf_keras_2_model.h5"; String inputsOutputPath = "modelimport/keras/examples/cnn_no_bias/mnist_cnn_no_bias_tf_keras_2_inputs_and_outputs.h5"; importEndModelTest(modelPath, inputsOutputPath, true, true, true, false); } @Test public void importSparseXent() throws Exception { String modelPath = "modelimport/keras/examples/simple_sparse_xent/simple_sparse_xent_mlp_keras_2_model.h5"; String inputsOutputPath = "modelimport/keras/examples/simple_sparse_xent/simple_sparse_xent_mlp_keras_2_inputs_and_outputs.h5"; MultiLayerNetwork net = importEndModelTest(modelPath, inputsOutputPath, true, true, true, true); Layer outLayer = net.getOutputLayer(); assertTrue(outLayer instanceof org.deeplearning4j.nn.layers.LossLayer); LossLayer llConf = (LossLayer) outLayer.getConfig(); assertEquals(new LossSparseMCXENT(), llConf.getLossFn()); } /** * GAN import tests */ @Test public void importDcganMnistDiscriminator() throws Exception { importSequentialModelH5Test("modelimport/keras/examples/mnist_dcgan/dcgan_discriminator_epoch_50.h5"); } @Test public void importDcganMnistGenerator() throws Exception { importSequentialModelH5Test("modelimport/keras/examples/mnist_dcgan/dcgan_generator_epoch_50.h5"); } /** * Auxillary classifier GAN import test */ @Test public void importAcganDiscriminator() throws Exception { ComputationGraph model = importFunctionalModelH5Test("modelimport/keras/examples/acgan/acgan_discriminator_1_epochs.h5"); INDArray input = Nd4j.create(10, 28, 28, 1); //NHWC INDArray[] output = model.output(input); } @Test @Ignore //AB 2020/04/22 Ignored until Keras model import updated to use NHWC support public void importAcganGenerator() throws Exception { ComputationGraph model = importFunctionalModelH5Test("modelimport/keras/examples/acgan/acgan_generator_1_epochs.h5"); //System.out.println(model.summary()) ; INDArray latent = Nd4j.create(10, 100); INDArray label = Nd4j.create(10, 1); INDArray[] output = model.output(latent, label); } @Test public void importAcganCombined() throws Exception { ComputationGraph model = importFunctionalModelH5Test("modelimport/keras/examples/acgan/acgan_combined_1_epochs.h5"); // TODO: imports, but incorrectly. Has only one input, should have two. } /** * Deep convolutional GAN import test */ @Test public void importDcganDiscriminator() throws Exception { importSequentialModelH5Test("modelimport/keras/examples/gans/dcgan_discriminator.h5"); } @Test public void importDcganGenerator() throws Exception { importSequentialModelH5Test("modelimport/keras/examples/gans/dcgan_generator.h5"); } /** * Wasserstein GAN import test */ @Test public void importWganDiscriminator() throws Exception { for (int i = 0; i < 100; i++) { // run a few times to make sure HDF5 doesn't crash importSequentialModelH5Test("modelimport/keras/examples/gans/wgan_discriminator.h5"); } } @Test public void importWganGenerator() throws Exception { importSequentialModelH5Test("modelimport/keras/examples/gans/wgan_generator.h5"); } @Test public void importCnn1d() throws Exception { importSequentialModelH5Test("modelimport/keras/examples/cnn1d/cnn1d_flatten_tf_keras2.h5"); } /** * DGA classifier test */ @Test public void importDgaClassifier() throws Exception { importSequentialModelH5Test("modelimport/keras/examples/dga_classifier/keras2_dga_classifier_tf_model.h5"); } /** * Reshape flat input into 3D to fit into an LSTM model */ @Test public void importFlatIntoLSTM() throws Exception { importFunctionalModelH5Test("modelimport/keras/examples/reshape_to_rnn/reshape_model.h5"); } /** * Functional LSTM test */ @Test public void importFunctionalLstmTfKeras2() throws Exception { String modelPath = "modelimport/keras/examples/functional_lstm/lstm_functional_tf_keras_2.h5"; // No training enabled ComputationGraph graphNoTrain = importFunctionalModelH5Test(modelPath, null, false); System.out.println(graphNoTrain.summary()); // Training enabled ComputationGraph graph = importFunctionalModelH5Test(modelPath, null, true); System.out.println(graph.summary()); // Make predictions int miniBatch = 32; INDArray input = Nd4j.ones(miniBatch, 10, 4); //NWC format - with nIn=4, seqLength = 10 INDArray[] out = graph.output(input); // Fit model graph.fit(new INDArray[]{input}, out); } /** * U-Net */ @Test public void importUnetTfKeras2() throws Exception { importFunctionalModelH5Test( "modelimport/keras/examples/unet/unet_keras_2_tf.h5", null, true); } /** * ResNet50 */ @Test public void importResnet50() throws Exception { importFunctionalModelH5Test("modelimport/keras/examples/resnet/resnet50_weights_tf_dim_ordering_tf_kernels.h5"); } /** * DenseNet */ @Test public void importDenseNet() throws Exception { importFunctionalModelH5Test("modelimport/keras/examples/densenet/densenet121_tf_keras_2.h5"); } /** * SqueezeNet */ @Test public void importSqueezeNet() throws Exception { importFunctionalModelH5Test("modelimport/keras/examples/squeezenet/squeezenet.h5"); } /** * MobileNet */ @Test public void importMobileNet() throws Exception { ComputationGraph graph = importFunctionalModelH5Test("modelimport/keras/examples/mobilenet/alternative.hdf5"); INDArray input = Nd4j.ones(10, 299, 299, 3); graph.output(input); } /** * InceptionV3 Keras 2 no top */ @Test public void importInceptionKeras2() throws Exception { int[] inputShape = new int[]{299, 299, 3}; ComputationGraph graph = importFunctionalModelH5Test( "modelimport/keras/examples/inception/inception_tf_keras_2.h5", inputShape, false); INDArray input = Nd4j.ones(10, 299, 299, 3); //TF = channels last = NHWC graph.output(input); System.out.println(graph.summary()); } /** * InceptionV3 */ @Test @Ignore // Takes unreasonably long, but works public void importInception() throws Exception { ComputationGraph graph = importFunctionalModelH5Test( "modelimport/keras/examples/inception/inception_v3_complete.h5"); INDArray input = Nd4j.ones(10, 299, 299, 3); //TF = channels last = NHWC graph.output(input); System.out.println(graph.summary()); } /** * Inception V4 */ @Test @Ignore // Model and weights have about 170mb, too large for test resources and also too excessive to enable as unit test public void importInceptionV4() throws Exception { String modelUrl = DL4JResources.getURLString( "models/inceptionv4_keras_imagenet_weightsandconfig.h5"); File kerasFile = testDir.newFile("inceptionv4_keras_imagenet_weightsandconfig.h5"); if (!kerasFile.exists()) { FileUtils.copyURLToFile(new URL(modelUrl), kerasFile); kerasFile.deleteOnExit(); } int[] inputShape = new int[]{299, 299, 3}; ComputationGraph graph = importFunctionalModelH5Test( kerasFile.getAbsolutePath(), inputShape, false); // System.out.println(graph.summary()); } /** * Xception */ @Test public void importXception() throws Exception { int[] inputShape = new int[]{299, 299, 3}; ComputationGraph graph = importFunctionalModelH5Test( "modelimport/keras/examples/xception/xception_tf_keras_2.h5", inputShape, false); } /** * Seq2seq model */ @Test @Ignore // does not work yet, needs DL4J enhancements public void importSeq2Seq() throws Exception { importFunctionalModelH5Test("modelimport/keras/examples/seq2seq/full_model_seq2seq_5549.h5"); } /** * Import all AlphaGo Zero model variants, i.e. * - Dual residual architecture * - Dual convolutional architecture * - Separate (policy and value) residual architecture * - Separate (policy and value) convolutional architecture */ @Test @Ignore //AB 20200427 Bad keras model - Keras JSON has input shape [null, 10, 19, 19] (i.e., NCHW) but all layers are set to channels_last public void importSepConvPolicy() throws Exception { ComputationGraph model = importFunctionalModelH5Test("modelimport/keras/examples/agz/sep_conv_policy.h5"); INDArray input = Nd4j.create(32, 19, 19, 10); model.output(input); } @Test @Ignore //AB 20200427 Bad keras model - Keras JSON has input shape [null, 10, 19, 19] (i.e., NCHW) but all layers are set to channels_last public void importSepResPolicy() throws Exception { ComputationGraph model = importFunctionalModelH5Test("modelimport/keras/examples/agz/sep_res_policy.h5"); INDArray input = Nd4j.create(32, 19, 19, 10); model.output(input); } @Test @Ignore //AB 20200427 Bad keras model - Keras JSON has input shape [null, 10, 19, 19] (i.e., NCHW) but all layers are set to channels_last public void importSepConvValue() throws Exception { ComputationGraph model = importFunctionalModelH5Test("modelimport/keras/examples/agz/sep_conv_value.h5"); INDArray input = Nd4j.create(32, 19, 19, 10); model.output(input); } @Test @Ignore //AB 20200427 Bad keras model - Keras JSON has input shape [null, 10, 19, 19] (i.e., NCHW) but all layers are set to channels_last public void importSepResValue() throws Exception { ComputationGraph model = importFunctionalModelH5Test("modelimport/keras/examples/agz/sep_res_value.h5"); INDArray input = Nd4j.create(32, 19, 19, 10); model.output(input); } @Test @Ignore //AB 20200427 Bad keras model - Keras JSON has input shape [null, 10, 19, 19] (i.e., NCHW) but all layers are set to channels_last public void importDualRes() throws Exception { ComputationGraph model = importFunctionalModelH5Test("modelimport/keras/examples/agz/dual_res.h5"); INDArray input = Nd4j.create(32, 19, 19, 10); model.output(input); } @Test @Ignore //AB 20200427 Bad keras model - Keras JSON has input shape [null, 10, 19, 19] (i.e., NCHW) but all layers are set to channels_last public void importDualConv() throws Exception { ComputationGraph model = importFunctionalModelH5Test("modelimport/keras/examples/agz/dual_conv.h5"); INDArray input = Nd4j.create(32, 19, 19, 10); model.output(input); } /** * MTCNN */ @Test public void importMTCNN() throws Exception { ComputationGraph model = importFunctionalModelH5Test("modelimport/keras/examples/48net_complete.h5"); } @Test @Ignore // TODO: fails, since we can't use OldSoftMax on >2D data (here: convolution layer) // TODO: also related to #6339, fix this together public void importMTCNN2D() throws Exception { ComputationGraph model = importFunctionalModelH5Test("modelimport/keras/examples/12net.h5", new int[] {24, 24, 3}, false); INDArray input = Nd4j.create(10, 3, 24, 24); model.output(input); // System.out.println(model.summary()); } /** * Masking layers (simple Masking into LSTM) */ @Test public void testMaskingZeroValue() throws Exception { MultiLayerNetwork model = importSequentialModelH5Test( "modelimport/keras/examples/masking/masking_zero_lstm.h5"); model.summary(); } @Test public void testMaskingTwoValue() throws Exception { MultiLayerNetwork model = importSequentialModelH5Test( "modelimport/keras/examples/masking/masking_two_lstm.h5"); model.summary(); } @Test public void testCausalCon1D() throws Exception { String[] names = new String[]{ "causal_conv1d_k2_s1_d1_cl_model.h5", "causal_conv1d_k2_s1_d2_cl_model.h5", "causal_conv1d_k2_s2_d1_cl_model.h5", "causal_conv1d_k2_s3_d1_cl_model.h5", "causal_conv1d_k3_s1_d1_cl_model.h5", "causal_conv1d_k3_s1_d2_cl_model.h5", "causal_conv1d_k3_s2_d1_cl_model.h5", "causal_conv1d_k3_s3_d1_cl_model.h5", "causal_conv1d_k4_s1_d1_cl_model.h5", "causal_conv1d_k4_s1_d2_cl_model.h5", "causal_conv1d_k4_s2_d1_cl_model.h5", "causal_conv1d_k4_s3_d1_cl_model.h5" }; for(String name : names ){ System.out.println("Starting test: " + name); String modelPath = "modelimport/keras/examples/causal_conv1d/" + name; String inputsOutputPath = "modelimport/keras/examples/causal_conv1d/" + (name.substring(0,name.length()-"model.h5".length()) + "inputs_and_outputs.h5"); MultiLayerNetwork net = importEndModelTest(modelPath, inputsOutputPath, true, true, true, true, false, null, null); Layer l = net.getLayer(0); Convolution1DLayer c1d = (Convolution1DLayer) l.getConfig(); assertEquals(ConvolutionMode.Causal, c1d.getConvolutionMode()); } } @Test public void testCon1D() throws Exception { String[] names = new String[]{ "conv1d_k2_s1_d1_cf_same_model.h5", "conv1d_k2_s1_d1_cf_valid_model.h5", "conv1d_k2_s1_d1_cl_same_model.h5", "conv1d_k2_s1_d1_cl_valid_model.h5", "conv1d_k2_s1_d2_cf_same_model.h5", "conv1d_k2_s1_d2_cf_valid_model.h5", "conv1d_k2_s1_d2_cl_same_model.h5", "conv1d_k2_s1_d2_cl_valid_model.h5", "conv1d_k2_s2_d1_cf_same_model.h5", "conv1d_k2_s2_d1_cf_valid_model.h5", "conv1d_k2_s2_d1_cl_same_model.h5", "conv1d_k2_s2_d1_cl_valid_model.h5", "conv1d_k2_s3_d1_cf_same_model.h5", "conv1d_k2_s3_d1_cf_valid_model.h5", "conv1d_k2_s3_d1_cl_same_model.h5", "conv1d_k2_s3_d1_cl_valid_model.h5", "conv1d_k3_s1_d1_cf_same_model.h5", "conv1d_k3_s1_d1_cf_valid_model.h5", "conv1d_k3_s1_d1_cl_same_model.h5", "conv1d_k3_s1_d1_cl_valid_model.h5", "conv1d_k3_s1_d2_cf_same_model.h5", "conv1d_k3_s1_d2_cf_valid_model.h5", "conv1d_k3_s1_d2_cl_same_model.h5", "conv1d_k3_s1_d2_cl_valid_model.h5", "conv1d_k3_s2_d1_cf_same_model.h5", "conv1d_k3_s2_d1_cf_valid_model.h5", "conv1d_k3_s2_d1_cl_same_model.h5", "conv1d_k3_s2_d1_cl_valid_model.h5", "conv1d_k3_s3_d1_cf_same_model.h5", "conv1d_k3_s3_d1_cf_valid_model.h5", "conv1d_k3_s3_d1_cl_same_model.h5", "conv1d_k3_s3_d1_cl_valid_model.h5", "conv1d_k4_s1_d1_cf_same_model.h5", "conv1d_k4_s1_d1_cf_valid_model.h5", "conv1d_k4_s1_d1_cl_same_model.h5", "conv1d_k4_s1_d1_cl_valid_model.h5", "conv1d_k4_s1_d2_cf_same_model.h5", "conv1d_k4_s1_d2_cf_valid_model.h5", "conv1d_k4_s1_d2_cl_same_model.h5", "conv1d_k4_s1_d2_cl_valid_model.h5", "conv1d_k4_s2_d1_cf_same_model.h5", "conv1d_k4_s2_d1_cf_valid_model.h5", "conv1d_k4_s2_d1_cl_same_model.h5", "conv1d_k4_s2_d1_cl_valid_model.h5", "conv1d_k4_s3_d1_cf_same_model.h5", "conv1d_k4_s3_d1_cf_valid_model.h5", "conv1d_k4_s3_d1_cl_same_model.h5", "conv1d_k4_s3_d1_cl_valid_model.h5", }; for(String name : names ){ System.out.println("Starting test: " + name); String modelPath = "modelimport/keras/examples/conv1d/" + name; String inputsOutputPath = "modelimport/keras/examples/conv1d/" + (name.substring(0,name.length()-"model.h5".length()) + "inputs_and_outputs.h5"); importEndModelTest(modelPath, inputsOutputPath, true, true, true, true, false, null, null); //f, f2); } } @Test public void testActivationLayers() throws Exception { String[] names = new String[]{ "ELU_0_model.h5", "LeakyReLU_0_model.h5", "ReLU_0_model.h5", "ReLU_1_model.h5", "ReLU_2_model.h5", "ReLU_3_model.h5", "Softmax_0_model.h5", "ThresholdReLU_0_model.h5", }; for(String name : names ){ System.out.println("Starting test: " + name); String modelPath = "modelimport/keras/examples/activations/" + name; String inputsOutputPath = "modelimport/keras/examples/activations/" + (name.substring(0,name.length()-"model.h5".length()) + "inputs_and_outputs.h5"); importEndModelTest(modelPath, inputsOutputPath, true, true, true, true, false, null, null); } } private ComputationGraph importFunctionalModelH5Test(String modelPath) throws Exception { return importFunctionalModelH5Test(modelPath, null, false); } private ComputationGraph importFunctionalModelH5Test(String modelPath, int[] inputShape, boolean train) throws Exception { File modelFile; try(InputStream is = Resources.asStream(modelPath)) { modelFile = createTempFile(TEMP_MODEL_FILENAME, H5_EXTENSION); Files.copy(is, modelFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } KerasModelBuilder builder = new KerasModel().modelBuilder().modelHdf5Filename(modelFile.getAbsolutePath()) .enforceTrainingConfig(train); if (inputShape != null) { builder.inputShape(inputShape); } KerasModel model = builder.buildModel(); return model.getComputationGraph(); } private MultiLayerNetwork importSequentialModelH5Test(String modelPath) throws Exception { return importSequentialModelH5Test(modelPath, null); } private MultiLayerNetwork importSequentialModelH5Test(String modelPath, int[] inputShape) throws Exception { try(InputStream is = Resources.asStream(modelPath)) { File modelFile = createTempFile(TEMP_MODEL_FILENAME, H5_EXTENSION); Files.copy(is, modelFile.toPath(), StandardCopyOption.REPLACE_EXISTING); KerasModelBuilder builder = new KerasModel().modelBuilder().modelHdf5Filename(modelFile.getAbsolutePath()) .enforceTrainingConfig(false); if (inputShape != null) { builder.inputShape(inputShape); } KerasSequentialModel model = builder.buildSequential(); return model.getMultiLayerNetwork(); } } public MultiLayerNetwork importEndModelTest(String modelPath, String inputsOutputsPath, boolean tfOrdering, boolean checkPredictions, boolean checkGradients, boolean enforceTrainingConfig) throws Exception { return importEndModelTest(modelPath, inputsOutputsPath, tfOrdering, checkPredictions, checkGradients, true, enforceTrainingConfig, null, null); } public MultiLayerNetwork importEndModelTest(String modelPath, String inputsOutputsPath, boolean tfOrdering, boolean checkPredictions, boolean checkGradients, boolean enforceTrainingConfig, boolean checkAuc, Function<INDArray,INDArray> inputPreProc, BiFunction<String,INDArray,INDArray> expectedPreProc) throws Exception { MultiLayerNetwork model; try(InputStream is = Resources.asStream(modelPath)) { File modelFile = createTempFile(TEMP_MODEL_FILENAME, H5_EXTENSION); Files.copy(is, modelFile.toPath(), StandardCopyOption.REPLACE_EXISTING); KerasSequentialModel kerasModel = new KerasModel().modelBuilder().modelHdf5Filename(modelFile.getAbsolutePath()) .enforceTrainingConfig(enforceTrainingConfig).buildSequential(); model = kerasModel.getMultiLayerNetwork(); } File outputsFile = createTempFile(TEMP_OUTPUTS_FILENAME, H5_EXTENSION); try(InputStream is = Resources.asStream(inputsOutputsPath)) { Files.copy(is, outputsFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } try (Hdf5Archive outputsArchive = new Hdf5Archive(outputsFile.getAbsolutePath())) { if (checkPredictions) { INDArray input = getInputs(outputsArchive, tfOrdering)[0]; if(inputPreProc != null) input = inputPreProc.apply(input); Map<String, INDArray> activationsKeras = getActivations(outputsArchive, tfOrdering); for (int i = 0; i < model.getLayers().length; i++) { String layerName = model.getLayerNames().get(i); if (activationsKeras.containsKey(layerName)) { INDArray activationsDl4j = model.feedForwardToLayer(i, input, false).get(i + 1); INDArray exp = activationsKeras.get(layerName); if(expectedPreProc != null) exp = expectedPreProc.apply(layerName, exp); compareINDArrays(layerName, exp, activationsDl4j, EPS); } } INDArray predictionsKeras = getPredictions(outputsArchive, tfOrdering)[0]; INDArray predictionsDl4j = model.output(input, false); if(expectedPreProc != null) predictionsKeras = expectedPreProc.apply("output", predictionsKeras); compareINDArrays("predictions", predictionsKeras, predictionsDl4j, EPS); INDArray outputs = getOutputs(outputsArchive, true)[0]; if(outputs.rank() == 1){ outputs = outputs.reshape(outputs.length(), 1); } val nOut = (int) outputs.size(-1); if(checkAuc) compareMulticlassAUC("predictions", outputs, predictionsKeras, predictionsDl4j, nOut, EPS); } if (checkGradients && ! SKIP_GRAD_CHECKS) { Random r = new Random(12345); INDArray input = getInputs(outputsArchive, tfOrdering)[0]; INDArray predictionsDl4j = model.output(input, false); //Infer one-hot labels... this probably won't work for all INDArray testLabels = Nd4j.create(predictionsDl4j.shape()); if (testLabels.rank() == 2) { for (int i = 0; i < testLabels.size(0); i++) { testLabels.putScalar(i, r.nextInt((int) testLabels.size(1)), 1.0); } } else if (testLabels.rank() == 3) { for (int i = 0; i < testLabels.size(0); i++) { for (int j = 0; j < testLabels.size(1); j++) { testLabels.putScalar(i, j, r.nextInt((int) testLabels.size(1)), 1.0); } } } else { throw new RuntimeException("Cannot gradient check 4d output array"); } checkGradients(model, input, testLabels); } } return model; } private static INDArray[] getInputs(Hdf5Archive archive, boolean tensorFlowImageDimOrdering) throws Exception { List<String> inputNames = (List<String>) KerasModelUtils .parseJsonString(archive.readAttributeAsJson(GROUP_ATTR_INPUTS)).get(GROUP_ATTR_INPUTS); INDArray[] inputs = new INDArray[inputNames.size()]; for (int i = 0; i < inputNames.size(); i++) { inputs[i] = archive.readDataSet(inputNames.get(i), GROUP_ATTR_INPUTS); } return inputs; } private static Map<String, INDArray> getActivations(Hdf5Archive archive, boolean tensorFlowImageDimOrdering) throws Exception { Map<String, INDArray> activations = new HashMap<String, INDArray>(); for (String layerName : archive.getDataSets(GROUP_ACTIVATIONS)) { INDArray activation = archive.readDataSet(layerName, GROUP_ACTIVATIONS); activations.put(layerName, activation); } return activations; } private static INDArray[] getOutputs(Hdf5Archive archive, boolean tensorFlowImageDimOrdering) throws Exception { List<String> outputNames = (List<String>) KerasModelUtils .parseJsonString(archive.readAttributeAsJson(GROUP_ATTR_OUTPUTS)).get(GROUP_ATTR_OUTPUTS); INDArray[] outputs = new INDArray[outputNames.size()]; for (int i = 0; i < outputNames.size(); i++) { outputs[i] = archive.readDataSet(outputNames.get(i), GROUP_ATTR_OUTPUTS); } return outputs; } private static INDArray[] getPredictions(Hdf5Archive archive, boolean tensorFlowImageDimOrdering) throws Exception { List<String> outputNames = (List<String>) KerasModelUtils .parseJsonString(archive.readAttributeAsJson(GROUP_ATTR_OUTPUTS)).get(GROUP_ATTR_OUTPUTS); INDArray[] predictions = new INDArray[outputNames.size()]; for (int i = 0; i < outputNames.size(); i++) { predictions[i] = archive.readDataSet(outputNames.get(i), GROUP_PREDICTIONS); } return predictions; } private static void compareINDArrays(String label, INDArray expected, INDArray actual, double eps) { if(!expected.equalShapes(actual)){ throw new IllegalStateException("Shapes do not match for \"" + label + "\": got " + Arrays.toString(expected.shape()) + " vs " + Arrays.toString(actual.shape())); } INDArray diff = expected.sub(actual.castTo(expected.dataType())); double min = diff.minNumber().doubleValue(); double max = diff.maxNumber().doubleValue(); log.info(label + ": " + expected.equalsWithEps(actual, eps) + ", " + min + ", " + max); double threshold = 1e-7; double aAbsMax = Math.max(Math.abs(expected.minNumber().doubleValue()), Math.abs(expected.maxNumber().doubleValue())); double bAbsMax = Math.max(Math.abs(actual.minNumber().doubleValue()), Math.abs(actual.maxNumber().doubleValue())); // skip too small absolute inputs if (Math.abs(aAbsMax) > threshold && Math.abs(bAbsMax) > threshold) { boolean eq = expected.equalsWithEps(actual.castTo(expected.dataType()), eps); if(!eq){ System.out.println("Expected: " + Arrays.toString(expected.shape()) + ", actual: " + Arrays.toString(actual.shape())); System.out.println("Expected:\n" + expected); System.out.println("Actual: \n" + actual); } assertTrue("Output differs: " + label, eq); } } private static void compareMulticlassAUC(String label, INDArray target, INDArray a, INDArray b, int nbClasses, double eps) { ROCMultiClass evalA = new ROCMultiClass(100); evalA.eval(target, a); double avgAucA = evalA.calculateAverageAUC(); ROCMultiClass evalB = new ROCMultiClass(100); evalB.eval(target, b); double avgAucB = evalB.calculateAverageAUC(); assertEquals(avgAucA, avgAucB, EPS); double[] aucA = new double[nbClasses]; double[] aucB = new double[nbClasses]; if (nbClasses > 1) { for (int i = 0; i < nbClasses; i++) { aucA[i] = evalA.calculateAUC(i); aucB[i] = evalB.calculateAUC(i); } assertArrayEquals(aucA, aucB, EPS); } } public static void checkGradients(MultiLayerNetwork net, INDArray input, INDArray labels) { double eps = 1e-6; double max_rel_error = 1e-3; double min_abs_error = 1e-8; MultiLayerNetwork netToTest; if (net.getOutputLayer() instanceof IOutputLayer) { netToTest = net; } else { org.deeplearning4j.nn.conf.layers.Layer l; if (labels.rank() == 2) { l = new LossLayer.Builder() .lossFunction(LossFunctions.LossFunction.MSE) .activation(Activation.IDENTITY) .build(); } else { //Rank 3 l = new RnnOutputLayer.Builder() .lossFunction(LossFunctions.LossFunction.MSE) .activation(Activation.IDENTITY) .nIn(labels.size(1)) .nOut(labels.size(1)) .build(); } netToTest = new TransferLearning.Builder(net) .fineTuneConfiguration(new FineTuneConfiguration.Builder() .updater(new NoOp()) .dropOut(0.0) .build()) .addLayer(l) .build(); } log.info("Num params: " + net.numParams()); for (Layer l : netToTest.getLayers()) { // Remove any dropout manually - until this is fixed: // https://github.com/deeplearning4j/deeplearning4j/issues/4368 l.conf().getLayer().setIDropout(null); //Also swap out activation functions... this is a bit of a hack, but should make the net gradient checkable... if (l.conf().getLayer() instanceof FeedForwardLayer) { FeedForwardLayer ffl = (FeedForwardLayer) l.conf().getLayer(); IActivation activation = ffl.getActivationFn(); if (activation instanceof ActivationReLU || activation instanceof ActivationLReLU) { ffl.setActivationFn(new ActivationSoftPlus()); } else if (activation instanceof ActivationHardTanH) { ffl.setActivationFn(new ActivationTanH()); } } } Nd4j.setDataType(DataType.DOUBLE); boolean passed = GradientCheckUtil.checkGradients(new GradientCheckUtil.MLNConfig().net(netToTest).input(input) .labels(labels).subset(true).maxPerParam(9)); assertTrue("Gradient check failed", passed); } private File createTempFile(String prefix, String suffix) throws IOException { return testDir.newFile(prefix + "-" + System.nanoTime() + suffix); } }
package de.jpaw.batch.examples; import de.jpaw.batch.endpoints.BatchReaderTextFile; import de.jpaw.batch.endpoints.BatchWriterTextFile; import de.jpaw.batch.impl.BatchExecutorUnthreaded; import de.jpaw.batch.processors.BatchProcessorFactoryIdentity; public final class BatchTextFileCopyST { private BatchTextFileCopyST() { } public static void main(String[] args) throws Exception { new BatchExecutorUnthreaded<String, String>().run(args, new BatchReaderTextFile(), new BatchWriterTextFile(), new BatchProcessorFactoryIdentity<String>() ); } }
package com.huaweicloud.sdk.as.v1.model; import com.huaweicloud.sdk.core.SdkResponse; import java.util.function.Consumer; import java.util.Objects; /** * Response Object */ public class BatchProtectScalingInstancesResponse extends SdkResponse { @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } return true; } @Override public int hashCode() { return Objects.hash(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class BatchProtectScalingInstancesResponse {\n"); sb.append("}"); return sb.toString(); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package cn.hanbell.erp.entity; import java.io.Serializable; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; /** * * @author C1587 */ @Entity @Table(name = "secgsys") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Secgsys.findAll", query = "SELECT s FROM Secgsys s"), @NamedQuery(name = "Secgsys.findByPK", query = "SELECT s FROM Secgsys s WHERE s.secgsysPK.sysno = :sysno AND s.secgsysPK.groupno = :groupno AND s.secgsysPK.gtype = :gtype"), @NamedQuery(name = "Secgsys.findBySysno", query = "SELECT s FROM Secgsys s WHERE s.secgsysPK.sysno = :sysno"), @NamedQuery(name = "Secgsys.findByGroupnoAndGtype", query = "SELECT s FROM Secgsys s WHERE s.secgsysPK.groupno = :groupno AND s.secgsysPK.gtype = :gtype")}) public class Secgsys implements Serializable { private static final long serialVersionUID = 1L; @EmbeddedId protected SecgsysPK secgsysPK; public Secgsys() { } public Secgsys(SecgsysPK secgsysPK) { this.secgsysPK = secgsysPK; } public Secgsys(String sysno, String groupno, String gtype) { this.secgsysPK = new SecgsysPK(sysno, groupno, gtype); } public SecgsysPK getSecgsysPK() { return secgsysPK; } public void setSecgsysPK(SecgsysPK secgsysPK) { this.secgsysPK = secgsysPK; } @Override public int hashCode() { int hash = 0; hash += (secgsysPK != null ? secgsysPK.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Secgsys)) { return false; } Secgsys other = (Secgsys) object; if ((this.secgsysPK == null && other.secgsysPK != null) || (this.secgsysPK != null && !this.secgsysPK.equals(other.secgsysPK))) { return false; } return true; } @Override public String toString() { return "cn.hanbell.erp.entity.Secgsys[ secgsysPK=" + secgsysPK + " ]"; } }
package io.electrum.giftcard.api.model; import io.electrum.vas.Utils; import io.electrum.vas.model.Customer; import io.electrum.vas.model.Transaction; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonProperty; /** * Information about the load made on the gift card. */ @ApiModel(description = "Information about the load made on the gift card.") public class LoadResponse extends Transaction implements IGiftCardExtTransaction{ private GiftcardAmounts amounts = null; private Card card = null; private PosInfo posInfo = null; private Product product = null; private Customer cardHolder = null; public LoadResponse amounts(GiftcardAmounts amounts) { this.amounts = amounts; return this; } /** * Indicates the amount which was requested to be loaded onto the card, the amount which was loaded and the balance * of the gift card after the load. * * @return amounts **/ @ApiModelProperty(required = true, value = "Indicates the amount which was requested to be loaded onto the card, the amount which was loaded and the balance of the gift card after the load.") @JsonProperty("amounts") @NotNull public GiftcardAmounts getAmounts() { return amounts; } public void setAmounts(GiftcardAmounts amounts) { this.amounts = amounts; } /** * Information about the gift card being loaded. * * @return card **/ @ApiModelProperty(required = true, value = "Information about the gift card being loaded.") @JsonProperty("card") @NotNull public Card getCard() { return card; } public void setCard(Card card) { this.card = card; } public LoadResponse posInfo(PosInfo posInfo) { this.posInfo = posInfo; return this; } /** * Information about the POS. * * @return posInfo **/ @ApiModelProperty(value = "Information about the POS.") @JsonProperty("posInfo") public PosInfo getPosInfo() { return posInfo; } public void setPosInfo(PosInfo posInfo) { this.posInfo = posInfo; } public LoadResponse product(Product product) { this.product = product; return this; } /** * Information about the gift card product being loaded. * * @return product **/ @ApiModelProperty(value = "Information about the gift card product being loaded.") @JsonProperty("product") public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } public LoadResponse cardHolder(Customer cardHolder) { this.cardHolder = cardHolder; return this; } /** * Information about the card holder. * * @return cardHolder **/ @ApiModelProperty(value = "Information about the card holder.") @JsonProperty("cardHolder") public Customer getCardHolder() { return cardHolder; } public void setCardHolder(Customer cardHolder) { this.cardHolder = cardHolder; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class LoadResponse {\n"); sb.append(" id: ").append(Utils.toIndentedString(id)).append("\n"); sb.append(" time: ").append(Utils.toIndentedString(time)).append("\n"); sb.append(" originator: ").append(Utils.toIndentedString(originator)).append("\n"); sb.append(" client: ").append(Utils.toIndentedString(client)).append("\n"); sb.append(" settlementEntity: ").append(Utils.toIndentedString(settlementEntity)).append("\n"); sb.append(" receiver: ").append(Utils.toIndentedString(receiver)).append("\n"); sb.append(" thirdPartyIdentifiers: ").append(Utils.toIndentedString(thirdPartyIdentifiers)).append("\n"); sb.append(" amounts: ").append(Utils.toIndentedString(amounts)).append("\n"); sb.append(" card: ").append(Utils.toIndentedString(card)).append("\n"); sb.append(" posInfo: ").append(Utils.toIndentedString(posInfo)).append("\n"); sb.append(" product: ").append(Utils.toIndentedString(product)).append("\n"); sb.append(" slipData: ").append(Utils.toIndentedString(slipData)).append("\n"); sb.append(" customer: ").append(Utils.toIndentedString(cardHolder)).append("\n"); sb.append("}"); return sb.toString(); } }
package io.github.a5h73y.parkour.utility; import static io.github.a5h73y.parkour.other.ParkourConstants.ERROR_NO_EXIST; import static io.github.a5h73y.parkour.other.ParkourConstants.ERROR_UNKNOWN_PLAYER; import io.github.a5h73y.parkour.Parkour; import io.github.a5h73y.parkour.enums.Permission; import io.github.a5h73y.parkour.other.ParkourValidation; import io.github.a5h73y.parkour.type.course.CourseInfo; import io.github.a5h73y.parkour.type.player.PlayerInfo; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Collection; import java.util.HashSet; import java.util.Set; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.OfflinePlayer; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.Nullable; /** * Parkour Plugin related utility methods. */ public class PluginUtils { /** * Broadcasts a message to each online player and the server. * * @param message message to broadcast * @param permission permission to receive message */ public static void broadcastMessage(String message, Permission permission) { Bukkit.broadcast(message, permission.getPermission()); log(message); } /** * Log plugin events, varying in severity. * 0 - Info; 1 - Warn; 2 - Severe; 3 - Debug. * * @param message log message * @param severity (0 - 3) */ public static void log(String message, int severity) { switch (severity) { case 1: Parkour.getInstance().getLogger().warning(message); break; case 2: Parkour.getInstance().getLogger().severe("! " + message); break; case 3: Parkour.getInstance().getLogger().info("~ " + message); break; case 0: default: Parkour.getInstance().getLogger().info(message); break; } } /** * Log plugin info message. * * @param message log message */ public static void log(String message) { log(message, 0); } /** * Debug a message to the console. * Has to be manually enabled in the config. * * @param message message to log */ public static void debug(String message) { if (Parkour.getDefaultConfig().getBoolean("Debug", false)) { log(message, 3); } } /** * Write message to `Parkour.log` file. * Used to log 'incriminating' events to a separate file that can't be erased. * Examples: playerA deleted courseB * * @param message message to log */ public static void logToFile(String message) { if (!Parkour.getDefaultConfig().getBoolean("Other.LogToFile")) { return; } File saveTo = new File(Parkour.getInstance().getDataFolder(), "Parkour.log"); if (!saveTo.exists()) { try { saveTo.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } try (FileWriter writer = new FileWriter(saveTo, true); BufferedWriter bw = new BufferedWriter(writer)) { bw.write(DateTimeUtils.getDisplayDateTime() + " " + message + System.lineSeparator()); } catch (IOException e) { log(e.getMessage(), 2); log(e.toString(), 2); } } /** * Convert a list of material names to a Set of Materials. * * @param rawMaterials list of material strings * @return Set of {@link Material} */ public static Set<Material> convertToValidMaterials(Collection<String> rawMaterials) { Set<Material> validMaterials = new HashSet<>(); for (String rawMaterial : rawMaterials) { Material material = Material.getMaterial(rawMaterial.toUpperCase()); if (material != null) { validMaterials.add(material); } else { log("Material '" + rawMaterial + "' is invalid", 2); } } return validMaterials; } /** * Get the Server's minor version. * Will strip the Bukkit version to just the distinguishable version (14, 15, etc.). * If the version is unrecognisable, assume it is under 1.13 (where most things drastically changed). * * @return server version */ public static int getMinorServerVersion() { String version = Bukkit.getBukkitVersion().split("-")[0].split("\\.")[1]; return ValidationUtils.isInteger(version) ? Integer.parseInt(version) : 12; } /** * Find {@link GameMode} by name. * * @param gameMode requested gamemode * @return matching {@link GameMode} */ public static GameMode getGameMode(String gameMode) { return GameMode.valueOf(gameMode.toUpperCase()); } public static boolean doesGameModeExist(String gameMode) { return getGameMode(gameMode) != null; } /** * Delete Command. * Possible choices include Course, Checkpoint, Lobby, ParkourKit, AutoStart. * Each option will create a Question for the Sender to confirm. * * @param sender command sender * @param command command choice * @param argument argument value */ public static void deleteCommand(CommandSender sender, String command, String argument) { Parkour parkour = Parkour.getInstance(); switch (command.toLowerCase()) { case "course": if (!ParkourValidation.canDeleteCourse(sender, argument)) { return; } parkour.getQuestionManager().askDeleteCourseQuestion(sender, argument); break; case "checkpoint": if (!ParkourValidation.canDeleteCheckpoint(sender, argument)) { return; } int checkpoints = CourseInfo.getCheckpointAmount(argument); parkour.getQuestionManager().askDeleteCheckpointQuestion(sender, argument, checkpoints); break; case "lobby": if (!ParkourValidation.canDeleteLobby(sender, argument)) { return; } parkour.getQuestionManager().askDeleteLobbyQuestion(sender, argument); break; case "kit": case "parkourkit": if (!ParkourValidation.canDeleteParkourKit(sender, argument)) { return; } parkour.getQuestionManager().askDeleteKitQuestion(sender, argument); break; case "autostart": if (!(sender instanceof Player)) { TranslationUtils.sendMessage(sender, "This command can only be performed by players!"); return; } Location location = ((Player) sender).getLocation(); String coordinates = location.getBlockX() + "-" + location.getBlockY() + "-" + location.getBlockZ(); if (!ParkourValidation.canDeleteAutoStart((Player) sender, argument, coordinates)) { return; } parkour.getQuestionManager().askDeleteAutoStartQuestion(sender, coordinates); break; default: TranslationUtils.sendInvalidSyntax(sender, "delete", "(course / checkpoint / lobby / kit / autostart) (name)"); break; } } /** * Reset Command. * Possible choices include Course, Player, Leaderboard, Prize. * Each option will create a Question for the Sender to confirm. * * @param sender command sender * @param command command choice * @param argument argument value * @param extraArgument extra argument value */ public static void resetCommand(CommandSender sender, String command, String argument, @Nullable String extraArgument) { Parkour parkour = Parkour.getInstance(); switch (command.toLowerCase()) { case "course": if (!parkour.getCourseManager().doesCourseExists(argument)) { TranslationUtils.sendValueTranslation(ERROR_NO_EXIST, argument, sender); return; } parkour.getQuestionManager().askResetCourseQuestion(sender, argument); break; case "player": OfflinePlayer targetPlayer = Bukkit.getOfflinePlayer(argument); if (!PlayerInfo.hasPlayerInfo(targetPlayer)) { TranslationUtils.sendTranslation(ERROR_UNKNOWN_PLAYER, sender); return; } parkour.getQuestionManager().askResetPlayerQuestion(sender, argument); break; case "leaderboard": if (!parkour.getCourseManager().doesCourseExists(argument)) { TranslationUtils.sendValueTranslation(ERROR_NO_EXIST, argument, sender); return; } if (extraArgument != null) { parkour.getQuestionManager().askResetPlayerLeaderboardQuestion(sender, argument, extraArgument); } else { parkour.getQuestionManager().askResetLeaderboardQuestion(sender, argument); } break; case "prize": if (!parkour.getCourseManager().doesCourseExists(argument)) { TranslationUtils.sendValueTranslation(ERROR_NO_EXIST, argument, sender); return; } parkour.getQuestionManager().askResetPrizeQuestion(sender, argument); break; default: TranslationUtils.sendInvalidSyntax(sender, "reset", "(course / player / leaderboard / prize) (argument)"); break; } } /** * Cache Command. * View the number of results in each cache. * Provide an argument to clear the selected cache. * * @param sender command sender * @param argument argument value */ public static void cacheCommand(CommandSender sender, @Nullable String argument) { Parkour parkour = Parkour.getInstance(); if (argument != null) { switch (argument.toLowerCase()) { case "course": case "courses": parkour.getCourseManager().clearCache(); break; case "database": parkour.getDatabase().clearCache(); break; case "lobby": case "lobbies": parkour.getLobbyManager().clearCache(); break; case "parkourkit": case "parkourkits": parkour.getParkourKitManager().clearCache(); break; case "sound": case "sounds": parkour.getSoundsManager().clearCache(); break; case "all": case "clear": clearAllCache(); break; default: TranslationUtils.sendInvalidSyntax(sender, "cache", "[course / database / lobby / parkourkit / sound]"); return; } TranslationUtils.sendPropertySet(sender, "Cache", StringUtils.standardizeText(argument), "empty"); } else { TranslationUtils.sendHeading("Parkour Cache", sender); TranslationUtils.sendValue(sender, "Courses Cached", parkour.getCourseManager().getCacheSize()); TranslationUtils.sendValue(sender, "Database Times Cached", parkour.getDatabase().getCacheSize()); TranslationUtils.sendValue(sender, "Lobbies Cached", parkour.getLobbyManager().getCacheSize()); TranslationUtils.sendValue(sender, "ParkourKits Cached", parkour.getParkourKitManager().getCacheSize()); TranslationUtils.sendValue(sender, "Sounds Cached", parkour.getSoundsManager().getCacheSize()); } } /** * Clear all the Caches. */ public static void clearAllCache() { Parkour parkour = Parkour.getInstance(); parkour.getCourseManager().clearCache(); parkour.getDatabase().clearCache(); parkour.getLobbyManager().clearCache(); parkour.getParkourKitManager().clearCache(); parkour.getSoundsManager().clearCache(); } }
/** * This project is licensed under the Apache License, Version 2.0 * if the following condition is met: * (otherwise it cannot be used by anyone but the author, Kevin, only) * * The original KommonLee project is owned by Lee, Seong Hyun (Kevin). * * -What does it mean to you? * Nothing, unless you want to take the ownership of * "the original project" (not yours or forked & modified one). * You are free to use it for both non-commercial and commercial projects * and free to modify it as the Apache License allows. * * -So why is this condition necessary? * It is only to protect the original project (See the case of Java). * * * Copyright 2009 Lee, Seong Hyun (Kevin) * * 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.elixirian.kommonlee.asm.analysis; import static org.assertj.core.api.Assertions.*; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import java.lang.reflect.Constructor; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentMap; import org.elixirian.kommonlee.asm.analysis.ConstantsForTesting.TestPojo; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; /** * @author Lee, SeongHyun (Kevin) * @version 0.0.1 (2010-06-22) */ public class AsmMethodAndConstructorAnalyserTest { private AsmMethodAndConstructorAnalyser asmMethodAndConstructorAnalyser; /** * @throws java.lang.Exception */ @BeforeClass public static void setUpBeforeClass() throws Exception { } /** * @throws java.lang.Exception */ @AfterClass public static void tearDownAfterClass() throws Exception { } /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { asmMethodAndConstructorAnalyser = new AsmMethodAndConstructorAnalyser(); } /** * @throws java.lang.Exception */ @After public void tearDown() throws Exception { } @Test public final void testAsmMethodAndConstructorAnalyser() { final AsmMethodAndConstructorAnalyser asmMethodAndConstructorAnalyser = new AsmMethodAndConstructorAnalyser(); assertThat(asmMethodAndConstructorAnalyser.getMethodAndConstructorCollector()).isInstanceOf(MethodAndConstructorCollector.class); assertThat(asmMethodAndConstructorAnalyser.getMethodAndConstructorCollector() .getExternalTypeCacheMap()).isNull(); assertThat(asmMethodAndConstructorAnalyser.getMethodCollector()).isInstanceOf(MethodCollector.class); assertThat(asmMethodAndConstructorAnalyser.getMethodCollector() .getExternalTypeCacheMap()).isNull(); assertThat(asmMethodAndConstructorAnalyser.getConstructorCollector()).isInstanceOf(ConstructorCollector.class); assertThat(asmMethodAndConstructorAnalyser.getConstructorCollector() .getExternalTypeCacheMap()).isNull(); } @Test public final void testAsmMethodAndConstructorAnalyserMapOfStringClassOfQ() { @SuppressWarnings("unchecked") /* given */ final ConcurrentMap<String, Class<?>> otherKnownTypesMap = mock(ConcurrentMap.class); /* when */ final AsmMethodAndConstructorAnalyser asmMethodAndConstructorAnalyser = new AsmMethodAndConstructorAnalyser(otherKnownTypesMap); /* then */ assertThat(asmMethodAndConstructorAnalyser.getMethodAndConstructorCollector()).isInstanceOf(MethodAndConstructorCollector.class); assertThat(asmMethodAndConstructorAnalyser.getMethodAndConstructorCollector() .getExternalTypeCacheMap()).isSameAs(otherKnownTypesMap); assertThat(asmMethodAndConstructorAnalyser.getMethodAndConstructorCollector() .getExternalTypeCacheMap()).isEqualTo(otherKnownTypesMap); assertThat(asmMethodAndConstructorAnalyser.getMethodAndConstructorCollector() .getExternalTypeCacheMap()).hasSize(otherKnownTypesMap.size()); assertThat(asmMethodAndConstructorAnalyser.getMethodCollector()).isInstanceOf(MethodCollector.class); assertThat(asmMethodAndConstructorAnalyser.getMethodCollector() .getExternalTypeCacheMap()).isSameAs(otherKnownTypesMap); assertThat(asmMethodAndConstructorAnalyser.getMethodCollector() .getExternalTypeCacheMap()).isEqualTo(otherKnownTypesMap); assertThat(asmMethodAndConstructorAnalyser.getMethodCollector() .getExternalTypeCacheMap()).hasSize(otherKnownTypesMap.size()); assertThat(asmMethodAndConstructorAnalyser.getConstructorCollector()).isInstanceOf(ConstructorCollector.class); assertThat(asmMethodAndConstructorAnalyser.getConstructorCollector() .getExternalTypeCacheMap()).isSameAs(otherKnownTypesMap); assertThat(asmMethodAndConstructorAnalyser.getConstructorCollector() .getExternalTypeCacheMap()).isEqualTo(otherKnownTypesMap); assertThat(asmMethodAndConstructorAnalyser.getConstructorCollector() .getExternalTypeCacheMap()).hasSize(otherKnownTypesMap.size()); } @Test public final void testFindMethodsAndConstructorsWithParameterNames() { final List<Constructor<?>> constructors = TestUtil.getNonSynthetic(TestPojo.class.getDeclaredConstructors()); final List<Method> methods = TestUtil.getNonSyntheticNonBridge(TestPojo.class.getDeclaredMethods()); final Map<Member, String[]> methodsAndConstructorsMap = asmMethodAndConstructorAnalyser.findMethodsAndConstructorsWithParameterNames(TestPojo.class); assertThat(methodsAndConstructorsMap).hasSize(constructors.size() + methods.size()); for (final Constructor<?> constructor : constructors) { assertTrue(methodsAndConstructorsMap.containsKey(constructor)); } for (final Method method : methods) { assertThat(methodsAndConstructorsMap).containsKey(method); } } @Test public final void testFindMethodsWithParameterNames() { final List<Method> methods = TestUtil.getNonSyntheticNonBridge(TestPojo.class.getDeclaredMethods()); final Map<Method, String[]> methodsAndConstructorsMap = asmMethodAndConstructorAnalyser.findMethodsWithParameterNames(TestPojo.class); assertThat(methodsAndConstructorsMap).hasSameSizeAs(methods); for (final Method method : methods) { assertTrue(methodsAndConstructorsMap.containsKey(method)); } } class AnotherTestPojo { private String name; public int getId() { return 1; } } @Test public final void testFindMethodsWithParameterNames2() { final AnotherTestPojo anotherTestPojo = new AnotherTestPojo(); /* @formatter:off */ /* * The following two lines of code cause the Java compiler to generate synthetic methods to mutate and access the * instance member variable name in the AnotherPojo class. So the number of DeclaredMethods becomes * the number of methods that can be seen in the source code + 2. */ anotherTestPojo.name = "Kevin"; // Compiler generates mutator final String name = anotherTestPojo.name; // Compiler generates accessor /* @formatter:on */ final List<Method> methods = TestUtil.getNonSyntheticNonBridge(AnotherTestPojo.class.getDeclaredMethods()); final Map<Method, String[]> methodsAndConstructorsMap = asmMethodAndConstructorAnalyser.findMethodsWithParameterNames(AnotherTestPojo.class); assertThat(methodsAndConstructorsMap).hasSameSizeAs(methods); for (final Method method : methods) { assertTrue(methodsAndConstructorsMap.containsKey(method)); } } @Test public final void testFindConstructorsWithParameterNames() { final Map<Constructor<TestPojo>, String[]> methodsAndConstructorsMap = asmMethodAndConstructorAnalyser.findConstructorsWithParameterNames(TestPojo.class); final List<Constructor<?>> constructors = TestUtil.getNonSynthetic(TestPojo.class.getDeclaredConstructors()); assertEquals(constructors.size(), methodsAndConstructorsMap.size()); for (final Constructor<?> constructor : constructors) { assertTrue(methodsAndConstructorsMap.containsKey(constructor)); } } }
package org.visallo.core.config; import com.google.common.base.Throwables; import org.apache.logging.log4j.core.config.Configurator; import org.json.JSONObject; import org.visallo.core.exception.VisalloException; import org.visallo.core.exception.VisalloResourceNotFoundException; import org.visallo.core.util.VisalloLogger; import org.visallo.core.util.VisalloLoggerFactory; import java.io.File; import java.lang.reflect.Constructor; import java.net.URISyntaxException; import java.net.URL; import java.util.HashMap; import java.util.Map; public abstract class ConfigurationLoader { public static final String ENV_CONFIGURATION_LOADER = "VISALLO_CONFIGURATION_LOADER"; private static Configuration configuration; private final Map initParameters; private JSONObject configurationInfo = new JSONObject(); protected ConfigurationLoader(Map initParameters) { this.initParameters = initParameters; } public static void configureLog4j() { ConfigurationLoader configurationLoader = createConfigurationLoader(); configurationLoader.doConfigureLog4j(); } public static Configuration load() { return load(new HashMap()); } public static Configuration load(Map p) { return load(getConfigurationLoaderClass(), p); } public static Class getConfigurationLoaderClass() { String configLoaderName = System.getenv(ENV_CONFIGURATION_LOADER); if (configLoaderName == null) { configLoaderName = System.getProperty(ENV_CONFIGURATION_LOADER); } if (configLoaderName != null) { return getConfigurationLoaderByName(configLoaderName); } return FileConfigurationLoader.class; } public static Configuration load(String configLoaderName, Map<String, String> initParameters) { Class configLoader; if (configLoaderName == null) { configLoader = getConfigurationLoaderClass(); } else { configLoader = getConfigurationLoaderByName(configLoaderName); } return load(configLoader, initParameters); } public static Class getConfigurationLoaderByName(String configLoaderName) { Class configLoader; try { configLoader = Class.forName(configLoaderName); } catch (ClassNotFoundException e) { throw new VisalloException("Could not load class " + configLoaderName, e); } return configLoader; } public static Configuration load(Class configLoader, Map initParameters) { ConfigurationLoader configurationLoader = createConfigurationLoader(configLoader, initParameters); if (configuration == null) { configuration = configurationLoader.createConfiguration(); } // This load method overload is at the bottom of the call hierarchy and is the only place guaranteed // to get called while loading configuration. It is also early enough in the startup process (ie before // SSL connection to databases or data stores are made) to set system properties and have them take effect. setSystemProperties(configuration); return configuration; } private static void setSystemProperties(Configuration configuration) { Map<String, String> systemProperties = configuration.getSubset("systemProperty"); for (Map.Entry<String, String> systemProperty : systemProperties.entrySet()) { System.setProperty(systemProperty.getKey(), systemProperty.getValue()); } } private static ConfigurationLoader createConfigurationLoader() { return createConfigurationLoader(null, null); } private static ConfigurationLoader createConfigurationLoader(Class configLoaderClass, Map initParameters) { if (configLoaderClass == null) { configLoaderClass = getConfigurationLoaderClass(); } if (initParameters == null) { initParameters = new HashMap<>(); } try { @SuppressWarnings("unchecked") Constructor constructor = configLoaderClass.getConstructor(Map.class); return (ConfigurationLoader) constructor.newInstance(initParameters); } catch (Exception e) { throw new VisalloException("Could not load configuration class: " + configLoaderClass.getName(), e); } } public abstract Configuration createConfiguration(); protected void doConfigureLog4j() { String fileName = System.getProperty("logQuiet") == null ? "log4j2.xml" : "log4j2-quiet.xml"; File log4jFile = null; String log4jLocation = null; try { log4jFile = resolveFileName(fileName); } catch (VisalloResourceNotFoundException e) { // OK, try classpath } if (log4jFile == null || !log4jFile.exists()) { URL log4jResource = getClass().getResource(fileName); System.err.println("Could not resolve log4j2.xml, using the fallback: " + log4jResource); try { if (log4jResource != null) { Configurator.initialize((String)null, null, log4jResource.toURI()); log4jLocation = log4jResource.toExternalForm(); } else { throw new VisalloResourceNotFoundException("Could not find log4j2.xml on the classpath"); } } catch (URISyntaxException e) { throw new VisalloException("Unable to load default log42.xml", e); } } else { log4jLocation = log4jFile.getAbsolutePath(); Configurator.initialize((String)null, null, log4jFile.toURI()); } VisalloLogger logger = VisalloLoggerFactory.getLogger(VisalloLoggerFactory.class); logger.info("Using ConfigurationLoader: %s", this.getClass().getName()); logger.info("Using log4j2.xml: %s", log4jLocation); } public abstract File resolveFileName(String fileName); protected Map getInitParameters() { return initParameters; } protected void setConfigurationInfo(String key, Object object) { configurationInfo.put(key, object); } public JSONObject getConfigurationInfo() { return configurationInfo; } }
//: concurrency/MultiLock.java // One thread can reacquire the same lock. import static net.mindview.util.Print.*; public class MultiLock { public synchronized void f1(int count) { if(count-- > 0) { print("f1() calling f2() with count " + count); f2(count); } } public synchronized void f2(int count) { if(count-- > 0) { print("f2() calling f1() with count " + count); f1(count); } } public static void main(String[] args) throws Exception { final MultiLock multiLock = new MultiLock(); new Thread() { public void run() { multiLock.f1(10); } }.start(); } } /* Output: f1() calling f2() with count 9 f2() calling f1() with count 8 f1() calling f2() with count 7 f2() calling f1() with count 6 f1() calling f2() with count 5 f2() calling f1() with count 4 f1() calling f2() with count 3 f2() calling f1() with count 2 f1() calling f2() with count 1 f2() calling f1() with count 0 *///:~
/* * 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 org.springframework.http.server.reactive; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; import javax.net.ssl.SSLSession; import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** * Default implementation of {@link SslInfo}. * * @author Rossen Stoyanchev * @since 5.0.2 */ final class DefaultSslInfo implements SslInfo { @Nullable private final String sessionId; @Nullable private final X509Certificate[] peerCertificates; DefaultSslInfo(String sessionId, X509Certificate[] peerCertificates) { Assert.notNull(peerCertificates, "No SSL certificates"); this.sessionId = sessionId; this.peerCertificates = peerCertificates; } DefaultSslInfo(SSLSession session) { Assert.notNull(session, "SSLSession is required"); this.sessionId = initSessionId(session); this.peerCertificates = initCertificates(session); } @Override @Nullable public String getSessionId() { return this.sessionId; } @Override @Nullable public X509Certificate[] getPeerCertificates() { return this.peerCertificates; } @Nullable private static String initSessionId(SSLSession session) { byte [] bytes = session.getId(); if (bytes == null) { return null; } StringBuilder sb = new StringBuilder(); for (byte b : bytes) { String digit = Integer.toHexString(b); if (digit.length() < 2) { sb.append('0'); } if (digit.length() > 2) { digit = digit.substring(digit.length() - 2); } sb.append(digit); } return sb.toString(); } @Nullable private static X509Certificate[] initCertificates(SSLSession session) { Certificate[] certificates; try { certificates = session.getPeerCertificates(); } catch (Throwable ex) { return null; } List<X509Certificate> result = new ArrayList<>(certificates.length); for (Certificate certificate : certificates) { if (certificate instanceof X509Certificate) { result.add((X509Certificate) certificate); } } return !result.isEmpty() ? result.toArray(new X509Certificate[result.size()]) : null; } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests.extensions; import com.microsoft.graph.models.extensions.EmbeddedSIMDeviceState; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.microsoft.graph.serializer.AdditionalDataManager; import com.microsoft.graph.serializer.IJsonBackedObject; import com.microsoft.graph.serializer.ISerializer; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Embedded SIMDevice State Collection Response. */ public class EmbeddedSIMDeviceStateCollectionResponse implements IJsonBackedObject { /** * The list of EmbeddedSIMDeviceState within this collection page */ @SerializedName("value") @Expose public java.util.List<EmbeddedSIMDeviceState> value; /** * The URL to the next page of this collection, or null */ @SerializedName("@odata.nextLink") @Expose(serialize = false) public String nextLink; private transient AdditionalDataManager additionalDataManager = new AdditionalDataManager(this); @Override public final AdditionalDataManager additionalDataManager() { return additionalDataManager; } /** * The raw representation of this class */ private JsonObject rawObject; /** * The serializer */ private ISerializer serializer; /** * Gets the raw representation of this class * * @return the raw representation of this class */ public JsonObject getRawObject() { return rawObject; } /** * Gets serializer * * @return the serializer */ protected ISerializer getSerializer() { return serializer; } /** * Sets the raw JSON object * * @param serializer the serializer * @param json the JSON object to set this object to */ public void setRawObject(final ISerializer serializer, final JsonObject json) { this.serializer = serializer; rawObject = json; if (json.has("value")) { final JsonArray array = json.getAsJsonArray("value"); for (int i = 0; i < array.size(); i++) { value.get(i).setRawObject(serializer, (JsonObject) array.get(i)); } } } }
/* * 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.alb.transform.v20200616; import com.aliyuncs.alb.model.v20200616.DeleteLoadBalancerResponse; import com.aliyuncs.transform.UnmarshallerContext; public class DeleteLoadBalancerResponseUnmarshaller { public static DeleteLoadBalancerResponse unmarshall(DeleteLoadBalancerResponse deleteLoadBalancerResponse, UnmarshallerContext _ctx) { deleteLoadBalancerResponse.setRequestId(_ctx.stringValue("DeleteLoadBalancerResponse.RequestId")); deleteLoadBalancerResponse.setJobId(_ctx.stringValue("DeleteLoadBalancerResponse.JobId")); return deleteLoadBalancerResponse; } }
/* * Copyright 2015-2020 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.timestreamwrite; import javax.annotation.Generated; import com.amazonaws.*; import com.amazonaws.regions.*; import com.amazonaws.services.timestreamwrite.model.*; /** * Interface for accessing Timestream Write. * <p> * <b>Note:</b> Do not directly implement this interface, new methods are added to it regularly. Extend from * {@link com.amazonaws.services.timestreamwrite.AbstractAmazonTimestreamWrite} instead. * </p> * <p> * <p> * Amazon Timestream is a fast, scalable, fully managed time series database service that makes it easy to store and * analyze trillions of time series data points per day. With Timestream, you can easily store and analyze IoT sensor * data to derive insights from your IoT applications. You can analyze industrial telemetry to streamline equipment * management and maintenance. You can also store and analyze log data and metrics to improve the performance and * availability of your applications. Timestream is built from the ground up to effectively ingest, process, and store * time series data. It organizes data to optimize query processing. It automatically scales based on the volume of data * ingested and on the query volume to ensure you receive optimal performance while inserting and querying data. As your * data grows over time, Timestream’s adaptive query processing engine spans across storage tiers to provide fast * analysis while reducing costs. * </p> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public interface AmazonTimestreamWrite { /** * The region metadata service name for computing region endpoints. You can use this value to retrieve metadata * (such as supported regions) of the service. * * @see RegionUtils#getRegionsForService(String) */ String ENDPOINT_PREFIX = "ingest.timestream"; /** * <p> * Creates a new Timestream database. If the KMS key is not specified, the database will be encrypted with a * Timestream managed KMS key located in your account. Refer to <a * href="https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#aws-managed-cmk">AWS managed KMS * keys</a> for more info. Service quotas apply. For more information, see <a * href="https://docs.aws.amazon.com/timestream/latest/developerguide/ts-limits.html">Access Management</a> in the * Timestream Developer Guide. * </p> * * @param createDatabaseRequest * @return Result of the CreateDatabase operation returned by the service. * @throws ConflictException * Timestream was unable to process this request because it contains resource that already exists. * @throws ValidationException * Invalid or malformed request. * @throws AccessDeniedException * You are not authorized to perform this action. * @throws ServiceQuotaExceededException * Instance quota of resource exceeded for this account. * @throws ThrottlingException * Too many requests were made by a user exceeding service quotas. The request was throttled. * @throws InvalidEndpointException * The requested endpoint was invalid. * @throws InternalServerException * Timestream was unable to fully process this request because of an internal server error. * @sample AmazonTimestreamWrite.CreateDatabase * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/timestream-write-2018-11-01/CreateDatabase" * target="_top">AWS API Documentation</a> */ CreateDatabaseResult createDatabase(CreateDatabaseRequest createDatabaseRequest); /** * <p> * The CreateTable operation adds a new table to an existing database in your account. In an AWS account, table * names must be at least unique within each Region if they are in the same database. You may have identical table * names in the same Region if the tables are in seperate databases. While creating the table, you must specify the * table name, database name, and the retention properties. Service quotas apply. For more information, see <a * href="https://docs.aws.amazon.com/timestream/latest/developerguide/ts-limits.html">Access Management</a> in the * Timestream Developer Guide. * </p> * * @param createTableRequest * @return Result of the CreateTable operation returned by the service. * @throws ConflictException * Timestream was unable to process this request because it contains resource that already exists. * @throws ValidationException * Invalid or malformed request. * @throws AccessDeniedException * You are not authorized to perform this action. * @throws ResourceNotFoundException * The operation tried to access a nonexistent resource. The resource might not be specified correctly, or * its status might not be ACTIVE. * @throws ServiceQuotaExceededException * Instance quota of resource exceeded for this account. * @throws ThrottlingException * Too many requests were made by a user exceeding service quotas. The request was throttled. * @throws InternalServerException * Timestream was unable to fully process this request because of an internal server error. * @throws InvalidEndpointException * The requested endpoint was invalid. * @sample AmazonTimestreamWrite.CreateTable * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/timestream-write-2018-11-01/CreateTable" target="_top">AWS * API Documentation</a> */ CreateTableResult createTable(CreateTableRequest createTableRequest); /** * <p> * Deletes a given Timestream database. <i>This is an irreversible operation. After a database is deleted, the time * series data from its tables cannot be recovered.</i> * </p> * <p> * All tables in the database must be deleted first, or a ValidationException error will be thrown. * </p> * <p> * Due to the nature of distributed retries, the operation can return either success or a ResourceNotFoundException. * Clients should consider them equivalent. * </p> * * @param deleteDatabaseRequest * @return Result of the DeleteDatabase operation returned by the service. * @throws InternalServerException * Timestream was unable to fully process this request because of an internal server error. * @throws ThrottlingException * Too many requests were made by a user exceeding service quotas. The request was throttled. * @throws ResourceNotFoundException * The operation tried to access a nonexistent resource. The resource might not be specified correctly, or * its status might not be ACTIVE. * @throws ValidationException * Invalid or malformed request. * @throws AccessDeniedException * You are not authorized to perform this action. * @throws InvalidEndpointException * The requested endpoint was invalid. * @sample AmazonTimestreamWrite.DeleteDatabase * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/timestream-write-2018-11-01/DeleteDatabase" * target="_top">AWS API Documentation</a> */ DeleteDatabaseResult deleteDatabase(DeleteDatabaseRequest deleteDatabaseRequest); /** * <p> * Deletes a given Timestream table. This is an irreversible operation. After a Timestream database table is * deleted, the time series data stored in the table cannot be recovered. * </p> * <p> * Due to the nature of distributed retries, the operation can return either success or a ResourceNotFoundException. * Clients should consider them equivalent. * </p> * * @param deleteTableRequest * @return Result of the DeleteTable operation returned by the service. * @throws InternalServerException * Timestream was unable to fully process this request because of an internal server error. * @throws ThrottlingException * Too many requests were made by a user exceeding service quotas. The request was throttled. * @throws ValidationException * Invalid or malformed request. * @throws ResourceNotFoundException * The operation tried to access a nonexistent resource. The resource might not be specified correctly, or * its status might not be ACTIVE. * @throws AccessDeniedException * You are not authorized to perform this action. * @throws InvalidEndpointException * The requested endpoint was invalid. * @sample AmazonTimestreamWrite.DeleteTable * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/timestream-write-2018-11-01/DeleteTable" target="_top">AWS * API Documentation</a> */ DeleteTableResult deleteTable(DeleteTableRequest deleteTableRequest); /** * <p> * Returns information about the database, including the database name, time that the database was created, and the * total number of tables found within the database. Service quotas apply. For more information, see <a * href="https://docs.aws.amazon.com/timestream/latest/developerguide/ts-limits.html">Access Management</a> in the * Timestream Developer Guide. * </p> * * @param describeDatabaseRequest * @return Result of the DescribeDatabase operation returned by the service. * @throws ResourceNotFoundException * The operation tried to access a nonexistent resource. The resource might not be specified correctly, or * its status might not be ACTIVE. * @throws ValidationException * Invalid or malformed request. * @throws AccessDeniedException * You are not authorized to perform this action. * @throws ThrottlingException * Too many requests were made by a user exceeding service quotas. The request was throttled. * @throws InternalServerException * Timestream was unable to fully process this request because of an internal server error. * @throws InvalidEndpointException * The requested endpoint was invalid. * @sample AmazonTimestreamWrite.DescribeDatabase * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/timestream-write-2018-11-01/DescribeDatabase" * target="_top">AWS API Documentation</a> */ DescribeDatabaseResult describeDatabase(DescribeDatabaseRequest describeDatabaseRequest); /** * <p> * DescribeEndpoints returns a list of available endpoints to make Timestream API calls against. This API is * available through both Write and Query. * </p> * <p> * Because Timestream’s SDKs are designed to transparently work with the service’s architecture, including the * management and mapping of the service endpoints, <i>it is not recommended that you use this API unless</i>: * </p> * <ul> * <li> * <p> * Your application uses a programming language that does not yet have SDK support * </p> * </li> * <li> * <p> * You require better control over the client-side implementation * </p> * </li> * </ul> * <p> * For detailed information on how to use DescribeEndpoints, see <a * href="https://docs.aws.amazon.com/timestream/latest/developerguide/Using-API.endpoint-discovery.html">The * Endpoint Discovery Pattern and REST APIs</a>. * </p> * * @param describeEndpointsRequest * @return Result of the DescribeEndpoints operation returned by the service. * @throws InternalServerException * Timestream was unable to fully process this request because of an internal server error. * @throws ValidationException * Invalid or malformed request. * @throws ThrottlingException * Too many requests were made by a user exceeding service quotas. The request was throttled. * @sample AmazonTimestreamWrite.DescribeEndpoints * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/timestream-write-2018-11-01/DescribeEndpoints" * target="_top">AWS API Documentation</a> */ DescribeEndpointsResult describeEndpoints(DescribeEndpointsRequest describeEndpointsRequest); /** * <p> * Returns information about the table, including the table name, database name, retention duration of the memory * store and the magnetic store. Service quotas apply. For more information, see <a * href="https://docs.aws.amazon.com/timestream/latest/developerguide/ts-limits.html">Access Management</a> in the * Timestream Developer Guide. * </p> * * @param describeTableRequest * @return Result of the DescribeTable operation returned by the service. * @throws ResourceNotFoundException * The operation tried to access a nonexistent resource. The resource might not be specified correctly, or * its status might not be ACTIVE. * @throws ValidationException * Invalid or malformed request. * @throws AccessDeniedException * You are not authorized to perform this action. * @throws ThrottlingException * Too many requests were made by a user exceeding service quotas. The request was throttled. * @throws InternalServerException * Timestream was unable to fully process this request because of an internal server error. * @throws InvalidEndpointException * The requested endpoint was invalid. * @sample AmazonTimestreamWrite.DescribeTable * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/timestream-write-2018-11-01/DescribeTable" target="_top">AWS * API Documentation</a> */ DescribeTableResult describeTable(DescribeTableRequest describeTableRequest); /** * <p> * Returns a list of your Timestream databases. Service quotas apply. For more information, see <a * href="https://docs.aws.amazon.com/timestream/latest/developerguide/ts-limits.html">Access Management</a> in the * Timestream Developer Guide. * </p> * * @param listDatabasesRequest * @return Result of the ListDatabases operation returned by the service. * @throws InternalServerException * Timestream was unable to fully process this request because of an internal server error. * @throws ThrottlingException * Too many requests were made by a user exceeding service quotas. The request was throttled. * @throws ValidationException * Invalid or malformed request. * @throws AccessDeniedException * You are not authorized to perform this action. * @throws InvalidEndpointException * The requested endpoint was invalid. * @sample AmazonTimestreamWrite.ListDatabases * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/timestream-write-2018-11-01/ListDatabases" target="_top">AWS * API Documentation</a> */ ListDatabasesResult listDatabases(ListDatabasesRequest listDatabasesRequest); /** * <p> * A list of tables, along with the name, status and retention properties of each table. * </p> * * @param listTablesRequest * @return Result of the ListTables operation returned by the service. * @throws InternalServerException * Timestream was unable to fully process this request because of an internal server error. * @throws ThrottlingException * Too many requests were made by a user exceeding service quotas. The request was throttled. * @throws ValidationException * Invalid or malformed request. * @throws ResourceNotFoundException * The operation tried to access a nonexistent resource. The resource might not be specified correctly, or * its status might not be ACTIVE. * @throws AccessDeniedException * You are not authorized to perform this action. * @throws InvalidEndpointException * The requested endpoint was invalid. * @sample AmazonTimestreamWrite.ListTables * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/timestream-write-2018-11-01/ListTables" target="_top">AWS * API Documentation</a> */ ListTablesResult listTables(ListTablesRequest listTablesRequest); /** * <p> * List all tags on a Timestream resource. * </p> * * @param listTagsForResourceRequest * @return Result of the ListTagsForResource operation returned by the service. * @throws ResourceNotFoundException * The operation tried to access a nonexistent resource. The resource might not be specified correctly, or * its status might not be ACTIVE. * @throws ThrottlingException * Too many requests were made by a user exceeding service quotas. The request was throttled. * @throws ValidationException * Invalid or malformed request. * @throws InvalidEndpointException * The requested endpoint was invalid. * @sample AmazonTimestreamWrite.ListTagsForResource * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/timestream-write-2018-11-01/ListTagsForResource" * target="_top">AWS API Documentation</a> */ ListTagsForResourceResult listTagsForResource(ListTagsForResourceRequest listTagsForResourceRequest); /** * <p> * Associate a set of tags with a Timestream resource. You can then activate these user-defined tags so that they * appear on the Billing and Cost Management console for cost allocation tracking. * </p> * * @param tagResourceRequest * @return Result of the TagResource operation returned by the service. * @throws ResourceNotFoundException * The operation tried to access a nonexistent resource. The resource might not be specified correctly, or * its status might not be ACTIVE. * @throws ServiceQuotaExceededException * Instance quota of resource exceeded for this account. * @throws ThrottlingException * Too many requests were made by a user exceeding service quotas. The request was throttled. * @throws ValidationException * Invalid or malformed request. * @throws InvalidEndpointException * The requested endpoint was invalid. * @sample AmazonTimestreamWrite.TagResource * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/timestream-write-2018-11-01/TagResource" target="_top">AWS * API Documentation</a> */ TagResourceResult tagResource(TagResourceRequest tagResourceRequest); /** * <p> * Removes the association of tags from a Timestream resource. * </p> * * @param untagResourceRequest * @return Result of the UntagResource operation returned by the service. * @throws ValidationException * Invalid or malformed request. * @throws ServiceQuotaExceededException * Instance quota of resource exceeded for this account. * @throws ThrottlingException * Too many requests were made by a user exceeding service quotas. The request was throttled. * @throws ResourceNotFoundException * The operation tried to access a nonexistent resource. The resource might not be specified correctly, or * its status might not be ACTIVE. * @throws InvalidEndpointException * The requested endpoint was invalid. * @sample AmazonTimestreamWrite.UntagResource * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/timestream-write-2018-11-01/UntagResource" target="_top">AWS * API Documentation</a> */ UntagResourceResult untagResource(UntagResourceRequest untagResourceRequest); /** * <p> * Modifies the KMS key for an existing database. While updating the database, you must specify the database name * and the identifier of the new KMS key to be used (<code>KmsKeyId</code>). If there are any concurrent * <code>UpdateDatabase</code> requests, first writer wins. * </p> * * @param updateDatabaseRequest * @return Result of the UpdateDatabase operation returned by the service. * @throws ValidationException * Invalid or malformed request. * @throws AccessDeniedException * You are not authorized to perform this action. * @throws ResourceNotFoundException * The operation tried to access a nonexistent resource. The resource might not be specified correctly, or * its status might not be ACTIVE. * @throws ServiceQuotaExceededException * Instance quota of resource exceeded for this account. * @throws ThrottlingException * Too many requests were made by a user exceeding service quotas. The request was throttled. * @throws InternalServerException * Timestream was unable to fully process this request because of an internal server error. * @throws InvalidEndpointException * The requested endpoint was invalid. * @sample AmazonTimestreamWrite.UpdateDatabase * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/timestream-write-2018-11-01/UpdateDatabase" * target="_top">AWS API Documentation</a> */ UpdateDatabaseResult updateDatabase(UpdateDatabaseRequest updateDatabaseRequest); /** * <p> * Modifies the retention duration of the memory store and magnetic store for your Timestream table. Note that the * change in retention duration takes effect immediately. For example, if the retention period of the memory store * was initially set to 2 hours and then changed to 24 hours, the memory store will be capable of holding 24 hours * of data, but will be populated with 24 hours of data 22 hours after this change was made. Timestream does not * retrieve data from the magnetic store to populate the memory store. * </p> * <p> * Service quotas apply. For more information, see <a * href="https://docs.aws.amazon.com/timestream/latest/developerguide/ts-limits.html">Access Management</a> in the * Timestream Developer Guide. * </p> * * @param updateTableRequest * @return Result of the UpdateTable operation returned by the service. * @throws InternalServerException * Timestream was unable to fully process this request because of an internal server error. * @throws ThrottlingException * Too many requests were made by a user exceeding service quotas. The request was throttled. * @throws ValidationException * Invalid or malformed request. * @throws ResourceNotFoundException * The operation tried to access a nonexistent resource. The resource might not be specified correctly, or * its status might not be ACTIVE. * @throws AccessDeniedException * You are not authorized to perform this action. * @throws InvalidEndpointException * The requested endpoint was invalid. * @sample AmazonTimestreamWrite.UpdateTable * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/timestream-write-2018-11-01/UpdateTable" target="_top">AWS * API Documentation</a> */ UpdateTableResult updateTable(UpdateTableRequest updateTableRequest); /** * <p> * The WriteRecords operation enables you to write your time series data into Timestream. You can specify a single * data point or a batch of data points to be inserted into the system. Timestream offers you with a flexible schema * that auto detects the column names and data types for your Timestream tables based on the dimension names and * data types of the data points you specify when invoking writes into the database. Timestream support eventual * consistency read semantics. This means that when you query data immediately after writing a batch of data into * Timestream, the query results might not reflect the results of a recently completed write operation. The results * may also include some stale data. If you repeat the query request after a short time, the results should return * the latest data. Service quotas apply. For more information, see <a * href="https://docs.aws.amazon.com/timestream/latest/developerguide/ts-limits.html">Access Management</a> in the * Timestream Developer Guide. * </p> * * @param writeRecordsRequest * @return Result of the WriteRecords operation returned by the service. * @throws InternalServerException * Timestream was unable to fully process this request because of an internal server error. * @throws ThrottlingException * Too many requests were made by a user exceeding service quotas. The request was throttled. * @throws ValidationException * Invalid or malformed request. * @throws ResourceNotFoundException * The operation tried to access a nonexistent resource. The resource might not be specified correctly, or * its status might not be ACTIVE. * @throws AccessDeniedException * You are not authorized to perform this action. * @throws RejectedRecordsException * WriteRecords would throw this exception in the following cases: </p> * <ul> * <li> * <p> * Records with duplicate data where there are multiple records with the same dimensions, timestamps, and * measure names but different measure values. * </p> * </li> * <li> * <p> * Records with timestamps that lie outside the retention duration of the memory store * </p> * </li> * <li> * <p> * Records with dimensions or measures that exceed the Timestream defined limits. * </p> * </li> * </ul> * <p> * For more information, see <a * href="https://docs.aws.amazon.com/timestream/latest/developerguide/ts-limits.html">Access Management</a> * in the Timestream Developer Guide. * @throws InvalidEndpointException * The requested endpoint was invalid. * @sample AmazonTimestreamWrite.WriteRecords * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/timestream-write-2018-11-01/WriteRecords" target="_top">AWS * API Documentation</a> */ WriteRecordsResult writeRecords(WriteRecordsRequest writeRecordsRequest); /** * Shuts down this client object, releasing any resources that might be held open. This is an optional method, and * callers are not expected to call it, but can if they want to explicitly release any open resources. Once a client * has been shutdown, it should not be used to make any more requests. */ void shutdown(); /** * Returns additional metadata for a previously executed successful request, typically used for debugging issues * where a service isn't acting as expected. This data isn't considered part of the result data returned by an * operation, so it's available through this separate, diagnostic interface. * <p> * Response metadata is only cached for a limited period of time, so if you need to access this extra diagnostic * information for an executed request, you should use this method to retrieve it as soon as possible after * executing a request. * * @param request * The originally executed request. * * @return The response metadata for the specified request, or null if none is available. */ ResponseMetadata getCachedResponseMetadata(AmazonWebServiceRequest request); }
/* * Copyright 2006-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.consol.citrus.jms.endpoint; import com.consol.citrus.exceptions.ActionTimeoutException; import com.consol.citrus.exceptions.CitrusRuntimeException; import com.consol.citrus.message.*; import com.consol.citrus.message.Message; import com.consol.citrus.message.correlation.ObjectStore; import com.consol.citrus.testng.AbstractTestNGUnitTest; import org.easymock.EasyMock; import org.testng.Assert; import org.testng.annotations.Test; import javax.jms.*; import java.util.HashMap; import java.util.Map; import static org.easymock.EasyMock.*; /** * @author Christoph Deppisch */ public class JmsEndpointSyncProducerTest extends AbstractTestNGUnitTest { private ConnectionFactory connectionFactory = org.easymock.EasyMock.createMock(ConnectionFactory.class); private Connection connection = EasyMock.createMock(Connection.class); private Session session = EasyMock.createMock(Session.class); private Destination destination = EasyMock.createMock(Destination.class); private Queue destinationQueue = EasyMock.createMock(Queue.class); private MessageConsumer messageConsumer = EasyMock.createMock(MessageConsumer.class); private MessageProducer messageProducer = EasyMock.createMock(MessageProducer.class); private Queue replyDestinationQueue = EasyMock.createMock(Queue.class); private TemporaryQueue tempReplyQueue = EasyMock.createMock(TemporaryQueue.class); private int retryCount = 0; @Test public void testSendMessageWithReplyDestination() throws JMSException { JmsSyncEndpoint endpoint = new JmsSyncEndpoint(); endpoint.getEndpointConfiguration().setConnectionFactory(connectionFactory); endpoint.getEndpointConfiguration().setDestination(destination); endpoint.getEndpointConfiguration().setReplyDestination(replyDestinationQueue); final Message message = new DefaultMessage("<TestRequest><Message>Hello World!</Message></TestRequest>"); Map<String, Object> responseHeaders = new HashMap<String, Object>(); TextMessage jmsResponse = new TextMessageImpl("<TestResponse>Hello World!</TestResponse>", responseHeaders); reset(connectionFactory, destination, connection, session, messageConsumer, messageProducer); expect(connectionFactory.createConnection()).andReturn(connection).once(); connection.start(); expectLastCall().once(); expect(connection.createSession(anyBoolean(), anyInt())).andReturn(session).once(); expect(session.createConsumer(replyDestinationQueue, "JMSCorrelationID = '123456789'")).andReturn(messageConsumer).once(); expect(messageConsumer.receive(anyLong())).andReturn(jmsResponse).once(); expect(session.createProducer(destination)).andReturn(messageProducer).once(); messageProducer.send((TextMessage)anyObject()); expectLastCall().once(); expect(session.createTextMessage("<TestRequest><Message>Hello World!</Message></TestRequest>")).andReturn( new TextMessageImpl("<TestRequest><Message>Hello World!</Message></TestRequest>", new HashMap<String, Object>())); replay(connectionFactory, destination, connection, session, messageConsumer, messageProducer); endpoint.createProducer().send(message, context); verify(connectionFactory, destination, connection, session, messageConsumer, messageProducer); } @Test public void testSendMessageWithReplyDestinationName() throws JMSException { JmsSyncEndpoint endpoint = new JmsSyncEndpoint(); endpoint.getEndpointConfiguration().setConnectionFactory(connectionFactory); endpoint.getEndpointConfiguration().setDestinationName("myDestination"); endpoint.getEndpointConfiguration().setReplyDestinationName("replyDestination"); final Message message = new DefaultMessage("<TestRequest><Message>Hello World!</Message></TestRequest>"); Map<String, Object> responseHeaders = new HashMap<String, Object>(); TextMessage jmsResponse = new TextMessageImpl("<TestResponse>Hello World!</TestResponse>", responseHeaders); reset(connectionFactory, destination, connection, session, messageConsumer, messageProducer); expect(connectionFactory.createConnection()).andReturn(connection).once(); connection.start(); expectLastCall().once(); expect(connection.createSession(anyBoolean(), anyInt())).andReturn(session).once(); expect(session.createQueue("replyDestination")).andReturn(replyDestinationQueue).once(); expect(session.createConsumer(replyDestinationQueue, "JMSCorrelationID = '123456789'")).andReturn(messageConsumer).once(); expect(messageConsumer.receive(anyLong())).andReturn(jmsResponse).once(); expect(session.createProducer(destinationQueue)).andReturn(messageProducer).once(); messageProducer.send((TextMessage)anyObject()); expectLastCall().once(); expect(session.createTextMessage("<TestRequest><Message>Hello World!</Message></TestRequest>")).andReturn( new TextMessageImpl("<TestRequest><Message>Hello World!</Message></TestRequest>", new HashMap<String, Object>())); expect(session.createQueue("myDestination")).andReturn(destinationQueue).once(); replay(connectionFactory, destination, connection, session, messageConsumer, messageProducer); endpoint.createProducer().send(message, context); verify(connectionFactory, destination, connection, session, messageConsumer, messageProducer); } @Test public void testSendMessageWithTemporaryReplyDestination() throws JMSException { JmsSyncEndpoint endpoint = new JmsSyncEndpoint(); endpoint.getEndpointConfiguration().setConnectionFactory(connectionFactory); endpoint.getEndpointConfiguration().setDestination(destination); final Message message = new DefaultMessage("<TestRequest><Message>Hello World!</Message></TestRequest>"); Map<String, Object> responseHeaders = new HashMap<String, Object>(); TextMessage jmsResponse = new TextMessageImpl("<TestResponse>Hello World!</TestResponse>", responseHeaders); reset(connectionFactory, destination, connection, session, messageConsumer, messageProducer, tempReplyQueue); expect(connectionFactory.createConnection()).andReturn(connection).once(); connection.start(); expectLastCall().once(); expect(connection.createSession(anyBoolean(), anyInt())).andReturn(session).once(); expect(session.createTemporaryQueue()).andReturn(tempReplyQueue).once(); expect(session.createConsumer(tempReplyQueue)).andReturn(messageConsumer).once(); expect(messageConsumer.receive(anyLong())).andReturn(jmsResponse).once(); expect(session.createProducer(destination)).andReturn(messageProducer).once(); messageProducer.send((TextMessage)anyObject()); expectLastCall().once(); expect(session.createTextMessage("<TestRequest><Message>Hello World!</Message></TestRequest>")).andReturn( new TextMessageImpl("<TestRequest><Message>Hello World!</Message></TestRequest>", new HashMap<String, Object>())); tempReplyQueue.delete(); expectLastCall().once(); replay(connectionFactory, destination, connection, session, messageConsumer, messageProducer, tempReplyQueue); endpoint.createProducer().send(message, context); verify(connectionFactory, destination, connection, session, messageConsumer, messageProducer, tempReplyQueue); } @Test @SuppressWarnings("rawtypes") public void testSendMessageWithReplyHandler() throws JMSException { JmsSyncEndpoint endpoint = new JmsSyncEndpoint(); endpoint.getEndpointConfiguration().setConnectionFactory(connectionFactory); endpoint.getEndpointConfiguration().setDestination(destination); endpoint.getEndpointConfiguration().setReplyDestination(replyDestinationQueue); final Message message = new DefaultMessage("<TestRequest><Message>Hello World!</Message></TestRequest>"); Map<String, Object> responseHeaders = new HashMap<String, Object>(); TextMessage jmsResponse = new TextMessageImpl("<TestResponse>Hello World!</TestResponse>", responseHeaders); reset(connectionFactory, destination, connection, session, messageConsumer, messageProducer); expect(connectionFactory.createConnection()).andReturn(connection).once(); connection.start(); expectLastCall().once(); expect(connection.createSession(anyBoolean(), anyInt())).andReturn(session).once(); expect(session.createConsumer(replyDestinationQueue, "JMSCorrelationID = '123456789'")).andReturn(messageConsumer).once(); expect(messageConsumer.receive(anyLong())).andReturn(jmsResponse).once(); expect(session.createProducer(destination)).andReturn(messageProducer).once(); messageProducer.send((TextMessage)anyObject()); expectLastCall().once(); expect(session.createTextMessage("<TestRequest><Message>Hello World!</Message></TestRequest>")).andReturn( new TextMessageImpl("<TestRequest><Message>Hello World!</Message></TestRequest>", new HashMap<String, Object>())); replay(connectionFactory, destination, connection, session, messageConsumer, messageProducer); endpoint.createProducer().send(message, context); verify(connectionFactory, destination, connection, session, messageConsumer, messageProducer); } @Test @SuppressWarnings("rawtypes") public void testSendMessageWithReplyMessageCorrelator() throws JMSException { JmsSyncEndpoint endpoint = new JmsSyncEndpoint(); endpoint.getEndpointConfiguration().setConnectionFactory(connectionFactory); endpoint.getEndpointConfiguration().setDestination(destination); endpoint.getEndpointConfiguration().setReplyDestination(replyDestinationQueue); MessageCorrelator correlator = new DefaultMessageCorrelator(); endpoint.getEndpointConfiguration().setCorrelator(correlator); final Message message = new DefaultMessage("<TestRequest><Message>Hello World!</Message></TestRequest>"); Map<String, Object> responseHeaders = new HashMap<String, Object>(); TextMessage jmsResponse = new TextMessageImpl("<TestResponse>Hello World!</TestResponse>", responseHeaders); reset(connectionFactory, destination, connection, session, messageConsumer, messageProducer); expect(connectionFactory.createConnection()).andReturn(connection).once(); connection.start(); expectLastCall().once(); expect(connection.createSession(anyBoolean(), anyInt())).andReturn(session).once(); expect(session.createConsumer(replyDestinationQueue, "JMSCorrelationID = '123456789'")).andReturn(messageConsumer).once(); expect(messageConsumer.receive(anyLong())).andReturn(jmsResponse).once(); expect(session.createProducer(destination)).andReturn(messageProducer).once(); messageProducer.send((TextMessage)anyObject()); expectLastCall().once(); expect(session.createTextMessage("<TestRequest><Message>Hello World!</Message></TestRequest>")).andReturn( new TextMessageImpl("<TestRequest><Message>Hello World!</Message></TestRequest>", new HashMap<String, Object>())); replay(connectionFactory, destination, connection, session, messageConsumer, messageProducer); endpoint.createProducer().send(message, context); verify(connectionFactory, destination, connection, session, messageConsumer, messageProducer); } @Test public void testSendEmptyMessage() throws JMSException { JmsSyncEndpoint endpoint = new JmsSyncEndpoint(); endpoint.getEndpointConfiguration().setConnectionFactory(connectionFactory); endpoint.getEndpointConfiguration().setDestination(destination); try { endpoint.createProducer().send(null, context); } catch(IllegalArgumentException e) { Assert.assertEquals(e.getMessage(), "Message is empty - unable to send empty message"); return; } Assert.fail("Missing " + CitrusRuntimeException.class + " because of sending empty message"); } @Test public void testOnReplyMessage() { JmsSyncEndpoint endpoint = new JmsSyncEndpoint(); final Message message = new DefaultMessage("<TestRequest><Message>Hello World!</Message></TestRequest>"); JmsSyncProducer jmsSyncProducer = (JmsSyncProducer)endpoint.createProducer(); jmsSyncProducer.getCorrelationManager().saveCorrelationKey( endpoint.getEndpointConfiguration().getCorrelator().getCorrelationKeyName(jmsSyncProducer.getName()), jmsSyncProducer.toString(), context); jmsSyncProducer.getCorrelationManager().store(jmsSyncProducer.toString(), message); Assert.assertEquals(jmsSyncProducer.receive(context), message); } @Test public void testOnReplyMessageWithCorrelatorKey() { JmsSyncEndpoint endpoint = new JmsSyncEndpoint(); final Message message = new DefaultMessage("<TestRequest><Message>Hello World!</Message></TestRequest>"); JmsSyncProducer jmsSyncProducer = (JmsSyncProducer)endpoint.createProducer(); jmsSyncProducer.getCorrelationManager().store(new DefaultMessageCorrelator().getCorrelationKey(message), message); Assert.assertEquals(jmsSyncProducer.receive(new DefaultMessageCorrelator().getCorrelationKey(message), context), message); } @Test public void testReplyMessageRetries() { retryCount = 0; final Message message = new DefaultMessage("<TestRequest><Message>Hello World!</Message></TestRequest>"); JmsSyncEndpoint endpoint = new JmsSyncEndpoint(); ((JmsSyncProducer)endpoint.createProducer()).getCorrelationManager().setObjectStore(new ObjectStore<Message>() { @Override public void add(String correlationKey, Message object) { } @Override public Message remove(String correlationKey) { retryCount++; if (retryCount == 5) { return message; } else { return null; } } }); JmsSyncProducer jmsSyncProducer = (JmsSyncProducer)endpoint.createConsumer(); jmsSyncProducer.getCorrelationManager().saveCorrelationKey( endpoint.getEndpointConfiguration().getCorrelator().getCorrelationKeyName(jmsSyncProducer.getName()), jmsSyncProducer.toString(), context); Assert.assertEquals(retryCount, 0); Assert.assertEquals(jmsSyncProducer.receive(context, 2500), message); Assert.assertEquals(retryCount, 5); } @Test public void testReplyMessageRetriesExceeded() { retryCount = 0; JmsSyncEndpoint endpoint = new JmsSyncEndpoint(); endpoint.getEndpointConfiguration().setPollingInterval(300L); ((JmsSyncProducer)endpoint.createProducer()).getCorrelationManager().setObjectStore(new ObjectStore<Message>() { @Override public void add(String correlationKey, Message object) { } @Override public Message remove(String correlationKey) { retryCount++; return null; } }); JmsSyncProducer jmsSyncProducer = (JmsSyncProducer)endpoint.createConsumer(); jmsSyncProducer.getCorrelationManager().saveCorrelationKey( endpoint.getEndpointConfiguration().getCorrelator().getCorrelationKeyName(jmsSyncProducer.getName()), jmsSyncProducer.toString(), context); Assert.assertEquals(retryCount, 0); try { jmsSyncProducer.receive(context, 800); Assert.fail("Missing action timeout exception"); } catch (ActionTimeoutException e) { Assert.assertEquals(retryCount, 4); } } @Test public void testIntervalGreaterThanTimeout() { retryCount = 0; JmsSyncEndpoint endpoint = new JmsSyncEndpoint(); endpoint.getEndpointConfiguration().setPollingInterval(1000L); ((JmsSyncProducer)endpoint.createProducer()).getCorrelationManager().setObjectStore(new ObjectStore<Message>() { @Override public void add(String correlationKey, Message object) { } @Override public Message remove(String correlationKey) { retryCount++; return null; } }); JmsSyncProducer jmsSyncProducer = (JmsSyncProducer)endpoint.createConsumer(); jmsSyncProducer.getCorrelationManager().saveCorrelationKey( endpoint.getEndpointConfiguration().getCorrelator().getCorrelationKeyName(jmsSyncProducer.getName()), jmsSyncProducer.toString(), context); Assert.assertEquals(retryCount, 0); try { jmsSyncProducer.receive(context, 250); Assert.fail("Missing action timeout exception"); } catch (ActionTimeoutException e) { Assert.assertEquals(retryCount, 2); } } @Test public void testZeroTimeout() { retryCount = 0; JmsSyncEndpoint endpoint = new JmsSyncEndpoint(); endpoint.getEndpointConfiguration().setPollingInterval(1000L); ((JmsSyncProducer)endpoint.createProducer()).getCorrelationManager().setObjectStore(new ObjectStore<Message>() { @Override public void add(String correlationKey, Message object) { } @Override public Message remove(String correlationKey) { retryCount++; return null; } }); JmsSyncProducer jmsSyncProducer = (JmsSyncProducer)endpoint.createConsumer(); jmsSyncProducer.getCorrelationManager().saveCorrelationKey( endpoint.getEndpointConfiguration().getCorrelator().getCorrelationKeyName(jmsSyncProducer.getName()), jmsSyncProducer.toString(), context); Assert.assertEquals(retryCount, 0); try { jmsSyncProducer.receive(context, 0); Assert.fail("Missing action timeout exception"); } catch (ActionTimeoutException e) { Assert.assertEquals(retryCount, 1); } } }
/* * Copyright (c) 2015, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder 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 * HOLDER 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 no.nordicsemi.android.nrftoolbox.csc; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattService; import android.content.Context; import java.util.LinkedList; import java.util.Queue; import java.util.UUID; import no.nordicsemi.android.log.Logger; import no.nordicsemi.android.nrftoolbox.profile.BleManager; import no.nordicsemi.android.nrftoolbox.parser.CSCMeasurementParser; public class CSCManager extends BleManager<CSCManagerCallbacks> { /** Cycling Speed and Cadence service UUID */ public final static UUID CYCLING_SPEED_AND_CADENCE_SERVICE_UUID = UUID.fromString("00001816-0000-1000-8000-00805f9b34fb"); /** Cycling Speed and Cadence Measurement characteristic UUID */ private static final UUID CSC_MEASUREMENT_CHARACTERISTIC_UUID = UUID.fromString("00002A5B-0000-1000-8000-00805f9b34fb"); private static final byte WHEEL_REVOLUTIONS_DATA_PRESENT = 0x01; // 1 bit private static final byte CRANK_REVOLUTION_DATA_PRESENT = 0x02; // 1 bit private BluetoothGattCharacteristic mCSCMeasurementCharacteristic; public CSCManager(final Context context) { super(context); } @Override protected BleManagerGattCallback getGattCallback() { return mGattCallback; } /** * BluetoothGatt callbacks for connection/disconnection, service discovery, receiving indication, etc */ private final BleManagerGattCallback mGattCallback = new BleManagerGattCallback() { @Override protected Queue<Request> initGatt(final BluetoothGatt gatt) { final LinkedList<Request> requests = new LinkedList<>(); requests.push(Request.newEnableNotificationsRequest(mCSCMeasurementCharacteristic)); return requests; } @Override public boolean isRequiredServiceSupported(final BluetoothGatt gatt) { final BluetoothGattService service = gatt.getService(CYCLING_SPEED_AND_CADENCE_SERVICE_UUID); if (service != null) { mCSCMeasurementCharacteristic = service.getCharacteristic(CSC_MEASUREMENT_CHARACTERISTIC_UUID); } return mCSCMeasurementCharacteristic != null; } @Override protected void onDeviceDisconnected() { mCSCMeasurementCharacteristic = null; } @Override public void onCharacteristicNotified(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) { if (mLogSession != null) Logger.a(mLogSession, CSCMeasurementParser.parse(characteristic)); // Decode the new data int offset = 0; final int flags = characteristic.getValue()[offset]; // 1 byte offset += 1; final boolean wheelRevPresent = (flags & WHEEL_REVOLUTIONS_DATA_PRESENT) > 0; final boolean crankRevPreset = (flags & CRANK_REVOLUTION_DATA_PRESENT) > 0; if (wheelRevPresent) { final int wheelRevolutions = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT32, offset); offset += 4; final int lastWheelEventTime = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, offset); // 1/1024 s offset += 2; // Notify listener about the new measurement mCallbacks.onWheelMeasurementReceived(wheelRevolutions, lastWheelEventTime); } if (crankRevPreset) { final int crankRevolutions = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, offset); offset += 2; final int lastCrankEventTime = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, offset); // offset += 2; // Notify listener about the new measurement mCallbacks.onCrankMeasurementReceived(crankRevolutions, lastCrankEventTime); } } }; }
package fun.boomcat.luckyhe.mirai.plugin.luckyminecraftqqchatmiraiconsole.pojo; public class SessionGroup { private long id; private String name; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "SessionGroup{" + "id=" + id + ", name='" + name + '\'' + '}'; } public SessionGroup(long id, String name) { this.id = id; this.name = name; } }
//============================================================================== // This software is part of the Open Standard for Unattended Sensors (OSUS) // reference implementation (OSUS-R). // // To the extent possible under law, the author(s) have dedicated all copyright // and related and neighboring rights to this software to the public domain // worldwide. This software is distributed without any warranty. // // You should have received a copy of the CC0 Public Domain Dedication along // with this software. If not, see // <http://creativecommons.org/publicdomain/zero/1.0/>. //============================================================================== package mil.dod.th.ose.time.service; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.mockito.Mockito.*; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.nio.ByteBuffer; import mil.dod.th.ose.time.service.util.ChangeSystemTimeWrapper; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; /** * Tests thread which listens to a socket and alters the system time. * * @author nickmarcucci * */ public class TestTimeChangeServiceThread { private TimeChangeServiceThread m_SUT; private ServerSocket m_ServerSocket; private ChangeSystemTimeWrapper m_SysTimeWrapper; @Before public void init() throws SocketException { m_ServerSocket = mock(ServerSocket.class); m_SysTimeWrapper = mock(ChangeSystemTimeWrapper.class); m_SUT = new TimeChangeServiceThread(m_ServerSocket, m_SysTimeWrapper); verify(m_ServerSocket).setSoTimeout(eq(10000)); } /** * Verify that thread can be successfully run and a call to set the system time * is made. */ @Test public void testRun() throws IOException, InterruptedException { Socket client = mock(Socket.class); when(m_ServerSocket.accept()).thenReturn(client); long time = System.currentTimeMillis(); ByteBuffer buffer = ByteBuffer.allocate(8); buffer.putLong(time); InputStream stream = new ByteArrayInputStream(buffer.array()); when(client.getInputStream()).thenReturn(stream); //kick off runner Thread thread = new Thread(m_SUT); thread.start(); //give thread time to run ArgumentCaptor<Long> captor = ArgumentCaptor.forClass(Long.class); verify(m_SysTimeWrapper, timeout(1000)).setSystemTime(captor.capture()); m_SUT.stopRun(); thread.join(5000); verify(client, atLeast(1)).setSoTimeout(eq(10000)); assertThat(captor.getValue().longValue(), is(time)); } /** * Verify that a heartbeat message does not cause the system time to be set. */ @Test public void testRunHeartbeatMessage() throws IOException, InterruptedException { Socket client = mock(Socket.class); when(m_ServerSocket.accept()).thenReturn(client); long heartbeat = -22L; ByteBuffer buffer = ByteBuffer.allocate(8); buffer.putLong(heartbeat); InputStream stream = new ByteArrayInputStream(buffer.array()); when(client.getInputStream()).thenReturn(stream); //kick off runner Thread thread = new Thread(m_SUT); thread.start(); //give thread time to run Thread.sleep(50); m_SUT.stopRun(); thread.join(5000); verify(m_SysTimeWrapper, never()).setSystemTime(Mockito.anyLong()); } /** * Verify if no input received socket timeout occurs and the system time is never set. */ @Test public void testRunReadTimeout() throws IOException, InterruptedException { Socket client = mock(Socket.class); when(m_ServerSocket.accept()).thenReturn(client); InputStream stream = mock(InputStream.class); when(client.getInputStream()).thenReturn(stream); doThrow(SocketException.class). when(stream).read(Mockito.any(byte[].class), Mockito.anyInt(), Mockito.anyInt()); //kick off runner Thread thread = new Thread(m_SUT); thread.start(); //give thread time to run Thread.sleep(100); m_SUT.stopRun(); thread.join(5000); verify(m_SysTimeWrapper, never()).setSystemTime(Mockito.anyLong()); } /** * Verify if input stream closed, then the client is closed as well. */ @Test public void testRunReadEndofInputStream() throws IOException, InterruptedException { Socket client = mock(Socket.class); when(m_ServerSocket.accept()).thenReturn(client); InputStream stream = mock(InputStream.class); when(client.getInputStream()).thenReturn(stream); when(stream.read(Mockito.any(byte[].class), Mockito.anyInt(), Mockito.anyInt())).thenReturn(-1); //kick off runner Thread thread = new Thread(m_SUT); thread.start(); verify(stream, timeout(1000).atLeast(1)).close(); m_SUT.stopRun(); thread.join(5000); verify(m_SysTimeWrapper, never()).setSystemTime(Mockito.anyLong()); verify(client, atLeast(1)).close(); } /** * Verify that an exception with opening a socket's input stream * cause the code to go back to listen for a new client and closes * the client connection. */ @Test public void testRunInputStreamException() throws IOException, InterruptedException { Socket client = mock(Socket.class); when(m_ServerSocket.accept()).thenReturn(client); doThrow(IOException.class).when(client).getInputStream(); //kick off runner Thread thread = new Thread(m_SUT); thread.start(); //give thread time to run verify(m_ServerSocket, timeout(1000).atLeast(2)).accept(); verify(client, atLeast(1)).close(); verify(m_SysTimeWrapper, never()).setSystemTime(Mockito.anyLong()); m_SUT.stopRun(); thread.join(5000); } /** * Verify that an exception with the server socket receiving client connections * is handled properly. */ @Test public void testRunServerAcceptException() throws IOException, InterruptedException { doThrow(IOException.class).when(m_ServerSocket).accept(); Thread thread = new Thread(m_SUT); thread.start(); verify(m_ServerSocket, timeout(2000).atLeast(2)).accept(); m_SUT.stopRun(); thread.join(5000); verify(m_SysTimeWrapper, never()).setSystemTime(Mockito.anyLong()); } /** * Verify server socket and client connections are closed properly. */ @Test public void testStopRun() throws IOException, InterruptedException { Socket client = mock(Socket.class); when(m_ServerSocket.accept()).thenReturn(client); long time = System.currentTimeMillis(); ByteBuffer buffer = ByteBuffer.allocate(8); buffer.putLong(time); InputStream stream = new ByteArrayInputStream(buffer.array()); when(client.getInputStream()).thenReturn(stream); //kick off runner Thread thread = new Thread(m_SUT); thread.start(); Thread.sleep(50); m_SUT.stopRun(); thread.join(5000); verify(client, atLeast(1)).close(); verify(m_ServerSocket).close(); } /** * Verify stop called and an exception is properly handled. */ @Test public void testStopRunThrowException() throws IOException { doThrow(IOException.class).when(m_ServerSocket).close(); m_SUT.stopRun(); verify(m_ServerSocket).close(); } }
package com.gsnathan.android_scouter; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Spinner; import com.cepheuen.elegantnumberbutton.view.ElegantNumberButton; import com.google.android.material.snackbar.Snackbar; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; public class MainActivity extends AppCompatActivity { EditText teamText, notesText; Spinner sandStartPosition, sandStartPiece, climb; ElegantNumberButton sandCargo, sandHatch, shipCargo, shipHatch, rocketCargo, rocketHatch, dropCargo, dropHatch; CheckBox level1, level2, level3; ArrayList<ElegantNumberButton> counters; int[] counterValues; CSVWriterTool writer; Button deleteButton; public static StringBuilder ultimate; int saves = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); teamText = findViewById(R.id.editTeamNumber); notesText = findViewById(R.id.editNotes); sandStartPosition = findViewById(R.id.spin_sand_start); sandStartPiece = findViewById(R.id.spin_sand_piece); climb = findViewById(R.id.spin_climb); sandCargo = findViewById(R.id.sand_cargo_count); sandHatch = findViewById(R.id.sand_hatch_count); shipCargo = findViewById(R.id.game_ship_cargo_count); shipHatch = findViewById(R.id.game_ship_hatch_count); rocketCargo = findViewById(R.id.game_rocket_cargo_count); rocketHatch = findViewById(R.id.game_rocket_hatch_count); dropCargo = findViewById(R.id.drop_cargo_count); dropHatch = findViewById(R.id.drop_hatch_count); counters = new ArrayList<ElegantNumberButton>() { { add(sandCargo); add(sandHatch); add(shipCargo); add(shipHatch); add(rocketCargo); add(rocketHatch); add(dropCargo); add(dropHatch); } }; counterValues = new int[counters.size()]; level1 = findViewById(R.id.rocket_level1); level2 = findViewById(R.id.rocket_level2); level3 = findViewById(R.id.rocket_level3); deleteButton = findViewById(R.id.clearButton); deleteButton.setOnClickListener(v -> clearView()); deleteButton.setOnLongClickListener(v -> { AlertDialog.Builder deleteLog = new AlertDialog.Builder(MainActivity.this); deleteLog.setMessage("Are you sure you want to delete the whole file? You will lose all data!"); deleteLog.setCancelable(false); deleteLog.setPositiveButton( "Yes", (dialog, id) -> { try { writer.clearCSV(); saves = 0; clearView(); } catch (IOException e) { e.printStackTrace(); } dialog.cancel(); }); deleteLog.setNegativeButton( "No", (dialog, id) -> dialog.cancel()); AlertDialog deleteCSV = deleteLog.create(); deleteCSV.show(); return false; }); writer = new CSVWriterTool(); updateCounterValues(); } private void updateCounterValues() { for(ElegantNumberButton e : counters){ e.setOnValueChangeListener((view, oldValue, newValue) -> { counterValues[counters.indexOf(e)] = newValue; Log.d("Counts", Arrays.toString(counterValues)); }); } } public void saveData(View v) { String teamNum = teamText.getText().toString(); int startSpinnerChoice = sandStartPosition.getSelectedItemPosition(); int startSpinnerPiece = sandStartPiece.getSelectedItemPosition(); int sandCargo = counterValues[0]; int sandHatch = counterValues[1]; int shipCargo = counterValues[2]; int shipHatch = counterValues[3]; int rocketCargo = counterValues[4]; int rocketHatches = counterValues[5]; int ifLevel1 = level1.isChecked() ? 1 : 0; int ifLevel2 = level2.isChecked() ? 1 : 0; int ifLevel3 = level3.isChecked() ? 1 : 0; int dropCargo = counterValues[6]; int dropHatch = counterValues[7]; int climbPosition = climb.getSelectedItemPosition(); String notes = notesText.getText().toString().isEmpty() ? "No Notes" : notesText.getText().toString(); String[] data = {teamNum, String.valueOf(startSpinnerChoice), String.valueOf(startSpinnerPiece), String.valueOf(sandCargo), String.valueOf(sandHatch), String.valueOf(shipCargo), String.valueOf(shipHatch), String.valueOf(rocketCargo), String.valueOf(rocketHatches), String.valueOf(ifLevel1), String.valueOf(ifLevel2), String.valueOf(ifLevel3), String.valueOf(dropCargo), String.valueOf(dropHatch), String.valueOf(climbPosition), notes}; try { writer.writeLineToCSV(data); } catch (IOException e) { Snackbar mySnackBar = Snackbar.make(findViewById(android.R.id.content), "IOEXCEPTION", Snackbar.LENGTH_LONG); mySnackBar.show(); } clearView(); Snackbar mySnackBar = Snackbar.make(findViewById(android.R.id.content), "Saved data!", Snackbar.LENGTH_LONG); mySnackBar.show(); saves++; if(saves == 5){ Snackbar snack = Snackbar.make(findViewById(android.R.id.content), "Please scan with the master app! (10 saves)", Snackbar.LENGTH_LONG); snack.show(); } } private void clearView() { teamText.getText().clear(); sandStartPosition.setSelection(0); sandStartPiece.setSelection(0); for (ElegantNumberButton e : counters){ e.setNumber("0"); } Arrays.fill(counterValues, 0); level1.setChecked(false); level2.setChecked(false); level3.setChecked(false); climb.setSelection(0); notesText.getText().clear(); } public void genQR(View v) { ArrayList<String[]> dataList = null; try { dataList = writer.readCsvAsList(); ultimate = new StringBuilder(); ultimate.append(""); for (int x = 0; x < dataList.size(); x++) { for (String s : dataList.get(x)) { ultimate.append(s).append(","); } if (x != dataList.size() - 1) ultimate.append("br,"); } } catch (IOException e) { e.printStackTrace(); } QRDialog dialog = new QRDialog(); dialog.show(getSupportFragmentManager(), "h"); } }
/* * Copyright (c) 2015 Cloudera, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cloudera.nav.sdk.model.entities; import com.cloudera.nav.sdk.model.HiveIdGenerator; import com.cloudera.nav.sdk.model.SourceType; import com.cloudera.nav.sdk.model.annotations.MClass; import com.cloudera.nav.sdk.model.annotations.MProperty; /** * Represents a Hive table; uniquely identified by the source id, database name, * and table name */ @MClass(model = "hv_table") public class HiveTable extends Entity { @MProperty private String databaseName; public HiveTable() { setSourceType(SourceType.HIVE); setEntityType(EntityType.TABLE); } public HiveTable(String sourceId, String db, String table) { this(); setSourceId(sourceId); setDatabaseName(db); setTableName(table); setIdentity(generateId()); } /** * A Hive table is identified by the source id, database name, and table name * * @return the entity id for this Hive table */ @Override public String generateId() { return HiveIdGenerator.generateTableId(getSourceId(), getDatabaseName(), getTableName()); } public String getDatabaseName() { return databaseName; } public void setDatabaseName(String databaseName) { this.databaseName = databaseName; } /** * @return the table name. This aliases getName */ public String getTableName() { return getName(); } /** * Change the table name. This aliases setName * @param tableName */ public void setTableName(String tableName) { setName(tableName); } }
package lib.ui.android; import io.appium.java_client.AppiumDriver; import lib.ui.NavigationUI; public class AndroidNavigationUI extends NavigationUI { static { MY_LISTS_LINK = "xpath://android.widget.FrameLayout[@content-desc='My lists']"; } public AndroidNavigationUI(AppiumDriver driver) { super(driver); } }
/** * Copyright (c) 2009 - 2012 AppWork UG(haftungsbeschränkt) <e-mail@appwork.org> * * This file is part of org.appwork.utils.awf * * This software is licensed under the Artistic License 2.0, * see the LICENSE file or http://www.opensource.org/licenses/artistic-license-2.0.php * for details */ package org.appwork.utils.awfc; /** * @author Daniel Wilhelm * */ public class AWFCEntry { private final byte[] hash; private final String path; private final boolean isFile; private final long size; public AWFCEntry(final String path, final long size, final byte[] hash) { if (path.endsWith("/")) { this.path = path.substring(0, path.length() - 1); this.isFile = false; this.size = 0; this.hash = null; } else { if (size < 0) { throw new IllegalArgumentException("Size must be >=0"); } this.size = size; this.isFile = true; this.path = path; this.hash = hash; } } public byte[] getHash() { return this.hash; } public String getPath() { return this.path; } public long getSize() { return this.size; } public boolean isFile() { return this.isFile; } @Override public String toString() { return "AWFCEntry [path=" + this.path + ", isFile=" + this.isFile + ", size=" + this.size + "]"; } }
package gov.cms.qpp.conversion.model.error; import org.apache.commons.text.StringSubstitutor; import gov.cms.qpp.conversion.DocumentationReference; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * Error codes that may be returned by the converter */ public enum ErrorCode implements LocalizedError { ENCODER_MISSING(1, "Failed to find an encoder"), NOT_VALID_XML_DOCUMENT(2, "The file is not a valid XML document. The file you are submitting is not a " + "properly formatted XML document. Please check your document to ensure proper formatting."), UNEXPECTED_ERROR(3, "Unexpected exception occurred during conversion. " + ServiceCenter.MESSAGE), UNEXPECTED_ENCODE_ERROR(4, "Unexpected exception occurred during encoding. " + ServiceCenter.MESSAGE), NOT_VALID_QRDA_DOCUMENT(5, "The file is not a QRDA-III XML document. " + "Please ensure that the submission complies with the `(Submission year's)` implementation guide. " + "`(Implementation guide link)`", true), MEASURE_GUID_MISSING(6, "The measure GUID supplied `(Provided measure id)` is invalid. Please see the `(Submission year's)` IG " + DocumentationReference.MEASURE_IDS + " for valid measure GUIDs.", true), CHILD_MEASURE_MISSING(7, "The measure reference results must have at least one measure. " + "Please review the measures section of your file as it cannot be empty."), AGGREGATE_COUNT_VALUE_NOT_SINGULAR(8, "The `(Parent element)` has `(number of aggregate counts)` aggregate count values." + " A single aggregate count value is required.", true), AGGREGATE_COUNT_VALUE_NOT_INTEGER(9, "Aggregate count value must be an integer"), PI_MEASURE_PERFORMED_RNR_MEASURE_PERFORMED_EXACT(11, "This PI Reference and Results is missing a required " + "Measure Performed child"), PI_MEASURE_PERFORMED_RNR_MEASURE_ID_NOT_SINGULAR(12, "This PI Measure Performed Reference and Results requires " + "a single Measure ID"), DENOMINATOR_COUNT_INVALID(13, "Denominator count must be less than or equal to Initial Population count " + "for a measure that is a proportion measure"), POPULATION_CRITERIA_COUNT_INCORRECT(14, "The electronic measure id: `(Current eMeasure ID)` requires `(Number of Subpopulations required)` " + "`(Type of Subpopulation required)`(s) but there are `(Number of Subpopulations existing)`", true), PI_NUMERATOR_DENOMINATOR_PARENT_NOT_PI_SECTION(15, "PI Numerator Denominator element should have a PI " + "Section element as a parent"), PI_NUMERATOR_DENOMINATOR_MISSING_MEASURE_ID(16, "PI Numerator Denominator element does not contain a " + "measure name ID"), PI_NUMERATOR_DENOMINATOR_MISSING_CHILDREN(17, "PI Numerator Denominator element does not have any child " + "elements"), PI_NUMERATOR_DENOMINATOR_VALIDATOR_EXACTLY_ONE_NUMERATOR_OR_DENOMINATOR_CHILD_NODE(18, "This PI Numerator Denominator " + "element requires exactly one `(Denominator|Numerator)` element child", true), PI_SECTION_MISSING_REPORTING_PARAMETER_ACT(22, "The PI Section must have one Reporting Parameter Act." + " Please ensure the Reporting Parameters Act complies with the Implementation Guide (IG)." + " Here is a link to the IG Reporting Parameter Act section: " + DocumentationReference.REPORTING_PARAMETERS_ACT), CLINICAL_DOCUMENT_MISSING_PI_OR_IA_OR_ECQM_CHILD(23, "Clinical Document element must have at least one child " + "element of type PI, IA, or Measure section"), CLINICAL_DOCUMENT_MISSING_PROGRAM_NAME(24, "Clinical Document must have one and only one program name." + " Valid program names are `(list of valid program names)`", true), CLINICAL_DOCUMENT_INCORRECT_PROGRAM_NAME(25, "The Clinical Document program name `(program name)` is not recognized. Valid " + "program names are `(list of valid program names)`.", true), CLINICAL_DOCUMENT_CONTAINS_DUPLICATE_PI_SECTIONS(26, "Clinical Document contains duplicate PI sections"), CLINICAL_DOCUMENT_CONTAINS_DUPLICATE_IA_SECTIONS(27, "Clinical Document contains duplicate IA sections"), CLINICAL_DOCUMENT_CONTAINS_DUPLICATE_ECQM_SECTIONS(28, "Clinical Document contains duplicate Measure " + "sections"), REPORTING_PARAMETERS_MUST_CONTAIN_SINGLE_PERFORMANCE_START(29, "Must have one and only one performance period " + "start. Please see the Implementation Guide for information on the performance period here: " //NOSONAR + DocumentationReference.PERFORMANCE_PERIOD), REPORTING_PARAMETERS_MUST_CONTAIN_SINGLE_PERFORMANCE_END(30, "Must have one and only one performance period end. " + "Please see the Implementation Guide for information on the performance period here: " //NOSONAR + DocumentationReference.PERFORMANCE_PERIOD), REPORTING_PARAMETERS_MISSING_PERFORMANCE_YEAR(31, "Must have a performance year. " + "Please see the Implementation Guide for information on the performance period here: " //NOSONAR + DocumentationReference.PERFORMANCE_PERIOD), QUALITY_MEASURE_SECTION_REQUIRED_REPORTING_PARAM_REQUIREMENT(32, "The Quality Measure Section must have " + "exactly one Reporting Parameter Act. " + "Please ensure the Reporting Parameters Act complies with the Implementation Guide (IG). " + "Here is a link to the IG Reporting Parameter Act section: " + DocumentationReference.REPORTING_PARAMETERS_ACT), PERFORMANCE_RATE_INVALID_VALUE(33, "The Performance Rate `(supplied value)` is invalid. " + "It must be a decimal between 0 and 1.", true), CPC_CLINICAL_DOCUMENT_MISSING_PRACTICE_SITE_ADDRESS(34, "CPC+ submissions must contain a practice site address." + " Please refer to the `(Submission year's)` IG for more details " + DocumentationReference.PRACTICE_SITE_ADDRESS + " regarding practice site addresses.", true), CPC_CLINICAL_DOCUMENT_ONLY_ONE_APM_ALLOWED(35, "One and only one Alternative Payment Model (APM) Entity " + "Identifier should be specified. Here is a link to the IG section on identifiers: " + DocumentationReference.IDENTIFIERS), CPC_CLINICAL_DOCUMENT_ONE_MEASURE_SECTION_REQUIRED(36, "CPC+ submissions must contain one Measure section"), CPC_QUALITY_MEASURE_ID_INVALID_PERFORMANCE_RATE_COUNT(37, "CPC+ submissions must contain correct number of performance rate(s). " + "Correct Number is `(Expected value)` for measure `(Given measure id)`", true), NUMERATOR_DENOMINATOR_CHILD_EXACT(39, "This PI `(Numerator or Denominator)` element has an incorrect number of Aggregate Count children. A PI " + "`(Numerator or Denominator)` must have exactly one Aggregate Count element", true), NUMERATOR_DENOMINATOR_MUST_BE_INTEGER(41, "This PI `(Numerator or Denominator)` element Aggregate Value '`(value)`' is not an integer", true), NUMERATOR_DENOMINATOR_INVALID_VALUE(42, "This PI `(Numerator or Denominator)` element Aggregate Value has an invalid value of '`(value)`'", true), IA_SECTION_MISSING_IA_MEASURE(43, "The IA Section must have at least one Improvement Activity"), IA_SECTION_MISSING_REPORTING_PARAM(44, "The IA Section must have one Reporting Parameter Act. " + "Please ensure the Reporting Parameters Act complies with the Implementation Guide (IG). " + "Here is a link to the IG Reporting Parameter Act section: " + DocumentationReference.REPORTING_PARAMETERS_ACT), IA_SECTION_WRONG_CHILD(45, "The IA Section must contain only Improvement Activities and a Reporting Parameter Act"), CPC_QUALITY_MEASURE_ID_MISSING_STRATA(48, "Missing strata `(Reporting Stratum UUID)` for " + "`(Current subpopulation type)` measure `(Current subpopulation UUID)`. " + "Here is a link to the IG valid Measure Ids section: " + DocumentationReference.MEASURE_IDS, true), CPC_QUALITY_MEASURE_ID_STRATA_MISMATCH(49,"Amount of stratifications `(Current number of " + "Reporting Stratifiers)` does not meet expectations " + "`(Number of stratifiers required)` for `(Current subpopulation type)` measure " + "`(Current Subpopulation UUID)`. Expected strata: `(Expected strata uuid list)`. " + "Please refer to the Implementation Guide for correct stratification UUID's here: " + DocumentationReference.MEASURE_IDS, true), IA_MEASURE_INCORRECT_CHILDREN_COUNT(50, "An IA performed measure reference and results must " + "have exactly one measure performed child"), IA_MEASURE_INVALID_TYPE(51, "A single measure performed value is required and must be either a Y or an N."), MEASURE_PERFORMED_MISSING_AGGREGATE_COUNT(52, "The measure data with population id '`(population id)`' must have exactly one " + "Aggregate Count.", true), MEASURE_DATA_VALUE_NOT_INTEGER(53, "Measure data with population id '`(population id)`' " + "must be a whole number greater than or equal to 0", true), CPC_PERFORMANCE_PERIOD_START(55, "A CPC Plus Performance period start must be 01/01/2018. " + "Please refer to the IG for more information here: " + DocumentationReference.CPC_PLUS_SUBMISSIONS), CPC_PERFORMANCE_PERIOD_END(56, "A CPC Plus Performance period end must be 12/31/2018. " + "Please refer to the IG for more information here: " + DocumentationReference.CPC_PLUS_SUBMISSIONS), QUALITY_MEASURE_ID_MISSING_SINGLE_MEASURE_POPULATION(57, "The measure reference results must have a single " + "measure population"), QUALITY_MEASURE_ID_MISSING_SINGLE_MEASURE_TYPE(58, "The measure reference results must have a single " + "measure type"), QUALITY_MEASURE_ID_INCORRECT_UUID(59, "The electronic measure id: `(Current eMeasure ID)` requires a " + "`(Subpopulation type)` with the correct UUID of `(Correct uuid required)`. Here is a link to the IG " + "containing all the valid measure ids: " + DocumentationReference.MEASURE_IDS, true), QUALITY_MEASURE_ID_MISSING_SINGLE_PERFORMANCE_RATE(61, "A Performance Rate must contain a single " + "Numerator UUID reference."), CPC_CLINICAL_DOCUMENT_EMPTY_APM(62, "The Alternative Payment Model (APM) Entity Identifier must not be empty. " + "Here is a link to the IG section on identifiers: " + DocumentationReference.IDENTIFIERS), CPC_CLINICAL_DOCUMENT_INVALID_APM(63, "The Alternative Payment Model (APM) Entity Identifier is not valid. " + " Here is a link to the IG section on identifiers: " + DocumentationReference.IDENTIFIERS), CPC_PLUS_TOO_FEW_QUALITY_MEASURE_CATEGORY(64, "CPC+ Submissions must have at least `(CPC+ measure group minimum)` " + "of the following `(CPC+ measure group label)` measures: `(Listing of valid measure ids)`", true), CPC_PLUS_TOO_FEW_QUALITY_MEASURES(65, "CPC+ Submissions must have at least `(Overall CPC+ measure minimum)` of " + "the following measures: `(Listing of all CPC+ measure ids)`.", true), CPC_PLUS_MISSING_SUPPLEMENTAL_CODE(66, "Missing the `(Supplemental Type)` - `(Type Qualification)` supplemental data for code " + "`(Supplemental Data Code)` for the measure id `(Measure Id)`'s Sub-population `(Sub Population)`", true), CPC_PLUS_SUPPLEMENTAL_DATA_MISSING_COUNT(67, "Must have one count for Supplemental Data `(Supplemental Data Code)` " + "on Sub-population `(Sub Population)` for the measure id `(Measure Id)`", true), CPC_PLUS_SUBMISSION_ENDED(68, "Your CPC+ submission was made after the CPC+ Measure section submission deadline of " + "`(Submission end date)`. Your CPC+ QRDA III file has not been processed. Please contact CPC+ Support at " + "`(CPC+ contact email)` for assistance.", true), INVALID_PERFORMANCE_PERIOD_FORMAT(69, "`(Performance period start or end date)` is an invalid date format. " + "Please use a standard ISO date format. " + "Example valid values are 2018-02-26, 2018/02/26T01:45:23, or 2018-02-26T01:45:23.123. " + "Please see the Implementation Guide for information on the performance period here: " + DocumentationReference.PERFORMANCE_PERIOD, true), MISSING_OR_DUPLICATED_MEASURE_GUID(70, "The measure section measure reference and results has an incorrect number of " + "measure GUID supplied. Please ensure that only one measure GUID is provided per measure."), MEASURES_RNR_WITH_DUPLICATED_MEASURE_GUID(71, "Two or more different measure section measure reference and results have " + "the same measure GUID. Please ensure that each measure section measure reference and results do not have " + "the same measure GUID."), PERFORMANCE_RATE_MISSING(72, "The Performance Rate is missing"), VIRTUAL_GROUP_ID_REQUIRED(78, "The Program 'Mips Virtual Group' was found. The required entity id for this " + "program name was missing. Please provide a virtual group identifier with the 'Mips Virtual Group' program name."), MISSING_PII_VALIDATOR(79, "There is no PII validator present, so NPI/Alternative Payment Model (APM) " + "combinations cannot be verified"), INCORRECT_API_NPI_COMBINATION(80, "The given National Provider (NPI) Identifier and Alternative Payment Model (APM) " + "are not a valid combination"); private static final Map<Integer, ErrorCode> CODE_TO_VALUE = Arrays.stream(values()) .collect(Collectors.toMap(ErrorCode::getCode, Function.identity())); public static final String CT_LABEL = "CT - "; private final int code; private final String message; private final boolean hasFormat; private final List<String> messageVariables; ErrorCode(int code, String message) { this(code, message, false); } ErrorCode(int code, String message, boolean hasFormat) { this.code = code; this.message = message; this.hasFormat = hasFormat; this.messageVariables = new ArrayList<>(); initMessageMarkers(message); } private void initMessageMarkers(String message) { Matcher matcher = VariableMarker.REPLACE_PATTERN.matcher(message); while (matcher.find()) { messageVariables.add(matcher.group(1)); } } /** * Gets the message associated with this error code */ public final String getMessage() { return CT_LABEL + message; } /** * Self returning */ @Override public final ErrorCode getErrorCode() { return this; } public final int getCode() { return code; } /** * Creates a formatted version of this error code, or throws an exception * * @param arguments arguments to format with * @return the formatted version of this error code, or throws an exception if formatting is * not supported. */ public final LocalizedError format(Object... arguments) { if (hasFormat) { String formatted = subValues(arguments); return new FormattedErrorCode(this, formatted); } throw new IllegalStateException(this + " does not support formatting"); } private String subValues(Object... arguments) { Map<String, String> valueSub = new HashMap<>(); IntStream.range(0, arguments.length).forEach(index -> valueSub.put(messageVariables.get(index), arguments[index].toString())); return new StringSubstitutor(valueSub, "`(", ")`").replace(getMessage()); } public static ErrorCode getByCode(int code) { return CODE_TO_VALUE.get(code); } private static final class VariableMarker { static final Pattern REPLACE_PATTERN = Pattern.compile("`\\(([^()]*)\\)`"); } private static final class ServiceCenter { static final String MESSAGE = "Please contact the Service Center for assistance via phone at " + "1-866-288-8292 or TTY: 1-877-715-6222, or by emailing QPP@cms.hhs.gov"; } }
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.config.subscription; import com.yahoo.config.ConfigInstance; import com.yahoo.config.ConfigurationRuntimeException; import com.yahoo.foo.SimpletypesConfig; import com.yahoo.foo.AppConfig; import com.yahoo.config.subscription.impl.ConfigSubscription; import com.yahoo.vespa.config.ConfigKey; import com.yahoo.vespa.config.TimingValues; import org.junit.Ignore; import org.junit.Test; import java.util.Collections; import java.util.List; import static org.junit.Assert.*; /** * @author hmusum * @author Ulf Lillengen */ public class ConfigSubscriptionTest { @Test public void testEquals() { ConfigSubscriber sub = new ConfigSubscriber(); final String payload = "boolval true"; ConfigSubscription<SimpletypesConfig> a = ConfigSubscription.get(new ConfigKey<>(SimpletypesConfig.class, "test"), sub, new RawSource(payload), new TimingValues()); ConfigSubscription<SimpletypesConfig> b = ConfigSubscription.get(new ConfigKey<>(SimpletypesConfig.class, "test"), sub, new RawSource(payload), new TimingValues()); ConfigSubscription<SimpletypesConfig> c = ConfigSubscription.get(new ConfigKey<>(SimpletypesConfig.class, "test2"), sub, new RawSource(payload), new TimingValues()); assertEquals(b, a); assertEquals(a, a); assertEquals(b, b); assertEquals(c, c); assertNotEquals(c, a); assertNotEquals(c, b); ConfigSubscriber subscriber = new ConfigSubscriber(); ConfigSet configSet = new ConfigSet(); AppConfig.Builder a0builder = new AppConfig.Builder().message("A message, 0").times(88); configSet.addBuilder("app/0", a0builder); AppConfig.Builder a1builder = new AppConfig.Builder().message("A message, 1").times(89); configSet.addBuilder("app/1", a1builder); ConfigSubscription<AppConfig> c1 = ConfigSubscription.get( new ConfigKey<>(AppConfig.class, "app/0"), subscriber, configSet, new TimingValues()); ConfigSubscription<AppConfig> c2 = ConfigSubscription.get( new ConfigKey<>(AppConfig.class, "app/1"), subscriber, configSet, new TimingValues()); assertEquals(c1, c1); assertNotEquals(c1, c2); sub.close(); } @Test public void testSubscribeInterface() { ConfigSubscriber sub = new ConfigSubscriber(); ConfigHandle<SimpletypesConfig> handle = sub.subscribe(SimpletypesConfig.class, "raw:boolval true", 10000); assertNotNull(handle); sub.nextConfig(false); assertTrue(handle.getConfig().boolval()); //assertTrue(sub.getSource() instanceof RawSource); sub.close(); } // Test that subscription is closed and subscriptionHandles is empty if we get an exception // (only the last is possible to test right now). @Test @Ignore public void testSubscribeWithException() { TestConfigSubscriber sub = new TestConfigSubscriber(); ConfigSourceSet configSourceSet = new ConfigSourceSet(Collections.singletonList("tcp/localhost:99999")); try { sub.subscribe(SimpletypesConfig.class, "configid", configSourceSet, new TimingValues().setSubscribeTimeout(100)); fail(); } catch (ConfigurationRuntimeException e) { assertEquals(0, sub.getSubscriptionHandles().size()); } } private static class TestConfigSubscriber extends ConfigSubscriber { List<ConfigHandle<? extends ConfigInstance>> getSubscriptionHandles() { return subscriptionHandles; } } }
package com.cds.promotion.data.entity; /** * @Author: chengzj * @CreateDate: 2019/1/17 14:09 * @Version: 3.0.0 */ public class ClockOnReq { /** * user_id : 用户id * location : 经纬度 * address : 打卡地址 * time : 打卡时间 * description : 打卡说明 * type : 类型 0 下班打卡,1上班打卡 */ private String user_id; private String type; private String location; private String address; // private String time; private String description; public ClockOnReq() { } public ClockOnReq(String user_id, String type, String location) { this.user_id = user_id; this.type = type; this.location = location; } public String getUser_id() { return user_id; } public void setUser_id(String user_id) { this.user_id = user_id; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
/* ### * IP: GHIDRA * * 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 ghidra.framework.main; import java.awt.*; import java.util.*; import java.util.List; import javax.swing.*; import docking.DialogComponentProvider; import docking.tool.ToolConstants; import docking.widgets.table.*; import ghidra.framework.data.ContentHandler; import ghidra.framework.model.*; import ghidra.framework.project.tool.GhidraToolTemplate; import ghidra.util.HelpLocation; import resources.ResourceManager; class SetToolAssociationsDialog extends DialogComponentProvider { private final FrontEndTool tool; private ToolAssociationTableModel model; private GTable table; SetToolAssociationsDialog(FrontEndTool tool) { super("Set Tool Associations", true); this.tool = tool; setHelpLocation(new HelpLocation(ToolConstants.TOOL_HELP_TOPIC, "Set Tool Associations")); addWorkPanel(createWorkPanel()); addOKButton(); addCancelButton(); setPreferredSize(400, 400); setRememberLocation(false); } private JComponent createWorkPanel() { JPanel mainPanel = new JPanel(new BorderLayout()); model = new ToolAssociationTableModel(); table = new GTable(model); final JButton editButton = new JButton("Edit"); editButton.addActionListener(e -> { int selectedRow = table.getSelectedRow(); ToolAssociationInfo info = model.getRowObject(selectedRow); if (info == null) { return; } ContentHandler contentHandler = info.getContentHandler(); Class<? extends DomainObject> domainClass = contentHandler.getDomainObjectClass(); PickToolDialog dialog = new PickToolDialog(tool, domainClass); dialog.showDialog(); ToolTemplate template = dialog.getSelectedToolTemplate(); if (template != null) { info.setCurrentTool(template); model.fireTableDataChanged(); } }); editButton.setEnabled(false); final JButton resetButton = new JButton("Restore Default"); resetButton.addActionListener(e -> { int selectedRow = table.getSelectedRow(); ToolAssociationInfo info = model.getRowObject(selectedRow); if (info != null) { info.restoreDefaultAssociation(); table.repaint(); } }); resetButton.setEnabled(false); table.setRowHeight(28); // make big enough for tool icons table.setColumnHeaderPopupEnabled(false); // don't allow column configuration table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.setDefaultRenderer(ContentHandler.class, new ContentHandlerRenderer()); table.setDefaultRenderer(GhidraToolTemplate.class, new ToolTemplateRenderer()); table.getSelectionModel().addListSelectionListener(e -> { if (e.getValueIsAdjusting()) { return; } int selectedRow = table.getSelectedRow(); ToolAssociationInfo info = model.getRowObject(selectedRow); if (info == null) { editButton.setEnabled(false); resetButton.setEnabled(false); return; } editButton.setEnabled(true); resetButton.setEnabled(!info.isDefault()); }); loadList(); JPanel buttonPanel = new JPanel(); buttonPanel.add(editButton); buttonPanel.add(Box.createHorizontalStrut(5)); buttonPanel.add(resetButton); mainPanel.add(new JScrollPane(table), BorderLayout.CENTER); mainPanel.add(buttonPanel, BorderLayout.SOUTH); return mainPanel; } private void loadList() { Project project = tool.getProject(); ToolServices toolServices = project.getToolServices(); Set<ToolAssociationInfo> infos = toolServices.getContentTypeToolAssociations(); model.setData(new ArrayList<>(infos)); } void showDialog() { clearStatusText(); tool.showDialog(this); } @Override protected void okCallback() { applyUserChoices(); close(); } private void applyUserChoices() { Set<ToolAssociationInfo> set = new HashSet<>(model.getModelData()); tool.getToolServices().setContentTypeToolAssociations(set); } //================================================================================================== // Inner Classes //================================================================================================== private class ToolAssociationTableModel extends AbstractSortedTableModel<ToolAssociationInfo> { private List<ToolAssociationInfo> data; ToolAssociationTableModel() { super(0); this.data = Collections.emptyList(); } void setData(List<ToolAssociationInfo> data) { this.data = data; fireTableDataChanged(); } @Override public String getName() { return "Set Tool Association"; } @Override public Object getColumnValueForRow(ToolAssociationInfo t, int column) { switch (column) { case 0: return t.getContentHandler(); case 1: return t.getCurrentTemplate(); } return null; } @Override public String getColumnName(int column) { switch (column) { case 0: return "Content Type"; case 1: return "Tool"; } return null; } @Override public Class<?> getColumnClass(int column) { switch (column) { case 0: return ContentHandler.class; case 1: return GhidraToolTemplate.class; } return null; } @Override public List<ToolAssociationInfo> getModelData() { return data; } @Override public boolean isSortable(int columnIndex) { return columnIndex == 0; } @Override public int getColumnCount() { return 2; } @Override public int getRowCount() { return data.size(); } @Override protected Comparator<ToolAssociationInfo> createSortComparator(int column) { switch (column) { case 0: return new ContentHandlerComparator(); case 1: return new ToolTemplateComparator(); } return super.createSortComparator(column); } } private class ContentHandlerComparator implements Comparator<ToolAssociationInfo> { @Override public int compare(ToolAssociationInfo o1, ToolAssociationInfo o2) { return o1.getContentHandler().getContentType().compareTo( o2.getContentHandler().getContentType()); } } private class ToolTemplateComparator implements Comparator<ToolAssociationInfo> { @Override public int compare(ToolAssociationInfo o1, ToolAssociationInfo o2) { return o1.getCurrentTemplate().getName().compareTo(o2.getCurrentTemplate().getName()); } } private class ContentHandlerRenderer extends GTableCellRenderer { @Override public Component getTableCellRendererComponent(GTableCellRenderingData data) { JLabel renderer = (JLabel) super.getTableCellRendererComponent(data); Object value = data.getValue(); // // Content Type: icon - name // ContentHandler handler = (ContentHandler) value; renderer.setIcon(handler.getIcon()); renderer.setText(handler.getContentType()); return renderer; } } private class ToolTemplateRenderer extends GTableCellRenderer { @Override public Component getTableCellRendererComponent(GTableCellRenderingData data) { JLabel renderer = (JLabel) super.getTableCellRendererComponent(data); Object value = data.getValue(); int row = data.getRowViewIndex(); ToolTemplate template = (ToolTemplate) value; if (template == null) { renderDefaultTool(renderer, row); return renderer; } renderer.setIcon(template.getIcon()); renderer.setText(template.getName()); return renderer; } private void renderDefaultTool(JLabel renderer, int row) { ToolAssociationInfo info = model.getRowObject(row); ToolTemplate template = info.getDefaultTemplate(); if (template == null) { return; } renderer.setForeground(Color.LIGHT_GRAY); Icon icon = null; if (template.getName().equals(info.getAssociatedToolName())) { icon = ResourceManager.getDisabledIcon(template.getIcon()); } else { icon = ResourceManager.getDisabledIcon(ResourceManager.getScaledIcon( ResourceManager.loadImage("images/EmptyIcon.gif"), 24, 24)); } renderer.setText(info.getAssociatedToolName()); renderer.setIcon(icon); } } }
package party.threebody.skean.samples.navyapp.domain; import party.threebody.skean.data.LastUpdateTime; import javax.persistence.Column; import javax.persistence.Id; import javax.persistence.Table; import java.time.LocalDateTime; import java.util.List; @Table(name = "navy_fleet") public class Fleet { @Id String countryCode; @Id String code; @Column String name; @Column String leaderName; @LastUpdateTime LocalDateTime updateTime; List<Ship> ships; public Fleet() { } public Fleet(String countryCode, String code, String name, String leaderName, List<Ship> ships) { this.countryCode = countryCode; this.code = code; this.name = name; this.leaderName = leaderName; this.ships = ships; } public String getCountryCode() { return countryCode; } public void setCountryCode(String countryCode) { this.countryCode = countryCode; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLeaderName() { return leaderName; } public void setLeaderName(String leaderName) { this.leaderName = leaderName; } public LocalDateTime getUpdateTime() { return updateTime; } public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; } public List<Ship> getShips() { return ships; } public void setShips(List<Ship> ships) { this.ships = ships; } }
/* * Copyright 2015 the original author or authors. * @https://github.com/scouter-project/scouter * * 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 scouter.lang.step; import scouter.io.DataInputX; import scouter.io.DataOutputX; import java.io.IOException; public class HashedMessageStep extends StepSingle { public int hash; public int time; public int value; public HashedMessageStep() { } public HashedMessageStep(int start_time) { this.start_time = start_time; } public byte getStepType() { return StepEnum.HASHED_MESSAGE; } public int getHash() { return hash; } public int getTime() { return time; } public int getValue() { return value; } public String toString() { return "HashedMessageStep " + hash; } public void write(DataOutputX out) throws IOException { super.write(out); out.writeDecimal(hash); out.writeDecimal(time); out.writeDecimal(value); } public Step read(DataInputX in) throws IOException { super.read(in); this.hash = (int) in.readDecimal(); this.time = (int) in.readDecimal(); this.value = (int) in.readDecimal(); return this; } }
/* * Copyright 2004-2015 the Seasar Foundation and the Others. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.seasar.extension.dataset.types; import org.seasar.extension.dataset.ColumnType; import org.seasar.framework.conversion.StringConversionUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 文字列用の {@link ColumnType}です。 * * @author higa * */ public class StringType extends ObjectType { final static private Logger logger = LoggerFactory.getLogger(StringType.class); /** * トリムするかどうか。 */ protected boolean trim; StringType() { this(true); } StringType(final boolean trim) { this.trim = trim; } @Override public Object convert(Object value, String formatPattern) { String s = StringConversionUtil.toString(value, formatPattern); if (s != null && trim) { s = s.trim(); } if ("".equals(s)) { s = null; } return s; } @Override public Object convert(Class<?> clazz, Object value) { if (clazz == Integer.class) { return Integer.valueOf("" + value); } return value; } @Override public Class getType() { return String.class; } }
/* * 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.drds.model.v20190123; import java.util.List; import com.aliyuncs.AcsResponse; import com.aliyuncs.drds.transform.v20190123.DescribeTableListByTypeResponseUnmarshaller; import com.aliyuncs.transform.UnmarshallerContext; /** * @author auto create * @version */ public class DescribeTableListByTypeResponse extends AcsResponse { private String requestId; private Boolean success; private Integer pageNumber; private Integer pageSize; private Integer total; private List<ListItem> list; public String getRequestId() { return this.requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public Boolean getSuccess() { return this.success; } public void setSuccess(Boolean success) { this.success = success; } public Integer getPageNumber() { return this.pageNumber; } public void setPageNumber(Integer pageNumber) { this.pageNumber = pageNumber; } public Integer getPageSize() { return this.pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } public Integer getTotal() { return this.total; } public void setTotal(Integer total) { this.total = total; } public List<ListItem> getList() { return this.list; } public void setList(List<ListItem> list) { this.list = list; } public static class ListItem { private String tableName; private String property; public String getTableName() { return this.tableName; } public void setTableName(String tableName) { this.tableName = tableName; } public String getProperty() { return this.property; } public void setProperty(String property) { this.property = property; } } @Override public DescribeTableListByTypeResponse getInstance(UnmarshallerContext context) { return DescribeTableListByTypeResponseUnmarshaller.unmarshall(this, context); } @Override public boolean checkShowJsonItemName() { return false; } }
package com.example.nanchen.aiyaschoolpush.net.retrofit; /** * * 自定义异常 * * @author nanchen * @fileName AiYaSchoolPush * @packageName com.example.nanchen.aiyaschoolpush.net * @date 2016/09/27 09:19 */ public class ApiException extends RuntimeException { public int retCode; public String msg; public ApiException(int retCode,String msg){ this.retCode = retCode; this.msg = msg; } public String getMsg() { return msg; } public int getRetCode() { return retCode; } }