text
stringlengths
7
1.01M
/* * Copyright 2014 Toxic Bakery * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.qzy.library.viewpagertransform; import android.view.View; public class RotateUpTransformer extends ABaseTransformer { private static final float ROT_MOD = -15f; @Override protected void onTransform(View view, float position) { final float width = view.getWidth(); final float rotation = ROT_MOD * position; view.setPivotX(width * 0.5f); view.setPivotY(0f); view.setTranslationX(0f); view.setRotation(rotation); } @Override protected boolean isPagingEnabled() { return true; } }
/* * Copyright 2017-2022 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.emrcontainers.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.emrcontainers.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * DescribeVirtualClusterResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DescribeVirtualClusterResultJsonUnmarshaller implements Unmarshaller<DescribeVirtualClusterResult, JsonUnmarshallerContext> { public DescribeVirtualClusterResult unmarshall(JsonUnmarshallerContext context) throws Exception { DescribeVirtualClusterResult describeVirtualClusterResult = new DescribeVirtualClusterResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return describeVirtualClusterResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("virtualCluster", targetDepth)) { context.nextToken(); describeVirtualClusterResult.setVirtualCluster(VirtualClusterJsonUnmarshaller.getInstance().unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return describeVirtualClusterResult; } private static DescribeVirtualClusterResultJsonUnmarshaller instance; public static DescribeVirtualClusterResultJsonUnmarshaller getInstance() { if (instance == null) instance = new DescribeVirtualClusterResultJsonUnmarshaller(); return instance; } }
/* * Copyright 2015 mk. * * 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.krysalis.barcode4j.impl.datamatrix.encoder; import java.awt.Dimension; import java.io.UnsupportedEncodingException; import java.util.EnumMap; import java.util.Map; import org.krysalis.barcode4j.impl.datamatrix.DataMatrixSymbolInfo; import org.krysalis.barcode4j.impl.datamatrix.SymbolShapeHint; /** * * @author mk */ public class EncoderContext { private static final String DEFAULT_ASCII_ENCODING = "ISO-8859-1"; private final String msg; private SymbolShapeHint shape = SymbolShapeHint.FORCE_NONE; private Dimension minSize; private Dimension maxSize; private final StringBuilder codewords; private int pos = 0; private Encodation newEncoding = null; private DataMatrixSymbolInfo symbolInfo; private int skipAtEnd = 0; private final Map<Encodation, Encoder> encoders = new EnumMap<Encodation, Encoder>(Encodation.class); public EncoderContext(String msg) { this(convertMessageToBinary(msg)); } public EncoderContext(byte[] data) { //From this point on Strings are not Unicode anymore! final StringBuilder sb = new StringBuilder(data.length); for (int i = 0; i < data.length; i++) { final char ch = (char) (data[i] & 0xff); sb.append(ch); } this.msg = sb.toString(); //Not Unicode here! this.codewords = new StringBuilder(msg.length()); initializeEncoders(); } private static byte[] convertMessageToBinary(String msg) { //From this point on Strings are not Unicode anymore! final byte[] msgBinary; try { msgBinary = msg.getBytes(DEFAULT_ASCII_ENCODING); } catch (UnsupportedEncodingException e) { throw new UnsupportedOperationException("Unsupported encoding: " + e.getMessage()); } final StringBuilder sb = new StringBuilder(msgBinary.length); for (int i = 0; i < msgBinary.length; i++) { final char ch = (char) (msgBinary[i] & 0xff); if (ch == '?' && msg.charAt(i) != '?') { throw new IllegalArgumentException("Message contains characters outside " + DEFAULT_ASCII_ENCODING + " encoding."); } sb.append(ch); } return msgBinary; } public DataMatrixSymbolInfo getSymbolInfo() { return symbolInfo; } public void setSymbolShape(SymbolShapeHint shape) { this.shape = shape; } private void initializeEncoders() { encoders.put(Encodation.ASCII_ENCODATION, new AsciiEncoder()); encoders.put(Encodation.BASE256_ENCODATION, new Base256Encoder()); encoders.put(Encodation.C40_ENCODATION, new C40Encoder()); encoders.put(Encodation.EDIFACT_ENCODATION, new EdifactEncoder()); encoders.put(Encodation.TEXT_ENCODATION, new TextEncoder()); encoders.put(Encodation.X12_ENCODATION, new X12Encoder()); } public void setSizeConstraints(Dimension minSize, Dimension maxSize) { this.minSize = minSize; this.maxSize = maxSize; } public String getMessage() { return this.msg; } public void setSkipAtEnd(int count) { this.skipAtEnd = count; } public char getCurrentChar() { return msg.charAt(pos); } public char getCurrent() { return msg.charAt(pos); } public void writeCodewords(String codewords) { this.codewords.append(codewords); } public void writeCodeword(char codeword) { this.codewords.append(codeword); } public int getCodewordCount() { return this.codewords.length(); } public void signalEncoderChange(Encodation encoding) { this.newEncoding = encoding; } public void resetEncoderSignal() { this.newEncoding = null; } public boolean hasMoreCharacters() { return pos < getTotalMessageCharCount(); } private int getTotalMessageCharCount() { return msg.length() - skipAtEnd; } public int getRemainingCharacters() { return getTotalMessageCharCount() - pos; } public void updateSymbolInfo() { updateSymbolInfo(getCodewordCount()); } public void updateSymbolInfo(int len) { if (this.symbolInfo == null || len > this.symbolInfo.getDataCapacity()) { this.symbolInfo = DataMatrixSymbolInfo.lookup(len, shape, minSize, maxSize, true); } } public void resetSymbolInfo() { this.symbolInfo = null; } public void incPos(int cnt) { pos += cnt; } public void incPos() { ++pos; } public int getPos() { return pos; } public String getCodeword() { return codewords.toString(); } public void encode(Encodation enc) { if (enc == null) { return; } encoders.get(enc).encode(this); } public Encodation getNewEncoding() { return newEncoding; } }
package io.gitee.ludii.excel.annotation; import io.gitee.ludii.excel.converts.WriteConverter; import io.gitee.ludii.excel.enums.CellDataTypeEnum; import io.gitee.ludii.excel.write.config.annotation.ExcelWriteField; import io.gitee.ludii.excel.write.config.annotation.ExcelWriteFieldAdapter; import java.lang.annotation.Annotation; /** * @author 陆迪 * @date 2022/4/27 */ public class DefaultExcelWriteFieldAdapter implements ExcelWriteFieldAdapter { private final ExcelField excelField; public DefaultExcelWriteFieldAdapter(ExcelField excelField) { this.excelField = excelField; } @Override public String title() { return excelField.title(); } @Override public CellDataTypeEnum excelType() { return excelField.excelType(); } @Override public String dataFormatPattern() { return excelField.dataFormatPattern(); } @Override public long sort() { return excelField.sort(); } @Override public boolean ignore() { return excelField.ignore(); } @Override public Class<? extends WriteConverter<?>> writeConverterClazz() { return excelField.writeConverterClazz(); } @Override public Class<? extends Annotation> annotationType() { return excelField.annotationType().getAnnotation(ExcelWriteField.class).annotationType(); } }
/* * Adobe Experience Manager (AEM) API * Swagger AEM is an OpenAPI specification for Adobe Experience Manager (AEM) API * * The version of the OpenAPI document: 3.4.0-pre.0 * Contact: opensource@shinesolutions.com * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.shinesolutions.swaggeraem4j.model; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; /** * Model tests for SamlConfigurationPropertyItemsLong */ public class SamlConfigurationPropertyItemsLongTest { private final SamlConfigurationPropertyItemsLong model = new SamlConfigurationPropertyItemsLong(); /** * Model tests for SamlConfigurationPropertyItemsLong */ @Test public void testSamlConfigurationPropertyItemsLong() { // TODO: test SamlConfigurationPropertyItemsLong } /** * Test the property 'name' */ @Test public void nameTest() { // TODO: test name } /** * Test the property 'optional' */ @Test public void optionalTest() { // TODO: test optional } /** * Test the property 'isSet' */ @Test public void isSetTest() { // TODO: test isSet } /** * Test the property 'type' */ @Test public void typeTest() { // TODO: test type } /** * Test the property 'value' */ @Test public void valueTest() { // TODO: test value } /** * Test the property 'description' */ @Test public void descriptionTest() { // TODO: test description } }
/* * 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.hive.ql.parse; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.rules.TestRule; import java.util.Collections; public class TestReplIncrementalLoadAcidTablesWithJsonMessage extends TestReplicationScenariosIncrementalLoadAcidTables { @Rule public TestRule replV1BackwardCompat; @BeforeClass public static void classLevelSetup() throws Exception { internalBeforeClassSetup(Collections.emptyMap(), TestReplIncrementalLoadAcidTablesWithJsonMessage.class); } @Before public void setup() throws Throwable { replV1BackwardCompat = primary.getReplivationV1CompatRule(Collections.emptyList()); super.setup(); } }
/** * 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.pulsar.client.api; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import com.google.common.collect.Sets; import java.lang.reflect.Field; import java.net.URL; import java.util.Optional; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.apache.bookkeeper.test.PortManager; import org.apache.pulsar.broker.NoOpShutdownService; import org.apache.pulsar.broker.PulsarService; import org.apache.pulsar.broker.ServiceConfiguration; import org.apache.pulsar.broker.loadbalance.LoadManager; import org.apache.pulsar.broker.loadbalance.ResourceUnit; import org.apache.pulsar.broker.loadbalance.impl.ModularLoadManagerImpl; import org.apache.pulsar.broker.loadbalance.impl.SimpleLoadManagerImpl; import org.apache.pulsar.broker.service.BrokerService; import org.apache.pulsar.broker.service.nonpersistent.NonPersistentReplicator; import org.apache.pulsar.broker.service.nonpersistent.NonPersistentTopic; import org.apache.pulsar.client.admin.PulsarAdmin; import org.apache.pulsar.client.impl.ConsumerImpl; import org.apache.pulsar.client.impl.ProducerImpl; import org.apache.pulsar.common.naming.NamespaceBundle; import org.apache.pulsar.common.naming.TopicName; import org.apache.pulsar.common.policies.data.ClusterData; import org.apache.pulsar.common.policies.data.NonPersistentPublisherStats; import org.apache.pulsar.common.policies.data.NonPersistentSubscriptionStats; import org.apache.pulsar.common.policies.data.NonPersistentTopicStats; import org.apache.pulsar.common.policies.data.SubscriptionStats; import org.apache.pulsar.common.policies.data.TenantInfo; import org.apache.pulsar.zookeeper.LocalBookkeeperEnsemble; import org.apache.pulsar.zookeeper.ZookeeperServerTest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class NonPersistentTopicTest extends ProducerConsumerBase { private static final Logger log = LoggerFactory.getLogger(NonPersistentTopicTest.class); private final String configClusterName = "r1"; @DataProvider(name = "subscriptionType") public Object[][] getSubscriptionType() { return new Object[][] { { SubscriptionType.Shared }, { SubscriptionType.Exclusive } }; } @DataProvider(name = "loadManager") public Object[][] getLoadManager() { return new Object[][] { { SimpleLoadManagerImpl.class.getCanonicalName() }, { ModularLoadManagerImpl.class.getCanonicalName() } }; } @BeforeMethod @Override protected void setup() throws Exception { super.internalSetup(); super.producerBaseSetup(); } @AfterMethod @Override protected void cleanup() throws Exception { super.internalCleanup(); } @Test(dataProvider = "subscriptionType") public void testNonPersistentTopic(SubscriptionType type) throws Exception { log.info("-- Starting {} test --", methodName); final String topic = "non-persistent://my-property/my-ns/unacked-topic"; ConsumerImpl<byte[]> consumer = (ConsumerImpl<byte[]>) pulsarClient.newConsumer().topic(topic) .subscriptionName("subscriber-1").subscriptionType(type).subscribe(); Producer<byte[]> producer = pulsarClient.newProducer().topic(topic).create(); int totalProduceMsg = 500; for (int i = 0; i < totalProduceMsg; i++) { String message = "my-message-" + i; producer.send(message.getBytes()); Thread.sleep(10); } Message<?> msg = null; Set<String> messageSet = Sets.newHashSet(); for (int i = 0; i < totalProduceMsg; i++) { msg = consumer.receive(1, TimeUnit.SECONDS); if (msg != null) { consumer.acknowledge(msg); String receivedMessage = new String(msg.getData()); log.debug("Received message: [{}]", receivedMessage); String expectedMessage = "my-message-" + i; testMessageOrderAndDuplicates(messageSet, receivedMessage, expectedMessage); } else { break; } } assertEquals(messageSet.size(), totalProduceMsg); producer.close(); consumer.close(); log.info("-- Exiting {} test --", methodName); } @Test(dataProvider = "subscriptionType") public void testPartitionedNonPersistentTopic(SubscriptionType type) throws Exception { log.info("-- Starting {} test --", methodName); final String topic = "non-persistent://my-property/my-ns/partitioned-topic"; admin.topics().createPartitionedTopic(topic, 5); Consumer<byte[]> consumer = pulsarClient.newConsumer().topic(topic).subscriptionName("subscriber-1") .subscriptionType(type).subscribe(); Producer<byte[]> producer = pulsarClient.newProducer().topic(topic) .enableBatching(false) .messageRoutingMode(MessageRoutingMode.SinglePartition) .create(); int totalProduceMsg = 500; for (int i = 0; i < totalProduceMsg; i++) { String message = "my-message-" + i; producer.send(message.getBytes()); Thread.sleep(10); } Message<?> msg = null; Set<String> messageSet = Sets.newHashSet(); for (int i = 0; i < totalProduceMsg; i++) { msg = consumer.receive(1, TimeUnit.SECONDS); if (msg != null) { consumer.acknowledge(msg); String receivedMessage = new String(msg.getData()); log.debug("Received message: [{}]", receivedMessage); String expectedMessage = "my-message-" + i; testMessageOrderAndDuplicates(messageSet, receivedMessage, expectedMessage); } else { break; } } assertEquals(messageSet.size(), totalProduceMsg); producer.close(); consumer.close(); log.info("-- Exiting {} test --", methodName); } @Test(dataProvider = "subscriptionType") public void testPartitionedNonPersistentTopicWithTcpLookup(SubscriptionType type) throws Exception { log.info("-- Starting {} test --", methodName); final int numPartitions = 5; final String topic = "non-persistent://my-property/my-ns/partitioned-topic"; admin.topics().createPartitionedTopic(topic, numPartitions); PulsarClient client = PulsarClient.builder().serviceUrl("pulsar://localhost:" + BROKER_PORT) .statsInterval(0, TimeUnit.SECONDS).build(); Consumer<byte[]> consumer = client.newConsumer().topic(topic).subscriptionName("subscriber-1") .subscriptionType(type).subscribe(); Producer<byte[]> producer = pulsarClient.newProducer().topic(topic) .enableBatching(false) .messageRoutingMode(MessageRoutingMode.SinglePartition) .create(); // Ensure all partitions exist for (int i = 0; i < numPartitions; i++) { TopicName partition = TopicName.get(topic).getPartition(i); assertNotNull(pulsar.getBrokerService().getTopicReference(partition.toString())); } int totalProduceMsg = 500; for (int i = 0; i < totalProduceMsg; i++) { String message = "my-message-" + i; producer.send(message.getBytes()); Thread.sleep(10); } Message<?> msg = null; Set<String> messageSet = Sets.newHashSet(); for (int i = 0; i < totalProduceMsg; i++) { msg = consumer.receive(1, TimeUnit.SECONDS); if (msg != null) { consumer.acknowledge(msg); String receivedMessage = new String(msg.getData()); log.debug("Received message: [{}]", receivedMessage); String expectedMessage = "my-message-" + i; testMessageOrderAndDuplicates(messageSet, receivedMessage, expectedMessage); } else { break; } } assertEquals(messageSet.size(), totalProduceMsg); producer.close(); consumer.close(); log.info("-- Exiting {} test --", methodName); client.close(); } /** * It verifies that broker doesn't dispatch messages if consumer runs out of permits filled out with messages */ @Test(dataProvider = "subscriptionType") public void testConsumerInternalQueueMaxOut(SubscriptionType type) throws Exception { log.info("-- Starting {} test --", methodName); final String topic = "non-persistent://my-property/my-ns/unacked-topic"; final int queueSize = 10; ConsumerImpl<byte[]> consumer = (ConsumerImpl<byte[]>) pulsarClient.newConsumer().topic(topic) .receiverQueueSize(queueSize).subscriptionName("subscriber-1").subscriptionType(type).subscribe(); Producer<byte[]> producer = pulsarClient.newProducer().topic(topic).create(); int totalProduceMsg = 50; for (int i = 0; i < totalProduceMsg; i++) { String message = "my-message-" + i; producer.send(message.getBytes()); Thread.sleep(10); } Message<?> msg = null; Set<String> messageSet = Sets.newHashSet(); for (int i = 0; i < totalProduceMsg; i++) { msg = consumer.receive(1, TimeUnit.SECONDS); if (msg != null) { consumer.acknowledge(msg); String receivedMessage = new String(msg.getData()); log.debug("Received message: [{}]", receivedMessage); String expectedMessage = "my-message-" + i; testMessageOrderAndDuplicates(messageSet, receivedMessage, expectedMessage); } else { break; } } assertEquals(messageSet.size(), queueSize); producer.close(); consumer.close(); log.info("-- Exiting {} test --", methodName); } /** * Verifies that broker should failed to publish message if producer publishes messages more than rate limit */ @Test public void testProducerRateLimit() throws Exception { int defaultNonPersistentMessageRate = conf.getMaxConcurrentNonPersistentMessagePerConnection(); try { final String topic = "non-persistent://my-property/my-ns/unacked-topic"; // restart broker with lower publish rate limit conf.setMaxConcurrentNonPersistentMessagePerConnection(1); stopBroker(); startBroker(); // produce message concurrently ExecutorService executor = Executors.newFixedThreadPool(5); AtomicBoolean failed = new AtomicBoolean(false); Consumer<byte[]> consumer = pulsarClient.newConsumer().topic(topic).subscriptionName("subscriber-1") .subscribe(); Producer<byte[]> producer = pulsarClient.newProducer().topic(topic).create(); byte[] msgData = "testData".getBytes(); final int totalProduceMessages = 10; CountDownLatch latch = new CountDownLatch(totalProduceMessages); for (int i = 0; i < totalProduceMessages; i++) { executor.submit(() -> { try { producer.send(msgData); } catch (Exception e) { log.error("Failed to send message", e); failed.set(true); } latch.countDown(); }); } latch.await(); Message<?> msg = null; Set<String> messageSet = Sets.newHashSet(); for (int i = 0; i < totalProduceMessages; i++) { msg = consumer.receive(500, TimeUnit.MILLISECONDS); if (msg != null) { messageSet.add(new String(msg.getData())); } else { break; } } // publish should not be failed assertFalse(failed.get()); // but as message should be dropped at broker: broker should not receive the message assertNotEquals(messageSet.size(), totalProduceMessages); executor.shutdown(); producer.close(); } finally { conf.setMaxConcurrentNonPersistentMessagePerConnection(defaultNonPersistentMessageRate); } } /** * verifies message delivery with multiple consumers on shared and failover subscriptions * * @throws Exception */ @Test public void testMultipleSubscription() throws Exception { log.info("-- Starting {} test --", methodName); final String topic = "non-persistent://my-property/my-ns/unacked-topic"; ConsumerImpl<byte[]> consumer1Shared = (ConsumerImpl<byte[]>) pulsarClient.newConsumer().topic(topic) .subscriptionName("subscriber-shared").subscriptionType(SubscriptionType.Shared).subscribe(); ConsumerImpl<byte[]> consumer2Shared = (ConsumerImpl<byte[]>) pulsarClient.newConsumer().topic(topic) .subscriptionName("subscriber-shared").subscriptionType(SubscriptionType.Shared).subscribe(); ConsumerImpl<byte[]> consumer1FailOver = (ConsumerImpl<byte[]>) pulsarClient.newConsumer().topic(topic) .subscriptionName("subscriber-fo").subscriptionType(SubscriptionType.Failover).subscribe(); ConsumerImpl<byte[]> consumer2FailOver = (ConsumerImpl<byte[]>) pulsarClient.newConsumer().topic(topic) .subscriptionName("subscriber-fo").subscriptionType(SubscriptionType.Failover).subscribe(); Producer<byte[]> producer = pulsarClient.newProducer().topic(topic).create(); int totalProduceMsg = 500; for (int i = 0; i < totalProduceMsg; i++) { String message = "my-message-" + i; producer.send(message.getBytes()); Thread.sleep(10); } // consume from shared-subscriptions Message<?> msg = null; Set<String> messageSet = Sets.newHashSet(); for (int i = 0; i < totalProduceMsg; i++) { msg = consumer1Shared.receive(500, TimeUnit.MILLISECONDS); if (msg != null) { messageSet.add(new String(msg.getData())); } else { break; } } for (int i = 0; i < totalProduceMsg; i++) { msg = consumer2Shared.receive(500, TimeUnit.MILLISECONDS); if (msg != null) { messageSet.add(new String(msg.getData())); } else { break; } } assertEquals(messageSet.size(), totalProduceMsg); // consume from failover-subscriptions messageSet.clear(); for (int i = 0; i < totalProduceMsg; i++) { msg = consumer1FailOver.receive(500, TimeUnit.MILLISECONDS); if (msg != null) { messageSet.add(new String(msg.getData())); } else { break; } } for (int i = 0; i < totalProduceMsg; i++) { msg = consumer2FailOver.receive(500, TimeUnit.MILLISECONDS); if (msg != null) { messageSet.add(new String(msg.getData())); } else { break; } } assertEquals(messageSet.size(), totalProduceMsg); producer.close(); consumer1Shared.close(); consumer2Shared.close(); consumer1FailOver.close(); consumer2FailOver.close(); log.info("-- Exiting {} test --", methodName); } /** * verifies that broker is capturing topic stats correctly */ @Test public void testTopicStats() throws Exception { final String topicName = "non-persistent://my-property/my-ns/unacked-topic"; final String subName = "non-persistent"; final int timeWaitToSync = 100; NonPersistentTopicStats stats; SubscriptionStats subStats; Consumer<byte[]> consumer = pulsarClient.newConsumer().topic(topicName) .subscriptionType(SubscriptionType.Shared).subscriptionName(subName).subscribe(); Thread.sleep(timeWaitToSync); NonPersistentTopic topicRef = (NonPersistentTopic) pulsar.getBrokerService().getTopicReference(topicName).get(); assertNotNull(topicRef); rolloverPerIntervalStats(pulsar); stats = topicRef.getStats(); subStats = stats.getSubscriptions().values().iterator().next(); // subscription stats assertEquals(stats.getSubscriptions().keySet().size(), 1); assertEquals(subStats.consumers.size(), 1); Producer<byte[]> producer = pulsarClient.newProducer().topic(topicName).create(); Thread.sleep(timeWaitToSync); int totalProducedMessages = 100; for (int i = 0; i < totalProducedMessages; i++) { String message = "my-message-" + i; producer.send(message.getBytes()); } Thread.sleep(timeWaitToSync); rolloverPerIntervalStats(pulsar); stats = topicRef.getStats(); subStats = stats.getSubscriptions().values().iterator().next(); assertTrue(subStats.msgRateOut > 0); assertEquals(subStats.consumers.size(), 1); assertTrue(subStats.msgThroughputOut > 0); // consumer stats assertTrue(subStats.consumers.get(0).msgRateOut > 0.0); assertTrue(subStats.consumers.get(0).msgThroughputOut > 0.0); assertEquals(subStats.msgRateRedeliver, 0.0); producer.close(); consumer.close(); } /** * verifies that non-persistent topic replicates using replicator */ @Test public void testReplicator() throws Exception { ReplicationClusterManager replication = new ReplicationClusterManager(); replication.setupReplicationCluster(); try { final String globalTopicName = "non-persistent://pulsar/global/ns/nonPersistentTopic"; final int timeWaitToSync = 100; NonPersistentTopicStats stats; SubscriptionStats subStats; PulsarClient client1 = PulsarClient.builder().serviceUrl(replication.url1.toString()).build(); PulsarClient client2 = PulsarClient.builder().serviceUrl(replication.url2.toString()).build(); PulsarClient client3 = PulsarClient.builder().serviceUrl(replication.url3.toString()).build(); ConsumerImpl<byte[]> consumer1 = (ConsumerImpl<byte[]>) client1.newConsumer().topic(globalTopicName) .subscriptionName("subscriber-1").subscribe(); ConsumerImpl<byte[]> consumer2 = (ConsumerImpl<byte[]>) client1.newConsumer().topic(globalTopicName) .subscriptionName("subscriber-2").subscribe(); ConsumerImpl<byte[]> repl2Consumer = (ConsumerImpl<byte[]>) client2.newConsumer().topic(globalTopicName) .subscriptionName("subscriber-1").subscribe(); ConsumerImpl<byte[]> repl3Consumer = (ConsumerImpl<byte[]>) client3.newConsumer().topic(globalTopicName) .subscriptionName("subscriber-1").subscribe(); Producer<byte[]> producer = client1.newProducer().topic(globalTopicName) .enableBatching(false) .messageRoutingMode(MessageRoutingMode.SinglePartition) .create(); Thread.sleep(timeWaitToSync); PulsarService replicationPulasr = replication.pulsar1; // Replicator for r1 -> r2,r3 NonPersistentTopic topicRef = (NonPersistentTopic) replication.pulsar1.getBrokerService() .getTopicReference(globalTopicName).get(); NonPersistentReplicator replicatorR2 = (NonPersistentReplicator) topicRef.getPersistentReplicator("r2"); NonPersistentReplicator replicatorR3 = (NonPersistentReplicator) topicRef.getPersistentReplicator("r3"); assertNotNull(topicRef); assertNotNull(replicatorR2); assertNotNull(replicatorR3); rolloverPerIntervalStats(replicationPulasr); stats = topicRef.getStats(); subStats = stats.getSubscriptions().values().iterator().next(); // subscription stats assertEquals(stats.getSubscriptions().keySet().size(), 2); assertEquals(subStats.consumers.size(), 1); Thread.sleep(timeWaitToSync); int totalProducedMessages = 100; for (int i = 0; i < totalProducedMessages; i++) { String message = "my-message-" + i; producer.send(message.getBytes()); } // (1) consume by consumer1 Message<?> msg = null; Set<String> messageSet = Sets.newHashSet(); for (int i = 0; i < totalProducedMessages; i++) { msg = consumer1.receive(300, TimeUnit.MILLISECONDS); if (msg != null) { String receivedMessage = new String(msg.getData()); testMessageOrderAndDuplicates(messageSet, receivedMessage, "my-message-" + i); } else { break; } } assertEquals(messageSet.size(), totalProducedMessages); // (2) consume by consumer2 messageSet.clear(); for (int i = 0; i < totalProducedMessages; i++) { msg = consumer2.receive(300, TimeUnit.MILLISECONDS); if (msg != null) { String receivedMessage = new String(msg.getData()); testMessageOrderAndDuplicates(messageSet, receivedMessage, "my-message-" + i); } else { break; } } assertEquals(messageSet.size(), totalProducedMessages); // (3) consume by repl2consumer messageSet.clear(); for (int i = 0; i < totalProducedMessages; i++) { msg = repl2Consumer.receive(300, TimeUnit.MILLISECONDS); if (msg != null) { String receivedMessage = new String(msg.getData()); testMessageOrderAndDuplicates(messageSet, receivedMessage, "my-message-" + i); } else { break; } } assertEquals(messageSet.size(), totalProducedMessages); // (4) consume by repl3consumer messageSet.clear(); for (int i = 0; i < totalProducedMessages; i++) { msg = repl3Consumer.receive(300, TimeUnit.MILLISECONDS); if (msg != null) { String receivedMessage = new String(msg.getData()); testMessageOrderAndDuplicates(messageSet, receivedMessage, "my-message-" + i); } else { break; } } assertEquals(messageSet.size(), totalProducedMessages); Thread.sleep(timeWaitToSync); rolloverPerIntervalStats(replicationPulasr); stats = topicRef.getStats(); subStats = stats.getSubscriptions().values().iterator().next(); assertTrue(subStats.msgRateOut > 0); assertEquals(subStats.consumers.size(), 1); assertTrue(subStats.msgThroughputOut > 0); // consumer stats assertTrue(subStats.consumers.get(0).msgRateOut > 0.0); assertTrue(subStats.consumers.get(0).msgThroughputOut > 0.0); assertEquals(subStats.msgRateRedeliver, 0.0); producer.close(); consumer1.close(); repl2Consumer.close(); repl3Consumer.close(); client1.close(); client2.close(); client3.close(); } finally { replication.shutdownReplicationCluster(); } } /** * verifies load manager assigns topic only if broker started in non-persistent mode * * <pre> * 1. Start broker with disable non-persistent topic mode * 2. Create namespace with non-persistency set * 3. Create non-persistent topic * 4. Load-manager should not be able to find broker * 5. Create producer on that topic should fail * </pre> */ @Test(dataProvider = "loadManager") public void testLoadManagerAssignmentForNonPersistentTestAssignment(String loadManagerName) throws Exception { final String namespace = "my-property/my-ns"; final String topicName = "non-persistent://" + namespace + "/loadManager"; final String defaultLoadManagerName = conf.getLoadManagerClassName(); final boolean defaultENableNonPersistentTopic = conf.isEnableNonPersistentTopics(); try { // start broker to not own non-persistent namespace and create non-persistent namespace stopBroker(); conf.setEnableNonPersistentTopics(false); conf.setLoadManagerClassName(loadManagerName); startBroker(); Field field = PulsarService.class.getDeclaredField("loadManager"); field.setAccessible(true); @SuppressWarnings("unchecked") AtomicReference<LoadManager> loadManagerRef = (AtomicReference<LoadManager>) field.get(pulsar); LoadManager manager = LoadManager.create(pulsar); manager.start(); LoadManager oldLoadManager = loadManagerRef.getAndSet(manager); oldLoadManager.stop(); NamespaceBundle fdqn = pulsar.getNamespaceService().getBundle(TopicName.get(topicName)); LoadManager loadManager = pulsar.getLoadManager().get(); ResourceUnit broker = null; try { broker = loadManager.getLeastLoaded(fdqn).get(); } catch (Exception e) { // Ok. (ModulearLoadManagerImpl throws RuntimeException incase don't find broker) } assertNull(broker); try { Producer<byte[]> producer = pulsarClient.newProducer().topic(topicName).createAsync().get(1, TimeUnit.SECONDS); producer.close(); fail("topic loading should have failed"); } catch (Exception e) { // Ok } assertFalse(pulsar.getBrokerService().getTopicReference(topicName).isPresent()); } finally { conf.setEnableNonPersistentTopics(defaultENableNonPersistentTopic); conf.setLoadManagerClassName(defaultLoadManagerName); } } /** * verifies: broker should reject non-persistent topic loading if broker is not enable for non-persistent topic * * @param loadManagerName * @throws Exception */ @Test public void testNonPersistentTopicUnderPersistentNamespace() throws Exception { final String namespace = "my-property/my-ns"; final String topicName = "non-persistent://" + namespace + "/persitentNamespace"; final boolean defaultENableNonPersistentTopic = conf.isEnableNonPersistentTopics(); try { conf.setEnableNonPersistentTopics(false); stopBroker(); startBroker(); try { Producer<byte[]> producer = pulsarClient.newProducer().topic(topicName).createAsync().get(1, TimeUnit.SECONDS); producer.close(); fail("topic loading should have failed"); } catch (Exception e) { // Ok } assertFalse(pulsar.getBrokerService().getTopicReference(topicName).isPresent()); } finally { conf.setEnableNonPersistentTopics(defaultENableNonPersistentTopic); } } /** * verifies that broker started with onlyNonPersistent mode doesn't own persistent-topic * * @param loadManagerName * @throws Exception */ @Test(dataProvider = "loadManager") public void testNonPersistentBrokerModeRejectPersistentTopic(String loadManagerName) throws Exception { final String namespace = "my-property/my-ns"; final String topicName = "persistent://" + namespace + "/loadManager"; final String defaultLoadManagerName = conf.getLoadManagerClassName(); final boolean defaultEnablePersistentTopic = conf.isEnablePersistentTopics(); final boolean defaultEnableNonPersistentTopic = conf.isEnableNonPersistentTopics(); try { // start broker to not own non-persistent namespace and create non-persistent namespace stopBroker(); conf.setEnableNonPersistentTopics(true); conf.setEnablePersistentTopics(false); conf.setLoadManagerClassName(loadManagerName); startBroker(); Field field = PulsarService.class.getDeclaredField("loadManager"); field.setAccessible(true); @SuppressWarnings("unchecked") AtomicReference<LoadManager> loadManagerRef = (AtomicReference<LoadManager>) field.get(pulsar); LoadManager manager = LoadManager.create(pulsar); manager.start(); LoadManager oldLoadManager = loadManagerRef.getAndSet(manager); oldLoadManager.stop(); NamespaceBundle fdqn = pulsar.getNamespaceService().getBundle(TopicName.get(topicName)); LoadManager loadManager = pulsar.getLoadManager().get(); ResourceUnit broker = null; try { broker = loadManager.getLeastLoaded(fdqn).get(); } catch (Exception e) { // Ok. (ModulearLoadManagerImpl throws RuntimeException incase don't find broker) } assertNull(broker); try { Producer<byte[]> producer = pulsarClient.newProducer().topic(topicName).createAsync().get(1, TimeUnit.SECONDS); producer.close(); fail("topic loading should have failed"); } catch (Exception e) { // Ok } assertFalse(pulsar.getBrokerService().getTopicReference(topicName).isPresent()); } finally { conf.setEnablePersistentTopics(defaultEnablePersistentTopic); conf.setEnableNonPersistentTopics(defaultEnableNonPersistentTopic); conf.setLoadManagerClassName(defaultLoadManagerName); } } /** * Verifies msg-drop stats * * @throws Exception */ @Test public void testMsgDropStat() throws Exception { int defaultNonPersistentMessageRate = conf.getMaxConcurrentNonPersistentMessagePerConnection(); try { final String topicName = "non-persistent://my-property/my-ns/stats-topic"; // restart broker with lower publish rate limit conf.setMaxConcurrentNonPersistentMessagePerConnection(1); stopBroker(); startBroker(); Consumer<byte[]> consumer = pulsarClient.newConsumer().topic(topicName).subscriptionName("subscriber-1") .receiverQueueSize(1).subscribe(); Consumer<byte[]> consumer2 = pulsarClient.newConsumer().topic(topicName).subscriptionName("subscriber-2") .receiverQueueSize(1).subscriptionType(SubscriptionType.Shared).subscribe(); ProducerImpl<byte[]> producer = (ProducerImpl<byte[]>) pulsarClient.newProducer().topic(topicName) .enableBatching(false) .messageRoutingMode(MessageRoutingMode.SinglePartition) .create(); String firstTimeConnected = producer.getConnectedSince(); ExecutorService executor = Executors.newFixedThreadPool(5); byte[] msgData = "testData".getBytes(); final int totalProduceMessages = 200; CountDownLatch latch = new CountDownLatch(totalProduceMessages); for (int i = 0; i < totalProduceMessages; i++) { executor.submit(() -> { producer.sendAsync(msgData).handle((msg, e) -> { latch.countDown(); return null; }); }); } latch.await(); NonPersistentTopic topic = (NonPersistentTopic) pulsar.getBrokerService().getOrCreateTopic(topicName).get(); pulsar.getBrokerService().updateRates(); NonPersistentTopicStats stats = topic.getStats(); NonPersistentPublisherStats npStats = stats.getPublishers().get(0); NonPersistentSubscriptionStats sub1Stats = stats.getSubscriptions().get("subscriber-1"); NonPersistentSubscriptionStats sub2Stats = stats.getSubscriptions().get("subscriber-2"); assertTrue(npStats.msgDropRate > 0); assertTrue(sub1Stats.msgDropRate > 0); assertTrue(sub2Stats.msgDropRate > 0); producer.close(); consumer.close(); consumer2.close(); executor.shutdown(); } finally { conf.setMaxConcurrentNonPersistentMessagePerConnection(defaultNonPersistentMessageRate); } } class ReplicationClusterManager { URL url1; PulsarService pulsar1; BrokerService ns1; PulsarAdmin admin1; LocalBookkeeperEnsemble bkEnsemble1; URL url2; ServiceConfiguration config2; PulsarService pulsar2; BrokerService ns2; PulsarAdmin admin2; LocalBookkeeperEnsemble bkEnsemble2; URL url3; ServiceConfiguration config3; PulsarService pulsar3; BrokerService ns3; PulsarAdmin admin3; LocalBookkeeperEnsemble bkEnsemble3; ZookeeperServerTest globalZkS; ExecutorService executor = new ThreadPoolExecutor(5, 20, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); static final int TIME_TO_CHECK_BACKLOG_QUOTA = 5; // Default frequency public int getBrokerServicePurgeInactiveFrequency() { return 60; } public boolean isBrokerServicePurgeInactiveTopic() { return false; } void setupReplicationCluster() throws Exception { log.info("--- Starting ReplicatorTestBase::setup ---"); int globalZKPort = PortManager.nextFreePort(); globalZkS = new ZookeeperServerTest(globalZKPort); globalZkS.start(); // Start region 1 int zkPort1 = PortManager.nextFreePort(); bkEnsemble1 = new LocalBookkeeperEnsemble(3, zkPort1, () -> PortManager.nextFreePort()); bkEnsemble1.start(); int webServicePort1 = PortManager.nextFreePort(); // NOTE: we have to instantiate a new copy of System.getProperties() to make sure pulsar1 and pulsar2 have // completely // independent config objects instead of referring to the same properties object ServiceConfiguration config1 = new ServiceConfiguration(); config1.setClusterName(configClusterName); config1.setAdvertisedAddress("localhost"); config1.setWebServicePort(Optional.ofNullable(webServicePort1)); config1.setZookeeperServers("127.0.0.1:" + zkPort1); config1.setConfigurationStoreServers("127.0.0.1:" + globalZKPort + "/foo"); config1.setBrokerDeleteInactiveTopicsEnabled(isBrokerServicePurgeInactiveTopic()); config1.setBrokerServicePurgeInactiveFrequencyInSeconds( inSec(getBrokerServicePurgeInactiveFrequency(), TimeUnit.SECONDS)); config1.setBrokerServicePort(Optional.ofNullable(PortManager.nextFreePort())); config1.setBacklogQuotaCheckIntervalInSeconds(TIME_TO_CHECK_BACKLOG_QUOTA); config1.setAllowAutoTopicCreationType("non-partitioned"); pulsar1 = new PulsarService(config1); pulsar1.setShutdownService(new NoOpShutdownService()); pulsar1.start(); ns1 = pulsar1.getBrokerService(); url1 = new URL("http://127.0.0.1:" + webServicePort1); admin1 = PulsarAdmin.builder().serviceHttpUrl(url1.toString()).build(); // Start region 2 // Start zk & bks int zkPort2 = PortManager.nextFreePort(); bkEnsemble2 = new LocalBookkeeperEnsemble(3, zkPort2, () -> PortManager.nextFreePort()); bkEnsemble2.start(); int webServicePort2 = PortManager.nextFreePort(); config2 = new ServiceConfiguration(); config2.setClusterName("r2"); config2.setWebServicePort(Optional.ofNullable(webServicePort2)); config2.setAdvertisedAddress("localhost"); config2.setZookeeperServers("127.0.0.1:" + zkPort2); config2.setConfigurationStoreServers("127.0.0.1:" + globalZKPort + "/foo"); config2.setBrokerDeleteInactiveTopicsEnabled(isBrokerServicePurgeInactiveTopic()); config2.setBrokerServicePurgeInactiveFrequencyInSeconds( inSec(getBrokerServicePurgeInactiveFrequency(), TimeUnit.SECONDS)); config2.setBrokerServicePort(Optional.ofNullable(PortManager.nextFreePort())); config2.setBacklogQuotaCheckIntervalInSeconds(TIME_TO_CHECK_BACKLOG_QUOTA); config2.setAllowAutoTopicCreationType("non-partitioned"); pulsar2 = new PulsarService(config2); pulsar2.setShutdownService(new NoOpShutdownService()); pulsar2.start(); ns2 = pulsar2.getBrokerService(); url2 = new URL("http://127.0.0.1:" + webServicePort2); admin2 = PulsarAdmin.builder().serviceHttpUrl(url2.toString()).build(); // Start region 3 // Start zk & bks int zkPort3 = PortManager.nextFreePort(); bkEnsemble3 = new LocalBookkeeperEnsemble(3, zkPort3, () -> PortManager.nextFreePort()); bkEnsemble3.start(); int webServicePort3 = PortManager.nextFreePort(); config3 = new ServiceConfiguration(); config3.setClusterName("r3"); config3.setWebServicePort(Optional.ofNullable(webServicePort3)); config3.setAdvertisedAddress("localhost"); config3.setZookeeperServers("127.0.0.1:" + zkPort3); config3.setConfigurationStoreServers("127.0.0.1:" + globalZKPort + "/foo"); config3.setBrokerDeleteInactiveTopicsEnabled(isBrokerServicePurgeInactiveTopic()); config3.setBrokerServicePurgeInactiveFrequencyInSeconds( inSec(getBrokerServicePurgeInactiveFrequency(), TimeUnit.SECONDS)); config3.setBrokerServicePort(Optional.ofNullable(PortManager.nextFreePort())); config3.setAllowAutoTopicCreationType("non-partitioned"); pulsar3 = new PulsarService(config3); pulsar3.setShutdownService(new NoOpShutdownService()); pulsar3.start(); ns3 = pulsar3.getBrokerService(); url3 = new URL("http://127.0.0.1:" + webServicePort3); admin3 = PulsarAdmin.builder().serviceHttpUrl(url3.toString()).build(); // Provision the global namespace admin1.clusters().createCluster("r1", new ClusterData(url1.toString(), null, pulsar1.getSafeBrokerServiceUrl(), pulsar1.getBrokerServiceUrlTls())); admin1.clusters().createCluster("r2", new ClusterData(url2.toString(), null, pulsar2.getSafeBrokerServiceUrl(), pulsar1.getBrokerServiceUrlTls())); admin1.clusters().createCluster("r3", new ClusterData(url3.toString(), null, pulsar3.getSafeBrokerServiceUrl(), pulsar1.getBrokerServiceUrlTls())); admin1.clusters().createCluster("global", new ClusterData("http://global:8080")); admin1.tenants().createTenant("pulsar", new TenantInfo( Sets.newHashSet("appid1", "appid2", "appid3"), Sets.newHashSet("r1", "r2", "r3"))); admin1.namespaces().createNamespace("pulsar/global/ns"); admin1.namespaces().setNamespaceReplicationClusters("pulsar/global/ns", Sets.newHashSet("r1", "r2", "r3")); assertEquals(admin2.clusters().getCluster("r1").getServiceUrl(), url1.toString()); assertEquals(admin2.clusters().getCluster("r2").getServiceUrl(), url2.toString()); assertEquals(admin2.clusters().getCluster("r3").getServiceUrl(), url3.toString()); assertEquals(admin2.clusters().getCluster("r1").getBrokerServiceUrl(), pulsar1.getSafeBrokerServiceUrl()); assertEquals(admin2.clusters().getCluster("r2").getBrokerServiceUrl(), pulsar2.getSafeBrokerServiceUrl()); assertEquals(admin2.clusters().getCluster("r3").getBrokerServiceUrl(), pulsar3.getSafeBrokerServiceUrl()); Thread.sleep(100); log.info("--- ReplicatorTestBase::setup completed ---"); } private int inSec(int time, TimeUnit unit) { return (int) TimeUnit.SECONDS.convert(time, unit); } void shutdownReplicationCluster() throws Exception { log.info("--- Shutting down ---"); executor.shutdown(); admin1.close(); admin2.close(); admin3.close(); pulsar3.close(); ns3.close(); pulsar2.close(); ns2.close(); pulsar1.close(); ns1.close(); bkEnsemble1.stop(); bkEnsemble2.stop(); bkEnsemble3.stop(); globalZkS.stop(); } } private void rolloverPerIntervalStats(PulsarService pulsar) { try { pulsar.getExecutor().submit(() -> pulsar.getBrokerService().updateRates()).get(); } catch (Exception e) { log.error("Stats executor error", e); } } }
/* * Copyright (c) 2008-2014 MongoDB, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bson.json; import org.bson.BsonRegularExpression; import org.junit.Test; import static org.junit.Assert.assertEquals; public class JsonScannerTest { @Test public void testEndOfFile() { String json = "\t "; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.END_OF_FILE, token.getType()); assertEquals("<eof>", token.getValue()); assertEquals(-1, buffer.read()); } @Test public void testBeginObject() { String json = "\t {x"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.BEGIN_OBJECT, token.getType()); assertEquals("{", token.getValue()); assertEquals('x', buffer.read()); } @Test public void testEndObject() { String json = "\t }x"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.END_OBJECT, token.getType()); assertEquals("}", token.getValue()); assertEquals('x', buffer.read()); } @Test public void testBeginArray() { String json = "\t [x"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.BEGIN_ARRAY, token.getType()); assertEquals("[", token.getValue()); assertEquals('x', buffer.read()); } @Test public void testEndArray() { String json = "\t ]x"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.END_ARRAY, token.getType()); assertEquals("]", token.getValue()); assertEquals('x', buffer.read()); } @Test public void testParentheses() { String json = "\t (jj)x"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.LEFT_PAREN, token.getType()); assertEquals("(", token.getValue()); token = scanner.nextToken(); token = scanner.nextToken(); assertEquals(JsonTokenType.RIGHT_PAREN, token.getType()); assertEquals('x', buffer.read()); } @Test public void testNameSeparator() { String json = "\t :x"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.COLON, token.getType()); assertEquals(":", token.getValue()); assertEquals('x', buffer.read()); } @Test public void testValueSeparator() { String json = "\t ,x"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.COMMA, token.getType()); assertEquals(",", token.getValue()); assertEquals('x', buffer.read()); } @Test public void testEmptyString() { String json = "\t \"\"x"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.STRING, token.getType()); assertEquals("", token.getValue()); assertEquals('x', buffer.read()); } @Test public void test1CharacterString() { String json = "\t \"1\"x"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.STRING, token.getType()); assertEquals("1", token.getValue()); assertEquals('x', buffer.read()); } @Test public void test2CharacterString() { String json = "\t \"12\"x"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.STRING, token.getType()); assertEquals("12", token.getValue()); assertEquals('x', buffer.read()); } @Test public void test3CharacterString() { String json = "\t \"123\"x"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.STRING, token.getType()); assertEquals("123", token.getValue()); assertEquals('x', buffer.read()); } @Test public void testEscapeSequences() { String json = "\t \"x\\\"\\\\\\/\\b\\f\\n\\r\\t\\u0030y\"x"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.STRING, token.getType()); assertEquals("x\"\\/\b\f\n\r\t0y", token.getValue()); assertEquals('x', buffer.read()); } @Test public void testTrue() { String json = "\t true,"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.UNQUOTED_STRING, token.getType()); assertEquals("true", token.getValue()); assertEquals(',', buffer.read()); } @Test public void testMinusInfinity() { String json = "\t -Infinity]"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.DOUBLE, token.getType()); assertEquals(Double.NEGATIVE_INFINITY, token.getValue()); assertEquals(']', buffer.read()); } @Test public void testFalse() { String json = "\t false,"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.UNQUOTED_STRING, token.getType()); assertEquals("false", token.getValue()); assertEquals(',', buffer.read()); } @Test public void testNull() { String json = "\t null,"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.UNQUOTED_STRING, token.getType()); assertEquals("null", token.getValue()); assertEquals(',', buffer.read()); } @Test public void testUndefined() { String json = "\t undefined,"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.UNQUOTED_STRING, token.getType()); assertEquals("undefined", token.getValue()); assertEquals(',', buffer.read()); } @Test public void testUnquotedStringWithSeparator() { String json = "\t name123:1"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.UNQUOTED_STRING, token.getType()); assertEquals("name123", token.getValue()); assertEquals(':', buffer.read()); } @Test public void testUnquotedString() { String json = "name123"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.UNQUOTED_STRING, token.getType()); assertEquals("name123", token.getValue()); assertEquals(-1, buffer.read()); } @Test public void testZero() { String json = "\t 0,"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.INT32, token.getType()); assertEquals(0, token.getValue()); assertEquals(',', buffer.read()); } @Test public void testMinusZero() { String json = "\t -0,"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.INT32, token.getType()); assertEquals(-0, token.getValue()); assertEquals(',', buffer.read()); } @Test public void testOne() { String json = "\t 1,"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.INT32, token.getType()); assertEquals(1, token.getValue()); assertEquals(',', buffer.read()); } @Test public void testMinusOne() { String json = "\t -1,"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.INT32, token.getType()); assertEquals(-1, token.getValue()); assertEquals(',', buffer.read()); } @Test public void testTwelve() { String json = "\t 12,"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.INT32, token.getType()); assertEquals(12, token.getValue()); assertEquals(',', buffer.read()); } @Test public void testMinusTwelve() { String json = "\t -12,"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.INT32, token.getType()); assertEquals(-12, token.getValue()); assertEquals(',', buffer.read()); } @Test public void testZeroPointZero() { String json = "\t 0.0,"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.DOUBLE, token.getType()); assertEquals(0.0, token.getValue()); assertEquals(',', buffer.read()); } @Test public void testMinusZeroPointZero() { String json = "\t -0.0,"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.DOUBLE, token.getType()); assertEquals(-0.0, token.getValue()); assertEquals(',', buffer.read()); } @Test public void testZeroExponentOne() { String json = "\t 0e1,"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.DOUBLE, token.getType()); assertEquals(0e1, token.getValue()); assertEquals(',', buffer.read()); } @Test public void testMinusZeroExponentOne() { String json = "\t -0e1,"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.DOUBLE, token.getType()); assertEquals(-0e1, token.getValue()); assertEquals(',', buffer.read()); } @Test public void testZeroExponentMinusOne() { String json = "\t 0e-1,"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.DOUBLE, token.getType()); assertEquals(0e-1, token.getValue()); assertEquals(',', buffer.read()); } @Test public void testMinusZeroExponentMinusOne() { String json = "\t -0e-1,"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.DOUBLE, token.getType()); assertEquals(-0e-1, token.getValue()); assertEquals(',', buffer.read()); } @Test public void testOnePointTwo() { String json = "\t 1.2,"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.DOUBLE, token.getType()); assertEquals(1.2, token.getValue()); assertEquals(',', buffer.read()); } @Test public void testMinusOnePointTwo() { String json = "\t -1.2,"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.DOUBLE, token.getType()); assertEquals(-1.2, token.getValue()); assertEquals(',', buffer.read()); } @Test public void testOneExponentTwelve() { String json = "\t 1e12,"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.DOUBLE, token.getType()); assertEquals(1e12, token.getValue()); assertEquals(',', buffer.read()); } @Test public void testMinusZeroExponentTwelve() { String json = "\t -1e12,"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.DOUBLE, token.getType()); assertEquals(-1e12, token.getValue()); assertEquals(',', buffer.read()); } @Test public void testOneExponentMinuesTwelve() { String json = "\t 1e-12,"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.DOUBLE, token.getType()); assertEquals(1e-12, token.getValue()); assertEquals(',', buffer.read()); } @Test public void testMinusZeroExponentMinusTwelve() { String json = "\t -1e-12,"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.DOUBLE, token.getType()); assertEquals(-1e-12, token.getValue()); assertEquals(',', buffer.read()); } @Test public void testRegularExpressionEmpty() { String json = "\t //,"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.REGULAR_EXPRESSION, token.getType()); BsonRegularExpression regularExpression = token.getValue(BsonRegularExpression.class); assertEquals("", regularExpression.getPattern()); assertEquals("", regularExpression.getOptions()); assertEquals(',', buffer.read()); } @Test public void testRegularExpressionPattern() { String json = "\t /pattern/,"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.REGULAR_EXPRESSION, token.getType()); assertEquals("pattern", token.getValue(BsonRegularExpression.class).getPattern()); assertEquals(',', buffer.read()); } @Test public void testRegularExpressionPatternAndOptions() { String json = "\t /pattern/im,"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.REGULAR_EXPRESSION, token.getType()); BsonRegularExpression regularExpression = token.getValue(BsonRegularExpression.class); assertEquals("pattern", regularExpression.getPattern()); assertEquals("im", regularExpression.getOptions()); assertEquals(',', buffer.read()); } @Test public void testRegularExpressionPatternAndEscapeSequence() { String json = "\t /patte\\.n/,"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); assertEquals(JsonTokenType.REGULAR_EXPRESSION, token.getType()); assertEquals("patte\\.n", token.getValue(BsonRegularExpression.class).getPattern()); assertEquals(',', buffer.read()); } @Test(expected = JsonParseException.class) public void testInvalidRegularExpression() { String json = "\t /pattern/nsk,"; JsonBuffer buffer = new JsonBuffer(json); JsonScanner scanner = new JsonScanner(buffer); JsonToken token = scanner.nextToken(); } @Test(expected = JsonParseException.class) public void testInvalidInput() { String json = "\t &&"; JsonScanner scanner = new JsonScanner(json); scanner.nextToken(); } @Test(expected = JsonParseException.class) public void testInvalidNumber() { String json = "\t 123a]"; JsonScanner scanner = new JsonScanner(json); scanner.nextToken(); } @Test(expected = JsonParseException.class) public void testInvalidInfinity() { String json = "\t -Infinnity]"; JsonScanner scanner = new JsonScanner(json); scanner.nextToken(); } }
package com.zeshan.syncnotes; import org.parse4j.Parse; import org.parse4j.util.ParseRegistry; public class ParseSetup { public void initializeParse() { ParseRegistry.registerSubclass(Note.class); Parse.initialize("iqnAuoS1KihbbhQBvfjlu0wFlVvPSTukN8J8ncpz", "uaZc6oGzjaFOnoUfqxqIsp6UnanOlBOfyHRmqPac"); } }
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.refactoring.modularize; import com.android.tools.idea.projectsystem.ProjectSystemUtil; import com.intellij.ide.highlighter.JavaFileType; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.refactoring.RefactoringActionHandler; import com.intellij.refactoring.actions.BaseJavaRefactoringAction; import org.jetbrains.android.util.AndroidUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class AndroidModularizeAction extends BaseJavaRefactoringAction { @Override protected boolean isAvailableInEditorOnly() { return false; } @Override protected boolean isAvailableForFile(PsiFile file) { return file != null && file.getFileType() == JavaFileType.INSTANCE && AndroidUtils.hasAndroidFacets(file.getProject()); } @Override protected boolean isEnabledOnDataContext(@NotNull DataContext dataContext) { // Hide action if last Gradle sync was unsuccessful. Project project = CommonDataKeys.PROJECT.getData(dataContext); if (project != null && !ProjectSystemUtil.getSyncManager(project).getLastSyncResult().isSuccessful()) { return false; } for (PsiElement element : getPsiElementArray(dataContext)) { if (!isAvailableForFile(element.getContainingFile())) { return false; } } PsiFile file = CommonDataKeys.PSI_FILE.getData(dataContext); return file == null || isAvailableForFile(file); } @Override protected boolean isAvailableOnElementInEditorAndFile(@NotNull PsiElement element, @NotNull Editor editor, @NotNull PsiFile file, @NotNull DataContext context) { Project project = file.getProject(); return ProjectSystemUtil.getSyncManager(project).getLastSyncResult().isSuccessful(); } @Override protected boolean isEnabledOnElements(@NotNull PsiElement[] elements) { return false; } @Nullable @Override protected RefactoringActionHandler getHandler(@NotNull DataContext dataContext) { return new AndroidModularizeHandler(); } }
/* * Copyright (c) 2008-2016 Haulmont. * * 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.haulmont.cuba.web.gui.components.mainwindow; import com.haulmont.cuba.core.global.Messages; import com.haulmont.cuba.core.global.MetadataTools; import com.haulmont.cuba.core.global.UserSessionSource; import com.haulmont.cuba.gui.Dialogs; import com.haulmont.cuba.gui.components.mainwindow.UserIndicator; import com.haulmont.cuba.security.app.UserManagementService; import com.haulmont.cuba.security.entity.User; import com.haulmont.cuba.security.entity.UserSubstitution; import com.haulmont.cuba.security.global.UserSession; import com.haulmont.cuba.web.AppUI; import com.haulmont.cuba.web.actions.ChangeSubstUserAction; import com.haulmont.cuba.web.actions.DoNotChangeSubstUserAction; import com.haulmont.cuba.web.gui.components.WebAbstractComponent; import com.haulmont.cuba.web.widgets.CubaComboBox; import com.vaadin.data.HasValue.ValueChangeEvent; import com.vaadin.ui.Label; import org.apache.commons.lang3.StringUtils; import javax.inject.Inject; import java.util.ArrayList; import java.util.List; import java.util.function.Function; import static com.haulmont.cuba.gui.ComponentsHelper.getScreenContext; import static com.vaadin.server.Sizeable.Unit; import static org.apache.commons.lang3.StringUtils.isNotEmpty; public class WebUserIndicator extends WebAbstractComponent<com.vaadin.ui.CssLayout> implements UserIndicator { protected static final String USER_INDICATOR_STYLENAME = "c-userindicator"; protected final Function<? super User, String> DEFAULT_USER_NAME_FORMATTER = this::getDefaultUserCaption; protected Label userNameLabel; protected CubaComboBox<User> userComboBox; protected Function<? super User, String> userNameFormatter = DEFAULT_USER_NAME_FORMATTER; protected MetadataTools metadataTools; public WebUserIndicator() { component = new com.vaadin.ui.CssLayout(); component.setPrimaryStyleName(USER_INDICATOR_STYLENAME); } @Inject public void setMetadataTools(MetadataTools metadataTools) { this.metadataTools = metadataTools; } @Override public void refreshUserSubstitutions() { component.removeAllComponents(); UserSessionSource uss = beanLocator.get(UserSessionSource.NAME); List<UserSubstitution> substitutions = getUserSubstitutions(); AppUI ui = AppUI.getCurrent(); User currentOrSubstitutedUser = uss.getUserSession().getCurrentOrSubstitutedUser(); if (substitutions.isEmpty()) { String substitutedUserCaption = getSubstitutedUserCaption(currentOrSubstitutedUser); userComboBox = null; userNameLabel = new Label(substitutedUserCaption); userNameLabel.setStyleName("c-user-select-label"); userNameLabel.setSizeUndefined(); if (ui != null && ui.isTestMode()) { userNameLabel.setCubaId("currentUserLabel"); } component.addComponent(userNameLabel); component.setDescription(substitutedUserCaption); } else { userNameLabel = null; userComboBox = new CubaComboBox<>(); userComboBox.setEmptySelectionAllowed(false); userComboBox.setItemCaptionGenerator(this::getSubstitutedUserCaption); userComboBox.setStyleName("c-user-select-combobox"); if (ui != null) { if (ui.isTestMode()) { userComboBox.setCubaId("substitutedUserSelect"); } if (ui.isPerformanceTestMode()) { userComboBox.setId(ui.getTestIdManager().getTestId("substitutedUserSelect")); } } List<User> options = new ArrayList<>(); User sessionUser = uss.getUserSession().getUser(); options.add(sessionUser); for (UserSubstitution substitution : substitutions) { User substitutedUser = substitution.getSubstitutedUser(); options.add(substitutedUser); } userComboBox.setItems(options); userComboBox.setValue(currentOrSubstitutedUser); userComboBox.addValueChangeListener(this::substitutedUserChanged); component.addComponent(userComboBox); component.setDescription(null); } adjustWidth(); adjustHeight(); } protected void substitutedUserChanged(ValueChangeEvent<User> event) { UserSessionSource uss = beanLocator.get(UserSessionSource.NAME); User newUser = event.getValue(); UserSession userSession = uss.getUserSession(); if (userSession == null) { throw new RuntimeException("No user session found"); } User oldUser = userSession.getSubstitutedUser() == null ? userSession.getUser() : userSession.getSubstitutedUser(); if (!oldUser.equals(newUser)) { String newUserName = StringUtils.isBlank(newUser.getName()) ? newUser.getLogin() : newUser.getName(); Messages messages = beanLocator.get(Messages.NAME); Dialogs dialogs = getScreenContext(this).getDialogs(); dialogs.createOptionDialog() .withCaption(messages.getMainMessage("substUserSelectDialog.title")) .withMessage(messages.formatMainMessage("substUserSelectDialog.msg", newUserName)) .withType(Dialogs.MessageType.WARNING) .withActions( new ChangeSubstUserAction(userComboBox.getValue()) { @Override public void doRevert() { super.doRevert(); revertToCurrentUser(); } }, new DoNotChangeSubstUserAction() { @Override public void actionPerform(com.haulmont.cuba.gui.components.Component component) { super.actionPerform(component); revertToCurrentUser(); } }) .show(); } } protected String getSubstitutedUserCaption(User user) { return userNameFormatter.apply(user); } protected String getDefaultUserCaption(User user) { return isNotEmpty(user.getName()) ? user.getName() : metadataTools.getInstanceName(user); } protected List<UserSubstitution> getUserSubstitutions() { UserManagementService userManagementService = beanLocator.get(UserManagementService.NAME); UserSessionSource uss = beanLocator.get(UserSessionSource.NAME); return userManagementService.getSubstitutedUsers(uss.getUserSession().getUser().getId()); } protected void revertToCurrentUser() { UserSessionSource uss = beanLocator.get(UserSessionSource.NAME); UserSession us = uss.getUserSession(); userComboBox.setValue(us.getCurrentOrSubstitutedUser()); } @Override public void setWidth(String width) { super.setWidth(width); adjustWidth(); } @Override public void setHeight(String height) { super.setHeight(height); adjustHeight(); } protected void adjustWidth() { if (getWidth() < 0) { if (userNameLabel != null) { userNameLabel.setWidth(-1, Unit.PIXELS); } else if (userComboBox != null) { userComboBox.setWidthUndefined(); } } else { if (userNameLabel != null) { userNameLabel.setWidth(100, Unit.PERCENTAGE); } else if (userComboBox != null) { userComboBox.setWidth(100, Unit.PERCENTAGE); } } } protected void adjustHeight() { if (getHeight() < 0) { if (userNameLabel != null) { userNameLabel.setHeight(-1, Unit.PIXELS); } else if (userComboBox != null) { userComboBox.setHeight(-1, Unit.PIXELS); } } else { if (userNameLabel != null) { userNameLabel.setHeight(100, Unit.PERCENTAGE); } else if (userComboBox != null) { userComboBox.setHeight(100, Unit.PERCENTAGE); } } } @Override public void setUserNameFormatter(Function<? super User, String> userNameFormatter) { this.userNameFormatter = userNameFormatter; refreshUserSubstitutions(); } @SuppressWarnings("unchecked") @Override public Function<User, String> getUserNameFormatter() { return (Function<User, String>) userNameFormatter; } }
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.controller.versions; import com.yahoo.component.Version; import com.yahoo.config.provision.SystemName; import com.yahoo.vespa.hosted.controller.Controller; import com.yahoo.vespa.hosted.controller.application.ApplicationList; import com.yahoo.vespa.hosted.controller.application.InstanceList; import java.time.Instant; import java.time.ZoneOffset; import java.util.List; import static com.yahoo.config.application.api.DeploymentSpec.UpgradePolicy; /** * Information about a particular Vespa version. * VespaVersions are identified by their version number and ordered by increasing version numbers. * * This is immutable. * * @author bratseth */ public class VespaVersion implements Comparable<VespaVersion> { private final Version version; private final String releaseCommit; private final Instant committedAt; private final boolean isControllerVersion; private final boolean isSystemVersion; private final boolean isReleased; private final List<NodeVersion> nodeVersions; private final Confidence confidence; public VespaVersion(Version version, String releaseCommit, Instant committedAt, boolean isControllerVersion, boolean isSystemVersion, boolean isReleased, List<NodeVersion> nodeVersions, Confidence confidence) { this.version = version; this.releaseCommit = releaseCommit; this.committedAt = committedAt; this.isControllerVersion = isControllerVersion; this.isSystemVersion = isSystemVersion; this.isReleased = isReleased; this.nodeVersions = nodeVersions; this.confidence = confidence; } public static Confidence confidenceFrom(DeploymentStatistics statistics, Controller controller) { InstanceList all = InstanceList.from(controller.jobController().deploymentStatuses(ApplicationList.from(controller.applications().asList()) .withProductionDeployment())); // 'production on this': All production deployment jobs upgrading to this version have completed without failure InstanceList productionOnThis = all.matching(instance -> statistics.productionSuccesses().stream().anyMatch(run -> run.id().application().equals(instance))) .not().failingUpgrade() .not().upgradingTo(statistics.version()); InstanceList failingOnThis = all.matching(instance -> statistics.failingUpgrades().stream().anyMatch(run -> run.id().application().equals(instance))); // 'broken' if any Canary fails if ( ! failingOnThis.with(UpgradePolicy.canary).isEmpty()) return Confidence.broken; // 'broken' if 4 non-canary was broken by this, and that is at least 10% of all if (nonCanaryApplicationsBroken(statistics.version(), failingOnThis, productionOnThis)) return Confidence.broken; // 'low' unless all canary applications are upgraded if (productionOnThis.with(UpgradePolicy.canary).size() < all.withProductionDeployment().with(UpgradePolicy.canary).size()) return Confidence.low; // 'high' if 90% of all default upgrade applications upgraded if (productionOnThis.with(UpgradePolicy.defaultPolicy).size() >= all.withProductionDeployment().with(UpgradePolicy.defaultPolicy).size() * 0.9) return Confidence.high; return Confidence.normal; } /** Returns the version number of this Vespa version */ public Version versionNumber() { return version; } /** Returns the sha of the release tag commit for this version in git */ public String releaseCommit() { return releaseCommit; } /** Returns the time of the release commit */ public Instant committedAt() { return committedAt; } /** Returns whether this is the current version of controllers in this system (the lowest version across all * controllers) */ public boolean isControllerVersion() { return isControllerVersion; } /** * Returns whether this is the current version of the infrastructure of the system * (i.e the lowest version across all controllers and all config servers in all zones). * A goal of the controllers is to eventually (limited by safety and upgrade capacity) drive * all applications to this version. * * Note that the self version may be higher than the current system version if * all config servers are not yet upgraded to the version of the controllers. */ public boolean isSystemVersion() { return isSystemVersion; } /** Returns whether the artifacts of this release are available in the configured maven repository. */ public boolean isReleased() { return isReleased; } /** Returns the versions of nodes allocated to system applications (across all zones) */ public List<NodeVersion> nodeVersions() { return nodeVersions; } /** Returns the confidence we have in this versions suitability for production */ public Confidence confidence() { return confidence; } @Override public int compareTo(VespaVersion other) { return this.versionNumber().compareTo(other.versionNumber()); } @Override public int hashCode() { return versionNumber().hashCode(); } @Override public boolean equals(Object other) { if (other == this) return true; if ( ! (other instanceof VespaVersion)) return false; return ((VespaVersion)other).versionNumber().equals(this.versionNumber()); } /** The confidence of a version. */ public enum Confidence { /** Rollout was aborted. The system infrastructure should stay on, or roll back to, its current version */ aborted, /** This version has been proven defective */ broken, /** We don't have sufficient evidence that this version is working */ low, /** We have sufficient evidence that this version is working */ normal, /** We have overwhelming evidence that this version is working */ high; /** Returns true if this confidence is at least as high as the given confidence */ public boolean equalOrHigherThan(Confidence other) { return this.compareTo(other) >= 0; } /** Returns true if this can be changed to target at given instant */ public boolean canChangeTo(Confidence target, SystemName system, Instant instant) { if (this.equalOrHigherThan(normal)) return true; // Confidence can always change from >= normal if (!target.equalOrHigherThan(normal)) return true; // Confidence can always change to < normal var hourOfDay = instant.atZone(ZoneOffset.UTC).getHour(); var dayOfWeek = instant.atZone(ZoneOffset.UTC).getDayOfWeek(); var hourEnd = system == SystemName.Public ? 13 : 11; // Confidence can only be raised between 05:00:00 and 11:59:59Z (13:59:59Z for public), and not during weekends or Friday. return hourOfDay >= 5 && hourOfDay <= hourEnd && dayOfWeek.getValue() < 5; } } private static boolean nonCanaryApplicationsBroken(Version version, InstanceList failingOnThis, InstanceList productionOnThis) { InstanceList failingNonCanaries = failingOnThis.startedFailingOn(version).not().with(UpgradePolicy.canary); InstanceList productionNonCanaries = productionOnThis.not().with(UpgradePolicy.canary); if (productionNonCanaries.size() + failingNonCanaries.size() == 0) return false; // 'broken' if 4 non-canary was broken by this, and that is at least 10% of all int brokenByThisVersion = failingNonCanaries.size(); return brokenByThisVersion >= 4 && brokenByThisVersion >= productionOnThis.size() * 0.1; } }
/* * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. */ /* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. */ package org.opensearch.common.transport; import com.carrotsearch.hppc.IntArrayList; import java.util.StringTokenizer; public class PortsRange { private final String portRange; public PortsRange(String portRange) { this.portRange = portRange; } public String getPortRangeString() { return portRange; } public int[] ports() throws NumberFormatException { final IntArrayList ports = new IntArrayList(); iterate(new PortCallback() { @Override public boolean onPortNumber(int portNumber) { ports.add(portNumber); return false; } }); return ports.toArray(); } public boolean iterate(PortCallback callback) throws NumberFormatException { StringTokenizer st = new StringTokenizer(portRange, ","); boolean success = false; while (st.hasMoreTokens() && !success) { String portToken = st.nextToken().trim(); int index = portToken.indexOf('-'); if (index == -1) { int portNumber = Integer.parseInt(portToken.trim()); success = callback.onPortNumber(portNumber); if (success) { break; } } else { int startPort = Integer.parseInt(portToken.substring(0, index).trim()); int endPort = Integer.parseInt(portToken.substring(index + 1).trim()); if (endPort < startPort) { throw new IllegalArgumentException("Start port [" + startPort + "] must be greater than end port [" + endPort + "]"); } for (int i = startPort; i <= endPort; i++) { success = callback.onPortNumber(i); if (success) { break; } } } } return success; } public interface PortCallback { boolean onPortNumber(int portNumber); } @Override public String toString() { return "PortsRange{" + "portRange='" + portRange + '\'' + '}'; } }
package AGEval; import java.util.ArrayList; import java.util.HashMap; public class AleSimulatorNode { private Class myClass; private HashMap<String, AleSimulatorNode> myChildren; private int nextPass; private ArrayList<ArrayList<EvalStep>> myVisitors; private String signature; public AleSimulatorNode(Class agent){ myClass = agent; myChildren = new HashMap<String, AleSimulatorNode>(); myVisitors = myClass.getVisitors(); nextPass = 0; signature = "[" + myClass.getName() + "]: "; } /** Adds a child with childName matching the name given in AG */ public void addChild(String childName, IFace type, AleSimulatorNode child){ if (myClass.hasChild(childName, type)){ if (!myChildren.containsKey(childName)){ myChildren.put(childName, child); } else { System.err.println("Warning: " + myClass.getName() + " already has a child " + childName); } } else { System.err.println("Warning: " + myClass.getName() + " does not have a member child called " + childName); } } /** Sanity check before running */ public boolean ready(){ for (String childName : myClass.getChildMappings().keySet()){ if (!myChildren.containsKey(childName)){ return false; } } return true; } /** Recursive sanity check to be called externally at the top level */ public boolean allReady(){ if (!ready()){ return false; } for (AleSimulatorNode child : myChildren.values()){ if (!child.allReady()){ return false; } } return true; } public String visit(){ String trace = new String(); if (nextPass < myVisitors.size()) for (EvalStep step : myVisitors.get(nextPass)){ if (step.getType() == EvalStep.EvalType.CALL){ EvalStepCall callStep = (EvalStepCall) step; for (String childName : myClass.getChildNamesForType(callStep.getTypeToCall())){ trace += signature + "CALL: " + childName + " [" + callStep.getVisitNum() + "]\n"; trace += myChildren.get(childName).visit(); } } else { trace += signature + step.toString() + "\n"; } } nextPass++; trace += signature + "RETURN\n"; return trace; } }
package de.gg.game.ui.screens; import de.eskalon.commons.core.EskalonApplication; import de.eskalon.commons.screens.AbstractEskalonUIScreen; import de.gg.game.core.ProjektGGApplication; public abstract class AbstractGGUIScreen extends AbstractEskalonUIScreen { protected ProjektGGApplication application; public AbstractGGUIScreen(ProjektGGApplication application) { super(application.getWidth(), application.getHeight()); this.application = application; } @Override protected EskalonApplication getApplication() { return application; } }
package io.quarkus.vertx.http.security; import java.util.Optional; import javax.enterprise.context.ApplicationScoped; import io.quarkus.security.AuthenticationFailedException; import io.quarkus.security.identity.AuthenticationRequestContext; import io.quarkus.security.identity.IdentityProvider; import io.quarkus.security.identity.SecurityIdentity; import io.quarkus.security.identity.request.UsernamePasswordAuthenticationRequest; import io.quarkus.security.runtime.QuarkusPrincipal; import io.quarkus.security.runtime.QuarkusSecurityIdentity; import io.smallrye.mutiny.Uni; @ApplicationScoped public class TestIdentityProvider implements IdentityProvider<UsernamePasswordAuthenticationRequest> { @Override public Class<UsernamePasswordAuthenticationRequest> getRequestType() { return UsernamePasswordAuthenticationRequest.class; } @Override public Uni<SecurityIdentity> authenticate(UsernamePasswordAuthenticationRequest request, AuthenticationRequestContext context) { TestIdentityController.TestIdentity ident = TestIdentityController.idenitities.get(request.getUsername()); if (ident == null) { return Uni.createFrom().optional(Optional.empty()); } if (!ident.password.equals(new String(request.getPassword().getPassword()))) { return Uni.createFrom().failure(new AuthenticationFailedException()); } QuarkusSecurityIdentity identity = QuarkusSecurityIdentity.builder() .setPrincipal(new QuarkusPrincipal(ident.username)) .addRoles(ident.roles) .addCredential(request.getPassword()) .build(); return Uni.createFrom().item(identity); } }
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.messagebus; import com.yahoo.text.Utf8String; /** * Superclass for objects that can be either explicitly (Message) or implicitly (Reply) routed. Note that protocol * implementors should never subclass this directly, but rather through the {@link Message} and {@link Reply} classes. * * A routable can be regarded as a protocol-defined value with additional message bus related state. The state is what * differentiates two Routables that carry the same value. This includes the application context attached to the * routable and the {@link CallStack} used to track the path of the routable within messagebus. When a routable is * copied (if the protocol supports it) only the value part is copied. The state must be explicitly transfered by * invoking the {@link #swapState(Routable)} method. That method is used to transfer the state from a message to the * corresponding reply, or to a different message if the application decides to replace it. * * @author Simon Thoresen Hult */ public abstract class Routable { private final CallStack callStack = new CallStack(); private final Trace trace = new Trace(); private Object context = null; /** * Discards this routable. Invoking this prevents the auto-generation of replies if you later discard the routable. * This is a required step to ensure safe shutdown if you need destroy a message bus instance while there are still * messages and replies alive in your application. */ public void discard() { context = null; callStack.clear(); trace.clear(); } /** * Swaps the state that makes this routable unique to another routable. The state is what identifies a routable for * message bus, so only one message can ever have the same state. This function must be called explicitly when * cloning and copying messages. * * @param rhs The routable to swap state with. */ public void swapState(Routable rhs) { Object context = this.context; this.context = rhs.context; rhs.context = context; callStack.swap(rhs.getCallStack()); trace.swap(rhs.getTrace()); } /** * Pushes the given reply handler onto the call stack of this routable, also storing the current context. * * @param handler The handler to push. */ public void pushHandler(ReplyHandler handler) { callStack.push(handler, context); } /** * <p>This is a convenience method for calling {@link CallStack#pop(Routable)} on the {@link CallStack} of this * Routable. It equals calling <code>routable.getCallStack().pop(routable)</code>.</p> * * @return The handler that was popped. * @see CallStack#pop(Routable) */ public ReplyHandler popHandler() { return callStack.pop(this); } /** Returns the context of this routable. */ public Object getContext() { return context; } /** * Sets a new context for this routable. Please note that the context is <u>not</u> something that is passed along a * message, it is simply a user context for the handler currently manipulating a message. When the corresponding * reply reaches the registered reply handler, its content will be the same as that of the outgoing message. More * technically, this context is contained in the callstack of a routable. */ public void setContext(Object context) { this.context = context; } /** Returns the callstack of this routable. */ public CallStack getCallStack() { return callStack; } /** Returns the trace object of this routable. */ public Trace getTrace() { return trace; } /** * Return the name of the protocol that defines this routable. This must be implemented by all inheriting classes, * and should then return the result of {@link com.yahoo.messagebus.Protocol#getName} of its protocol. * * @return the name of the protocol defining this message. */ public abstract Utf8String getProtocol(); /** * Returns the type of this routable. The id '0' is reserved for the EmptyReply class. Other ids must be defined by * the application protocol. */ public abstract int getType(); }
package net.minecraft.client.renderer.chunk; import java.util.BitSet; import java.util.Set; import net.minecraft.util.EnumFacing; public class SetVisibility { private static final int COUNT_FACES = EnumFacing.values().length; private final BitSet bitSet; public SetVisibility() { this.bitSet = new BitSet(COUNT_FACES * COUNT_FACES); } public void setManyVisible(Set<EnumFacing> p_178620_1_) { for (EnumFacing enumfacing : p_178620_1_) { for (EnumFacing enumfacing1 : p_178620_1_) { this.setVisible(enumfacing, enumfacing1, true); } } } public void setVisible(EnumFacing facing, EnumFacing facing2, boolean p_178619_3_) { this.bitSet.set(facing.ordinal() + facing2.ordinal() * COUNT_FACES, p_178619_3_); this.bitSet.set(facing2.ordinal() + facing.ordinal() * COUNT_FACES, p_178619_3_); } public void setAllVisible(boolean visible) { this.bitSet.set(0, this.bitSet.size(), visible); } public boolean isVisible(EnumFacing facing, EnumFacing facing2) { return this.bitSet.get(facing.ordinal() + facing2.ordinal() * COUNT_FACES); } public String toString() { StringBuilder stringbuilder = new StringBuilder(); stringbuilder.append(' '); for (EnumFacing enumfacing : EnumFacing.values()) { stringbuilder.append(' ').append(enumfacing.toString().toUpperCase().charAt(0)); } stringbuilder.append('\n'); for (EnumFacing enumfacing2 : EnumFacing.values()) { stringbuilder.append(enumfacing2.toString().toUpperCase().charAt(0)); for (EnumFacing enumfacing1 : EnumFacing.values()) { if (enumfacing2 == enumfacing1) { stringbuilder.append(" "); } else { boolean flag = this.isVisible(enumfacing2, enumfacing1); stringbuilder.append(' ').append((char) (flag ? 'Y' : 'n')); } } stringbuilder.append('\n'); } return stringbuilder.toString(); } }
/* * Copyright 2016 Albert Tregnaghi * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions * and limitations under the License. * */ package de.jcup.asciidoctoreditor.toolbar; import org.eclipse.jface.resource.ImageDescriptor; import de.jcup.asciidoctoreditor.AsciiDoctorEditor; public class ShowPreviewInExternalBrowserAction extends ToolbarAction { private static ImageDescriptor IMG_EXTERNAL_BROWSER = createToolbarImageDescriptor("preview_external_browser.png"); public ShowPreviewInExternalBrowserAction(AsciiDoctorEditor editor) { super(editor); initUI(); } private void initUI() { setImageDescriptor(IMG_EXTERNAL_BROWSER); setToolTipText("Asciidoctor preview in external browser."); } @Override public void run() { asciiDoctorEditor.setInternalPreview(false); asciiDoctorEditor.openInExternalBrowser(); } }
/* * MIT License * Copyright <2021-2022> * * 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. * @Author: Sinda * @Email: xhuicloud@163.com */ package com.xhuicloud.pay.properties; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.stereotype.Component; /** * @program: XHuiCloud * @description: PayProperties * @author: Sinda * @create: 2020-06-15 09:37 */ @Data @Component @RefreshScope @ConfigurationProperties(prefix = "pay") public class PayProperties { private String domain; private Alipay alipay; private WeChat weChat; @Data public class Alipay{ /** * 同步通知 */ private String returnUrl; /** * 异步通知 */ private String notifyUrl; /** * 订单过期时间 */ private String expireTime; } @Data public class WeChat{ /** * 同步通知 */ private String refundNotifyUrl; /** * 异步通知 */ private String notifyUrl; /** * 订单过期时间 */ private String expireTime; } }
package seedu.address.logic.commands; import static java.util.Objects.requireNonNull; import static seedu.address.logic.parser.CliSyntax.PREFIX_ADDRESS; import static seedu.address.logic.parser.CliSyntax.PREFIX_CUSTOMER; import static seedu.address.logic.parser.CliSyntax.PREFIX_EMAIL; import static seedu.address.logic.parser.CliSyntax.PREFIX_NAME; import static seedu.address.logic.parser.CliSyntax.PREFIX_PHONE; import static seedu.address.logic.parser.CliSyntax.PREFIX_REMARK; import static seedu.address.logic.parser.CliSyntax.PREFIX_RENTALPRICE; import static seedu.address.logic.parser.CliSyntax.PREFIX_SELLINGPRICE; import static seedu.address.logic.parser.CliSyntax.PREFIX_TAG; import seedu.address.logic.CommandHistory; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.model.Model; import seedu.address.model.person.Person; /** * Adds a person to the address book. */ public class AddCommand extends Command { public static final String COMMAND_WORD = "add"; public static final String MESSAGE_USAGE_BUYER = "Parameters for buyer: " + PREFIX_CUSTOMER + "CUSTOMER_TYPE " + PREFIX_NAME + "NAME " + PREFIX_PHONE + "PHONE " + PREFIX_EMAIL + "EMAIL " + PREFIX_REMARK + "REMARK \n" + "Example for buyer: " + COMMAND_WORD + " " + PREFIX_CUSTOMER + "buyer " + PREFIX_NAME + "Ian Berry " + PREFIX_PHONE + "96254182 " + PREFIX_EMAIL + "ianberry@example.com " + PREFIX_REMARK + "I am a buyer\n"; public static final String MESSAGE_USAGE_SELLER = "Parameters for seller: " + PREFIX_CUSTOMER + "CUSTOMER_TYPE " + PREFIX_NAME + "NAME " + PREFIX_PHONE + "PHONE " + PREFIX_EMAIL + "EMAIL " + PREFIX_REMARK + "REMARK " + PREFIX_ADDRESS + "ADDRESS " + PREFIX_SELLINGPRICE + "SELLING_PRICE " + "[" + PREFIX_TAG + "TAG" + "]...\n" + "Example for seller: " + COMMAND_WORD + " " + PREFIX_CUSTOMER + "seller " + PREFIX_NAME + "Amanda Brown " + PREFIX_PHONE + "92615231 " + PREFIX_EMAIL + "amandabrown@example.com " + PREFIX_REMARK + "I am a seller " + PREFIX_ADDRESS + "Blk 288D Jurong East Street 77, #13-38 " + PREFIX_SELLINGPRICE + "500000 " + PREFIX_TAG + "MRT\n"; public static final String MESSAGE_USAGE_LANDLORD = "Parameters for landlord: " + PREFIX_CUSTOMER + "CUSTOMER_TYPE " + PREFIX_NAME + "NAME " + PREFIX_PHONE + "PHONE " + PREFIX_EMAIL + "EMAIL " + PREFIX_REMARK + "REMARK " + PREFIX_ADDRESS + "ADDRESS " + PREFIX_RENTALPRICE + "RENTAL_PRICE " + "[" + PREFIX_TAG + "TAG" + "]...\n" + "Example for landlord: " + COMMAND_WORD + " " + PREFIX_CUSTOMER + "landlord " + PREFIX_NAME + "Matt Thomson " + PREFIX_PHONE + "81524521 " + PREFIX_EMAIL + "johnd@example.com " + PREFIX_REMARK + "I am a landlord " + PREFIX_ADDRESS + "Blk 131 Geylang East Ave 1, #06-40 " + PREFIX_RENTALPRICE + "2500 " + PREFIX_TAG + "MRT \n"; public static final String MESSAGE_USAGE_TENANT = "Parameters for tenant: " + PREFIX_CUSTOMER + "CUSTOMER_TYPE " + PREFIX_NAME + "NAME " + PREFIX_PHONE + "PHONE " + PREFIX_EMAIL + "EMAIL " + PREFIX_REMARK + "REMARK \n" + "Example for tenant: " + COMMAND_WORD + " " + PREFIX_CUSTOMER + "tenant " + PREFIX_NAME + "Evan Bell " + PREFIX_PHONE + "91756212 " + PREFIX_EMAIL + "evanbell@example.com " + PREFIX_REMARK + "I am a tenant\n"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Adds a person to the address book. \n" + MESSAGE_USAGE_BUYER + MESSAGE_USAGE_SELLER + MESSAGE_USAGE_LANDLORD + MESSAGE_USAGE_TENANT; public static final String MESSAGE_SUCCESS = "New person added: %1$s"; public static final String MESSAGE_DUPLICATE_PERSON = "This person already exists in the address book"; public static final String MESSAGE_DUPLICATE_PERSON_ARCHIVE = "This person already exists in the archive book"; public static final String MESSAGE_DUPLICATE_PERSON_PIN = "This person already exists in the pin book"; public static final String MESSAGE_DUPLICATE_IDENTITY_FIELD = "Customer with one or more duplicate identity " + "field found in address book"; public static final String MESSAGE_DUPLICATE_IDENTITY_FIELD_ARCHIVE = "Customer with one or more duplicate " + "identity field found in archive book"; public static final String MESSAGE_DUPLICATE_IDENTITY_FIELD_PIN = "Customer with one or more duplicate " + "identity field found in pin book"; private final Person toAdd; /** * Creates an AddCommand to add the specified {@code Person} */ public AddCommand(Person person) { requireNonNull(person); toAdd = person; } @Override public CommandResult execute(Model model, CommandHistory history) throws CommandException { requireNonNull(model); if (model.hasPerson(toAdd)) { throw new CommandException(MESSAGE_DUPLICATE_PERSON); } else if (model.hasPersonArchive(toAdd)) { throw new CommandException(MESSAGE_DUPLICATE_PERSON_ARCHIVE); } else if (model.hasPersonPin(toAdd)) { throw new CommandException(MESSAGE_DUPLICATE_PERSON_PIN); } else if (model.hasSameIdentityField(toAdd)) { throw new CommandException(MESSAGE_DUPLICATE_IDENTITY_FIELD); } else if (model.hasSameIdentityFieldArchive(toAdd)) { throw new CommandException(MESSAGE_DUPLICATE_IDENTITY_FIELD_ARCHIVE); } else if (model.hasSameIdentityFieldPin(toAdd)) { throw new CommandException(MESSAGE_DUPLICATE_IDENTITY_FIELD_PIN); } model.addPerson(toAdd); model.commitBooks(); model.setSelectedPinPerson(null); model.setSelectedPerson(toAdd); return new CommandResult(String.format(MESSAGE_SUCCESS, toAdd)); } @Override public boolean requiresMainList() { return true; } @Override public boolean requiresArchiveList() { return false; } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof AddCommand // instanceof handles nulls && toAdd.equals(((AddCommand) other).toAdd)); } }
package com.farerboy.framework.boot.util; import com.alibaba.fastjson.JSON; import org.apache.commons.lang3.ClassUtils; import org.apache.commons.lang3.StringUtils; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.net.JarURLConnection; import java.net.URL; import java.net.URLDecoder; import java.util.*; import java.util.jar.JarEntry; import java.util.jar.JarFile; public class ClassUtil { private static final Map<String, Class<?>> primitiveClassMap; static { primitiveClassMap = new HashMap<>(); primitiveClassMap.put("byte", int.class); primitiveClassMap.put("short", short.class); primitiveClassMap.put("int", int.class); primitiveClassMap.put("long", long.class); primitiveClassMap.put("char", char.class); primitiveClassMap.put("float", float.class); primitiveClassMap.put("double", double.class); primitiveClassMap.put("boolean", boolean.class); primitiveClassMap.put("void", void.class); } public static Class<?> forName(String className) { Class<?> clazz = primitiveClassMap.get(className); if (clazz != null) { return clazz; } try { return Class.forName(className); } catch (ClassNotFoundException e) { throw new RuntimeException("Class.forName(className) exception. className=" + className, e); } } public static <T> T newInstance(String className) { Class<?> clazz; try { clazz = Class.forName(className); } catch (Throwable e) { throw new RuntimeException("Class.forName(className) exception. className=" + className, e); } return (T)newInstance(clazz); } public static <T> T newInstance(Class<T> clazz) { T instance; try { instance = clazz.newInstance(); } catch (Throwable e) { throw new RuntimeException("clazz.newInstance() exception. clazz=" + clazz.getName(), e); } return instance; } public static Method getMethod(String destClass, String methodName, String[] argClassNames) { Class<?> clazz = ClassUtil.forName(destClass); Class<?>[] argClasses; if (argClassNames == null) { argClasses = null; } else if (argClassNames.length == 0) { argClasses = new Class<?>[] {}; } else { argClasses = Arrays.stream(argClassNames).map(ClassUtil::forName).toArray(Class<?>[]::new); } Method method; try { method = clazz.getMethod(methodName, argClasses); } catch (NoSuchMethodException e) { throw new RuntimeException("clazz.getMethod(methodName, argClasses) exception. clazz=" + destClass + ",methodName=" + methodName + ",argClasses=" + JSON.toJSONString(argClasses), e); } return method; } // public static String[] getArgNames(Method method) { // return getArgNames(method, false); // } // // public static String[] getBeautifulArgNames(Method method) { // return getArgNames(method, true); // } // private static DefaultParameterNameDiscoverer defaultParameterNameDiscoverer; /** * @param defaultClassName 如果为true,当获取不到真实参数名时返回类型名(首字母小写),返回如:[ "arg0","arg1"] */ // private static String[] getArgNames(Method method, boolean defaultClassName) { // if (defaultParameterNameDiscoverer == null) { // synchronized (ClassUtils.class) { // if (defaultParameterNameDiscoverer == null) { // defaultParameterNameDiscoverer = new DefaultParameterNameDiscoverer(); // } // } // } // // String[] argNames = defaultParameterNameDiscoverer.getParameterNames(method); // if (argNames == null) { // if (defaultClassName) { // argNames = Arrays.stream(method.getParameterTypes()) // .map(Class::getSimpleName) // .map(StringUtils::uncapitalize) // .toArray(String[]::new); // } else { // argNames = Arrays.stream(method.getParameters()) // .map(Parameter::getName) // .toArray(String[]::new); // } // } // return argNames; // } /** * 通过包名获取包内所有类 */ public static List<Class<?>> getAllClassByPackageName(Package pkg) { String packageName = pkg.getName(); // 获取当前包下以及子包下所以的类 List<Class<?>> returnClassList = getClasses(packageName); return returnClassList; } /** * 通过接口名取得某个接口下所有实现这个接口的类 */ public static List<Class<?>> getAllClassByInterface(Class<?> c) { List<Class<?>> returnClassList = null; if (c.isInterface()) { // 获取当前的包名 String packageName = c.getPackage().getName(); // 获取当前包下以及子包下所以的类 List<Class<?>> allClass = getClasses(packageName); if (allClass != null) { returnClassList = new ArrayList<Class<?>>(); for (Class<?> cls : allClass) { // 判断是否是同一个接口 if (c.isAssignableFrom(cls)) { // 本身不加入进去 if (!c.equals(cls)) { returnClassList.add(cls); } } } } } return returnClassList; } /** * 取得某一类所在包的所有类名 不含迭代 */ public static String[] getPackageAllClassName(String classLocation, String packageName) { // 将packageName分解 String[] packagePathSplit = packageName.split("[.]"); String realClassLocation = classLocation; int packageLength = packagePathSplit.length; for (int i = 0; i < packageLength; i++) { realClassLocation = realClassLocation + File.separator + packagePathSplit[i]; } File packeageDir = new File(realClassLocation); if (packeageDir.isDirectory()) { String[] allClassName = packeageDir.list(); return allClassName; } return null; } /** * 从包package中获取所有的Class */ private static List<Class<?>> getClasses(String packageName) { // 第一个class类的集合 List<Class<?>> classes = new ArrayList<Class<?>>(); // 是否循环迭代 boolean recursive = true; // 获取包的名字 并进行替换 String packageDirName = packageName.replace('.', '/'); // 定义一个枚举的集合 并进行循环来处理这个目录下的things Enumeration<URL> dirs; try { dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName); // 循环迭代下去 while (dirs.hasMoreElements()) { // 获取下一个元素 URL url = dirs.nextElement(); // 得到协议的名称 String protocol = url.getProtocol(); // 如果是以文件的形式保存在服务器上 if ("file".equals(protocol)) { // 获取包的物理路径 String filePath = URLDecoder.decode(url.getFile(), "UTF-8"); // 以文件的方式扫描整个包下的文件 并添加到集合中 findAndAddClassesInPackageByFile(packageName, filePath, recursive, classes); } else if ("jar".equals(protocol)) { // 如果是jar包文件 // 定义一个JarFile JarFile jar; try { // 获取jar jar = ((JarURLConnection) url.openConnection()).getJarFile(); // 从此jar包 得到一个枚举类 Enumeration<JarEntry> entries = jar.entries(); // 同样的进行循环迭代 while (entries.hasMoreElements()) { // 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件 JarEntry entry = entries.nextElement(); String name = entry.getName(); // 如果是以/开头的 if (name.charAt(0) == '/') { // 获取后面的字符串 name = name.substring(1); } // 如果前半部分和定义的包名相同 if (name.startsWith(packageDirName)) { int idx = name.lastIndexOf('/'); // 如果以"/"结尾 是一个包 if (idx != -1) { // 获取包名 把"/"替换成"." packageName = name.substring(0, idx).replace('/', '.'); } // 如果可以迭代下去 并且是一个包 if ((idx != -1) || recursive) { // 如果是一个.class文件 而且不是目录 if (name.endsWith(".class") && !entry.isDirectory()) { // 去掉后面的".class" 获取真正的类名 String className = name.substring(packageName.length() + 1, name.length() - 6); try { // 添加到classes classes.add(Class.forName(packageName + '.' + className)); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } } } } catch (IOException e) { e.printStackTrace(); } } } } catch (IOException e) { e.printStackTrace(); } return classes; } /** * 以文件的形式来获取包下的所有Class * */ private static void findAndAddClassesInPackageByFile(String packageName, String packagePath, final boolean recursive, List<Class<?>> classes) { // 获取此包的目录 建立一个File File dir = new File(packagePath); // 如果不存在或者 也不是目录就直接返回 if (!dir.exists() || !dir.isDirectory()) { return; } // 如果存在 就获取包下的所有文件 包括目录 File[] dirfiles = dir.listFiles(new FileFilter() { // 自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件) @Override public boolean accept(File file) { return (recursive && file.isDirectory()) || (file.getName().endsWith(".class")); } }); // 循环所有文件 for (File file : dirfiles) { // 如果是目录 则继续扫描 if (file.isDirectory()) { findAndAddClassesInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), recursive, classes); } else { // 如果是java类文件 去掉后面的.class 只留下类名 String className = file.getName().substring(0, file.getName().length() - 6); try { // 添加到集合中去 classes.add(Class.forName(packageName + '.' + className)); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } } }
/* * 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.phoenix.schema.types; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.math.BigDecimal; import java.sql.Array; import java.sql.Date; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Time; import java.sql.Timestamp; import java.sql.Types; import java.util.Map; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.hadoop.hbase.util.Bytes; import org.apache.phoenix.query.QueryConstants; import org.apache.phoenix.schema.SortOrder; import org.junit.Test; public class PDataTypeForArraysTest { @Test public void testForIntegerArray() { Integer[] intArr = new Integer[2]; intArr[0] = 1; intArr[1] = 2; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PInteger.INSTANCE, intArr); PIntegerArray.INSTANCE.toObject(arr, PIntegerArray.INSTANCE); byte[] bytes = PIntegerArray.INSTANCE.toBytes(arr); PhoenixArray resultArr = (PhoenixArray) PIntegerArray.INSTANCE .toObject(bytes, 0, bytes.length); assertEquals(arr, resultArr); } @Test public void testForBooleanArray() { Boolean[] boolArr = new Boolean[2]; boolArr[0] = true; boolArr[1] = false; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PBoolean.INSTANCE, boolArr); PBooleanArray.INSTANCE.toObject(arr, PBooleanArray.INSTANCE); byte[] bytes = PBooleanArray.INSTANCE.toBytes(arr); PhoenixArray resultArr = (PhoenixArray) PBooleanArray.INSTANCE .toObject(bytes, 0, bytes.length); assertEquals(arr, resultArr); } @Test public void testForVarCharArray() { String[] strArr = new String[2]; strArr[0] = "abc"; strArr[1] = "klmnop"; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PVarchar.INSTANCE, strArr); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr); PhoenixArray resultArr = (PhoenixArray) PVarcharArray.INSTANCE .toObject(bytes, 0, bytes.length); assertEquals(arr, resultArr); } @Test public void testVarCharArrayWithNullValues1() { String[] strArr = new String[6]; strArr[0] = "abc"; strArr[1] = null; strArr[2] = "bcd"; strArr[3] = null; strArr[4] = null; strArr[5] = "b"; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PVarchar.INSTANCE, strArr); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr); PhoenixArray resultArr = (PhoenixArray) PVarcharArray.INSTANCE .toObject(bytes, 0, bytes.length); assertEquals(arr, resultArr); } @Test public void testVarCharArrayWithNullValues2() { String[] strArr = new String[6]; strArr[0] = "abc"; strArr[1] = null; strArr[2] = "bcd"; strArr[3] = null; strArr[4] = "cde"; strArr[5] = null; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray(PVarchar.INSTANCE, strArr); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr); PhoenixArray resultArr = (PhoenixArray) PVarcharArray.INSTANCE.toObject(bytes, 0, bytes.length); assertEquals(arr, resultArr); } @Test public void testVarCharArrayWithNullValues3() { String[] strArr = new String[6]; strArr[0] = "abc"; strArr[1] = null; strArr[2] = null; strArr[3] = null; strArr[4] = null; strArr[5] = null; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray(PVarchar.INSTANCE, strArr); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr); PhoenixArray resultArr = (PhoenixArray) PVarcharArray.INSTANCE.toObject(bytes, 0, bytes.length); assertEquals(arr, resultArr); } @Test public void testVarCharArrayWithNullValues4() { String[] strArr = new String[7]; strArr[0] = "abc"; strArr[1] = null; strArr[2] = null; strArr[3] = null; strArr[4] = null; strArr[5] = null; strArr[6] = "xys"; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray(PVarchar.INSTANCE, strArr); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr); PhoenixArray resultArr = (PhoenixArray) PVarcharArray.INSTANCE.toObject(bytes, 0, bytes.length); assertEquals(arr, resultArr); } @Test public void testVarCharArrayWithNullValues5() { String[] strArr = new String[6]; strArr[0] = "abc"; strArr[1] = "bcd"; strArr[2] = "cde"; strArr[3] = null; strArr[4] = null; strArr[5] = null; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray(PVarchar.INSTANCE, strArr); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr); PhoenixArray resultArr = (PhoenixArray) PVarcharArray.INSTANCE.toObject(bytes, 0, bytes.length); assertEquals(arr, resultArr); } @Test public void testVarCharArrayWithNullValues6() { String[] strArr = new String[6]; strArr[0] = "abc"; strArr[1] = null; strArr[2] = "cde"; strArr[3] = "bcd"; strArr[4] = null; strArr[5] = null; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray(PVarchar.INSTANCE, strArr); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr); PhoenixArray resultArr = (PhoenixArray) PVarcharArray.INSTANCE.toObject(bytes, 0, bytes.length); assertEquals(arr, resultArr); } @Test public void testVarCharArrayWithNullValues7() { String[] strArr = new String[6]; strArr[0] = null; strArr[1] = "abc"; strArr[2] = null; strArr[3] = "bcd"; strArr[4] = null; strArr[5] = "cde"; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray(PVarchar.INSTANCE, strArr); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr); PhoenixArray resultArr = (PhoenixArray) PVarcharArray.INSTANCE.toObject(bytes, 0, bytes.length); assertEquals(arr, resultArr); } @Test public void testForCharArray() { String[] strArr = new String[2]; strArr[0] = "a"; strArr[1] = "d"; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PChar.INSTANCE, strArr); byte[] bytes = PCharArray.INSTANCE.toBytes(arr); PhoenixArray resultArr = (PhoenixArray) PCharArray.INSTANCE.toObject( bytes, 0, bytes.length, PCharArray.INSTANCE, null, 1, null); assertEquals(arr, resultArr); } @Test public void testForLongArray() { Long[] longArr = new Long[2]; longArr[0] = 1l; longArr[1] = 2l; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PLong.INSTANCE, longArr); PLongArray.INSTANCE.toObject(arr, PLongArray.INSTANCE); byte[] bytes = PLongArray.INSTANCE.toBytes(arr); PhoenixArray resultArr = (PhoenixArray) PLongArray.INSTANCE.toObject( bytes, 0, bytes.length); assertEquals(arr, resultArr); } @Test public void testForSmallIntArray() { Short[] shortArr = new Short[2]; shortArr[0] = 1; shortArr[1] = 2; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PSmallint.INSTANCE, shortArr); PSmallintArray.INSTANCE.toObject(arr, PSmallintArray.INSTANCE); byte[] bytes = PSmallintArray.INSTANCE.toBytes(arr); PhoenixArray resultArr = (PhoenixArray) PSmallintArray.INSTANCE .toObject(bytes, 0, bytes.length); assertEquals(arr, resultArr); } @Test public void testForVarCharArrayForOddNumber() { String[] strArr = new String[3]; strArr[0] = "abx"; strArr[1] = "ereref"; strArr[2] = "random"; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PVarchar.INSTANCE, strArr); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr); PhoenixArray resultArr = (PhoenixArray) PVarcharArray.INSTANCE .toObject(bytes, 0, bytes.length); assertEquals(arr, resultArr); } @Test public void testForVarCharArrayOneElement() { String[] strArr = new String[1]; strArr[0] = "ereref"; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PVarchar.INSTANCE, strArr); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr); PhoenixArray resultArr = (PhoenixArray) PVarcharArray.INSTANCE .toObject(bytes, 0, bytes.length); assertEquals(arr, resultArr); } @Test public void testForVarcharArrayWith1ElementInLargerBuffer() { String[] strArr = new String[1]; strArr[0] = "abx"; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray(PVarchar.INSTANCE, strArr); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr); byte[] moreBytes = new byte[bytes.length + 20]; // Generate some garbage for (int i = 0; i < moreBytes.length; i++) { moreBytes[i] = (byte)-i; } System.arraycopy(bytes, 0, moreBytes, 10, bytes.length); PhoenixArray resultArr = (PhoenixArray) PVarcharArray.INSTANCE.toObject(moreBytes, 10, bytes.length); assertEquals(arr, resultArr); } @Test public void testForVarCharArrayForEvenNumberWithIndex() { String[] strArr = new String[5]; strArr[0] = "abx"; strArr[1] = "ereref"; strArr[2] = "random"; strArr[3] = "random12"; strArr[4] = "ranzzz"; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PVarchar.INSTANCE, strArr); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr); ImmutableBytesWritable ptr = new ImmutableBytesWritable(bytes); PArrayDataTypeDecoder.positionAtArrayElement(ptr, 4, PVarchar.INSTANCE, PVarchar.INSTANCE.getByteSize()); int offset = ptr.getOffset(); int length = ptr.getLength(); byte[] bs = ptr.get(); byte[] res = new byte[length]; System.arraycopy(bs, offset, res, 0, length); assertEquals("ranzzz", Bytes.toString(res)); } @Test public void testForVarCharArrayWithOneElementIndex() { String[] strArr = new String[1]; strArr[0] = "abx"; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PVarchar.INSTANCE, strArr); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr); ImmutableBytesWritable ptr = new ImmutableBytesWritable(bytes); PArrayDataTypeDecoder.positionAtArrayElement(ptr, 0, PVarchar.INSTANCE, PVarchar.INSTANCE.getByteSize()); int offset = ptr.getOffset(); int length = ptr.getLength(); byte[] bs = ptr.get(); byte[] res = new byte[length]; System.arraycopy(bs, offset, res, 0, length); assertEquals("abx", Bytes.toString(res)); } public void testVariableLengthArrayWithElementsMoreThanShortMax() { String[] strArr = new String[(2 * Short.MAX_VALUE) + 100]; for(int i = 0 ; i < (2 * Short.MAX_VALUE) + 100; i++ ) { String str = "abc"; for(int j = 0 ; j <= i ;j++) { str += "-"; } strArr[i] = str; } PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PVarchar.INSTANCE, strArr); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr); ImmutableBytesWritable ptr = new ImmutableBytesWritable(bytes); PArrayDataTypeDecoder.positionAtArrayElement(ptr, 3, PVarchar.INSTANCE, PVarchar.INSTANCE.getByteSize()); int offset = ptr.getOffset(); int length = ptr.getLength(); byte[] bs = ptr.get(); byte[] res = new byte[length]; System.arraycopy(bs, offset, res, 0, length); assertEquals("abc---", Bytes.toString(res)); } @Test public void testGetArrayLengthForVariableLengthArray() { String[] strArr = new String[5]; strArr[0] = "abx"; strArr[1] = "ereref"; strArr[2] = "random"; strArr[3] = "random12"; strArr[4] = "ranzzz"; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PVarchar.INSTANCE, strArr); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr); ImmutableBytesWritable ptr = new ImmutableBytesWritable(bytes); int result = PArrayDataType.getArrayLength(ptr, PVarchar.INSTANCE, null); assertEquals(5, result); } @Test public void testForVarCharArrayForOddNumberWithIndex() { String[] strArr = new String[5]; strArr[0] = "abx"; strArr[1] = "ereref"; strArr[2] = "random"; strArr[3] = "random12"; strArr[4] = "ran"; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PVarchar.INSTANCE, strArr); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr); ImmutableBytesWritable ptr = new ImmutableBytesWritable(bytes); PArrayDataTypeDecoder.positionAtArrayElement(ptr, 3, PVarchar.INSTANCE, PVarchar.INSTANCE.getByteSize()); int offset = ptr.getOffset(); int length = ptr.getLength(); byte[] bs = ptr.get(); byte[] res = new byte[length]; System.arraycopy(bs, offset, res, 0, length); assertEquals("random12", Bytes.toString(res)); } @Test public void testPositionSearchWithVarLengthArrayWithNullValue1() { String[] strArr = new String[5]; strArr[0] = "abx"; strArr[1] = "ereref"; strArr[2] = "random"; strArr[3] = null; strArr[4] = "ran"; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PVarchar.INSTANCE, strArr); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr); ImmutableBytesWritable ptr = new ImmutableBytesWritable(bytes); PArrayDataTypeDecoder.positionAtArrayElement(ptr, 2, PVarchar.INSTANCE, PVarchar.INSTANCE.getByteSize()); int offset = ptr.getOffset(); int length = ptr.getLength(); byte[] bs = ptr.get(); byte[] res = new byte[length]; System.arraycopy(bs, offset, res, 0, length); assertEquals("random", Bytes.toString(res)); } @Test public void testPositionSearchWithVarLengthArrayWithNullValue2() { String[] strArr = new String[5]; strArr[0] = "abx"; strArr[1] = "ereref"; strArr[2] = "random"; strArr[3] = "random12"; strArr[4] = null; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PVarchar.INSTANCE, strArr); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr); ImmutableBytesWritable ptr = new ImmutableBytesWritable(bytes); PArrayDataTypeDecoder.positionAtArrayElement(ptr, 2, PVarchar.INSTANCE, PVarchar.INSTANCE.getByteSize()); int offset = ptr.getOffset(); int length = ptr.getLength(); byte[] bs = ptr.get(); byte[] res = new byte[length]; System.arraycopy(bs, offset, res, 0, length); assertEquals("random", Bytes.toString(res)); } @Test public void testForVarCharArrayForOddNumberWithIndex3() { String[] strArr = new String[5]; strArr[0] = "abx"; strArr[1] = "ereref"; strArr[2] = "random"; strArr[3] = "random12"; strArr[4] = null; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PVarchar.INSTANCE, strArr); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr); ImmutableBytesWritable ptr = new ImmutableBytesWritable(bytes); PArrayDataTypeDecoder.positionAtArrayElement(ptr, 4, PVarchar.INSTANCE, PVarchar.INSTANCE.getByteSize()); int offset = ptr.getOffset(); int length = ptr.getLength(); byte[] bs = ptr.get(); byte[] res = new byte[length]; System.arraycopy(bs, offset, res, 0, length); assertEquals("", Bytes.toString(res)); } @Test public void testForVarCharArrayForOddNumberWithIndex4() { String[] strArr = new String[5]; strArr[0] = "abx"; strArr[1] = "ereref"; strArr[2] = "random"; strArr[3] = null; strArr[4] = null; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PVarchar.INSTANCE, strArr); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr); ImmutableBytesWritable ptr = new ImmutableBytesWritable(bytes); PArrayDataTypeDecoder.positionAtArrayElement(ptr, 3, PVarchar.INSTANCE, PVarchar.INSTANCE.getByteSize()); int offset = ptr.getOffset(); int length = ptr.getLength(); byte[] bs = ptr.get(); byte[] res = new byte[length]; System.arraycopy(bs, offset, res, 0, length); assertEquals("", Bytes.toString(res)); } @Test public void testForVarCharArrayForOddNumberWithIndex5() { String[] strArr = new String[5]; strArr[0] = "abx"; strArr[1] = "ereref"; strArr[2] = "random"; strArr[3] = null; strArr[4] = "random12"; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PVarchar.INSTANCE, strArr); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr); ImmutableBytesWritable ptr = new ImmutableBytesWritable(bytes); PArrayDataTypeDecoder.positionAtArrayElement(ptr, 4, PVarchar.INSTANCE, PVarchar.INSTANCE.getByteSize()); int offset = ptr.getOffset(); int length = ptr.getLength(); byte[] bs = ptr.get(); byte[] res = new byte[length]; System.arraycopy(bs, offset, res, 0, length); assertEquals("random12", Bytes.toString(res)); } @Test public void testForVarCharArrayForOddNumberWithIndex6() { String[] strArr = new String[6]; strArr[0] = "abx"; strArr[1] = "ereref"; strArr[2] = "random"; strArr[3] = null; strArr[4] = "random12"; strArr[5] = "random17"; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PVarchar.INSTANCE, strArr); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr); ImmutableBytesWritable ptr = new ImmutableBytesWritable(bytes); PArrayDataTypeDecoder.positionAtArrayElement(ptr, 4, PVarchar.INSTANCE, PVarchar.INSTANCE.getByteSize()); int offset = ptr.getOffset(); int length = ptr.getLength(); byte[] bs = ptr.get(); byte[] res = new byte[length]; System.arraycopy(bs, offset, res, 0, length); assertEquals("random12", Bytes.toString(res)); } @Test public void testPositionSearchWithVarLengthArrayWithNullValue5() { String[] strArr = new String[5]; strArr[0] = "abx"; strArr[1] = "ereref"; strArr[2] = "random"; strArr[3] = null; strArr[4] = "ran"; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PVarchar.INSTANCE, strArr); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr); ImmutableBytesWritable ptr = new ImmutableBytesWritable(bytes); PArrayDataTypeDecoder.positionAtArrayElement(ptr, 3, PVarchar.INSTANCE, PVarchar.INSTANCE.getByteSize()); int offset = ptr.getOffset(); int length = ptr.getLength(); byte[] bs = ptr.get(); byte[] res = new byte[length]; System.arraycopy(bs, offset, res, 0, length); assertEquals("", Bytes.toString(res)); } @Test public void testPositionSearchWithVarLengthArrayWithNullValueAtTheStart1() { String[] strArr = new String[5]; strArr[0] = null; strArr[1] = "ereref"; strArr[2] = "random"; strArr[3] = null; strArr[4] = "ran"; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PVarchar.INSTANCE, strArr); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr); ImmutableBytesWritable ptr = new ImmutableBytesWritable(bytes); PArrayDataTypeDecoder.positionAtArrayElement(ptr, 3, PVarchar.INSTANCE, PVarchar.INSTANCE.getByteSize()); int offset = ptr.getOffset(); int length = ptr.getLength(); byte[] bs = ptr.get(); byte[] res = new byte[length]; System.arraycopy(bs, offset, res, 0, length); assertEquals("", Bytes.toString(res)); } @Test public void testPositionSearchWithVarLengthArrayWithNullValueAtTheStart2() { String[] strArr = new String[5]; strArr[0] = null; strArr[1] = "ereref"; strArr[2] = "random"; strArr[3] = null; strArr[4] = "ran"; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PVarchar.INSTANCE, strArr); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr); ImmutableBytesWritable ptr = new ImmutableBytesWritable(bytes); PArrayDataTypeDecoder.positionAtArrayElement(ptr, 0, PVarchar.INSTANCE, PVarchar.INSTANCE.getByteSize()); int offset = ptr.getOffset(); int length = ptr.getLength(); byte[] bs = ptr.get(); byte[] res = new byte[length]; System.arraycopy(bs, offset, res, 0, length); assertEquals("", Bytes.toString(res)); } @Test public void testPositionSearchWithVarLengthArrayWithNullValueAtTheStart3() { String[] strArr = new String[5]; strArr[0] = null; strArr[1] = "ereref"; strArr[2] = "random"; strArr[3] = null; strArr[4] = "ran"; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PVarchar.INSTANCE, strArr); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr); ImmutableBytesWritable ptr = new ImmutableBytesWritable(bytes); PArrayDataTypeDecoder.positionAtArrayElement(ptr, 4, PVarchar.INSTANCE, PVarchar.INSTANCE.getByteSize()); int offset = ptr.getOffset(); int length = ptr.getLength(); byte[] bs = ptr.get(); byte[] res = new byte[length]; System.arraycopy(bs, offset, res, 0, length); assertEquals("ran", Bytes.toString(res)); } @Test public void testPositionSearchWithVarLengthArrayWithAllNulls() { String[] strArr = new String[5]; strArr[0] = null; strArr[1] = null; strArr[2] = null; strArr[3] = null; strArr[4] = null; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PVarchar.INSTANCE, strArr); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr); ImmutableBytesWritable ptr = new ImmutableBytesWritable(bytes); PArrayDataTypeDecoder.positionAtArrayElement(ptr, 4, PVarchar.INSTANCE, PVarchar.INSTANCE.getByteSize()); int offset = ptr.getOffset(); int length = ptr.getLength(); byte[] bs = ptr.get(); byte[] res = new byte[length]; System.arraycopy(bs, offset, res, 0, length); assertEquals("", Bytes.toString(res)); } @Test public void testForVarCharArrayForOneElementArrayWithIndex() { String[] strArr = new String[1]; strArr[0] = "abx"; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PVarchar.INSTANCE, strArr); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr); ImmutableBytesWritable ptr = new ImmutableBytesWritable(bytes); PArrayDataTypeDecoder.positionAtArrayElement(ptr, 0, PVarchar.INSTANCE, PVarchar.INSTANCE.getByteSize()); int offset = ptr.getOffset(); int length = ptr.getLength(); byte[] bs = ptr.get(); byte[] res = new byte[length]; System.arraycopy(bs, offset, res, 0, length); assertEquals("abx", Bytes.toString(res)); } @Test public void testForVarCharArrayForWithTwoelementsElementArrayWithIndex() { String[] strArr = new String[2]; strArr[0] = "abx"; strArr[1] = "ereref"; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PVarchar.INSTANCE, strArr); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr); ImmutableBytesWritable ptr = new ImmutableBytesWritable(bytes); PArrayDataTypeDecoder.positionAtArrayElement(ptr, 1, PVarchar.INSTANCE, PVarchar.INSTANCE.getByteSize()); int offset = ptr.getOffset(); int length = ptr.getLength(); byte[] bs = ptr.get(); byte[] res = new byte[length]; System.arraycopy(bs, offset, res, 0, length); assertEquals("ereref", Bytes.toString(res)); } @Test public void testLongArrayWithIndex() { Long[] longArr = new Long[4]; longArr[0] = 1l; longArr[1] = 2l; longArr[2] = 4l; longArr[3] = 5l; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PLong.INSTANCE, longArr); PLongArray.INSTANCE.toObject(arr, PLongArray.INSTANCE); byte[] bytes = PLongArray.INSTANCE.toBytes(arr); ImmutableBytesWritable ptr = new ImmutableBytesWritable(bytes); PArrayDataTypeDecoder.positionAtArrayElement(ptr, 2, PLong.INSTANCE, PLong.INSTANCE.getByteSize()); int offset = ptr.getOffset(); int length = ptr.getLength(); byte[] bs = ptr.get(); byte[] res = new byte[length]; System.arraycopy(bs, offset, res, 0, length); long result = (Long) PLong.INSTANCE.toObject(res); assertEquals(4l, result); } @Test public void testGetArrayLengthForFixedLengthArray() { Long[] longArr = new Long[4]; longArr[0] = 1l; longArr[1] = 2l; longArr[2] = 4l; longArr[3] = 5l; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PLong.INSTANCE, longArr); PLongArray.INSTANCE.toObject(arr, PLongArray.INSTANCE); byte[] bytes = PLongArray.INSTANCE.toBytes(arr); ImmutableBytesWritable ptr = new ImmutableBytesWritable(bytes); int length = PArrayDataType.getArrayLength(ptr, PLong.INSTANCE, null); assertEquals(4, length); } @Test public void testForVarcharArrayBiggerArraysNumber() { String[] strArr = new String[101]; for (int i = 0; i <= 100; i++) { strArr[i] = "abc" + i; } PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PVarchar.INSTANCE, strArr); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr); PhoenixArray resultArr = (PhoenixArray) PVarcharArray.INSTANCE .toObject(bytes, 0, bytes.length); assertEquals(arr, resultArr); } @Test public void testForTinyIntArray() { Byte[] byteArr = new Byte[2]; byteArr[0] = 1; byteArr[1] = 2; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PTinyint.INSTANCE, byteArr); PTinyintArray.INSTANCE.toObject(arr, PTinyintArray.INSTANCE); byte[] bytes = PTinyintArray.INSTANCE.toBytes(arr); PhoenixArray resultArr = (PhoenixArray) PTinyintArray.INSTANCE .toObject(bytes, 0, bytes.length); assertEquals(arr, resultArr); } @Test public void testForFloatArray() { Float[] floatArr = new Float[2]; floatArr[0] = 1.06f; floatArr[1] = 2.89f; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PFloat.INSTANCE, floatArr); PFloatArray.INSTANCE.toObject(arr, PFloatArray.INSTANCE); byte[] bytes = PFloatArray.INSTANCE.toBytes(arr); PhoenixArray resultArr = (PhoenixArray) PFloatArray.INSTANCE.toObject( bytes, 0, bytes.length); assertEquals(arr, resultArr); } @Test public void testForDoubleArray() { Double[] doubleArr = new Double[2]; doubleArr[0] = 1.06; doubleArr[1] = 2.89; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PDouble.INSTANCE, doubleArr); PDoubleArray.INSTANCE.toObject(arr, PDoubleArray.INSTANCE); byte[] bytes = PDoubleArray.INSTANCE.toBytes(arr); PhoenixArray resultArr = (PhoenixArray) PDoubleArray.INSTANCE .toObject(bytes, 0, bytes.length); assertEquals(arr, resultArr); } @Test public void testForDecimalArray() { BigDecimal[] bigDecimalArr = new BigDecimal[2]; bigDecimalArr[0] = new BigDecimal(89997); bigDecimalArr[1] = new BigDecimal(8999.995f); PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PDecimal.INSTANCE, bigDecimalArr); PDecimalArray.INSTANCE.toObject(arr, PDecimalArray.INSTANCE); byte[] bytes = PDecimalArray.INSTANCE.toBytes(arr); PhoenixArray resultArr = (PhoenixArray) PDecimalArray.INSTANCE .toObject(bytes, 0, bytes.length); assertEquals(arr, resultArr); } @Test public void testForTimeStampArray() { Timestamp[] timeStampArr = new Timestamp[2]; timeStampArr[0] = new Timestamp(System.currentTimeMillis()); timeStampArr[1] = new Timestamp(900000l); PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PTimestamp.INSTANCE, timeStampArr); PTimestampArray.INSTANCE.toObject(arr, PTimestampArray.INSTANCE); byte[] bytes = PTimestampArray.INSTANCE.toBytes(arr); PhoenixArray resultArr = (PhoenixArray) PTimestampArray.INSTANCE .toObject(bytes, 0, bytes.length); assertEquals(arr, resultArr); } @Test public void testForUnSignedTimeStampArray() { Timestamp[] timeStampArr = new Timestamp[2]; timeStampArr[0] = new Timestamp(System.currentTimeMillis()); timeStampArr[1] = new Timestamp(900000l); PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PUnsignedTimestamp.INSTANCE, timeStampArr); PUnsignedTimestampArray.INSTANCE.toObject(arr, PUnsignedTimestampArray.INSTANCE); byte[] bytes = PUnsignedTimestampArray.INSTANCE.toBytes(arr); PhoenixArray resultArr = (PhoenixArray) PUnsignedTimestampArray.INSTANCE .toObject(bytes, 0, bytes.length); assertEquals(arr, resultArr); } @Test public void testForTimeArray() { Time[] timeArr = new Time[2]; timeArr[0] = new Time(System.currentTimeMillis()); timeArr[1] = new Time(900000l); PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PTime.INSTANCE, timeArr); PTimeArray.INSTANCE.toObject(arr, PTimeArray.INSTANCE); byte[] bytes = PTimeArray.INSTANCE.toBytes(arr); PhoenixArray resultArr = (PhoenixArray) PTimeArray.INSTANCE.toObject( bytes, 0, bytes.length); assertEquals(arr, resultArr); } @Test public void testForUnsignedTimeArray() { Time[] timeArr = new Time[2]; timeArr[0] = new Time(System.currentTimeMillis()); timeArr[1] = new Time(900000l); PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PUnsignedTime.INSTANCE, timeArr); PUnsignedTimeArray.INSTANCE.toObject(arr, PUnsignedTimeArray.INSTANCE); byte[] bytes = PUnsignedTimeArray.INSTANCE.toBytes(arr); PhoenixArray resultArr = (PhoenixArray) PUnsignedTimeArray.INSTANCE .toObject(bytes, 0, bytes.length); assertEquals(arr, resultArr); } @Test public void testForDateArray() { Date[] dateArr = new Date[2]; dateArr[0] = new Date(System.currentTimeMillis()); dateArr[1] = new Date(System.currentTimeMillis() + System.currentTimeMillis()); PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PDate.INSTANCE, dateArr); PDateArray.INSTANCE.toObject(arr, PDateArray.INSTANCE); byte[] bytes = PDateArray.INSTANCE.toBytes(arr); PhoenixArray resultArr = (PhoenixArray) PDateArray.INSTANCE.toObject( bytes, 0, bytes.length); assertEquals(arr, resultArr); } @Test public void testForUnSignedDateArray() { Date[] dateArr = new Date[2]; dateArr[0] = new Date(System.currentTimeMillis()); dateArr[1] = new Date(System.currentTimeMillis() + System.currentTimeMillis()); PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PUnsignedDate.INSTANCE, dateArr); PUnsignedDateArray.INSTANCE.toObject(arr, PUnsignedDateArray.INSTANCE); byte[] bytes = PUnsignedDateArray.INSTANCE.toBytes(arr); PhoenixArray resultArr = (PhoenixArray) PUnsignedDateArray.INSTANCE .toObject(bytes, 0, bytes.length); assertEquals(arr, resultArr); } @Test public void testForUnSignedLongArray() { Long[] longArr = new Long[2]; longArr[0] = 1l; longArr[1] = 2l; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PUnsignedLong.INSTANCE, longArr); PUnsignedLongArray.INSTANCE.toObject(arr, PUnsignedLongArray.INSTANCE); byte[] bytes = PUnsignedLongArray.INSTANCE.toBytes(arr); PhoenixArray resultArr = (PhoenixArray) PUnsignedLongArray.INSTANCE .toObject(bytes, 0, bytes.length); assertEquals(arr, resultArr); } @Test public void testForUnSignedIntArray() { Integer[] intArr = new Integer[2]; intArr[0] = 1; intArr[1] = 2; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PUnsignedInt.INSTANCE, intArr); PUnsignedIntArray.INSTANCE .toObject(arr, PUnsignedIntArray.INSTANCE); byte[] bytes = PUnsignedIntArray.INSTANCE.toBytes(arr); PhoenixArray resultArr = (PhoenixArray) PUnsignedIntArray.INSTANCE .toObject(bytes, 0, bytes.length); assertEquals(arr, resultArr); } @Test public void testForUnSignedSmallIntArray() { Short[] shortArr = new Short[2]; shortArr[0] = 1; shortArr[1] = 2; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PUnsignedSmallint.INSTANCE, shortArr); PUnsignedSmallintArray.INSTANCE.toObject(arr, PUnsignedSmallintArray.INSTANCE); byte[] bytes = PUnsignedSmallintArray.INSTANCE.toBytes(arr); PhoenixArray resultArr = (PhoenixArray) PUnsignedSmallintArray.INSTANCE .toObject(bytes, 0, bytes.length); assertEquals(arr, resultArr); } @Test public void testForUnSignedTinyIntArray() { Byte[] byteArr = new Byte[2]; byteArr[0] = 1; byteArr[1] = 2; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PUnsignedTinyint.INSTANCE, byteArr); PUnsignedTinyintArray.INSTANCE.toObject(arr, PUnsignedTinyintArray.INSTANCE); byte[] bytes = PUnsignedTinyintArray.INSTANCE.toBytes(arr); PhoenixArray resultArr = (PhoenixArray) PUnsignedTinyintArray.INSTANCE .toObject(bytes, 0, bytes.length); assertEquals(arr, resultArr); } @Test public void testForUnSignedFloatArray() { Float[] floatArr = new Float[2]; floatArr[0] = 1.9993f; floatArr[1] = 2.786f; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PUnsignedFloat.INSTANCE, floatArr); PUnsignedFloatArray.INSTANCE.toObject(arr, PUnsignedFloatArray.INSTANCE); byte[] bytes = PUnsignedFloatArray.INSTANCE.toBytes(arr); PhoenixArray resultArr = (PhoenixArray) PUnsignedFloatArray.INSTANCE .toObject(bytes, 0, bytes.length); assertEquals(arr, resultArr); } @Test public void testForUnSignedDoubleArray() { Double[] doubleArr = new Double[2]; doubleArr[0] = 1.9993; doubleArr[1] = 2.786; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PUnsignedDouble.INSTANCE, doubleArr); PUnsignedDoubleArray.INSTANCE.toObject(arr, PUnsignedDoubleArray.INSTANCE); byte[] bytes = PUnsignedDoubleArray.INSTANCE.toBytes(arr); PhoenixArray resultArr = (PhoenixArray) PUnsignedDoubleArray.INSTANCE .toObject(bytes, 0, bytes.length); assertEquals(arr, resultArr); } @Test public void testForArrayComparisionsForFixedWidth() { Double[] doubleArr = new Double[2]; doubleArr[0] = 1.9993; doubleArr[1] = 2.786; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray(PUnsignedDouble.INSTANCE, doubleArr); PUnsignedDoubleArray.INSTANCE.toObject(arr, PUnsignedDoubleArray.INSTANCE); byte[] bytes1 = PUnsignedDoubleArray.INSTANCE.toBytes(arr); doubleArr = new Double[2]; doubleArr[0] = 1.9993; doubleArr[1] = 2.786; arr = PArrayDataType.instantiatePhoenixArray(PUnsignedDouble.INSTANCE, doubleArr); PUnsignedDoubleArray.INSTANCE.toObject(arr, PUnsignedDoubleArray.INSTANCE); byte[] bytes2 = PUnsignedDoubleArray.INSTANCE.toBytes(arr); assertTrue(Bytes.equals(bytes1, bytes2)); } @Test public void testForArrayComparisionsWithInEqualityForFixedWidth() { Double[] doubleArr = new Double[2]; doubleArr[0] = 1.9993; doubleArr[1] = 2.786; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray(PUnsignedDouble.INSTANCE, doubleArr); PUnsignedDoubleArray.INSTANCE.toObject(arr, PUnsignedDoubleArray.INSTANCE); byte[] bytes1 = PUnsignedDoubleArray.INSTANCE.toBytes(arr); doubleArr = new Double[3]; doubleArr[0] = 1.9993; doubleArr[1] = 2.786; doubleArr[2] = 6.3; arr = PArrayDataType.instantiatePhoenixArray(PUnsignedDouble.INSTANCE, doubleArr); PUnsignedDoubleArray.INSTANCE.toObject(arr, PUnsignedDoubleArray.INSTANCE); byte[] bytes2 = PUnsignedDoubleArray.INSTANCE.toBytes(arr); assertTrue(Bytes.compareTo(bytes1, bytes2) < 0); } @Test public void testForArrayComparisonsForVarWidthArrays() { String[] strArr = new String[5]; strArr[0] = "abc"; strArr[1] = "ereref"; strArr[2] = "random"; strArr[3] = "random1"; strArr[4] = "ran"; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray(PVarchar.INSTANCE, strArr); byte[] bytes1 = PVarcharArray.INSTANCE.toBytes(arr); strArr = new String[5]; strArr[0] = "abc"; strArr[1] = "ereref"; strArr[2] = "random"; strArr[3] = "random1"; strArr[4] = "ran"; arr = PArrayDataType.instantiatePhoenixArray(PVarchar.INSTANCE, strArr); byte[] bytes2 = PVarcharArray.INSTANCE.toBytes(arr); assertTrue(Bytes.equals(bytes1, bytes2)); } @Test public void testForArrayComparisonsInEqualityForVarWidthArrays() { String[] strArr = new String[5]; strArr[0] = "abc"; strArr[1] = "ereref"; strArr[2] = "random"; strArr[3] = "random1"; strArr[4] = "ran"; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray(PVarchar.INSTANCE, strArr); byte[] bytes1 = PVarcharArray.INSTANCE.toBytes(arr); strArr = new String[5]; strArr[0] = "abc"; strArr[1] = "ereref"; strArr[2] = "random"; strArr[3] = "random1"; arr = PArrayDataType.instantiatePhoenixArray(PVarchar.INSTANCE, strArr); byte[] bytes2 = PVarcharArray.INSTANCE.toBytes(arr); assertTrue(Bytes.compareTo(bytes1, bytes2) > 0); } @Test public void testForArrayComparsionInEqualityWithNullsRepeatingInTheMiddle() { String[] strArr = new String[6]; strArr[0] = null; strArr[1] = "ereref"; strArr[2] = "random"; strArr[3] = null; strArr[4] = "ran"; strArr[5] = "ran"; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray(PVarchar.INSTANCE, strArr); byte[] bytes1 = PVarcharArray.INSTANCE.toBytes(arr); strArr = new String[6]; strArr[0] = null; strArr[1] = "ereref"; strArr[2] = "random"; strArr[3] = null; strArr[4] = null; strArr[5] = "ran"; arr = PArrayDataType.instantiatePhoenixArray(PVarchar.INSTANCE, strArr); byte[] bytes2 = PVarcharArray.INSTANCE.toBytes(arr); assertTrue(Bytes.compareTo(bytes1, bytes2) > 0); } @Test public void testVarCharArrayWithGreatherThan255NullsInMiddle() { String strArr[] = new String[300]; strArr[0] = "abc"; strArr[1] = "bcd"; strArr[2] = null; strArr[3] = null; strArr[4] = "bcd"; for(int i = 5; i < strArr.length - 2; i++) { strArr[i] = null; } strArr[strArr.length - 1] = "abc"; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PVarchar.INSTANCE, strArr); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr); PhoenixArray resultArr = (PhoenixArray) PVarcharArray.INSTANCE .toObject(bytes, 0, bytes.length); assertEquals(arr, resultArr); } @Test public void testVarCharArrayComparisonWithGreaterThan255NullsinMiddle() { String strArr[] = new String[240]; strArr[0] = "abc"; strArr[1] = "bcd"; strArr[2] = null; strArr[3] = null; strArr[4] = "bcd"; strArr[strArr.length - 1] = "abc"; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PVarchar.INSTANCE, strArr); byte[] bytes1 = PVarcharArray.INSTANCE.toBytes(arr); strArr = new String[16]; strArr[0] = "abc"; strArr[1] = "bcd"; strArr[2] = null; strArr[3] = null; strArr[4] = "bcd"; strArr[strArr.length - 1] = "abc"; arr = PArrayDataType.instantiatePhoenixArray( PVarchar.INSTANCE, strArr); byte[] bytes2 = PVarcharArray.INSTANCE.toBytes(arr); assertTrue(Bytes.compareTo(bytes1, bytes2) < 0); } @Test public void testVarCharArrayComparisonWithGreaterThan255NullsinMiddle1() { String strArr[] = new String[500]; strArr[0] = "abc"; strArr[1] = "bcd"; strArr[2] = null; strArr[3] = null; strArr[4] = "bcd"; strArr[strArr.length - 1] = "abc"; PhoenixArray arr = PArrayDataType.instantiatePhoenixArray( PVarchar.INSTANCE, strArr); byte[] bytes1 = PVarcharArray.INSTANCE.toBytes(arr); strArr = new String[500]; strArr[0] = "abc"; strArr[1] = "bcd"; strArr[2] = null; strArr[3] = null; strArr[4] = "bcd"; strArr[strArr.length - 1] = "abc"; arr = PArrayDataType.instantiatePhoenixArray( PVarchar.INSTANCE, strArr); byte[] bytes2 = PVarcharArray.INSTANCE.toBytes(arr); assertTrue(Bytes.compareTo(bytes1, bytes2) == 0); } @Test public void testIsRowKeyOrderOptimized1() { Object[] objects = new Object[]{"a", "b", "c"}; PhoenixArray arr = new PhoenixArray(PVarchar.INSTANCE, objects); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr, PVarchar.INSTANCE, SortOrder.ASC); assertTrue(PArrayDataType.isRowKeyOrderOptimized(PVarcharArray.INSTANCE, SortOrder.ASC, bytes, 0, bytes.length)); } @Test public void testIsRowKeyOrderOptimized2() { Object[] objects = new Object[]{"a", "b", "c"}; PhoenixArray arr = new PhoenixArray(PVarchar.INSTANCE, objects); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr, SortOrder.DESC); assertTrue(PArrayDataType.isRowKeyOrderOptimized(PVarcharArray.INSTANCE, SortOrder.DESC, bytes, 0, bytes.length)); } @Test public void testIsRowKeyOrderOptimized3() { Object[] objects = new Object[]{"a", "b", "c"}; PhoenixArray arr = new PhoenixArray(PVarchar.INSTANCE, objects); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr, SortOrder.DESC); for (int i = 0; i < bytes.length; i++) { if (bytes[i] == QueryConstants.DESC_SEPARATOR_BYTE) { bytes[i] = QueryConstants.SEPARATOR_BYTE; } } assertFalse(PArrayDataType.isRowKeyOrderOptimized(PVarcharArray.INSTANCE, SortOrder.DESC, bytes, 0, bytes.length)); } @Test public void testIsRowKeyOrderOptimized4() { assertTrue(PArrayDataType.isRowKeyOrderOptimized(PVarcharArray.INSTANCE, SortOrder.DESC, null, 0, 0)); } @Test public void testIsRowKeyOrderOptimized5() { Object[] objects = new Object[]{1, 2, 3}; PhoenixArray arr = new PhoenixArray.PrimitiveIntPhoenixArray(PInteger.INSTANCE, objects); byte[] bytes = PIntegerArray.INSTANCE.toBytes(arr, PInteger.INSTANCE, SortOrder.ASC); assertTrue(PArrayDataType.isRowKeyOrderOptimized(PIntegerArray.INSTANCE, SortOrder.ASC, bytes, 0, bytes.length)); } @Test public void testVarcharArrayDesc(){ Object[] objects = new Object[]{"a", "b", null}; PhoenixArray arr = new PhoenixArray(PVarchar.INSTANCE, objects); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr, PVarchar.INSTANCE, SortOrder.DESC); PhoenixArray arr2 = (PhoenixArray)PVarcharArray.INSTANCE.toObject(bytes, SortOrder.DESC); assertEquals(arr, arr2); } @Test public void testPositionAtArrayElementWithDescArray(){ Object[] objects = new Object[]{"a", "b", null}; PhoenixArray arr = new PhoenixArray(PVarchar.INSTANCE, objects); byte[] bytes = PVarcharArray.INSTANCE.toBytes(arr, PVarchar.INSTANCE, SortOrder.DESC); ImmutableBytesWritable ptr = new ImmutableBytesWritable(bytes); PArrayDataTypeDecoder.positionAtArrayElement(ptr, 2, PVarchar.INSTANCE, null); String value = (String)PVarchar.INSTANCE.toObject(ptr, SortOrder.DESC); assertEquals(null, value); } @Test public void testIsCoercibleTo() { PDataTypeFactory typeFactory = PDataTypeFactory.getInstance(); for (PDataType<?> type : typeFactory.getTypes()) { if (type.isArrayType()) { Object arr = type.getSampleValue(); assertTrue(type.isCoercibleTo(type, arr)); } } } @Test public void testArrayConversion() { final String[] data = new String[] {"asdf", "qwerty"}; PhoenixArray phxArray = PArrayDataType.instantiatePhoenixArray(PVarchar.INSTANCE, data); assertTrue("Converting a PhoenixArray to a PhoenixArray should return the same object", phxArray == PVarcharArray.INSTANCE.toPhoenixArray(phxArray, PVarchar.INSTANCE)); // Create a skeleton of an Array which isn't a PhoenixArray. Make sure we can convert that. Array customArray = new Array() { @Override public String getBaseTypeName() throws SQLException { return "VARCHAR"; } @Override public int getBaseType() throws SQLException { return Types.VARCHAR; } @Override public Object getArray() throws SQLException { return data; } @Override public Object getArray(Map<String,Class<?>> map) throws SQLException { return null; } @Override public Object getArray(long index, int count) throws SQLException { return null; } @Override public Object getArray(long index, int count, Map<String,Class<?>> map) throws SQLException { return null; } @Override public ResultSet getResultSet() throws SQLException { return null; } @Override public ResultSet getResultSet(Map<String,Class<?>> map) throws SQLException { return null; } @Override public ResultSet getResultSet(long index, int count) throws SQLException { return null; } @Override public ResultSet getResultSet(long index, int count, Map<String,Class<?>> map) throws SQLException { return null; } @Override public void free() throws SQLException {} }; PhoenixArray copy = PVarcharArray.INSTANCE.toPhoenixArray(customArray, PVarchar.INSTANCE); assertEquals(phxArray, copy); } }
/* * 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.karaf.shell.ssh.keygenerator; import static java.util.Collections.singleton; import java.io.IOException; import java.io.InputStream; import java.io.InvalidClassException; import java.io.ObjectInputStream; import java.io.ObjectStreamClass; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.security.GeneralSecurityException; import java.security.KeyFactory; import java.security.KeyPair; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.Base64; import org.apache.sshd.common.keyprovider.AbstractKeyPairProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class OpenSSHKeyPairProvider extends AbstractKeyPairProvider { private static final Logger LOGGER = LoggerFactory.getLogger(OpenSSHKeyPairProvider.class); private Path privateKeyPath; private Path publicKeyPath; private String password; private KeyPair cachedKey; private String algorithm; private int keySize; public OpenSSHKeyPairProvider(Path privateKeyPath, Path publicKeyPath, String algorithm, int keySize, String password) { this.privateKeyPath = privateKeyPath; this.publicKeyPath = publicKeyPath; this.algorithm = algorithm; this.keySize = keySize; this.password = password; } @Override public synchronized Iterable<KeyPair> loadKeys() { if (cachedKey != null) { return singleton(cachedKey); } if (!privateKeyPath.toFile().exists()) { createServerKey(); } // 1. Try to read the PKCS8 private key. If it is RSA or DSA we can infer the public key directly from the // private key, so there is no need to load the public key. try (InputStream is = Files.newInputStream(privateKeyPath)) { KeyPair kp = KeyPairLoader.getKeyPair(is, password); cachedKey = kp; return singleton(kp); } catch (Exception e) { // 2. Failed to parse PKCS8 private key. Try to parse it directly and use the public key to create a KeyPair // This is what will happen if it is an elliptic curve key for example LOGGER.warn("Failed to parse keypair in {}. Attempting to parse it 'directly'", privateKeyPath); try { KeyPair kp = getKeyPairUsingPublicKeyFile(); LOGGER.info("Successfully loaded key pair"); cachedKey = kp; return singleton(cachedKey); } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException | IllegalArgumentException e1) { // 3. On a failure, see if we are dealing with a "legacy" keypair. LOGGER.warn("Failed to parse keypair in {}. Attempting to parse it as a legacy 'simple' key", privateKeyPath); try { KeyPair kp = convertLegacyKey(privateKeyPath); LOGGER.info("Successfully loaded legacy simple key. Converted to PEM format"); cachedKey = kp; return singleton(kp); } catch (Exception nested) { LOGGER.warn(privateKeyPath + " is not a 'simple' key either", nested); } } throw new RuntimeException(e); } } private KeyPair convertLegacyKey(Path privateKeyPath) throws GeneralSecurityException, IOException { KeyPair keypair = null; try (ObjectInputStream r = new KeyPairObjectInputStream(Files.newInputStream(privateKeyPath))) { keypair = (KeyPair)r.readObject(); } catch (ClassNotFoundException e) { throw new InvalidKeySpecException("Missing classes: " + e.getMessage(), e); } new PemWriter(privateKeyPath, publicKeyPath).writeKeyPair(algorithm, keypair); return keypair; } private KeyPair getKeyPairUsingPublicKeyFile() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { KeyFactory keyFactory = KeyFactory.getInstance(algorithm); // Read private key String content = new String(Files.readAllBytes(privateKeyPath), StandardCharsets.UTF_8); content = content.replace("-----BEGIN PRIVATE KEY-----", ""); content = content.replace("-----END PRIVATE KEY-----", ""); PKCS8EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(Base64.getMimeDecoder().decode(content)); PrivateKey privateKey = keyFactory.generatePrivate(encodedKeySpec); // Read public key content = new String(Files.readAllBytes(publicKeyPath), StandardCharsets.UTF_8); content = content.replace("-----BEGIN PUBLIC KEY-----", ""); content = content.replace("-----END PUBLIC KEY-----", ""); X509EncodedKeySpec encodedX509KeySpec = new X509EncodedKeySpec(Base64.getMimeDecoder().decode(content)); PublicKey publicKey = keyFactory.generatePublic(encodedX509KeySpec); return new KeyPair(publicKey, privateKey); } private KeyPair createServerKey() { try { LOGGER.info("Creating ssh server private key at " + privateKeyPath); KeyPair kp = new OpenSSHKeyPairGenerator(algorithm, keySize).generate(); new PemWriter(privateKeyPath, publicKeyPath).writeKeyPair(algorithm, kp); return kp; } catch (Exception e) { throw new RuntimeException("Key file generation failed", e); } } /** * Check the first Object that is resolved is a KeyPair instance */ private static class KeyPairObjectInputStream extends ObjectInputStream { private boolean valid; public KeyPairObjectInputStream(InputStream is) throws IOException { super(is); } @Override protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { if (!valid) { if (!desc.getName().equals(KeyPair.class.getName())) { throw new InvalidClassException("Unauthorized deserialization attempt", desc.getName()); } valid = true; } return super.resolveClass(desc); } } }
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.support.v4.preference; import android.support.v4.app.AlertDialog.Builder; import android.content.Context; import android.content.DialogInterface; import android.content.res.TypedArray; import android.os.Parcel; import android.os.Parcelable; import android.support.v4.preferencefragment.R; import android.util.AttributeSet; import java.util.HashSet; import java.util.Set; /** * A {@link Preference} that displays a list of entries as * a dialog. * <p> * This preference will store a set of strings into the SharedPreferences. * This set will contain one or more values from the * {@link #setEntryValues(CharSequence[])} array. * * @attr ref android.R.styleable#MultiSelectListPreference_entries * @attr ref android.R.styleable#MultiSelectListPreference_entryValues */ public class MultiSelectListPreference extends DialogPreference { private CharSequence[] mEntries; private CharSequence[] mEntryValues; private Set<String> mValues = new HashSet<String>(); private Set<String> mNewValues = new HashSet<String>(); private boolean mPreferenceChanged; public MultiSelectListPreference(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MultiSelectListPreference, 0, 0); mEntries = a.getTextArray(R.styleable.MultiSelectListPreference_entries); mEntryValues = a.getTextArray(R.styleable.MultiSelectListPreference_entryValues); a.recycle(); } public MultiSelectListPreference(Context context) { this(context, null); } /** * Sets the human-readable entries to be shown in the list. This will be * shown in subsequent dialogs. * <p> * Each entry must have a corresponding index in * {@link #setEntryValues(CharSequence[])}. * * @param entries The entries. * @see #setEntryValues(CharSequence[]) */ public void setEntries(CharSequence[] entries) { mEntries = entries; } /** * @see #setEntries(CharSequence[]) * @param entriesResId The entries array as a resource. */ public void setEntries(int entriesResId) { setEntries(getContext().getResources().getTextArray(entriesResId)); } /** * The list of entries to be shown in the list in subsequent dialogs. * * @return The list as an array. */ public CharSequence[] getEntries() { return mEntries; } /** * The array to find the value to save for a preference when an entry from * entries is selected. If a user clicks on the second item in entries, the * second item in this array will be saved to the preference. * * @param entryValues The array to be used as values to save for the preference. */ public void setEntryValues(CharSequence[] entryValues) { mEntryValues = entryValues; } /** * @see #setEntryValues(CharSequence[]) * @param entryValuesResId The entry values array as a resource. */ public void setEntryValues(int entryValuesResId) { setEntryValues(getContext().getResources().getTextArray(entryValuesResId)); } /** * Returns the array of values to be saved for the preference. * * @return The array of values. */ public CharSequence[] getEntryValues() { return mEntryValues; } /** * Sets the value of the key. This should contain entries in * {@link #getEntryValues()}. * * @param values The values to set for the key. */ public void setValues(Set<String> values) { mValues.clear(); mValues.addAll(values); persistStringSet(values); } /** * Retrieves the current value of the key. */ public Set<String> getValues() { return mValues; } /** * Returns the index of the given value (in the entry values array). * * @param value The value whose index should be returned. * @return The index of the value, or -1 if not found. */ public int findIndexOfValue(String value) { if (value != null && mEntryValues != null) { for (int i = mEntryValues.length - 1; i >= 0; i--) { if (mEntryValues[i].equals(value)) { return i; } } } return -1; } @Override protected void onPrepareDialogBuilder(Builder builder) { super.onPrepareDialogBuilder(builder); if (mEntries == null || mEntryValues == null) { throw new IllegalStateException( "MultiSelectListPreference requires an entries array and " + "an entryValues array."); } boolean[] checkedItems = getSelectedItems(); builder.setMultiChoiceItems(mEntries, checkedItems, new DialogInterface.OnMultiChoiceClickListener() { public void onClick(DialogInterface dialog, int which, boolean isChecked) { if (isChecked) { mPreferenceChanged |= mNewValues.add(mEntryValues[which].toString()); } else { mPreferenceChanged |= mNewValues.remove(mEntryValues[which].toString()); } } }); mNewValues.clear(); mNewValues.addAll(mValues); } private boolean[] getSelectedItems() { final CharSequence[] entries = mEntryValues; final int entryCount = entries.length; final Set<String> values = mValues; boolean[] result = new boolean[entryCount]; for (int i = 0; i < entryCount; i++) { result[i] = values.contains(entries[i].toString()); } return result; } @Override protected void onDialogClosed(boolean positiveResult) { super.onDialogClosed(positiveResult); if (positiveResult && mPreferenceChanged) { final Set<String> values = mNewValues; if (callChangeListener(values)) { setValues(values); } } mPreferenceChanged = false; } @Override protected Object onGetDefaultValue(TypedArray a, int index) { final CharSequence[] defaultValues = a.getTextArray(index); final int valueCount = defaultValues.length; final Set<String> result = new HashSet<String>(); for (int i = 0; i < valueCount; i++) { result.add(defaultValues[i].toString()); } return result; } @Override protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { setValues(restoreValue ? getPersistedStringSet(mValues) : (Set<String>) defaultValue); } @Override protected Parcelable onSaveInstanceState() { final Parcelable superState = super.onSaveInstanceState(); if (isPersistent()) { // No need to save instance state return superState; } final SavedState myState = new SavedState(superState); myState.values = getValues(); return myState; } private static class SavedState extends BaseSavedState { Set<String> values; public SavedState(Parcel source) { super(source); values = new HashSet<String>(); String[] strings = source.createStringArray(); final int stringCount = strings.length; for (int i = 0; i < stringCount; i++) { values.add(strings[i]); } } public SavedState(Parcelable superState) { super(superState); } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeStringArray(values.toArray(new String[0])); } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } }
package com.example.demo.service; import com.example.demo.model.SysRole; import com.example.demo.core.universal.Service; /** * @Description: SysRoleService接口 * @author 张瑶 * @date 2018/05/25 23:01 */ public interface SysRoleService extends Service<SysRole> { }
package s0700; import me.rainstorm.util.BitUtil; import org.junit.Test; /** * [762] Prime Number of Set Bits in Binary Representation * <p> * https://leetcode-cn.com/problems/prime-number-of-set-bits-in-binary-representation/description/ * <p> * algorithms * Easy (58.87%) * Total Accepted: 2.8K * Total Submissions: 4.7K * Testcase Example: '842\n888' * <p> * 给定两个整数 L 和 R ,找到闭区间 [L, R] 范围内,计算置位位数为质数的整数个数。 * <p> * (注意,计算置位代表二进制表示中1的个数。例如 21 的二进制表示 10101 有 3 个计算置位。还有,1 不是质数。) * <p> * 示例 1: * <p> * <p> * 输入: L = 6, R = 10 * 输出: 4 * 解释: * 6 -> 110 (2 个计算置位,2 是质数) * 7 -> 111 (3 个计算置位,3 是质数) * 9 -> 1001 (2 个计算置位,2 是质数) * 10-> 1010 (2 个计算置位,2 是质数) * <p> * <p> * 示例 2: * <p> * <p> * 输入: L = 10, R = 15 * 输出: 5 * 解释: * 10 -> 1010 (2 个计算置位, 2 是质数) * 11 -> 1011 (3 个计算置位, 3 是质数) * 12 -> 1100 (2 个计算置位, 2 是质数) * 13 -> 1101 (3 个计算置位, 3 是质数) * 14 -> 1110 (3 个计算置位, 3 是质数) * 15 -> 1111 (4 个计算置位, 4 不是质数) * <p> * <p> * 注意: * <p> * <p> * L, R 是 L <= R 且在 [1, 10^6] 中的整数。 * R - L 的最大值为 10000。 * * @author baochen1.zhang * @date 2019.04.10 */ public class N0762CountPrimeSetBits { @Test public void case1() { assert 4 == countPrimeSetBits(6, 10); } @Test public void case2() { assert 5 == countPrimeSetBits(10, 15); } @Test public void case3() { assert 23 == countPrimeSetBits(842, 888); } public int countPrimeSetBits(int L, int R) { int count = 0; for (int i = L; i <= R; ++i) { if (isPrime(BitUtil.countBit(i))) { count++; } } return count; } private boolean isPrime(int num) { return num == 2 || num == 3 || num == 5 || num == 7 || num == 11 || num == 13 || num == 17 || num == 19 || num == 23 || num == 29 || num == 31; } }
/* * Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.client.impl; import com.hazelcast.client.impl.protocol.ClientMessage; import com.hazelcast.client.impl.protocol.codec.ClientAddClusterViewListenerCodec; import com.hazelcast.cluster.Address; import com.hazelcast.cluster.Member; import com.hazelcast.internal.cluster.MemberInfo; import com.hazelcast.internal.cluster.impl.ClusterServiceImpl; import com.hazelcast.internal.cluster.impl.MembersView; import com.hazelcast.internal.cluster.impl.MembershipManager; import com.hazelcast.internal.nio.Connection; import com.hazelcast.internal.partition.InternalPartitionService; import com.hazelcast.internal.partition.PartitionReplica; import com.hazelcast.internal.partition.PartitionTableView; import com.hazelcast.internal.util.EmptyStatement; import com.hazelcast.internal.util.scheduler.CoalescingDelayedTrigger; import com.hazelcast.spi.impl.NodeEngine; import com.hazelcast.spi.impl.NodeEngineImpl; import com.hazelcast.spi.impl.executionservice.ExecutionService; import java.nio.channels.CancelledKeyException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import static com.hazelcast.instance.EndpointQualifier.CLIENT; public class ClusterViewListenerService { private static final int PUSH_PERIOD_IN_SECONDS = 30; private static final long PARTITION_UPDATE_DELAY_MS = 100; private static final long PARTITION_UPDATE_MAX_DELAY_MS = 500; private final Map<ClientEndpoint, Long> clusterListeningEndpoints = new ConcurrentHashMap<>(); private final NodeEngine nodeEngine; private final boolean advancedNetworkConfigEnabled; private final AtomicBoolean pushScheduled = new AtomicBoolean(); private final CoalescingDelayedTrigger delayedPartitionUpdateTrigger; // This is an emulation of the pre-4.1 partition state version. // We will increment this version if a partition table change is detected // while sending partition table to the client. // Because of the client compatibility requirement, this integer version // wil remain until the next major version of the client protocol. private final AtomicInteger partitionTableVersion = new AtomicInteger(); // Latest observed partition stamp private final AtomicLong latestPartitionStamp = new AtomicLong(); ClusterViewListenerService(NodeEngineImpl nodeEngine) { this.nodeEngine = nodeEngine; this.advancedNetworkConfigEnabled = nodeEngine.getConfig().getAdvancedNetworkConfig().isEnabled(); this.delayedPartitionUpdateTrigger = new CoalescingDelayedTrigger(nodeEngine.getExecutionService(), PARTITION_UPDATE_DELAY_MS, PARTITION_UPDATE_MAX_DELAY_MS, this::pushPartitionTableView); } private void schedulePeriodicPush() { ExecutionService executor = nodeEngine.getExecutionService(); executor.scheduleWithRepetition(this::pushView, PUSH_PERIOD_IN_SECONDS, PUSH_PERIOD_IN_SECONDS, TimeUnit.SECONDS); } private void pushView() { pushPartitionTableView(); sendToListeningEndpoints(getMemberListViewMessage()); } private void pushPartitionTableView() { ClientMessage partitionViewMessage = getPartitionViewMessageOrNull(); if (partitionViewMessage != null) { sendToListeningEndpoints(partitionViewMessage); } } public void onPartitionStateChange() { delayedPartitionUpdateTrigger.executeWithDelay(); } public void onMemberListChange() { sendToListeningEndpoints(getMemberListViewMessage()); } private void sendToListeningEndpoints(ClientMessage clientMessage) { for (Map.Entry<ClientEndpoint, Long> entry : clusterListeningEndpoints.entrySet()) { Long correlationId = entry.getValue(); //share the partition and membership table, copy only initial frame ClientMessage message = clientMessage.copyWithNewCorrelationId(correlationId); ClientEndpoint clientEndpoint = entry.getKey(); Connection connection = clientEndpoint.getConnection(); write(message, connection); } } private void write(ClientMessage message, Connection connection) { try { connection.write(message); } catch (CancelledKeyException ignored) { //if connection closes, while writing we can get CancelledKeyException. // In that case, we can safely ignore the exception EmptyStatement.ignore(ignored); } } public void registerListener(ClientEndpoint clientEndpoint, long correlationId) { if (pushScheduled.compareAndSet(false, true)) { schedulePeriodicPush(); } clusterListeningEndpoints.put(clientEndpoint, correlationId); ClientMessage memberListViewMessage = getMemberListViewMessage(); memberListViewMessage.setCorrelationId(correlationId); write(memberListViewMessage, clientEndpoint.getConnection()); ClientMessage partitionViewMessage = getPartitionViewMessageOrNull(); if (partitionViewMessage != null) { partitionViewMessage.setCorrelationId(correlationId); write(partitionViewMessage, clientEndpoint.getConnection()); } } private ClientMessage getPartitionViewMessageOrNull() { InternalPartitionService partitionService = (InternalPartitionService) nodeEngine.getPartitionService(); PartitionTableView partitionTableView = partitionService.createPartitionTableView(); Map<UUID, List<Integer>> partitions = getPartitions(partitionTableView); if (partitions.size() == 0) { return null; } int version; long currentStamp = partitionTableView.stamp(); long latestStamp = latestPartitionStamp.get(); if (currentStamp != latestStamp && latestPartitionStamp.compareAndSet(latestStamp, currentStamp)) { partitionTableVersion.incrementAndGet(); } version = partitionTableVersion.get(); return ClientAddClusterViewListenerCodec.encodePartitionsViewEvent(version, partitions.entrySet()); } private ClientMessage getMemberListViewMessage() { MembershipManager membershipManager = ((ClusterServiceImpl) nodeEngine.getClusterService()).getMembershipManager(); MembersView membersView = membershipManager.getMembersView(); int version = membersView.getVersion(); List<MemberInfo> members = membersView.getMembers(); ArrayList<MemberInfo> memberInfos = new ArrayList<>(); for (MemberInfo member : members) { memberInfos.add(new MemberInfo(clientAddressOf(member.getAddress()), member.getUuid(), member.getAttributes(), member.isLiteMember(), member.getVersion(), member.getAddressMap())); } return ClientAddClusterViewListenerCodec.encodeMembersViewEvent(version, memberInfos); } public void deregisterListener(ClientEndpoint clientEndpoint) { clusterListeningEndpoints.remove(clientEndpoint); } private Address clientAddressOf(Address memberAddress) { if (!advancedNetworkConfigEnabled) { return memberAddress; } Member member = nodeEngine.getClusterService().getMember(memberAddress); if (member != null) { return member.getAddressMap().get(CLIENT); } else { // partition table contains stale entries for members which are not in the member list return null; } } /** * If any partition does not have an owner, this method returns empty collection * * @param partitionTableView will be converted to address-&gt;partitions mapping * @return address-&gt;partitions mapping, where address is the client address of the member */ public Map<UUID, List<Integer>> getPartitions(PartitionTableView partitionTableView) { Map<UUID, List<Integer>> partitionsMap = new HashMap<>(); int partitionCount = partitionTableView.length(); for (int partitionId = 0; partitionId < partitionCount; partitionId++) { PartitionReplica owner = partitionTableView.getReplica(partitionId, 0); if (owner == null || owner.uuid() == null) { partitionsMap.clear(); return partitionsMap; } partitionsMap.computeIfAbsent(owner.uuid(), k -> new LinkedList<>()).add(partitionId); } return partitionsMap; } //for test purpose only public Map<ClientEndpoint, Long> getClusterListeningEndpoints() { return clusterListeningEndpoints; } }
package it.infn.ct.ThreadPool; import java.util.Enumeration; import java.util.Hashtable; import java.util.concurrent.TimeUnit; import javax.naming.Context; import javax.naming.Name; import javax.naming.NamingException; import javax.naming.RefAddr; import javax.naming.Reference; import com.sun.appserv.server.LifecycleEvent; import com.sun.appserv.server.ServerLifecycleException; public class ThreadPoolExecutorFactory implements javax.naming.spi.ObjectFactory, com.sun.appserv.server.LifecycleListener, java.io.Serializable { public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception { ThreadPoolExecutor tp = ThreadPoolExecutor.getInstance(); try { Reference reference = (Reference) obj; Enumeration<?> enumeration = reference.getAll(); TimeUnit timeUnit = ThreadPoolExecutor.defaultTimeUnit; long keepAliveTime = ThreadPoolExecutor.defaultKeepAliveTime; while (enumeration.hasMoreElements()) { RefAddr refAddr = (RefAddr) enumeration.nextElement(); String pname = refAddr.getType(); String pvalue = (String) refAddr.getContent(); if ("corePoolSize".equalsIgnoreCase(pname)) { tp.setCorePoolSize(Integer.parseInt(pvalue)); } else if ("maximumPoolSize".equalsIgnoreCase(pname)) { tp.setMaximumPoolSize(Integer.parseInt(pvalue)); } else if ("timeUnit".equalsIgnoreCase(pname)) { timeUnit = TimeUnit.valueOf(pvalue); } else if ("keepAliveTime".equalsIgnoreCase(pname)) { keepAliveTime = Long.parseLong(pvalue); } else if ("allowCoreThreadTimeOut".equalsIgnoreCase(pname)) { tp.allowCoreThreadTimeOut(Boolean.parseBoolean(pvalue)); } else if ("prestartAllCoreThreads".equalsIgnoreCase(pname)) { if (Boolean.parseBoolean(pvalue)) { tp.prestartAllCoreThreads(); } } else { throw new IllegalArgumentException("Unrecognized property name: " + pname); } } tp.setKeepAliveTime(keepAliveTime, timeUnit); } catch (Exception e) { throw (NamingException) (new NamingException()).initCause(e); } return tp; } public void handleEvent(LifecycleEvent event) throws ServerLifecycleException { if (event.getEventType() == LifecycleEvent.TERMINATION_EVENT) { ThreadPoolExecutor tp = ThreadPoolExecutor.getInstance(); System.out.println("About to purge and shutdown " + tp + ", active thread count: " + tp.getActiveCount()); tp.purge(); tp.shutdown(); } } }
package com.jme3.shaderblow.test.electricity; import com.jme3.app.SimpleApplication; import com.jme3.light.AmbientLight; import com.jme3.light.DirectionalLight; import com.jme3.material.Material; import com.jme3.material.RenderState.BlendMode; import com.jme3.material.RenderState.FaceCullMode; import com.jme3.math.ColorRGBA; import com.jme3.math.Vector3f; import com.jme3.renderer.RenderManager; import com.jme3.renderer.queue.RenderQueue.Bucket; import com.jme3.scene.Geometry; import com.jme3.scene.Mesh; import com.jme3.scene.Node; import com.jme3.scene.Spatial; import com.jme3.texture.Texture; /** * @author cvlad */ public class TestElectricity5 extends SimpleApplication { /** * * @param args */ public static void main(String[] args) { TestElectricity5 app = new TestElectricity5(); app.start(); } @Override public void simpleInitApp() { // this.assetManager.registerLocator("assets", FileLocator.class); Node model = (Node) assetManager.loadModel("Models/LightBlow/jme_lightblow.mesh.xml"); Material litMat = new Material(assetManager, "Common/MatDefs/Light/Lighting.j3md"); model.setMaterial(litMat); Electricity5Material mat = new Electricity5Material(assetManager, "MatDefs/Electricity/Electricity5.j3md"); mat.setLayers(10); mat.setWidth(0.2f); mat.setFloat("speed", 0.1f); mat.setFloat("thickness", 0.14f); Texture noiseTex = assetManager.loadTexture("Textures/Electricity/noise.png"); noiseTex.setWrap(Texture.WrapMode.Repeat); mat.setTexture("noise", noiseTex); mat.getAdditionalRenderState().setBlendMode(BlendMode.AlphaAdditive); mat.getAdditionalRenderState().setDepthWrite(false); mat.getAdditionalRenderState().setDepthTest(true); mat.getAdditionalRenderState().setFaceCullMode(FaceCullMode.Off); mat.setColor("color", ColorRGBA.Blue); for (Spatial child : model.getChildren()) { if (child instanceof Geometry) { Mesh mesh = ((Geometry) child).getMesh(); Geometry geo = new Geometry("electrified_" + child.getName()); geo.setQueueBucket(Bucket.Transparent); geo.setMesh(mesh); geo.setMaterial(mat); model.attachChild(geo); } } rootNode.attachChild(model); model.setLocalTranslation(new Vector3f(0, -1.5f, 5)); addLighting(); flyCam.setMoveSpeed(20); } private void addLighting() { DirectionalLight sun = new DirectionalLight(); sun.setColor(new ColorRGBA(0.6f, 0.6f, 0.6f, 0.6f)); sun.setDirection(new Vector3f(-1, -1, -1)); rootNode.addLight(sun); AmbientLight ambient = new AmbientLight(); ambient.setColor(new ColorRGBA(0.6f, 0.6f, 0.6f, 0.6f)); rootNode.addLight(ambient); } @Override public void simpleUpdate(float tpf) { // TODO: add update code } @Override public void simpleRender(RenderManager rm) { // TODO: add render code } }
/* * The MIT License (MIT) * * Copyright (c) 2015 Andoni del Olmo * * 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 org.ado.minesync.translation.drive; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpResponse; import com.google.api.services.drive.Drive; import com.google.api.services.drive.model.ChildList; import com.google.api.services.drive.model.ChildReference; import com.google.api.services.drive.model.File; import com.google.api.services.drive.model.FileList; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Class description here. * * @author andoni * @since 07.10.2014 */ public class DriveClient { private static final String FOLDER_NAME = "Mine Sync GitHub"; private static final String FILENAME_TEMPLATE = "Translations v.%s"; private static final String MICROSOFT_OFFICE_2007_MIME_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; private Drive drive; public DriveClient() { drive = DriveClientFactory.createDrive(); } public InputStream getTranslationFile(String version) throws IOException { final HashMap<String, File> translationFiles = getFilesInFolder(drive, FOLDER_NAME); final File translationFile = translationFiles.get(String.format(FILENAME_TEMPLATE, version)); if (translationFile == null) { throw new IOException(String.format("No translation file found for version %s.", version)); } System.out.println("Using \"" + translationFile.getTitle() + "\" to update strings."); final String exportUrl = translationFile.getExportLinks().get(MICROSOFT_OFFICE_2007_MIME_TYPE); final HttpResponse resp = drive.getRequestFactory().buildGetRequest(new GenericUrl(exportUrl)).execute(); return resp.getContent(); } private HashMap<String, File> getFilesInFolder(Drive service, String folderName) throws IOException { final HashMap<String, File> map = new HashMap<String, File>(); final Drive.Children.List request = service.children().list(getFile(service, folderName).getId()); do { try { ChildList children = request.execute(); System.out.println("Loading translation files..."); for (ChildReference child : children.getItems()) { final File file = service.files().get(child.getId()).execute(); System.out.println("* " + file.getTitle()); map.put(file.getTitle(), file); } request.setPageToken(children.getNextPageToken()); } catch (IOException e) { System.out.println("An error occurred: " + e); request.setPageToken(null); } } while (request.getPageToken() != null && request.getPageToken().length() > 0); return map; } private File getFile(Drive drive, String name) throws IOException { List<File> fileList = getAllFiles(drive); for (File file : fileList) { if (name.equals(file.getTitle())) { return file; } } return null; } private List<File> getAllFiles(Drive service) throws IOException { List<File> result = new ArrayList<File>(); Drive.Files.List request = service.files().list(); do { try { FileList files = request.execute(); result.addAll(files.getItems()); request.setPageToken(files.getNextPageToken()); } catch (IOException e) { System.out.println("An error occurred: " + e); request.setPageToken(null); } } while (request.getPageToken() != null && request.getPageToken().length() > 0); return result; } }
/* * 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.polygene.api.serialization; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Base64; import static java.nio.charset.StandardCharsets.UTF_8; /** * A Converter based on Java Serialization. * * Note that this Converter works with String representations. * The serialized payload is encoded using Base64. * This is suitable for text based formats, if you are using a binary format, see the serialization extension. * * Prefer using it with the {@link ConvertedBy} annotation. * If you register it as a serialization converter, it will catch all types. * Or you could extend it and override {@link #type()}. */ public class JavaSerializationConverter implements Converter<Object> { @Override public Class<Object> type() { return Object.class; } @Override public String toString( Object object ) { byte[] bytes = Base64.getEncoder().encode( serializeJava( object ) ); return new String( bytes, UTF_8 ); } @Override public Object fromString( String string ) { byte[] bytes = Base64.getDecoder().decode( string ); return deserializeJava( bytes ); } protected byte[] serializeJava( Object object ) { ByteArrayOutputStream bout = new ByteArrayOutputStream(); try( ObjectOutputStream out = new ObjectOutputStream( bout ) ) { out.writeUnshared( object ); out.flush(); return bout.toByteArray(); } catch( IOException ex ) { throw new SerializationException( "Unable to serialize using Java serialization", ex ); } } protected Object deserializeJava( byte[] bytes ) { try( ObjectInputStream oin = new ObjectInputStream( new ByteArrayInputStream( bytes ) ) ) { return oin.readObject(); } catch( IOException | ClassNotFoundException ex ) { throw new SerializationException( "Unable to deserialize using Java serialization", ex ); } } }
/* * Copyright (c) 2012, 2013, Trivadis (Anatole Tresch), Werner Keil. * * 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.javamoney.calc.common; import org.javamoney.moneta.Money; import org.junit.Test; import java.math.BigDecimal; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; /** * Created by atsticks on 15.05.16. * @link http://www.financeformulas.net/Present_Value_of_Annuity.html#calcHeader */ public class PresentValueOfAnnuityTest { @Test public void getRate() throws Exception { PresentValueOfAnnuity val = PresentValueOfAnnuity.of( Rate.of(0.03),1 ); assertEquals(val.getRate(), Rate.of(0.03)); } @Test public void getPeriods() throws Exception { PresentValueOfAnnuity val = PresentValueOfAnnuity.of( Rate.of(0.03),3654 ); assertEquals(val.getPeriods(), 3654); } @Test public void of_Period1() throws Exception { PresentValueOfAnnuity val = PresentValueOfAnnuity.of( Rate.of(0.05), 1 ); assertNotNull(val); } @Test public void of_Period0() throws Exception { PresentValueOfAnnuity val = PresentValueOfAnnuity.of( Rate.of(0.08),0 ); assertNotNull(val); } @Test public void calculate_Periods0() throws Exception { Money m = Money.of(10, "CHF"); PresentValueOfAnnuity val = PresentValueOfAnnuity.of( Rate.of(0.05), 0 ); assertEquals(Money.of(0,"CHF"), m.with(val)); val = PresentValueOfAnnuity.of( Rate.of(-0.05), 0 ); assertEquals(Money.of(0,"CHF"), m.with(val)); } @Test public void calculate_Periods1() throws Exception { Money m = Money.of(10, "CHF"); PresentValueOfAnnuity val = PresentValueOfAnnuity.of( Rate.of(0.05), 1 ); assertEquals(Money.of(9.523809523809524,"CHF").getNumber().doubleValue(), m.with(val).getNumber().doubleValue(),0.000001d); val = PresentValueOfAnnuity.of( Rate.of(-0.05), 1 ); assertEquals(Money.of(10.5263157894736842105263,"CHF").getNumber().doubleValue(), m.with(val).getNumber().doubleValue(), 0.00001d); } @Test public void calculate_PeriodsN() throws Exception { Money m = Money.of(10, "CHF"); PresentValueOfAnnuity val = PresentValueOfAnnuity.of( Rate.of(0.05), 10 ); assertEquals(Money.of(77.21734929184812,"CHF").getNumber().numberValue(BigDecimal.class) .doubleValue(), m.with(val).getNumber().numberValue(BigDecimal.class) .doubleValue(), 0.00000000000001d); val = PresentValueOfAnnuity.of( Rate.of(-0.05), 10 ); assertEquals(Money.of(134.0365140230186,"CHF").getNumber().numberValue(BigDecimal.class).doubleValue(), m.with(val).getNumber().numberValue(BigDecimal.class).doubleValue(), 0.000000000000001d); } @Test public void apply() throws Exception { PresentValueOfAnnuity val = PresentValueOfAnnuity.of( Rate.of(0.08), 10 ); Money m = Money.of(10, "CHF"); assertEquals(val.apply(m), m.with(val)); } @Test public void toStringTest() throws Exception { PresentValueOfAnnuity val = PresentValueOfAnnuity.of( Rate.of(0.05), 10 ); assertEquals("PresentValueOfAnnuity{rate=Rate[0.05], periods=10}", val.toString()); } }
class BooleanExpressions{ public static void main(String[] a){ System.out.println("Test booleanExpressions"); } } class Test{ int foo; int test(){ String a ; String b ; char z; char v; if(v == z){ a = "alain"; } if(!false){ b = "compiler"; } if(10 < 5 && 10 < 5){ a = "nope"; } if(10 < 5 || 10 < 5){ a = "yeah"; } return 0 ; } }
package com.github.solairerove.harald.application.dto.comment; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import java.io.Serializable; @Data @JsonInclude(JsonInclude.Include.NON_NULL) public class CommentRequest implements Serializable { private static final long serialVersionUID = 5842261256762549186L; @JsonProperty private String author; @JsonProperty private String date; @JsonProperty private String content; }
/** * * 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.openejb.test.entity.cmp; import javax.rmi.PortableRemoteObject; import javax.ejb.EJBHome; /** * [8] Should be run as the eigth test suite of the UnknownCmpTestClients */ public class UnknownEjbMetaDataTests extends UnknownCmpTestClient { public UnknownEjbMetaDataTests() { super("EJBMetaData."); } protected void setUp() throws Exception { super.setUp(); final Object obj = initialContext.lookup("client/tests/entity/cmp/UnknownCmpHome"); ejbHome = (UnknownCmpHome) PortableRemoteObject.narrow(obj, UnknownCmpHome.class); ejbMetaData = ejbHome.getEJBMetaData(); } //================================= // Test meta data methods // public void test01_getEJBHome() { try { final EJBHome home = ejbMetaData.getEJBHome(); assertNotNull("The EJBHome is null", home); } catch (final Exception e) { fail("Received Exception " + e.getClass() + " : " + e.getMessage()); } } public void test02_getHomeInterfaceClass() { try { final Class clazz = ejbMetaData.getHomeInterfaceClass(); assertNotNull("The Home Interface class is null", clazz); assertEquals(clazz, UnknownCmpHome.class); } catch (final Exception e) { fail("Received Exception " + e.getClass() + " : " + e.getMessage()); } } public void test03_getPrimaryKeyClass() { try { final Class clazz = ejbMetaData.getPrimaryKeyClass(); assertNotNull("The EJBMetaData is null", clazz); assertEquals(clazz, Object.class); } catch (final Exception e) { fail("Received Exception " + e.getClass() + " : " + e.getMessage()); } } public void test04_getRemoteInterfaceClass() { try { final Class clazz = ejbMetaData.getRemoteInterfaceClass(); assertNotNull("The Remote Interface class is null", clazz); assertEquals(clazz, UnknownCmpObject.class); } catch (final Exception e) { fail("Received Exception " + e.getClass() + " : " + e.getMessage()); } } public void test05_isSession() { try { assertTrue("EJBMetaData says this is a session bean", !ejbMetaData.isSession()); } catch (final Exception e) { fail("Received Exception " + e.getClass() + " : " + e.getMessage()); } } public void test06_isStatelessSession() { try { assertTrue("EJBMetaData says this is a stateless session bean", !ejbMetaData.isStatelessSession()); } catch (final Exception e) { fail("Received Exception " + e.getClass() + " : " + e.getMessage()); } } // // Test meta data methods //================================= }
/* * Copyright 2009 ZXing 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.google.zxing.web; import com.google.gwt.canvas.client.Canvas; import com.google.gwt.canvas.dom.client.CanvasPixelArray; import com.google.gwt.canvas.dom.client.Context2d; import com.google.gwt.canvas.dom.client.ImageData; import com.google.zxing.LuminanceSource; /** * This LuminanceSource implementation is meant for html canvas. * * @author dswitkin@google.com (Daniel Switkin) * @author Sean Owen * @author code@elektrowolle.de (Wolfgang Jung) * gwt implementation: Janusz Białobrzewski */ public final class CanvasLuminanceSource extends LuminanceSource { /** * Number of colors at each location in the array. * * Because image data is stored as RGBA, this is 4. */ private static final int NUM_COLORS = 4; /** * Offsets for each color use RGBA ordering. */ private static final int OFFSET_RED = 0; private static final int OFFSET_GREEN = 1; private static final int OFFSET_BLUE = 2; private static final int OFFSET_ALPHA = 3; private final Canvas image; private final ImageData imagedata; private final int left; private final int top; public CanvasLuminanceSource(Canvas image) { this(image, 0, 0, image.getCoordinateSpaceWidth(), image.getCoordinateSpaceHeight()); } public CanvasLuminanceSource(Canvas aImage, int left, int top, int width, int height) { super(width, height); int sourceWidth = aImage.getCoordinateSpaceWidth(); int sourceHeight = aImage.getCoordinateSpaceHeight(); if(left + width > sourceWidth || top + height > sourceHeight) { throw new IllegalArgumentException("Crop rectangle does not fit within image data."); } this.image = Canvas.createIfSupported(); this.image.setPixelSize(sourceWidth, sourceHeight); this.image.setCoordinateSpaceHeight(sourceHeight); this.image.setCoordinateSpaceWidth(sourceWidth); imagedata = aImage.getContext2d().getImageData(left, top, width, height); CanvasPixelArray data = imagedata.getData(); for (int i = 0; i < data.getLength(); i += NUM_COLORS) { if((data.get(i + 3) & 0xFF) == 0) { // The color of fully-transparent pixels is irrelevant. They are // often, technically, fully-transparent // black (0 alpha, and then 0 RGB). They are often used, of // course as the "white" area in a // barcode image. Force any such pixel to be white: int avg = 0xFF; data.set(i + OFFSET_RED, avg); data.set(i + OFFSET_GREEN, avg); data.set(i + OFFSET_BLUE, avg); data.set(i + OFFSET_ALPHA, avg); } else { int avg = (data.get(i + OFFSET_RED) + data.get(i + OFFSET_GREEN) + data.get(i + OFFSET_BLUE)) / 3; data.set(i + OFFSET_RED, avg); data.set(i + OFFSET_GREEN, avg); data.set(i + OFFSET_BLUE, avg); } } this.image.getContext2d().putImageData(imagedata, left, top); this.left = left; this.top = top; } @Override public byte[] getRow(int y, byte[] row) { if(y < 0 || y >= getHeight()) { throw new IllegalArgumentException("Requested row is outside the image: " + y); } int width = getWidth(); if(row == null || row.length < width) { row = new byte[width]; } int yoffset = top + y; for (int i = 0; i < width; i++) { row[i] = (byte) imagedata.getRedAt(left + i, yoffset); } return row; } @Override public byte[] getMatrix() { int width = getWidth(); int height = getHeight(); int area = width * height; byte[] matrix = new byte[area]; for (int i = 0; i < width; i++) for (int j = 0; j < height; j++) { int pixelInt = imagedata.getRedAt(left + i, top + j); byte pixelByte = (byte) pixelInt; matrix[i + j * width] = pixelByte; } return matrix; } @Override public boolean isCropSupported() { return true; } @Override public LuminanceSource crop(int left, int top, int width, int height) { return new CanvasLuminanceSource(image, this.left + left, this.top + top, width, height); } /** * This is always true, since the image is a gray-scale image. * * @return true */ @Override public boolean isRotateSupported() { return true; } @Override public LuminanceSource rotateCounterClockwise() { int sourceWidth = image.getCoordinateSpaceWidth(); int sourceHeight = image.getCoordinateSpaceHeight(); // Note width/height are flipped since we are rotating 90 degrees. Canvas rotatedImage = Canvas.createIfSupported(); rotatedImage.setCoordinateSpaceWidth(sourceWidth); rotatedImage.setCoordinateSpaceHeight(sourceHeight); Context2d ctx = rotatedImage.getContext2d(); // Rotate 90 degrees counterclockwise. ctx.transform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth); ctx.putImageData(imagedata, sourceWidth, sourceHeight); // Maintain the cropped region, but rotate it too. int width = getWidth(); return new CanvasLuminanceSource(rotatedImage, top, sourceWidth - (left + width), getHeight(), width); } @Override public LuminanceSource rotateCounterClockwise45() { int sourceWidth = image.getCoordinateSpaceWidth(); int sourceHeight = image.getCoordinateSpaceHeight(); int width = getWidth(); int height = getHeight(); int oldCenterX = left + width / 2; int oldCenterY = top + height / 2; Canvas rotatedImage = Canvas.createIfSupported(); int sourceDimension = Math.max(sourceWidth, sourceHeight); rotatedImage.setCoordinateSpaceWidth(sourceDimension); rotatedImage.setCoordinateSpaceHeight(sourceDimension); Context2d ctx = rotatedImage.getContext2d(); ctx.translate(oldCenterX, oldCenterY); // Rotate 45 degrees counterclockwise. ctx.rotate(-45 * Math.PI / 180); ctx.translate(-oldCenterX, -oldCenterY); ctx.putImageData(imagedata, sourceWidth, sourceHeight); int halfDimension = Math.max(width, height) / 2; int newLeft = Math.max(0, oldCenterX - halfDimension); int newTop = Math.max(0, oldCenterY - halfDimension); int newRight = Math.min(sourceDimension - 1, oldCenterX + halfDimension); int newBottom = Math.min(sourceDimension - 1, oldCenterY + halfDimension); return new CanvasLuminanceSource(rotatedImage, newLeft, newTop, newRight - newLeft, newBottom - newTop); } }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.12.16 at 01:02:03 PM EST // package xml.us.patent.grant.v44; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElements; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "headingOrP" }) @XmlRootElement(name = "sequence-list-text") public class SequenceListText { @XmlAttribute(name = "id") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID protected String id; @XmlElements({ @XmlElement(name = "heading", required = true, type = Heading.class), @XmlElement(name = "p", required = true, type = P.class) }) protected List<Object> headingOrP; /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the headingOrP property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the headingOrP property. * * <p> * For example, to add a new item, do as follows: * <pre> * getHeadingOrP().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Heading } * {@link P } * * */ public List<Object> getHeadingOrP() { if (headingOrP == null) { headingOrP = new ArrayList<Object>(); } return this.headingOrP; } }
package com.extnds.nooba.contactsmanageribmcampapp; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; /** * Created by Nooba(PratickRoy) on 11-09-2016. */ public class MainActivity extends AppCompatActivity implements ContactsViewFragment.ContactsViewFragmentCallback { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar actionBar = (Toolbar)findViewById(R.id.action_bar); setSupportActionBar(actionBar); if (savedInstanceState == null){ ContactsViewFragment contactsViewFragment = (ContactsViewFragment)getSupportFragmentManager().findFragmentByTag(ContactsViewFragment.TAG); if(contactsViewFragment==null) contactsViewFragment = ContactsViewFragment.newInstance(); getSupportFragmentManager() .beginTransaction() .replace(R.id.main_fragment_holder,contactsViewFragment) .commit(); } } @Override public void startAddFragment() { ContactsAddFragment contactsAddFragment = (ContactsAddFragment)getSupportFragmentManager().findFragmentByTag(ContactsAddFragment.TAG); if(contactsAddFragment==null) contactsAddFragment = ContactsAddFragment.newInstance(); getSupportFragmentManager() .beginTransaction() .replace(R.id.main_fragment_holder,contactsAddFragment) .addToBackStack(ContactsAddFragment.TAG) .commit(); } }
/* * 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 3 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, see <http://www.gnu.org/licenses/>. */ /* * Optimization.java * Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand * */ package weka.core; import weka.core.TechnicalInformation.Field; import weka.core.TechnicalInformation.Type; /** * Implementation of Active-sets method with BFGS update to solve optimization * problem with only bounds constraints in multi-dimensions. In this * implementation we consider both the lower and higher bound constraints. <p/> * * Here is the sketch of our searching strategy, and the detailed description * of the algorithm can be found in the Appendix of Xin Xu's MSc thesis:<p/> * Initialize everything, incl. initial value, direction, etc.<p/> * LOOP (main algorithm):<br/> * * 1. Perform the line search using the directions for free variables<br/> * 1.1 Check all the bounds that are not "active" (i.e. binding variables) * and compute the feasible step length to the bound for each of them<br/> * 1.2 Pick up the least feasible step length, say \alpha, and set it as * the upper bound of the current step length, i.e. * 0&lt;\lambda&lt;=\alpha<br/> * 1.3 Search for any possible step length&lt;=\alpha that can result the * "sufficient function decrease" (\alpha condition) AND "positive * definite inverse Hessian" (\beta condition), if possible, using * SAFEGUARDED polynomial interpolation. This step length is "safe" and * thus is used to compute the next value of the free variables .<br/> * 1.4 Fix the variable(s) that are newly bound to its constraint(s).<p/> * * 2. Check whether there is convergence of all variables or their gradients. * If there is, check the possibilities to release any current bindings of * the fixed variables to their bounds based on the "reliable" second-order * Lagarange multipliers if available. If it's available and negative for * one variable, then release it. If not available, use first-order * Lagarange multiplier to test release. If there is any released * variables, STOP the loop. Otherwise update the inverse of Hessian matrix * and gradient for the newly released variables and CONTINUE LOOP.<p/> * * 3. Use BFGS formula to update the inverse of Hessian matrix. Note the * already-fixed variables must have zeros in the corresponding entries * in the inverse Hessian.<p/> * * 4. Compute the new (newton) search direction d=H^{-1}*g, where H^{-1} is the * inverse Hessian and g is the Jacobian. Note that again, the already- * fixed variables will have zero direction.<p/> * * ENDLOOP<p/> * * A typical usage of this class is to create your own subclass of this class * and provide the objective function and gradients as follows:<p/> * <pre> * class MyOpt extends Optimization { * // Provide the objective function * protected double objectiveFunction(double[] x) { * // How to calculate your objective function... * // ... * } * * // Provide the first derivatives * protected double[] evaluateGradient(double[] x) { * // How to calculate the gradient of the objective function... * // ... * } * * // If possible, provide the index^{th} row of the Hessian matrix * protected double[] evaluateHessian(double[] x, int index) { * // How to calculate the index^th variable's second derivative * // ... * } * } * </pre> * * When it's the time to use it, in some routine(s) of other class... * <pre> * MyOpt opt = new MyOpt(); * * // Set up initial variable values and bound constraints * double[] x = new double[numVariables]; * // Lower and upper bounds: 1st row is lower bounds, 2nd is upper * double[] constraints = new double[2][numVariables]; * ... * * // Find the minimum, 200 iterations as default * x = opt.findArgmin(x, constraints); * while(x == null){ // 200 iterations are not enough * x = opt.getVarbValues(); // Try another 200 iterations * x = opt.findArgmin(x, constraints); * } * * // The minimal function value * double minFunction = opt.getMinFunction(); * ... * </pre> * * It is recommended that Hessian values be provided so that the second-order * Lagrangian multiplier estimate can be calcluated. However, if it is not * provided, there is no need to override the <code>evaluateHessian()</code> * function.<p/> * * REFERENCES (see also the <code>getTechnicalInformation()</code> method):<br/> * The whole model algorithm is adapted from Chapter 5 and other related * chapters in Gill, Murray and Wright(1981) "Practical Optimization", Academic * Press. and Gill and Murray(1976) "Minimization Subject to Bounds on the * Variables", NPL Report NAC72, while Chong and Zak(1996) "An Introduction to * Optimization", John Wiley &amp; Sons, Inc. provides us a brief but helpful * introduction to the method. <p/> * * Dennis and Schnabel(1983) "Numerical Methods for Unconstrained Optimization * and Nonlinear Equations", Prentice-Hall Inc. and Press et al.(1992) "Numeric * Recipe in C", Second Edition, Cambridge University Press. are consulted for * the polynomial interpolation used in the line search implementation. <p/> * * The Hessian modification in BFGS update uses Cholesky factorization and two * rank-one modifications:<br/> * Bk+1 = Bk + (Gk*Gk')/(Gk'Dk) + (dGk*(dGk)'))/[alpha*(dGk)'*Dk]. <br/> * where Gk is the gradient vector, Dk is the direction vector and alpha is the * step rate. <br/> * This method is due to Gill, Golub, Murray and Saunders(1974) ``Methods for * Modifying Matrix Factorizations'', Mathematics of Computation, Vol.28, * No.126, pp 505-535. <p/> * * @author Xin Xu (xx5@cs.waikato.ac.nz) * @version $Revision: 8034 $ * @see #getTechnicalInformation() */ public abstract class Optimization implements TechnicalInformationHandler, RevisionHandler { protected double m_ALF = 1.0e-4; protected double m_BETA = 0.9; protected double m_TOLX = 1.0e-6; protected double m_STPMX = 100.0; protected int m_MAXITS = 200; protected static boolean m_Debug = false; /** function value */ protected double m_f; /** G'*p */ private double m_Slope; /** Test if zero step in lnsrch */ private boolean m_IsZeroStep = false; /** Used when iteration overflow occurs */ private double[] m_X; /** Compute machine precision */ protected static double m_Epsilon, m_Zero; static { m_Epsilon=1.0; while(1.0+m_Epsilon > 1.0){ m_Epsilon /= 2.0; } m_Epsilon *= 2.0; m_Zero = Math.sqrt(m_Epsilon); if (m_Debug) System.err.print("Machine precision is "+m_Epsilon+ " and zero set to "+m_Zero); } /** * Returns an instance of a TechnicalInformation object, containing * detailed information about the technical background of this class, * e.g., paper reference or book this class is based on. * * @return the technical information about this class */ public TechnicalInformation getTechnicalInformation() { TechnicalInformation result; TechnicalInformation additional; result = new TechnicalInformation(Type.MASTERSTHESIS); result.setValue(Field.AUTHOR, "Xin Xu"); result.setValue(Field.YEAR, "2003"); result.setValue(Field.TITLE, "Statistical learning in multiple instance problem"); result.setValue(Field.SCHOOL, "University of Waikato"); result.setValue(Field.ADDRESS, "Hamilton, NZ"); result.setValue(Field.NOTE, "0657.594"); additional = result.add(Type.BOOK); additional.setValue(Field.AUTHOR, "P. E. Gill and W. Murray and M. H. Wright"); additional.setValue(Field.YEAR, "1981"); additional.setValue(Field.TITLE, "Practical Optimization"); additional.setValue(Field.PUBLISHER, "Academic Press"); additional.setValue(Field.ADDRESS, "London and New York"); additional = result.add(Type.TECHREPORT); additional.setValue(Field.AUTHOR, "P. E. Gill and W. Murray"); additional.setValue(Field.YEAR, "1976"); additional.setValue(Field.TITLE, "Minimization subject to bounds on the variables"); additional.setValue(Field.INSTITUTION, "National Physical Laboratory"); additional.setValue(Field.NUMBER, "NAC 72"); additional = result.add(Type.BOOK); additional.setValue(Field.AUTHOR, "E. K. P. Chong and S. H. Zak"); additional.setValue(Field.YEAR, "1996"); additional.setValue(Field.TITLE, "An Introduction to Optimization"); additional.setValue(Field.PUBLISHER, "John Wiley and Sons"); additional.setValue(Field.ADDRESS, "New York"); additional = result.add(Type.BOOK); additional.setValue(Field.AUTHOR, "J. E. Dennis and R. B. Schnabel"); additional.setValue(Field.YEAR, "1983"); additional.setValue(Field.TITLE, "Numerical Methods for Unconstrained Optimization and Nonlinear Equations"); additional.setValue(Field.PUBLISHER, "Prentice-Hall"); additional = result.add(Type.BOOK); additional.setValue(Field.AUTHOR, "W. H. Press and B. P. Flannery and S. A. Teukolsky and W. T. Vetterling"); additional.setValue(Field.YEAR, "1992"); additional.setValue(Field.TITLE, "Numerical Recipes in C"); additional.setValue(Field.PUBLISHER, "Cambridge University Press"); additional.setValue(Field.EDITION, "Second"); additional = result.add(Type.ARTICLE); additional.setValue(Field.AUTHOR, "P. E. Gill and G. H. Golub and W. Murray and M. A. Saunders"); additional.setValue(Field.YEAR, "1974"); additional.setValue(Field.TITLE, "Methods for modifying matrix factorizations"); additional.setValue(Field.JOURNAL, "Mathematics of Computation"); additional.setValue(Field.VOLUME, "28"); additional.setValue(Field.NUMBER, "126"); additional.setValue(Field.PAGES, "505-535"); return result; } /** * Subclass should implement this procedure to evaluate objective * function to be minimized * * @param x the variable values * @return the objective function value * @throws Exception if something goes wrong */ protected abstract double objectiveFunction(double[] x) throws Exception; /** * Subclass should implement this procedure to evaluate gradient * of the objective function * * @param x the variable values * @return the gradient vector * @throws Exception if something goes wrong */ protected abstract double[] evaluateGradient(double[] x) throws Exception; /** * Subclass is recommended to override this procedure to evaluate second-order * gradient of the objective function. If it's not provided, it returns * null. * * @param x the variables * @param index the row index in the Hessian matrix * @return one row (the row #index) of the Hessian matrix, null as default * @throws Exception if something goes wrong */ protected double[] evaluateHessian(double[] x, int index) throws Exception{ return null; } /** * Get the minimal function value * * @return minimal function value found */ public double getMinFunction() { return m_f; } /** * Set the maximal number of iterations in searching (Default 200) * * @param it the maximal number of iterations */ public void setMaxIteration(int it) { m_MAXITS=it; } /** * Set whether in debug mode * * @param db use debug or not */ public void setDebug(boolean db) { m_Debug = db; } /** * Get the variable values. Only needed when iterations exceeds * the max threshold. * * @return the current variable values */ public double[] getVarbValues() { return m_X; } /** * Find a new point x in the direction p from a point xold at which the * value of the function has decreased sufficiently, the positive * definiteness of B matrix (approximation of the inverse of the Hessian) * is preserved and no bound constraints are violated. Details see "Numerical * Methods for Unconstrained Optimization and Nonlinear Equations". * "Numeric Recipes in C" was also consulted. * * @param xold old x value * @param gradient gradient at that point * @param direct direction vector * @param stpmax maximum step length * @param isFixed indicating whether a variable has been fixed * @param nwsBounds non-working set bounds. Means these variables are free and * subject to the bound constraints in this step * @param wsBdsIndx index of variables that has working-set bounds. Means * these variables are already fixed and no longer subject to * the constraints * @return new value along direction p from xold, null if no step was taken * @throws Exception if an error occurs */ public double[] lnsrch(double[] xold, double[] gradient, double[] direct, double stpmax, boolean[] isFixed, double[][] nwsBounds, DynamicIntArray wsBdsIndx) throws Exception { int i, k,len=xold.length, fixedOne=-1; // idx of variable to be fixed double alam, alamin; // lambda to be found, and its lower bound // For convergence and bound test double temp,test,alpha=Double.POSITIVE_INFINITY,fold=m_f,sum; // For cubic interpolation double a,alam2=0,b,disc=0,maxalam=1.0,rhs1,rhs2,tmplam; double[] x = new double[len]; // New variable values // Scale the step for (sum=0.0,i=0;i<len;i++){ if(!isFixed[i]) // For fixed variables, direction = 0 sum += direct[i]*direct[i]; } sum = Math.sqrt(sum); if (m_Debug) System.err.println("fold: "+Utils.doubleToString(fold,10,7)+"\n"+ "sum: "+Utils.doubleToString(sum,10,7)+"\n"+ "stpmax: "+Utils.doubleToString(stpmax,10,7)); if (sum > stpmax){ for (i=0;i<len;i++) if(!isFixed[i]) direct[i] *= stpmax/sum; } else maxalam = stpmax/sum; // Compute initial rate of decrease, g'*d m_Slope=0.0; for (i=0;i<len;i++){ x[i] = xold[i]; if(!isFixed[i]) m_Slope += gradient[i]*direct[i]; } if (m_Debug) System.err.print("slope: " + Utils.doubleToString(m_Slope,10,7)+ "\n"); // Slope too small if(Math.abs(m_Slope)<=m_Zero){ if (m_Debug) System.err.println("Gradient and direction orthogonal -- "+ "Min. found with current fixed variables"+ " (or all variables fixed). Try to release"+ " some variables now."); return x; } // Err: slope > 0 if(m_Slope > m_Zero){ if(m_Debug) for(int h=0; h<x.length; h++) System.err.println(h+": isFixed="+isFixed[h]+", x="+ x[h]+", grad="+gradient[h]+", direct="+ direct[h]); throw new Exception("g'*p positive! -- Try to debug from here: line 327."); } // Compute LAMBDAmin and upper bound of lambda--alpha test=0.0; for(i=0;i<len;i++){ if(!isFixed[i]){// No need for fixed variables temp=Math.abs(direct[i])/Math.max(Math.abs(x[i]),1.0); if (temp > test) test=temp; } } if(test>m_Zero) // Not converge alamin = m_TOLX/test; else{ if (m_Debug) System.err.println("Zero directions for all free variables -- "+ "Min. found with current fixed variables"+ " (or all variables fixed). Try to release"+ " some variables now."); return x; } // Check whether any non-working-set bounds are "binding" for(i=0;i<len;i++){ if(!isFixed[i]){// No need for fixed variables double alpi; if((direct[i]<-m_Epsilon) && !Double.isNaN(nwsBounds[0][i])){//Not feasible alpi = (nwsBounds[0][i]-xold[i])/direct[i]; if(alpi <= m_Zero){ // Zero if (m_Debug) System.err.println("Fix variable "+i+ " to lower bound "+ nwsBounds[0][i]+ " from value "+ xold[i]); x[i] = nwsBounds[0][i]; isFixed[i]=true; // Fix this variable alpha = 0.0; nwsBounds[0][i]=Double.NaN; //Add cons. to working set wsBdsIndx.addElement(i); } else if(alpha > alpi){ // Fix one variable in one iteration alpha = alpi; fixedOne = i; } } else if((direct[i]>m_Epsilon) && !Double.isNaN(nwsBounds[1][i])){//Not feasible alpi = (nwsBounds[1][i]-xold[i])/direct[i]; if(alpi <= m_Zero){ // Zero if (m_Debug) System.err.println("Fix variable "+i+ " to upper bound "+ nwsBounds[1][i]+ " from value "+ xold[i]); x[i] = nwsBounds[1][i]; isFixed[i]=true; // Fix this variable alpha = 0.0; nwsBounds[1][i]=Double.NaN; //Add cons. to working set wsBdsIndx.addElement(i); } else if(alpha > alpi){ alpha = alpi; fixedOne = i; } } } } if (m_Debug){ System.err.println("alamin: " + Utils.doubleToString(alamin,10,7)); System.err.println("alpha: " + Utils.doubleToString(alpha,10,7)); } if(alpha <= m_Zero){ // Zero m_IsZeroStep = true; if (m_Debug) System.err.println("Alpha too small, try again"); return x; } alam = alpha; // Always try full feasible newton step if(alam > 1.0) alam = 1.0; // Iteration of one newton step, if necessary, backtracking is done double initF=fold, // Initial function value hi=alam, lo=alam, newSlope=0, fhi=m_f, flo=m_f;// Variables used for beta condition double[] newGrad; // Gradient on the new variable values kloop: for (k=0;;k++) { if(m_Debug) System.err.println("\nLine search iteration: " + k); for (i=0;i<len;i++){ if(!isFixed[i]){ x[i] = xold[i]+alam*direct[i]; // Compute xnew if(!Double.isNaN(nwsBounds[0][i]) && (x[i]<nwsBounds[0][i])){ x[i] = nwsBounds[0][i]; //Rounding error } else if(!Double.isNaN(nwsBounds[1][i]) && (x[i]>nwsBounds[1][i])){ x[i] = nwsBounds[1][i]; //Rounding error } } } m_f = objectiveFunction(x); // Compute fnew if(Double.isNaN(m_f)) throw new Exception("Objective function value is NaN!"); while(Double.isInfinite(m_f)){ // Avoid infinity if(m_Debug) System.err.println("Too large m_f. Shrink step by half."); alam *= 0.5; // Shrink by half if(alam <= m_Epsilon){ if(m_Debug) System.err.println("Wrong starting points, change them!"); return x; } for (i=0;i<len;i++) if(!isFixed[i]) x[i] = xold[i]+alam*direct[i]; m_f = objectiveFunction(x); if(Double.isNaN(m_f)) throw new Exception("Objective function value is NaN!"); initF = Double.POSITIVE_INFINITY; } if(m_Debug) { System.err.println("obj. function: " + Utils.doubleToString(m_f, 10, 7)); System.err.println("threshold: " + Utils.doubleToString(fold+m_ALF*alam*m_Slope,10,7)); } if(m_f<=fold+m_ALF*alam*m_Slope){// Alpha condition: sufficient function decrease if(m_Debug) System.err.println("Sufficient function decrease (alpha condition): "); newGrad = evaluateGradient(x); for(newSlope=0.0,i=0; i<len; i++) if(!isFixed[i]) newSlope += newGrad[i]*direct[i]; if(newSlope >= m_BETA*m_Slope){ // Beta condition: ensure pos. defnty. if(m_Debug) System.err.println("Increasing derivatives (beta condition): "); if((fixedOne!=-1) && (alam>=alpha)){ // Has bounds and over if(direct[fixedOne] > 0){ x[fixedOne] = nwsBounds[1][fixedOne]; // Avoid rounding error nwsBounds[1][fixedOne]=Double.NaN; //Add cons. to working set } else{ x[fixedOne] = nwsBounds[0][fixedOne]; // Avoid rounding error nwsBounds[0][fixedOne]=Double.NaN; //Add cons. to working set } if(m_Debug) System.err.println("Fix variable " +fixedOne+" to bound "+ x[fixedOne]+ " from value "+ xold[fixedOne]); isFixed[fixedOne]=true; // Fix the variable wsBdsIndx.addElement(fixedOne); } return x; } else if(k==0){ // First time: increase alam // Search for the smallest value not complying with alpha condition double upper = Math.min(alpha,maxalam); if(m_Debug) System.err.println("Alpha condition holds, increase alpha... "); while(!((alam>=upper) || (m_f>fold+m_ALF*alam*m_Slope))){ lo = alam; flo = m_f; alam *= 2.0; if(alam>=upper) // Avoid rounding errors alam=upper; for (i=0;i<len;i++) if(!isFixed[i]) x[i] = xold[i]+alam*direct[i]; m_f = objectiveFunction(x); if(Double.isNaN(m_f)) throw new Exception("Objective function value is NaN!"); newGrad = evaluateGradient(x); for(newSlope=0.0,i=0; i<len; i++) if(!isFixed[i]) newSlope += newGrad[i]*direct[i]; if(newSlope >= m_BETA*m_Slope){ if (m_Debug) System.err.println("Increasing derivatives (beta condition): \n"+ "newSlope = "+Utils.doubleToString(newSlope,10,7)); if((fixedOne!=-1) && (alam>=alpha)){ // Has bounds and over if(direct[fixedOne] > 0){ x[fixedOne] = nwsBounds[1][fixedOne]; // Avoid rounding error nwsBounds[1][fixedOne]=Double.NaN; //Add cons. to working set } else{ x[fixedOne] = nwsBounds[0][fixedOne]; // Avoid rounding error nwsBounds[0][fixedOne]=Double.NaN; //Add cons. to working set } if(m_Debug) System.err.println("Fix variable " +fixedOne+" to bound "+ x[fixedOne]+ " from value "+ xold[fixedOne]); isFixed[fixedOne]=true; // Fix the variable wsBdsIndx.addElement(fixedOne); } return x; } } hi = alam; fhi = m_f; break kloop; } else{ if(m_Debug) System.err.println("Alpha condition holds."); hi = alam2; lo = alam; flo = m_f; break kloop; } } else if (alam < alamin) { // No feasible lambda found if(initF<fold){ alam = Math.min(1.0,alpha); for (i=0;i<len;i++) if(!isFixed[i]) x[i] = xold[i]+alam*direct[i]; //Still take Alpha if (m_Debug) System.err.println("No feasible lambda: still take"+ " alpha="+alam); if((fixedOne!=-1) && (alam>=alpha)){ // Has bounds and over if(direct[fixedOne] > 0){ x[fixedOne] = nwsBounds[1][fixedOne]; // Avoid rounding error nwsBounds[1][fixedOne]=Double.NaN; //Add cons. to working set } else{ x[fixedOne] = nwsBounds[0][fixedOne]; // Avoid rounding error nwsBounds[0][fixedOne]=Double.NaN; //Add cons. to working set } if(m_Debug) System.err.println("Fix variable " +fixedOne+" to bound "+ x[fixedOne]+ " from value "+ xold[fixedOne]); isFixed[fixedOne]=true; // Fix the variable wsBdsIndx.addElement(fixedOne); } } else{ // Convergence on delta(x) for(i=0;i<len;i++) x[i]=xold[i]; m_f=fold; if (m_Debug) System.err.println("Cannot find feasible lambda"); } return x; } else { // Backtracking by polynomial interpolation if(k==0){ // First time backtrack: quadratic interpolation if(!Double.isInfinite(initF)) initF = m_f; // lambda = -g'(0)/(2*g''(0)) tmplam = -0.5*alam*m_Slope/((m_f-fold)/alam-m_Slope); } else { // Subsequent backtrack: cubic interpolation rhs1 = m_f-fold-alam*m_Slope; rhs2 = fhi-fold-alam2*m_Slope; a=(rhs1/(alam*alam)-rhs2/(alam2*alam2))/(alam-alam2); b=(-alam2*rhs1/(alam*alam)+alam*rhs2/(alam2*alam2))/(alam-alam2); if (a == 0.0) tmplam = -m_Slope/(2.0*b); else { disc=b*b-3.0*a*m_Slope; if (disc < 0.0) disc = 0.0; double numerator = -b+Math.sqrt(disc); if(numerator >= Double.MAX_VALUE){ numerator = Double.MAX_VALUE; if (m_Debug) System.err.print("-b+sqrt(disc) too large! Set it to MAX_VALUE."); } tmplam=numerator/(3.0*a); } if (m_Debug) System.err.print("Cubic interpolation: \n" + "a: " + Utils.doubleToString(a,10,7)+ "\n" + "b: " + Utils.doubleToString(b,10,7)+ "\n" + "disc: " + Utils.doubleToString(disc,10,7)+ "\n" + "tmplam: " + tmplam + "\n" + "alam: " + Utils.doubleToString(alam,10,7)+ "\n"); if (tmplam>0.5*alam) tmplam=0.5*alam; // lambda <= 0.5*lambda_old } } alam2=alam; fhi=m_f; alam=Math.max(tmplam,0.1*alam); // lambda >= 0.1*lambda_old if(alam>alpha){ throw new Exception("Sth. wrong in lnsrch:"+ "Lambda infeasible!(lambda="+alam+ ", alpha="+alpha+", upper="+tmplam+ "|"+(-alpha*m_Slope/(2.0*((m_f-fold)/alpha-m_Slope)))+ ", m_f="+m_f+", fold="+fold+ ", slope="+m_Slope); } } // Endfor(k=0;;k++) // Quadratic interpolation between lamda values between lo and hi. // If cannot find a value satisfying beta condition, use lo. double ldiff = hi-lo, lincr; if(m_Debug) System.err.println("Last stage of searching for beta condition (alam between " +Utils.doubleToString(lo,10,7)+" and " +Utils.doubleToString(hi,10,7)+")...\n"+ "Quadratic Interpolation(QI):\n"+ "Last newSlope = "+Utils.doubleToString(newSlope, 10, 7)); while((newSlope<m_BETA*m_Slope) && (ldiff>=alamin)){ lincr = -0.5*newSlope*ldiff*ldiff/(fhi-flo-newSlope*ldiff); if(m_Debug) System.err.println("fhi = "+fhi+"\n"+ "flo = "+flo+"\n"+ "ldiff = "+ldiff+"\n"+ "lincr (using QI) = "+lincr+"\n"); if(lincr<0.2*ldiff) lincr=0.2*ldiff; alam = lo+lincr; if(alam >= hi){ // We cannot go beyond the bounds, so the best we can try is hi alam=hi; lincr=ldiff; } for (i=0;i<len;i++) if(!isFixed[i]) x[i] = xold[i]+alam*direct[i]; m_f = objectiveFunction(x); if(Double.isNaN(m_f)) throw new Exception("Objective function value is NaN!"); if(m_f>fold+m_ALF*alam*m_Slope){ // Alpha condition fails, shrink lambda_upper ldiff = lincr; fhi = m_f; } else{ // Alpha condition holds newGrad = evaluateGradient(x); for(newSlope=0.0,i=0; i<len; i++) if(!isFixed[i]) newSlope += newGrad[i]*direct[i]; if(newSlope < m_BETA*m_Slope){ // Beta condition fails, shrink lambda_lower lo = alam; ldiff -= lincr; flo = m_f; } } } if(newSlope < m_BETA*m_Slope){ // Cannot satisfy beta condition, take lo if(m_Debug) System.err.println("Beta condition cannot be satisfied, take alpha condition"); alam=lo; for (i=0;i<len;i++) if(!isFixed[i]) x[i] = xold[i]+alam*direct[i]; m_f = flo; } else if(m_Debug) System.err.println("Both alpha and beta conditions are satisfied. alam=" +Utils.doubleToString(alam,10,7)); if((fixedOne!=-1) && (alam>=alpha)){ // Has bounds and over if(direct[fixedOne] > 0){ x[fixedOne] = nwsBounds[1][fixedOne]; // Avoid rounding error nwsBounds[1][fixedOne]=Double.NaN; //Add cons. to working set } else{ x[fixedOne] = nwsBounds[0][fixedOne]; // Avoid rounding error nwsBounds[0][fixedOne]=Double.NaN; //Add cons. to working set } if(m_Debug) System.err.println("Fix variable " +fixedOne+" to bound "+ x[fixedOne]+ " from value "+ xold[fixedOne]); isFixed[fixedOne]=true; // Fix the variable wsBdsIndx.addElement(fixedOne); } return x; } /** * Main algorithm. Descriptions see "Practical Optimization" * * @param initX initial point of x, assuming no value's on the bound! * @param constraints the bound constraints of each variable * constraints[0] is the lower bounds and * constraints[1] is the upper bounds * @return the solution of x, null if number of iterations not enough * @throws Exception if an error occurs */ public double[] findArgmin(double[] initX, double[][] constraints) throws Exception{ int l = initX.length; // Initially all variables are free, all bounds are constraints of // non-working-set constraints boolean[] isFixed = new boolean[l]; double[][] nwsBounds = new double[2][l]; // Record indice of fixed variables, simply for efficiency DynamicIntArray wsBdsIndx = new DynamicIntArray(constraints.length); // Vectors used to record the variable indices to be freed DynamicIntArray toFree=null, oldToFree=null; // Initial value of obj. function, gradient and inverse of the Hessian m_f = objectiveFunction(initX); if(Double.isNaN(m_f)) throw new Exception("Objective function value is NaN!"); double sum=0; double[] grad=evaluateGradient(initX), oldGrad, oldX, deltaGrad=new double[l], deltaX=new double[l], direct = new double[l], x = new double[l]; Matrix L = new Matrix(l, l); // Lower triangle of Cholesky factor double[] D = new double[l]; // Diagonal of Cholesky factor for(int i=0; i<l; i++){ L.setRow(i, new double[l]); L.setElement(i,i,1.0); D[i] = 1.0; direct[i] = -grad[i]; sum += grad[i]*grad[i]; x[i] = initX[i]; nwsBounds[0][i] = constraints[0][i]; nwsBounds[1][i] = constraints[1][i]; isFixed[i] = false; } double stpmax = m_STPMX*Math.max(Math.sqrt(sum), l); iterates: for(int step=0; step < m_MAXITS; step++){ if (m_Debug) System.err.println("\nIteration # " + step + ":"); // Try at most one feasible newton step, i.e. 0<lamda<=alpha oldX = x; oldGrad = grad; // Also update grad if (m_Debug) System.err.println("Line search ... "); m_IsZeroStep = false; x=lnsrch(x, grad, direct, stpmax, isFixed, nwsBounds, wsBdsIndx); if (m_Debug) System.err.println("Line search finished."); if(m_IsZeroStep){ // Zero step, simply delete rows/cols of D and L for(int f=0; f<wsBdsIndx.size(); f++){ int idx=wsBdsIndx.elementAt(f); L.setRow(idx, new double[l]); L.setColumn(idx, new double[l]); D[idx] = 0.0; } grad = evaluateGradient(x); step--; } else{ // Check converge on x boolean finish = false; double test=0.0; for(int h=0; h<l; h++){ deltaX[h] = x[h]-oldX[h]; double tmp=Math.abs(deltaX[h])/ Math.max(Math.abs(x[h]), 1.0); if(tmp > test) test = tmp; } if(test < m_Zero){ if (m_Debug) System.err.println("\nDeltaX converge: "+test); finish = true; } // Check zero gradient grad = evaluateGradient(x); test=0.0; double denom=0.0, dxSq=0.0, dgSq=0.0, newlyBounded=0.0; for(int g=0; g<l; g++){ if(!isFixed[g]){ deltaGrad[g] = grad[g] - oldGrad[g]; // Calculate the denominators denom += deltaX[g]*deltaGrad[g]; dxSq += deltaX[g]*deltaX[g]; dgSq += deltaGrad[g]*deltaGrad[g]; } else // Only newly bounded variables will be non-zero newlyBounded += deltaX[g]*(grad[g]-oldGrad[g]); // Note: CANNOT use projected gradient for testing // convergence because of newly bounded variables double tmp = Math.abs(grad[g])* Math.max(Math.abs(direct[g]),1.0)/ Math.max(Math.abs(m_f),1.0); if(tmp > test) test = tmp; } if(test < m_Zero){ if (m_Debug) System.err.println("Gradient converge: "+test); finish = true; } // dg'*dx could be < 0 using inexact lnsrch if(m_Debug) System.err.println("dg'*dx="+(denom+newlyBounded)); // dg'*dx = 0 if(Math.abs(denom+newlyBounded) < m_Zero) finish = true; int size = wsBdsIndx.size(); boolean isUpdate = true; // Whether to update BFGS formula // Converge: check whether release any current constraints if(finish){ if (m_Debug) System.err.println("Test any release possible ..."); if(toFree != null) oldToFree = (DynamicIntArray)toFree.copy(); toFree = new DynamicIntArray(wsBdsIndx.size()); for(int m=size-1; m>=0; m--){ int index=wsBdsIndx.elementAt(m); double[] hessian = evaluateHessian(x, index); double deltaL=0.0; if(hessian != null){ for(int mm=0; mm<hessian.length; mm++) if(!isFixed[mm]) // Free variable deltaL += hessian[mm]*direct[mm]; } // First and second order Lagrangian multiplier estimate // If user didn't provide Hessian, use first-order only double L1, L2; if(x[index] >= constraints[1][index]) // Upper bound L1 = -grad[index]; else if(x[index] <= constraints[0][index])// Lower bound L1 = grad[index]; else throw new Exception("x["+index+"] not fixed on the"+ " bounds where it should have been!"); // L2 = L1 + deltaL L2 = L1 + deltaL; if (m_Debug) System.err.println("Variable "+index+ ": Lagrangian="+L1+"|"+L2); //Check validity of Lagrangian multiplier estimate boolean isConverge = (2.0*Math.abs(deltaL)) < Math.min(Math.abs(L1), Math.abs(L2)); if((L1*L2>0.0) && isConverge){ //Same sign and converge: valid if(L2 < 0.0){// Negative Lagrangian: feasible toFree.addElement(index); wsBdsIndx.removeElementAt(m); finish=false; // Not optimal, cannot finish } } // Although hardly happen, better check it // If the first-order Lagrangian multiplier estimate is wrong, // avoid zigzagging if((hessian==null) && (toFree != null) && toFree.equal(oldToFree)) finish = true; } if(finish){// Min. found if (m_Debug) System.err.println("Minimum found."); m_f = objectiveFunction(x); if(Double.isNaN(m_f)) throw new Exception("Objective function value is NaN!"); return x; } // Free some variables for(int mmm=0; mmm<toFree.size(); mmm++){ int freeIndx=toFree.elementAt(mmm); isFixed[freeIndx] = false; // Free this variable if(x[freeIndx] <= constraints[0][freeIndx]){// Lower bound nwsBounds[0][freeIndx] = constraints[0][freeIndx]; if (m_Debug) System.err.println("Free variable "+freeIndx+ " from bound "+ nwsBounds[0][freeIndx]); } else{ // Upper bound nwsBounds[1][freeIndx] = constraints[1][freeIndx]; if (m_Debug) System.err.println("Free variable "+freeIndx+ " from bound "+ nwsBounds[1][freeIndx]); } L.setElement(freeIndx, freeIndx, 1.0); D[freeIndx] = 1.0; isUpdate = false; } } if(denom<Math.max(m_Zero*Math.sqrt(dxSq)*Math.sqrt(dgSq), m_Zero)){ if (m_Debug) System.err.println("dg'*dx negative!"); isUpdate = false; // Do not update } // If Hessian will be positive definite, update it if(isUpdate){ // modify once: dg*dg'/(dg'*dx) double coeff = 1.0/denom; // 1/(dg'*dx) updateCholeskyFactor(L,D,deltaGrad,coeff,isFixed); // modify twice: g*g'/(g'*p) coeff = 1.0/m_Slope; // 1/(g'*p) updateCholeskyFactor(L,D,oldGrad,coeff,isFixed); } } // Find new direction Matrix LD = new Matrix(l,l); // L*D double[] b = new double[l]; for(int k=0; k<l; k++){ if(!isFixed[k]) b[k] = -grad[k]; else b[k] = 0.0; for(int j=k; j<l; j++){ // Lower triangle if(!isFixed[j] && !isFixed[k]) LD.setElement(j, k, L.getElement(j,k)*D[k]); } } // Solve (LD)*y = -g, where y=L'*direct double[] LDIR = solveTriangle(LD, b, true, isFixed); LD = null; for(int m=0; m<LDIR.length; m++){ if(Double.isNaN(LDIR[m])) throw new Exception("L*direct["+m+"] is NaN!" +"|-g="+b[m]+"|"+isFixed[m] +"|diag="+D[m]); } // Solve L'*direct = y direct = solveTriangle(L, LDIR, false, isFixed); for(int m=0; m<direct.length; m++){ if(Double.isNaN(direct[m])) throw new Exception("direct is NaN!"); } //System.gc(); } if(m_Debug) System.err.println("Cannot find minimum"+ " -- too many interations!"); m_X = x; return null; } /** * Solve the linear equation of TX=B where T is a triangle matrix * It can be solved using back/forward substitution, with O(N^2) * complexity * @param t the matrix T * @param b the vector B * @param isLower whether T is a lower or higher triangle matrix * @param isZero which row(s) of T are not used when solving the equation. * If it's null or all 'false', then every row is used. * @return the solution of X */ public static double[] solveTriangle(Matrix t, double[] b, boolean isLower, boolean[] isZero){ int n = b.length; double[] result = new double[n]; if(isZero == null) isZero = new boolean[n]; if(isLower){ // lower triangle, forward-substitution int j = 0; while((j<n)&&isZero[j]){result[j]=0.0; j++;} // go to the first row if(j<n){ result[j] = b[j]/t.getElement(j,j); for(; j<n; j++){ if(!isZero[j]){ double numerator=b[j]; for(int k=0; k<j; k++) numerator -= t.getElement(j,k)*result[k]; result[j] = numerator/t.getElement(j,j); } else result[j] = 0.0; } } } else{ // Upper triangle, back-substitution int j=n-1; while((j>=0)&&isZero[j]){result[j]=0.0; j--;} // go to the last row if(j>=0){ result[j] = b[j]/t.getElement(j,j); for(; j>=0; j--){ if(!isZero[j]){ double numerator=b[j]; for(int k=j+1; k<n; k++) numerator -= t.getElement(k,j)*result[k]; result[j] = numerator/t.getElement(j,j); } else result[j] = 0.0; } } } return result; } /** * One rank update of the Cholesky factorization of B matrix in BFGS updates, * i.e. B = LDL', and B_{new} = LDL' + coeff*(vv') where L is a unit lower triangle * matrix and D is a diagonal matrix, and v is a vector.<br/> * When coeff > 0, we use C1 algorithm, and otherwise we use C2 algorithm described * in ``Methods for Modifying Matrix Factorizations'' * * @param L the unit triangle matrix L * @param D the diagonal matrix D * @param v the update vector v * @param coeff the coeffcient of update * @param isFixed which variables are not to be updated */ protected void updateCholeskyFactor(Matrix L, double[] D, double[] v, double coeff, boolean[] isFixed) throws Exception{ double t, p, b; int n = v.length; double[] vp = new double[n]; for (int i=0; i<v.length; i++) if(!isFixed[i]) vp[i]=v[i]; else vp[i]=0.0; if(coeff>0.0){ t = coeff; for(int j=0; j<n; j++){ if(isFixed[j]) continue; p = vp[j]; double d=D[j], dbarj=d+t*p*p; D[j] = dbarj; b = p*t/dbarj; t *= d/dbarj; for(int r=j+1; r<n; r++){ if(!isFixed[r]){ double l=L.getElement(r, j); vp[r] -= p*l; L.setElement(r, j, l+b*vp[r]); } else L.setElement(r, j, 0.0); } } } else{ double[] P = solveTriangle(L, v, true, isFixed); t = 0.0; for(int i=0; i<n; i++) if(!isFixed[i]) t += P[i]*P[i]/D[i]; double sqrt=1.0+coeff*t; sqrt = (sqrt<0.0)? 0.0 : Math.sqrt(sqrt); double alpha=coeff, sigma=coeff/(1.0+sqrt), rho, theta; for(int j=0; j<n; j++){ if(isFixed[j]) continue; double d=D[j]; p = P[j]*P[j]/d; theta = 1.0+sigma*p; t -= p; if(t<0.0) t=0.0; // Rounding error double plus = sigma*sigma*p*t; if((j<n-1) && (plus <= m_Zero)) plus=m_Zero; // Avoid rounding error rho = theta*theta + plus; D[j] = rho*d; if(Double.isNaN(D[j])){ throw new Exception("d["+j+"] NaN! P="+P[j]+",d="+d+ ",t="+t+",p="+p+",sigma="+sigma+ ",sclar="+coeff); } b=alpha*P[j]/(rho*d); alpha /= rho; rho = Math.sqrt(rho); double sigmaOld = sigma; sigma *= (1.0+rho)/(rho*(theta+rho)); if((j<n-1) && (Double.isNaN(sigma) || Double.isInfinite(sigma))) throw new Exception("sigma NaN/Inf! rho="+rho+ ",theta="+theta+",P["+j+"]="+ P[j]+",p="+p+",d="+d+",t="+t+ ",oldsigma="+sigmaOld); for(int r=j+1; r<n; r++){ if(!isFixed[r]){ double l=L.getElement(r, j); vp[r] -= P[j]*l; L.setElement(r, j, l+b*vp[r]); } else L.setElement(r, j, 0.0); } } } } /** * Implements a simple dynamic array for ints. */ private class DynamicIntArray implements RevisionHandler { /** The int array. */ private int[] m_Objects; /** The current size; */ private int m_Size = 0; /** The capacity increment */ private int m_CapacityIncrement = 1; /** The capacity multiplier. */ private int m_CapacityMultiplier = 2; /** * Constructs a vector with the given capacity. * * @param capacity the vector's initial capacity */ public DynamicIntArray(int capacity) { m_Objects = new int[capacity]; } /** * Adds an element to this vector. Increases its * capacity if its not large enough. * * @param element the element to add */ public final void addElement(int element) { if (m_Size == m_Objects.length) { int[] newObjects; newObjects = new int[m_CapacityMultiplier * (m_Objects.length + m_CapacityIncrement)]; System.arraycopy(m_Objects, 0, newObjects, 0, m_Size); m_Objects = newObjects; } m_Objects[m_Size] = element; m_Size++; } /** * Produces a copy of this vector. * * @return the new vector */ public final Object copy() { DynamicIntArray copy = new DynamicIntArray(m_Objects.length); copy.m_Size = m_Size; copy.m_CapacityIncrement = m_CapacityIncrement; copy.m_CapacityMultiplier = m_CapacityMultiplier; System.arraycopy(m_Objects, 0, copy.m_Objects, 0, m_Size); return copy; } /** * Returns the element at the given position. * * @param index the element's index * @return the element with the given index */ public final int elementAt(int index) { return m_Objects[index]; } /** * Check whether the two integer vectors equal to each other * Two integer vectors are equal if all the elements are the * same, regardless of the order of the elements * * @param b another integer vector * @return whether they are equal */ private boolean equal(DynamicIntArray b){ if((b==null) || (size()!=b.size())) return false; int size=size(); // Only values matter, order does not matter int[] sorta=Utils.sort(m_Objects), sortb=Utils.sort(b.m_Objects); for(int j=0; j<size;j++) if(m_Objects[sorta[j]] != b.m_Objects[sortb[j]]) return false; return true; } /** * Deletes an element from this vector. * * @param index the index of the element to be deleted */ public final void removeElementAt(int index) { System.arraycopy(m_Objects, index + 1, m_Objects, index, m_Size - index - 1); m_Size--; } /** * Removes all components from this vector and sets its * size to zero. */ public final void removeAllElements() { m_Objects = new int[m_Objects.length]; m_Size = 0; } /** * Returns the vector's current size. * * @return the vector's current size */ public final int size() { return m_Size; } /** * Returns the revision string. * * @return the revision */ public String getRevision() { return RevisionUtils.extract("$Revision: 8034 $"); } } }
package net.consensys.eventeum.dto.event.filter; /** * Supported event parameter types. * * @author Craig Williams <craig.williams@consensys.net> */ public enum ParameterType { INT256, UINT8, UINT256, ADDRESS, BYTES16, BYTES32, BOOL, STRING; }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: tribuo-core-impl.proto package org.tribuo.protos.core; /** * <pre> *SimpleTransform proto * </pre> * * Protobuf type {@code tribuo.core.SimpleTransformProto} */ public final class SimpleTransformProto extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:tribuo.core.SimpleTransformProto) SimpleTransformProtoOrBuilder { private static final long serialVersionUID = 0L; // Use SimpleTransformProto.newBuilder() to construct. private SimpleTransformProto(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private SimpleTransformProto() { op_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new SimpleTransformProto(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private SimpleTransformProto( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); op_ = s; break; } case 17: { firstOperand_ = input.readDouble(); break; } case 25: { secondOperand_ = input.readDouble(); break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.tribuo.protos.core.TribuoCoreImpl.internal_static_tribuo_core_SimpleTransformProto_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return org.tribuo.protos.core.TribuoCoreImpl.internal_static_tribuo_core_SimpleTransformProto_fieldAccessorTable .ensureFieldAccessorsInitialized( org.tribuo.protos.core.SimpleTransformProto.class, org.tribuo.protos.core.SimpleTransformProto.Builder.class); } public static final int OP_FIELD_NUMBER = 1; private volatile java.lang.Object op_; /** * <code>string op = 1;</code> * @return The op. */ @java.lang.Override public java.lang.String getOp() { java.lang.Object ref = op_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); op_ = s; return s; } } /** * <code>string op = 1;</code> * @return The bytes for op. */ @java.lang.Override public com.google.protobuf.ByteString getOpBytes() { java.lang.Object ref = op_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); op_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int FIRST_OPERAND_FIELD_NUMBER = 2; private double firstOperand_; /** * <code>double first_operand = 2;</code> * @return The firstOperand. */ @java.lang.Override public double getFirstOperand() { return firstOperand_; } public static final int SECOND_OPERAND_FIELD_NUMBER = 3; private double secondOperand_; /** * <code>double second_operand = 3;</code> * @return The secondOperand. */ @java.lang.Override public double getSecondOperand() { return secondOperand_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(op_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, op_); } if (java.lang.Double.doubleToRawLongBits(firstOperand_) != 0) { output.writeDouble(2, firstOperand_); } if (java.lang.Double.doubleToRawLongBits(secondOperand_) != 0) { output.writeDouble(3, secondOperand_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(op_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, op_); } if (java.lang.Double.doubleToRawLongBits(firstOperand_) != 0) { size += com.google.protobuf.CodedOutputStream .computeDoubleSize(2, firstOperand_); } if (java.lang.Double.doubleToRawLongBits(secondOperand_) != 0) { size += com.google.protobuf.CodedOutputStream .computeDoubleSize(3, secondOperand_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof org.tribuo.protos.core.SimpleTransformProto)) { return super.equals(obj); } org.tribuo.protos.core.SimpleTransformProto other = (org.tribuo.protos.core.SimpleTransformProto) obj; if (!getOp() .equals(other.getOp())) return false; if (java.lang.Double.doubleToLongBits(getFirstOperand()) != java.lang.Double.doubleToLongBits( other.getFirstOperand())) return false; if (java.lang.Double.doubleToLongBits(getSecondOperand()) != java.lang.Double.doubleToLongBits( other.getSecondOperand())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + OP_FIELD_NUMBER; hash = (53 * hash) + getOp().hashCode(); hash = (37 * hash) + FIRST_OPERAND_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( java.lang.Double.doubleToLongBits(getFirstOperand())); hash = (37 * hash) + SECOND_OPERAND_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( java.lang.Double.doubleToLongBits(getSecondOperand())); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static org.tribuo.protos.core.SimpleTransformProto parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.tribuo.protos.core.SimpleTransformProto parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.tribuo.protos.core.SimpleTransformProto parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.tribuo.protos.core.SimpleTransformProto parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.tribuo.protos.core.SimpleTransformProto parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.tribuo.protos.core.SimpleTransformProto parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.tribuo.protos.core.SimpleTransformProto parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static org.tribuo.protos.core.SimpleTransformProto parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static org.tribuo.protos.core.SimpleTransformProto parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static org.tribuo.protos.core.SimpleTransformProto parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static org.tribuo.protos.core.SimpleTransformProto parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static org.tribuo.protos.core.SimpleTransformProto parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(org.tribuo.protos.core.SimpleTransformProto prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> *SimpleTransform proto * </pre> * * Protobuf type {@code tribuo.core.SimpleTransformProto} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:tribuo.core.SimpleTransformProto) org.tribuo.protos.core.SimpleTransformProtoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.tribuo.protos.core.TribuoCoreImpl.internal_static_tribuo_core_SimpleTransformProto_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return org.tribuo.protos.core.TribuoCoreImpl.internal_static_tribuo_core_SimpleTransformProto_fieldAccessorTable .ensureFieldAccessorsInitialized( org.tribuo.protos.core.SimpleTransformProto.class, org.tribuo.protos.core.SimpleTransformProto.Builder.class); } // Construct using org.tribuo.protos.core.SimpleTransformProto.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); op_ = ""; firstOperand_ = 0D; secondOperand_ = 0D; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.tribuo.protos.core.TribuoCoreImpl.internal_static_tribuo_core_SimpleTransformProto_descriptor; } @java.lang.Override public org.tribuo.protos.core.SimpleTransformProto getDefaultInstanceForType() { return org.tribuo.protos.core.SimpleTransformProto.getDefaultInstance(); } @java.lang.Override public org.tribuo.protos.core.SimpleTransformProto build() { org.tribuo.protos.core.SimpleTransformProto result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public org.tribuo.protos.core.SimpleTransformProto buildPartial() { org.tribuo.protos.core.SimpleTransformProto result = new org.tribuo.protos.core.SimpleTransformProto(this); result.op_ = op_; result.firstOperand_ = firstOperand_; result.secondOperand_ = secondOperand_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.tribuo.protos.core.SimpleTransformProto) { return mergeFrom((org.tribuo.protos.core.SimpleTransformProto)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.tribuo.protos.core.SimpleTransformProto other) { if (other == org.tribuo.protos.core.SimpleTransformProto.getDefaultInstance()) return this; if (!other.getOp().isEmpty()) { op_ = other.op_; onChanged(); } if (other.getFirstOperand() != 0D) { setFirstOperand(other.getFirstOperand()); } if (other.getSecondOperand() != 0D) { setSecondOperand(other.getSecondOperand()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { org.tribuo.protos.core.SimpleTransformProto parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (org.tribuo.protos.core.SimpleTransformProto) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object op_ = ""; /** * <code>string op = 1;</code> * @return The op. */ public java.lang.String getOp() { java.lang.Object ref = op_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); op_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>string op = 1;</code> * @return The bytes for op. */ public com.google.protobuf.ByteString getOpBytes() { java.lang.Object ref = op_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); op_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>string op = 1;</code> * @param value The op to set. * @return This builder for chaining. */ public Builder setOp( java.lang.String value) { if (value == null) { throw new NullPointerException(); } op_ = value; onChanged(); return this; } /** * <code>string op = 1;</code> * @return This builder for chaining. */ public Builder clearOp() { op_ = getDefaultInstance().getOp(); onChanged(); return this; } /** * <code>string op = 1;</code> * @param value The bytes for op to set. * @return This builder for chaining. */ public Builder setOpBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); op_ = value; onChanged(); return this; } private double firstOperand_ ; /** * <code>double first_operand = 2;</code> * @return The firstOperand. */ @java.lang.Override public double getFirstOperand() { return firstOperand_; } /** * <code>double first_operand = 2;</code> * @param value The firstOperand to set. * @return This builder for chaining. */ public Builder setFirstOperand(double value) { firstOperand_ = value; onChanged(); return this; } /** * <code>double first_operand = 2;</code> * @return This builder for chaining. */ public Builder clearFirstOperand() { firstOperand_ = 0D; onChanged(); return this; } private double secondOperand_ ; /** * <code>double second_operand = 3;</code> * @return The secondOperand. */ @java.lang.Override public double getSecondOperand() { return secondOperand_; } /** * <code>double second_operand = 3;</code> * @param value The secondOperand to set. * @return This builder for chaining. */ public Builder setSecondOperand(double value) { secondOperand_ = value; onChanged(); return this; } /** * <code>double second_operand = 3;</code> * @return This builder for chaining. */ public Builder clearSecondOperand() { secondOperand_ = 0D; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:tribuo.core.SimpleTransformProto) } // @@protoc_insertion_point(class_scope:tribuo.core.SimpleTransformProto) private static final org.tribuo.protos.core.SimpleTransformProto DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new org.tribuo.protos.core.SimpleTransformProto(); } public static org.tribuo.protos.core.SimpleTransformProto getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<SimpleTransformProto> PARSER = new com.google.protobuf.AbstractParser<SimpleTransformProto>() { @java.lang.Override public SimpleTransformProto parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new SimpleTransformProto(input, extensionRegistry); } }; public static com.google.protobuf.Parser<SimpleTransformProto> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<SimpleTransformProto> getParserForType() { return PARSER; } @java.lang.Override public org.tribuo.protos.core.SimpleTransformProto getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
/* * Copyright 2002-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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.jms.remoting; import org.springframework.beans.factory.InitializingBean; import org.springframework.jms.listener.SessionAwareMessageListener; import org.springframework.jms.support.JmsUtils; import org.springframework.jms.support.converter.MessageConverter; import org.springframework.jms.support.converter.SimpleMessageConverter; import org.springframework.lang.Nullable; import org.springframework.remoting.support.RemoteInvocation; import org.springframework.remoting.support.RemoteInvocationBasedExporter; import org.springframework.remoting.support.RemoteInvocationResult; import javax.jms.*; /** * JMS message listener that exports the specified service bean as a * JMS service endpoint, accessible via a JMS invoker proxy. * * <p>Note that this class implements Spring's * {@link org.springframework.jms.listener.SessionAwareMessageListener} * interface, since it requires access to the active JMS Session. * Hence, this class can only be used with message listener containers * which support the SessionAwareMessageListener interface (e.g. Spring's * {@link org.springframework.jms.listener.DefaultMessageListenerContainer}). * * <p>Thanks to James Strachan for the original prototype that this * JMS invoker mechanism was inspired by! * * @author Juergen Hoeller * @author James Strachan * @since 2.0 * @see JmsInvokerClientInterceptor * @see JmsInvokerProxyFactoryBean */ public class JmsInvokerServiceExporter extends RemoteInvocationBasedExporter implements SessionAwareMessageListener<Message>, InitializingBean { private MessageConverter messageConverter = new SimpleMessageConverter(); private boolean ignoreInvalidRequests = true; @Nullable private Object proxy; /** * Specify the MessageConverter to use for turning request messages into * {@link org.springframework.remoting.support.RemoteInvocation} objects, * as well as {@link org.springframework.remoting.support.RemoteInvocationResult} * objects into response messages. * <p>Default is a {@link org.springframework.jms.support.converter.SimpleMessageConverter}, * using a standard JMS {@link javax.jms.ObjectMessage} for each invocation / * invocation result object. * <p>Custom implementations may generally adapt Serializables into * special kinds of messages, or might be specifically tailored for * translating RemoteInvocation(Result)s into specific kinds of messages. */ public void setMessageConverter(@Nullable MessageConverter messageConverter) { this.messageConverter = (messageConverter != null ? messageConverter : new SimpleMessageConverter()); } /** * Set whether invalidly formatted messages should be discarded. * Default is "true". * <p>Switch this flag to "false" to throw an exception back to the * listener container. This will typically lead to redelivery of * the message, which is usually undesirable - since the message * content will be the same (that is, still invalid). */ public void setIgnoreInvalidRequests(boolean ignoreInvalidRequests) { this.ignoreInvalidRequests = ignoreInvalidRequests; } @Override public void afterPropertiesSet() { this.proxy = getProxyForService(); } @Override public void onMessage(Message requestMessage, Session session) throws JMSException { RemoteInvocation invocation = readRemoteInvocation(requestMessage); if (invocation != null) { RemoteInvocationResult result = invokeAndCreateResult(invocation, this.proxy); writeRemoteInvocationResult(requestMessage, session, result); } } /** * Read a RemoteInvocation from the given JMS message. * @param requestMessage current request message * @return the RemoteInvocation object (or {@code null} * in case of an invalid message that will simply be ignored) * @throws javax.jms.JMSException in case of message access failure */ @Nullable protected RemoteInvocation readRemoteInvocation(Message requestMessage) throws JMSException { Object content = this.messageConverter.fromMessage(requestMessage); if (content instanceof RemoteInvocation) { return (RemoteInvocation) content; } return onInvalidRequest(requestMessage); } /** * Send the given RemoteInvocationResult as a JMS message to the originator. * @param requestMessage current request message * @param session the JMS Session to use * @param result the RemoteInvocationResult object * @throws javax.jms.JMSException if thrown by trying to send the message */ protected void writeRemoteInvocationResult( Message requestMessage, Session session, RemoteInvocationResult result) throws JMSException { Message response = createResponseMessage(requestMessage, session, result); MessageProducer producer = session.createProducer(requestMessage.getJMSReplyTo()); try { producer.send(response); } finally { JmsUtils.closeMessageProducer(producer); } } /** * Create the invocation result response message. * <p>The default implementation creates a JMS ObjectMessage for the given * RemoteInvocationResult object. It sets the response's correlation id * to the request message's correlation id, if any; otherwise to the * request message id. * @param request the original request message * @param session the JMS session to use * @param result the invocation result * @return the message response to send * @throws javax.jms.JMSException if creating the message failed */ protected Message createResponseMessage(Message request, Session session, RemoteInvocationResult result) throws JMSException { Message response = this.messageConverter.toMessage(result, session); String correlation = request.getJMSCorrelationID(); if (correlation == null) { correlation = request.getJMSMessageID(); } response.setJMSCorrelationID(correlation); return response; } /** * Callback that is invoked by {@link #readRemoteInvocation} * when it encounters an invalid request message. * <p>The default implementation either discards the invalid message or * throws a MessageFormatException - according to the "ignoreInvalidRequests" * flag, which is set to "true" (that is, discard invalid messages) by default. * @param requestMessage the invalid request message * @return the RemoteInvocation to expose for the invalid request (typically * {@code null} in case of an invalid message that will simply be ignored) * @throws javax.jms.JMSException in case of the invalid request supposed * to lead to an exception (instead of ignoring it) * @see #readRemoteInvocation * @see #setIgnoreInvalidRequests */ @Nullable protected RemoteInvocation onInvalidRequest(Message requestMessage) throws JMSException { if (this.ignoreInvalidRequests) { if (logger.isDebugEnabled()) { logger.debug("Invalid request message will be discarded: " + requestMessage); } return null; } else { throw new MessageFormatException("Invalid request message: " + requestMessage); } } }
/* * Copyright (c) 2020 GeekStore. * All rights reserved. */ package io.geekstore.data_import.parser; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * Created on Nov, 2020 by @author bobo */ @Data @AllArgsConstructor @NoArgsConstructor public class StringFacet { private String facet; private String value; }
package com.coderefer.LearnSpringBoot01.other; import lombok.Data; @Data public class HelloWorldBean { private String message; public HelloWorldBean(String message) { this.message = message; } }
package com.perforce.p4java.tests.qa; import static com.perforce.p4java.core.file.FileSpecBuilder.makeFileSpecList; import static com.perforce.p4java.tests.qa.Helper.FILE_SEP; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.util.HashMap; import java.util.List; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import com.perforce.p4java.client.IClient; import com.perforce.p4java.core.IChangelist; import com.perforce.p4java.core.IUser; import com.perforce.p4java.core.file.FileSpecBuilder; import com.perforce.p4java.core.file.FileStatAncilliaryOptions; import com.perforce.p4java.core.file.FileStatOutputOptions; import com.perforce.p4java.core.file.IExtendedFileSpec; import com.perforce.p4java.core.file.IFileSpec; import com.perforce.p4java.option.client.AddFilesOptions; import com.perforce.p4java.option.server.GetExtendedFilesOptions; import com.perforce.p4java.option.server.SetFileAttributesOptions; import com.perforce.p4java.server.IOptionsServer; import com.perforce.test.TestServer; public class SetFileAttributesTest { private static TestServer ts = null; private static Helper h = null; private static IOptionsServer server = null; private static IUser user = null; private static IClient client = null; private static File testFile = null; private static IChangelist pendingChange = null; // a file @BeforeClass public static void beforeClass() throws Throwable { h = new Helper(); ts = new TestServer(); ts.getServerExecutableSpecification().setCodeline(h.getServerVersion()); ts.start(); server = h.getServer(ts); server.setUserName(ts.getUser()); server.connect(); user = server.getUser(ts.getUser()); client = h.createClient(server, "client1"); server.setCurrentClient(client); testFile = new File(client.getRoot() + FILE_SEP + "foo.txt"); List<IFileSpec> createdFileSpecs = h.createFile(testFile.getAbsolutePath(), "SetFileAttributeTest"); IChangelist changelist = h.createChangelist(server, user, client); AddFilesOptions addFilesOptions = new AddFilesOptions(); addFilesOptions.setUseWildcards(true); addFilesOptions.setChangelistId(changelist.getId()); addFilesOptions.setFileType("text"); client.addFiles(createdFileSpecs, addFilesOptions); // set the propagated attribute HashMap<String, String> hm = new HashMap<String, String>(); hm.put("p_attrib_1", "p_aValue_1"); SetFileAttributesOptions sfOpts = new SetFileAttributesOptions(); sfOpts.setPropagateAttributes(true); server.setFileAttributes(createdFileSpecs, hm, sfOpts); changelist.refresh(); changelist.submit(false); // we need an edit so we can see an attribute propagate pendingChange = h.createChangelist(server, user, client); h.editFile(testFile.getAbsolutePath(), "SetFileAttributesTest", pendingChange, client); pendingChange.submit(false); pendingChange = h.createChangelist(server, user, client); } // revert open file and remove attributes between tests @Before public void cleanup() { try { List<IFileSpec> fileSpec = makeFileSpecList("//depot/..."); client.revertFiles(fileSpec, null); h.editFile(testFile.getAbsolutePath(), "SetFileAttributesTest", pendingChange, client); HashMap<String, String> hm = new HashMap<String, String>(); hm.put("attrib_1", null); SetFileAttributesOptions sfOpts = new SetFileAttributesOptions(); sfOpts.setSetOnSubmittedFiles(true); fileSpec = makeFileSpecList("//depot/...#1"); server.setFileAttributes(fileSpec, hm, sfOpts); } catch (Throwable t) { } } // make sure an attribute is set even with null options @Test public void nullSetFileAttributesOptions() throws Throwable { List<IFileSpec> fileSpec = makeFileSpecList(testFile.getAbsolutePath()); HashMap<String, String> hm = new HashMap<String, String>(); hm.put("attrib_1", "aValue_1"); server.setFileAttributes(fileSpec, hm, null); FileStatAncilliaryOptions aOpts = new FileStatAncilliaryOptions(); aOpts.setShowAttributes(true); FileStatOutputOptions oOpts = new FileStatOutputOptions(); oOpts.setOpenedFiles(true); GetExtendedFilesOptions opts = new GetExtendedFilesOptions(); opts.setAncilliaryOptions(aOpts); opts.setOutputOptions(oOpts); List<IExtendedFileSpec> results = server.getExtendedFiles(fileSpec, opts); assertTrue("Wrong number of file specs", results.size() == 1); assertTrue("Wrong number of attributes", results.get(0).getAttributes().size() == 2); assertTrue("Key not found", results.get(0).getAttributes().containsKey("attrib_1")); assertEquals("aValue_1", new String(results.get(0).getAttributes().get("attrib_1"))); assertTrue("Key not found", results.get(0).getAttributes().containsKey("p_attrib_1")); assertEquals("p_aValue_1", new String(results.get(0).getAttributes().get("p_attrib_1"))); } // set an attribute on a submitted file with the force flag @Test public void forceSet() throws Throwable { List<IFileSpec> fileSpec = makeFileSpecList(testFile.getAbsolutePath() + "#1"); // set the attribute HashMap<String, String> hm = new HashMap<String, String>(); hm.put("attrib_1", "aValue_1"); SetFileAttributesOptions sfOpts = new SetFileAttributesOptions(); sfOpts.setSetOnSubmittedFiles(true); server.setFileAttributes(fileSpec, hm, sfOpts); // setup the fstat call FileStatAncilliaryOptions aOpts = new FileStatAncilliaryOptions(); aOpts.setShowAttributes(true); FileStatOutputOptions oOpts = new FileStatOutputOptions(); oOpts.setOpenedFiles(true); GetExtendedFilesOptions opts = new GetExtendedFilesOptions(); opts.setAncilliaryOptions(aOpts); opts.setOutputOptions(oOpts); // actually run the query List<IExtendedFileSpec> results = server.getExtendedFiles(fileSpec, opts); assertTrue("Wrong number of file specs", results.size() == 1); assertTrue("Wrong number of attributes", results.get(0).getAttributes().size() == 2); assertTrue("Key not found", results.get(0).getAttributes().containsKey("attrib_1")); assertEquals("aValue_1", new String(results.get(0).getAttributes().get("attrib_1"))); assertTrue("Key not found", results.get(0).getAttributes().containsKey("p_attrib_1")); assertEquals("p_aValue_1", new String(results.get(0).getAttributes().get("p_attrib_1"))); } // set an attribute on a submitted file with the force flag @Test public void propagateSet() throws Throwable { List<IFileSpec> fileSpec = makeFileSpecList(testFile.getAbsolutePath() + "#1"); // setup the fstat call FileStatAncilliaryOptions aOpts = new FileStatAncilliaryOptions(); aOpts.setShowAttributes(true); FileStatOutputOptions oOpts = new FileStatOutputOptions(); GetExtendedFilesOptions opts = new GetExtendedFilesOptions(); opts.setAncilliaryOptions(aOpts); opts.setOutputOptions(oOpts); // verify #1 is correct List<IExtendedFileSpec> results = server.getExtendedFiles(fileSpec, opts); assertTrue("Wrong number of file specs", results.size() == 1); assertTrue(results.get(0).getAttributes().containsKey("p_attrib_1")); assertEquals("p_aValue_1", new String(results.get(0).getAttributes().get("p_attrib_1"))); // verify #2 fileSpec = makeFileSpecList(testFile.getAbsolutePath() + "#2"); results = server.getExtendedFiles(fileSpec, opts); assertTrue("Wrong number of file specs", results.size() == 1); assertTrue(results.get(0).getAttributes().containsKey("p_attrib_1")); assertEquals("p_aValue_1", new String(results.get(0).getAttributes().get("p_attrib_1"))); } @AfterClass public static void afterClass() { h.after(ts); } }
package com.sjl.bookmark.dao.impl; import android.content.Context; import android.database.Cursor; import com.sjl.bookmark.app.AppConstant; import com.sjl.bookmark.dao.CollectBookDao; import com.sjl.bookmark.dao.db.BaseDao; import com.sjl.bookmark.entity.zhuishu.table.BookChapter; import com.sjl.bookmark.entity.zhuishu.table.CollectBook; import com.sjl.core.util.file.FileUtils; import com.sjl.core.net.RxVoid; import com.sjl.core.util.log.LogUtils; import org.greenrobot.greendao.query.QueryBuilder; import java.io.IOException; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import io.reactivex.Single; import io.reactivex.SingleEmitter; import io.reactivex.SingleOnSubscribe; /** * 书架推荐图书 * * @author Kelly * @version 1.0.0 * @filename CollectBookDaoImpl.java * @time 2018/12/1 19:21 * @copyright(C) 2018 song */ public class CollectBookDaoImpl extends BaseDao<CollectBook> { private BookChapterDaoImpl bookChapterService; public CollectBookDaoImpl(Context context) { super(context); this.bookChapterService = new BookChapterDaoImpl(context); } /** * 保存推荐的图书 * * @param collBookBeans */ public void saveCollectBookBeans(List<CollectBook> collBookBeans) { int maxSortId = collBookBeans.size(); for (CollectBook bean : collBookBeans) { bean.setBookSortId(maxSortId);//为每一本书设置一个在书架排序id maxSortId--; if (bean.getBookChapters() != null) { //存储BookChapter(需要修改,如果存在id相同的则无视) bookChapterService.saveBookChapters(bean.getBookChapters()); } } LogUtils.i("书架空空如也,在线获取推荐的图书================"); for (CollectBook bean : collBookBeans) { LogUtils.i(bean.get_id() + "," + bean.getTitle() + "," + bean.getBookSortId()); } batchInsert(collBookBeans);//存在直接更新,不存在更新数据 } /** * 存储已收藏书籍 * * @param bean */ public void saveCollBookWithAsync(final CollectBook bean) { int maxSortId = getMaxSortId() <= 0 ? 1 : getMaxSortId() + 1;//获取最大排序id加1 bean.setBookSortId(maxSortId); //启动异步存储 daoSession.startAsyncSession() .runInTx(new Runnable() { @Override public void run() { if (bean.getBookChapters() != null) { // 存储BookChapterBean List<BookChapter> bookChapters = bean.getBookChapters(); bookChapterService.saveBookChapters(bookChapters); } //存储CollectBook (确保先后顺序,否则出错) daoSession.insertOrReplace(bean); } }); } /** * 获取图书的最大排序id * * @return */ private int getMaxSortId() { String sql = "SELECT max(BOOK_SORT_ID) as maxvalue FROM COLLECT_BOOK"; Cursor cursor = null; int count = -1; try { cursor = manager.getDb().rawQuery(sql, null); if (cursor == null || !cursor.moveToFirst()) { return count; } count = cursor.getInt(0); } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null) cursor.close(); } return count; } /** * 查询书籍转换为map * * @return */ public Map<String, CollectBook> collectBookListToMap() { List<CollectBook> localData = findAll(); if (localData != null && !localData.isEmpty()) { Map<String, CollectBook> result = new LinkedHashMap<String, CollectBook>(); for (CollectBook bean : localData) { result.put(bean.get_id(), bean); } return result; } return null; } /** * 降序查询所有书籍,BookSortId最大说明是最新添加的书籍 * * @return */ public List<CollectBook> findAll() { // daoSession.getCollectionDao().detachAll(); QueryBuilder<CollectBook> builder = (QueryBuilder<CollectBook>) daoSession.getDao(CollectBook.class).queryBuilder(); builder.orderDesc(CollectBookDao.Properties.BookSortId);//降序 return queryWithParams(builder); } /** * 重新设置顺序 * * @param bookList 返回新的顺序 */ public synchronized void resetCollectBookSortId(List<CollectBook> bookList) { LogUtils.i("resetCollectBookSortId后"); int i = bookList.size(); for (CollectBook bean : bookList) { bean.setBookSortId(i); // LogUtils.i(bean.get_id() + "," + bean.getTitle() + "," + bean.getBookSortId()); i--; } batchUpdate(bookList,CollectBook.class); } /** * 删除单本书 * * @param collectBook */ public void deleteCollectBook(CollectBook collectBook) { delete(collectBook); } /** * 保存单本书 * * @param collectBook */ public void saveCollectBook(CollectBook collectBook) { createOrUpdate(collectBook); } /** * 批量保存书 * * @param collectBook */ public void saveCollectBooks(List<CollectBook> collectBook) { batchInsert(collectBook); } /** * 删除在线图书相关数据 * * @param collectBook * @return */ public Single<RxVoid> deleteCollBookInRx(final CollectBook collectBook) { return Single.create(new SingleOnSubscribe<RxVoid>() { @Override public void subscribe(SingleEmitter<RxVoid> e) throws Exception { //查看文本中是否存在删除的数据 deleteBookFile(collectBook.get_id()); //删除下载任务 // deleteDownloadTask(bean.get_id()); //删除目录 bookChapterService.deleteBookChapter(collectBook.get_id()); //删除CollBook deleteCollectBook(collectBook); //删除阅读记录 DaoFactory.getBookRecordDao().deleteBookRecord(collectBook.get_id()); //删除推荐书籍记录 DaoFactory.getRecommendBookDao().deleteRecommendBookByBookId(collectBook.get_id()); e.onSuccess(new RxVoid()); } }); } /** * 删除所有书籍 * * @param all * @return */ public Single<RxVoid> deleteAllCollectBookInRx(final List<CollectBook> all) { return Single.create(new SingleOnSubscribe<RxVoid>() { @Override public void subscribe(SingleEmitter<RxVoid> e) throws Exception { for (CollectBook collectBook : all) { if (collectBook.isLocal()) {//不删除本地文件 bookChapterService.deleteBookChapter(collectBook.get_id()); deleteCollectBook(collectBook); DaoFactory.getBookRecordDao().deleteBookRecord(collectBook.get_id()); } else { //查看文本中是否存在删除的数据 deleteBookFile(collectBook.get_id()); //删除下载任务 //deleteDownloadTask(bean.get_id()); //删除章节目录 bookChapterService.deleteBookChapter(collectBook.get_id()); //删除CollBook deleteCollectBook(collectBook); //删除阅读记录 DaoFactory.getBookRecordDao().deleteBookRecord(collectBook.get_id()); //删除推荐书籍记录 DaoFactory.getRecommendBookDao().deleteRecommendBookByBookId(collectBook.get_id()); } } e.onSuccess(new RxVoid()); } }); } /** * 删除书籍文件 * * @param bookId */ public void deleteBookFile(String bookId) { try { FileUtils.deleteFile(AppConstant.BOOK_CACHE_PATH + bookId); } catch (IOException e) { e.printStackTrace(); } } /** * 查询书籍信息 * * @param bookId * @return */ public CollectBook getCollectBook(String bookId) { CollectBook bean = (CollectBook) daoSession.getDao(CollectBook.class).queryBuilder() .where(CollectBookDao.Properties._id.eq(bookId)) .unique(); return bean; } }
/* * Copyright 2016 DNAstack * * 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.dnastack.beacon.converter.util; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.json.simple.JSONObject; import java.io.OutputStream; /** * Abstract TaskOutput object to store the output of a single task * @author */ public abstract class TaskOutput<Stream extends OutputStream> { private Stream output; public TaskOutput(Stream output) { this.output = output; } /** * Get the raw TaskOutput * @return */ public Stream getOutput() { return output; } public <T> T toObject(JSONObject object, Class<T> clazz) { Gson gson = new GsonBuilder().create(); return gson.fromJson(object.toJSONString(), clazz); } }
package com.lframework.xingyun.api.bo.chart; import com.lframework.starter.web.bo.BaseBo; import com.lframework.xingyun.chart.dto.OrderChartTodayDto; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import java.math.BigDecimal; @Data @EqualsAndHashCode(callSuper = true) public class OrderChartTodayBo extends BaseBo<OrderChartTodayDto> { /** * 单据总金额 */ @ApiModelProperty("单据总金额") private BigDecimal totalAmount; /** * 单据总数量 */ @ApiModelProperty("单据总数量") private Integer totalNum; /** * 创建时间 */ @ApiModelProperty("创建时间") private String createHour; public OrderChartTodayBo() { } public OrderChartTodayBo(OrderChartTodayDto dto) { super(dto); } }
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.apache.cloudstack.query; import java.util.List; import org.apache.cloudstack.affinity.AffinityGroupResponse; import org.apache.cloudstack.api.command.admin.host.ListHostsCmd; import org.apache.cloudstack.api.command.admin.internallb.ListInternalLBVMsCmd; import org.apache.cloudstack.api.command.admin.router.ListRoutersCmd; import org.apache.cloudstack.api.command.admin.storage.ListImageStoresCmd; import org.apache.cloudstack.api.command.admin.storage.ListSecondaryStagingStoresCmd; import org.apache.cloudstack.api.command.admin.storage.ListStoragePoolsCmd; import org.apache.cloudstack.api.command.admin.user.ListUsersCmd; import org.apache.cloudstack.api.command.user.account.ListAccountsCmd; import org.apache.cloudstack.api.command.user.account.ListProjectAccountsCmd; import org.apache.cloudstack.api.command.user.event.ListEventsCmd; import org.apache.cloudstack.api.command.user.iso.ListIsosCmd; import org.apache.cloudstack.api.command.user.job.ListAsyncJobsCmd; import org.apache.cloudstack.api.command.user.offering.ListDiskOfferingsCmd; import org.apache.cloudstack.api.command.user.offering.ListServiceOfferingsCmd; import org.apache.cloudstack.api.command.user.project.ListProjectInvitationsCmd; import org.apache.cloudstack.api.command.user.project.ListProjectsCmd; import org.apache.cloudstack.api.command.user.securitygroup.ListSecurityGroupsCmd; import org.apache.cloudstack.api.command.user.tag.ListTagsCmd; import org.apache.cloudstack.api.command.user.template.ListTemplatesCmd; import org.apache.cloudstack.api.command.user.vm.ListVMsCmd; import org.apache.cloudstack.api.command.user.vmgroup.ListVMGroupsCmd; import org.apache.cloudstack.api.command.user.volume.ListResourceDetailsCmd; import org.apache.cloudstack.api.command.user.volume.ListVolumesCmd; import org.apache.cloudstack.api.command.user.zone.ListZonesByCmd; import org.apache.cloudstack.api.response.AccountResponse; import org.apache.cloudstack.api.response.AsyncJobResponse; import org.apache.cloudstack.api.response.DiskOfferingResponse; import org.apache.cloudstack.api.response.DomainRouterResponse; import org.apache.cloudstack.api.response.EventResponse; import org.apache.cloudstack.api.response.HostResponse; import org.apache.cloudstack.api.response.ImageStoreResponse; import org.apache.cloudstack.api.response.InstanceGroupResponse; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.ProjectAccountResponse; import org.apache.cloudstack.api.response.ProjectInvitationResponse; import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.cloudstack.api.response.ResourceDetailResponse; import org.apache.cloudstack.api.response.ResourceTagResponse; import org.apache.cloudstack.api.response.SecurityGroupResponse; import org.apache.cloudstack.api.response.ServiceOfferingResponse; import org.apache.cloudstack.api.response.StoragePoolResponse; import org.apache.cloudstack.api.response.TemplateResponse; import org.apache.cloudstack.api.response.UserResponse; import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.cloudstack.api.response.VolumeResponse; import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.exception.PermissionDeniedException; /** * Service used for list api query. * */ public interface QueryService { public ListResponse<UserResponse> searchForUsers(ListUsersCmd cmd) throws PermissionDeniedException; public ListResponse<EventResponse> searchForEvents(ListEventsCmd cmd); public ListResponse<ResourceTagResponse> listTags(ListTagsCmd cmd); public ListResponse<InstanceGroupResponse> searchForVmGroups(ListVMGroupsCmd cmd); public ListResponse<UserVmResponse> searchForUserVMs(ListVMsCmd cmd); public ListResponse<SecurityGroupResponse> searchForSecurityGroups(ListSecurityGroupsCmd cmd); public ListResponse<DomainRouterResponse> searchForRouters(ListRoutersCmd cmd); public ListResponse<ProjectInvitationResponse> listProjectInvitations(ListProjectInvitationsCmd cmd); public ListResponse<ProjectResponse> listProjects(ListProjectsCmd cmd); public ListResponse<ProjectAccountResponse> listProjectAccounts(ListProjectAccountsCmd cmd); public ListResponse<HostResponse> searchForServers(ListHostsCmd cmd); public ListResponse<VolumeResponse> searchForVolumes(ListVolumesCmd cmd); public ListResponse<StoragePoolResponse> searchForStoragePools(ListStoragePoolsCmd cmd); public ListResponse<ImageStoreResponse> searchForImageStores(ListImageStoresCmd cmd); public ListResponse<ImageStoreResponse> searchForSecondaryStagingStores(ListSecondaryStagingStoresCmd cmd); public ListResponse<AccountResponse> searchForAccounts(ListAccountsCmd cmd); public ListResponse<AsyncJobResponse> searchForAsyncJobs(ListAsyncJobsCmd cmd); public ListResponse<DiskOfferingResponse> searchForDiskOfferings(ListDiskOfferingsCmd cmd); public ListResponse<ServiceOfferingResponse> searchForServiceOfferings(ListServiceOfferingsCmd cmd); public ListResponse<ZoneResponse> listDataCenters(ListZonesByCmd cmd); public ListResponse<TemplateResponse> listTemplates(ListTemplatesCmd cmd); public ListResponse<TemplateResponse> listIsos(ListIsosCmd cmd); public ListResponse<AffinityGroupResponse> listAffinityGroups(Long affinityGroupId, String affinityGroupName, String affinityGroupType, Long vmId, String accountName, Long domainId, boolean isRecursive, boolean listAll, Long startIndex, Long pageSize); public List<ResourceDetailResponse> listResourceDetails(ListResourceDetailsCmd cmd); ListResponse<DomainRouterResponse> searchForInternalLbVms(ListInternalLBVMsCmd cmd); }
package hello.config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.rest.core.config.RepositoryRestConfiguration; import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer; import org.springframework.hateoas.server.LinkRelationProvider; import org.springframework.hateoas.server.core.EvoInflectorLinkRelationProvider; @Configuration public class Hateoas { private final static Logger log = LoggerFactory.getLogger(Hateoas.class); @Bean public LinkRelationProvider relProvider() { log.info("Using EvoInflectorLinkRelationProvider for HATEOAS relations"); return new EvoInflectorLinkRelationProvider(); } @Bean public RepositoryRestConfigurer repositoryRestConfigurer() { return new RepositoryRestConfigurer() { @Override public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) { config.setBasePath("/api"); } }; } }
/////////////////////////////////////////////////////////////////////////// // __ _ _ ________ // // / / ____ ____ _(_)____/ | / / ____/ // // / / / __ \/ __ `/ / ___/ |/ / / __ // // / /___/ /_/ / /_/ / / /__/ /| / /_/ / // // /_____/\____/\__, /_/\___/_/ |_/\____/ // // /____/ // // // // The Next Generation Logic Library // // // /////////////////////////////////////////////////////////////////////////// // // // Copyright 2015 Christoph Zengler // // // // 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.logicng.explanations.drup; import static org.assertj.core.api.Assertions.assertThat; import static org.logicng.datastructures.Tristate.FALSE; import static org.logicng.datastructures.Tristate.TRUE; import org.assertj.core.api.SoftAssertions; import org.junit.jupiter.api.Test; import org.logicng.LogicNGTest; import org.logicng.LongRunningTag; import org.logicng.datastructures.Tristate; import org.logicng.explanations.UNSATCore; import org.logicng.formulas.Formula; import org.logicng.formulas.FormulaFactory; import org.logicng.io.parsers.ParserException; import org.logicng.io.readers.DimacsReader; import org.logicng.propositions.ExtendedProposition; import org.logicng.propositions.Proposition; import org.logicng.propositions.PropositionBackpack; import org.logicng.propositions.StandardProposition; import org.logicng.solvers.MiniSat; import org.logicng.solvers.SATSolver; import org.logicng.solvers.SolverState; import org.logicng.solvers.sat.GlucoseConfig; import org.logicng.solvers.sat.MiniSatConfig; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Unit tests for {@link DRUPTrim}. * @version 2.0.0 * @since 1.3 */ public class DRUPTest implements LogicNGTest { private final FormulaFactory f = new FormulaFactory(); private final SATSolver[] solvers; public DRUPTest() { this.solvers = new SATSolver[3]; this.solvers[0] = MiniSat.miniSat(this.f, MiniSatConfig.builder().proofGeneration(true).incremental(true).build()); this.solvers[1] = MiniSat.miniSat(this.f, MiniSatConfig.builder().proofGeneration(true).incremental(false).build()); this.solvers[2] = MiniSat.glucose(this.f, MiniSatConfig.builder().proofGeneration(true).incremental(false).build(), GlucoseConfig.builder().build()); } @Test public void testUnsatCoresFromDimacs() throws IOException { final List<List<Formula>> cnfs = new ArrayList<>(3); cnfs.add(DimacsReader.readCNF("src/test/resources/drup/simple_input.cnf", this.f)); cnfs.add(DimacsReader.readCNF("src/test/resources/drup/pg4_input.cnf", this.f)); cnfs.add(DimacsReader.readCNF("src/test/resources/drup/avg_input.cnf", this.f, "var")); for (final SATSolver solver : this.solvers) { for (final List<Formula> cnf : cnfs) { solver.add(cnf); assertSolverUnsat(solver); final UNSATCore<Proposition> unsatCore = solver.unsatCore(); verifyCore(unsatCore, cnf); solver.reset(); } } } @Test @LongRunningTag public void testUnsatCoresFromLargeTestset() throws IOException { final File testFolder = new File("src/test/resources/sat"); final File[] files = testFolder.listFiles(); assert files != null; int count = 0; for (final SATSolver solver : this.solvers) { for (final File file : files) { final String fileName = file.getName(); if (fileName.endsWith(".cnf")) { final List<Formula> cnf = DimacsReader.readCNF(file, this.f); solver.add(cnf); if (solver.sat() == FALSE) { final UNSATCore<Proposition> unsatCore = solver.unsatCore(); verifyCore(unsatCore, cnf); count++; } solver.reset(); } } solver.reset(); } assertThat(count).isEqualTo(11 * this.solvers.length); } @Test public void testUnsatCoresAimTestset() throws IOException { final File testFolder = new File("src/test/resources/sat/unsat"); final File[] files = testFolder.listFiles(); assert files != null; int count = 0; for (final SATSolver solver : this.solvers) { for (final File file : files) { final String fileName = file.getName(); if (fileName.endsWith(".cnf")) { final List<Formula> cnf = DimacsReader.readCNF(file, this.f); solver.add(cnf); assertSolverUnsat(solver); final UNSATCore<Proposition> unsatCore = solver.unsatCore(); verifyCore(unsatCore, cnf); solver.reset(); count++; } } solver.reset(); } assertThat(count).isEqualTo(36 * this.solvers.length); } @Test public void testPropositionHandling() throws ParserException { final List<Proposition> propositions = new ArrayList<>(); propositions.add(new StandardProposition("P1", this.f.parse("((a & b) => c) & ((a & b) => d)"))); propositions.add(new StandardProposition("P2", this.f.parse("(c & d) <=> ~e"))); propositions.add(new StandardProposition("P3", this.f.parse("~e => f | g"))); propositions.add(new StandardProposition("P4", this.f.parse("(f => ~a) & (g => ~b) & p & q"))); propositions.add(new StandardProposition("P5", this.f.parse("a => b"))); propositions.add(new StandardProposition("P6", this.f.parse("a"))); propositions.add(new StandardProposition("P7", this.f.parse("g | h"))); propositions.add(new StandardProposition("P8", this.f.parse("(x => ~y | z) & (z | w)"))); for (final SATSolver solver : this.solvers) { solver.addPropositions(propositions); assertThat(solver.sat()).isEqualTo(FALSE); final UNSATCore<Proposition> unsatCore = solver.unsatCore(); assertThat(unsatCore.propositions()).containsExactlyInAnyOrder(propositions.get(0), propositions.get(1), propositions.get(2), propositions.get(3), propositions.get(4), propositions.get(5)); solver.reset(); } } @Test public void testPropositionIncDec() throws ParserException { final SATSolver solver = this.solvers[0]; final StandardProposition p1 = new StandardProposition("P1", this.f.parse("((a & b) => c) & ((a & b) => d)")); final StandardProposition p2 = new StandardProposition("P2", this.f.parse("(c & d) <=> ~e")); final StandardProposition p3 = new StandardProposition("P3", this.f.parse("~e => f | g")); final StandardProposition p4 = new StandardProposition("P4", this.f.parse("(f => ~a) & (g => ~b) & p & q")); final StandardProposition p5 = new StandardProposition("P5", this.f.parse("a => b")); final StandardProposition p6 = new StandardProposition("P6", this.f.parse("a")); final StandardProposition p7 = new StandardProposition("P7", this.f.parse("g | h")); final StandardProposition p8 = new StandardProposition("P8", this.f.parse("(x => ~y | z) & (z | w)")); final StandardProposition p9 = new StandardProposition("P9", this.f.parse("a & b")); final StandardProposition p10 = new StandardProposition("P10", this.f.parse("(p => q) & p")); final StandardProposition p11 = new StandardProposition("P11", this.f.parse("a & ~q")); solver.addPropositions(p1, p2, p3, p4); final SolverState state1 = solver.saveState(); solver.addPropositions(p5, p6); final SolverState state2 = solver.saveState(); solver.addPropositions(p7, p8); assertThat(solver.sat()).isEqualTo(FALSE); UNSATCore<Proposition> unsatCore = solver.unsatCore(); assertThat(unsatCore.propositions()).containsExactlyInAnyOrder(p1, p2, p3, p4, p5, p6); solver.loadState(state2); assertThat(solver.sat()).isEqualTo(FALSE); unsatCore = solver.unsatCore(); assertThat(unsatCore.propositions()).containsExactlyInAnyOrder(p1, p2, p3, p4, p5, p6); solver.loadState(state1); solver.add(p9); assertThat(solver.sat()).isEqualTo(FALSE); unsatCore = solver.unsatCore(); assertThat(unsatCore.propositions()).containsExactlyInAnyOrder(p1, p2, p3, p4, p9); solver.loadState(state1); solver.add(p5); solver.add(p6); assertThat(solver.sat()).isEqualTo(FALSE); unsatCore = solver.unsatCore(); assertThat(unsatCore.propositions()).containsExactlyInAnyOrder(p1, p2, p3, p4, p5, p6); solver.loadState(state1); solver.add(p10); solver.add(p11); assertThat(solver.sat()).isEqualTo(FALSE); unsatCore = solver.unsatCore(); assertThat(unsatCore.propositions()).containsExactlyInAnyOrder(p4, p11); } @Test public void testTrivialCasesPropositions() throws ParserException { for (final SATSolver solver : this.solvers) { assertSolverSat(solver); final StandardProposition p1 = new StandardProposition("P1", this.f.parse("$false")); solver.add(p1); assertSolverUnsat(solver); UNSATCore<Proposition> unsatCore = solver.unsatCore(); assertThat(unsatCore.propositions()).containsExactlyInAnyOrder(p1); solver.reset(); assertSolverSat(solver); final StandardProposition p2 = new StandardProposition("P2", this.f.parse("a")); solver.add(p2); assertSolverSat(solver); final StandardProposition p3 = new StandardProposition("P3", this.f.parse("~a")); solver.add(p3); assertSolverUnsat(solver); unsatCore = solver.unsatCore(); assertThat(unsatCore.propositions()).containsExactlyInAnyOrder(p2, p3); } } @Test public void testCoreAndAssumptions() throws ParserException { final FormulaFactory f = new FormulaFactory(); final SATSolver solver = MiniSat.miniSat(f, MiniSatConfig.builder().proofGeneration(true).cnfMethod(MiniSatConfig.CNFMethod.PG_ON_SOLVER).build()); final StandardProposition p1 = new StandardProposition(f.parse("A => B")); final StandardProposition p2 = new StandardProposition(f.parse("A & B => G")); final StandardProposition p3 = new StandardProposition(f.or(f.literal("X", false), f.literal("A", true))); final StandardProposition p4 = new StandardProposition(f.or(f.literal("X", false), f.literal("G", false))); final StandardProposition p5 = new StandardProposition(f.literal("G", false)); final StandardProposition p6 = new StandardProposition(f.literal("A", true)); solver.add(p1); solver.add(p2); solver.add(p3); solver.add(p4); // Assumption call solver.sat(f.variable("X")); solver.add(p5); solver.add(p6); solver.sat(); final UNSATCore<Proposition> unsatCore = solver.unsatCore(); assertThat(unsatCore.propositions()).containsExactlyInAnyOrder(p1, p2, p5, p6); } @Test public void testCoreAndAssumptions2() throws ParserException { final FormulaFactory f = new FormulaFactory(); final MiniSat solver = MiniSat.miniSat(f, MiniSatConfig.builder().proofGeneration(true).cnfMethod(MiniSatConfig.CNFMethod.PG_ON_SOLVER).build()); solver.add(f.parse("~C => D")); solver.add(f.parse("C => D")); solver.add(f.parse("D => B | A")); solver.add(f.parse("B => X")); solver.add(f.parse("B => ~X")); solver.sat(f.literal("A", false)); solver.add(f.parse("~A")); solver.sat(); assertThat(solver.unsatCore()).isNotNull(); } @Test public void testCoreAndAssumptions3() throws ParserException { // Unit test for DRUP issue which led to java.lang.ArrayIndexOutOfBoundsException: -1 final FormulaFactory f = new FormulaFactory(); final MiniSat solver = MiniSat.miniSat(f, MiniSatConfig.builder().proofGeneration(true).cnfMethod(MiniSatConfig.CNFMethod.PG_ON_SOLVER).build()); solver.add(f.parse("X => Y")); solver.add(f.parse("X => Z")); solver.add(f.parse("C => E")); solver.add(f.parse("D => ~F")); solver.add(f.parse("B => M")); solver.add(f.parse("D => N")); solver.add(f.parse("G => O")); solver.add(f.parse("A => B")); solver.add(f.parse("T1 <=> A & K & ~B & ~C")); solver.add(f.parse("T2 <=> A & B & C & K")); solver.add(f.parse("T1 + T2 = 1")); solver.sat(); // required for DRUP issue solver.add(f.parse("Y => ~X & D")); solver.add(f.parse("X")); solver.sat(); assertThat(solver.unsatCore()).isNotNull(); } @Test public void testWithCcPropositions() throws ParserException { final FormulaFactory f = new FormulaFactory(); final SATSolver solver = MiniSat.miniSat(f, MiniSatConfig.builder().proofGeneration(true).cnfMethod(MiniSatConfig.CNFMethod.PG_ON_SOLVER).build()); final ExtendedProposition<StringBackpack> p1 = new ExtendedProposition<>(new StringBackpack("CC"), f.parse("A + B + C <= 1")); final StandardProposition p2 = new StandardProposition(f.parse("A")); final StandardProposition p3 = new StandardProposition(f.parse("B")); final StandardProposition p4 = new StandardProposition(f.parse("X & Y")); solver.add(p1); solver.add(p2); solver.add(p3); solver.add(p4); assertThat(solver.sat()).isEqualTo(FALSE); assertThat(solver.unsatCore().propositions()).containsExactlyInAnyOrder(p1, p2, p3); } @Test public void testWithSpecialUnitCaseMiniSat() throws ParserException { final FormulaFactory f = new FormulaFactory(); final SATSolver solver = MiniSat.miniSat(f, MiniSatConfig.builder().proofGeneration(true).build()); final StandardProposition p1 = new StandardProposition(f.parse("a => b")); final StandardProposition p2 = new StandardProposition(f.parse("a => c | d")); final StandardProposition p3 = new StandardProposition(f.parse("b => c | d")); final StandardProposition p4 = new StandardProposition(f.parse("e | f | g | h => i")); final StandardProposition p5 = new StandardProposition(f.parse("~j => k | j")); final StandardProposition p6 = new StandardProposition(f.parse("b => ~(e | f)")); final StandardProposition p7 = new StandardProposition(f.parse("c => ~j")); final StandardProposition p8 = new StandardProposition(f.parse("l | m => ~i")); final StandardProposition p9 = new StandardProposition(f.parse("j => (f + g + h = 1)")); final StandardProposition p10 = new StandardProposition(f.parse("d => (l + m + e + f = 1)")); final StandardProposition p11 = new StandardProposition(f.parse("~k")); solver.addPropositions(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11); assertThat(solver.sat()).isEqualTo(TRUE); solver.add(f.variable("a")); assertThat(solver.sat()).isEqualTo(FALSE); assertThat(solver.unsatCore().propositions()).contains(p1, p2, p4, p5, p6, p7, p8, p9, p10, p11); } @Test public void testWithSpecialUnitCaseGlucose() throws ParserException { final FormulaFactory f = new FormulaFactory(); final SATSolver solver = MiniSat.glucose(f, MiniSatConfig.builder().proofGeneration(true).incremental(false).build(), GlucoseConfig.builder().build()); final StandardProposition p1 = new StandardProposition(f.parse("a => b")); final StandardProposition p2 = new StandardProposition(f.parse("a => c | d")); final StandardProposition p3 = new StandardProposition(f.parse("b => c | d")); final StandardProposition p4 = new StandardProposition(f.parse("e | f | g | h => i")); final StandardProposition p5 = new StandardProposition(f.parse("~j => k | j")); final StandardProposition p6 = new StandardProposition(f.parse("b => ~(e | f)")); final StandardProposition p7 = new StandardProposition(f.parse("c => ~j")); final StandardProposition p8 = new StandardProposition(f.parse("l | m => ~i")); final StandardProposition p9 = new StandardProposition(f.parse("j => (f + g + h = 1)")); final StandardProposition p10 = new StandardProposition(f.parse("d => (l + m + e + f = 1)")); final StandardProposition p11 = new StandardProposition(f.parse("~k")); solver.addPropositions(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11); assertThat(solver.sat()).isEqualTo(TRUE); solver.add(f.variable("a")); assertThat(solver.sat()).isEqualTo(FALSE); assertThat(solver.unsatCore().propositions()).contains(p1, p2, p4, p5, p6, p7, p8, p9, p10, p11); } /** * Checks that each formula of the core is part of the original problem and that the core is really unsat. * @param originalCore the original core * @param cnf the original problem */ private void verifyCore(final UNSATCore<Proposition> originalCore, final List<Formula> cnf) { final List<Formula> core = new ArrayList<>(originalCore.propositions().size()); for (final Proposition prop : originalCore.propositions()) { core.add(prop.formula()); } final SoftAssertions softly = new SoftAssertions(); softly.assertThat(cnf).as("Core contains only original clauses").containsAll(core); final MiniSat solver = MiniSat.glucose(this.f, MiniSatConfig.builder().proofGeneration(true).incremental(false).build(), GlucoseConfig.builder().build()); solver.add(core); softly.assertThat(solver.sat()).as("Core is unsatisfiable").isEqualTo(Tristate.FALSE); softly.assertAll(); } private static final class StringBackpack implements PropositionBackpack { private final String string; private StringBackpack(final String string) { this.string = string; } } }
package de.rexlmanu.mlgrush.plugin.event.type; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.experimental.Accessors; @AllArgsConstructor @Getter @Accessors(fluent = true) public class GameEvent<E> { private E target; }
/* * Copyright 2021 Anton Tananaev (anton@traccar.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.traccar.protocol; import io.netty.channel.Channel; import org.traccar.BaseProtocolDecoder; import org.traccar.DeviceSession; import org.traccar.Protocol; import org.traccar.helper.DateBuilder; import org.traccar.helper.Parser; import org.traccar.helper.PatternBuilder; import org.traccar.model.Position; import java.net.SocketAddress; import java.util.regex.Pattern; public class EnnfuProtocolDecoder extends BaseProtocolDecoder { public EnnfuProtocolDecoder(Protocol protocol) { super(protocol); } private static final Pattern PATTERN = new PatternBuilder() .text("Ennfu:") .number("(d+),") // imei .number("(dd)(dd)(dd).dd,") // time (hhmmss) .expression("([AV]),") // validity .number("(dd)(dd.d+),") // latitude .expression("([NS]),") .number("(ddd)(dd.d+),") // longitude .expression("([EW]),") .number("(d+.d+)?,") // speed .number("(d+.d+)?,") // course .number("(dd)(dd)(dd),") // date (ddmmyy) .number("(d+),") // rssi .number("(d+.d+),") // battery .number("(d+.d+),") // battery level .number("(Vd.dd)") // firmware version .compile(); @Override protected Object decode( Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { Parser parser = new Parser(PATTERN, (String) msg); if (!parser.matches()) { return null; } DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, parser.next()); if (deviceSession == null) { return null; } Position position = new Position(getProtocolName()); position.setDeviceId(deviceSession.getDeviceId()); DateBuilder dateBuilder = new DateBuilder() .setTime(parser.nextInt(), parser.nextInt(), parser.nextInt()); position.setValid(parser.next().equals("A")); position.setLatitude(parser.nextCoordinate()); position.setLongitude(parser.nextCoordinate()); position.setSpeed(parser.nextDouble(0)); position.setCourse(parser.nextDouble(0)); dateBuilder.setDateReverse(parser.nextInt(), parser.nextInt(), parser.nextInt()); position.setTime(dateBuilder.getDate()); position.set(Position.KEY_RSSI, parser.nextInt()); position.set(Position.KEY_BATTERY, parser.nextDouble()); position.set(Position.KEY_BATTERY_LEVEL, parser.nextDouble()); position.set(Position.KEY_VERSION_FW, parser.next()); return position; } }
/* * Copyright (C) 2014-2022 Philip Helger (www.helger.com) * philip[at]helger[dot]com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.helger.photon.security.user; import java.time.LocalDateTime; import java.util.Locale; import java.util.Map; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.NotThreadSafe; import com.helger.commons.ValueEnforcer; import com.helger.commons.annotation.Nonempty; import com.helger.commons.datetime.PDTFactory; import com.helger.commons.equals.EqualsHelper; import com.helger.commons.state.EChange; import com.helger.commons.string.ToStringGenerator; import com.helger.commons.type.ObjectType; import com.helger.photon.security.CSecurity; import com.helger.photon.security.object.StubObject; import com.helger.security.password.hash.PasswordHash; import com.helger.tenancy.AbstractBusinessObject; /** * Default implementation of the {@link IUser} interface. * * @author Philip Helger */ @NotThreadSafe public class User extends AbstractBusinessObject implements IUser { public static final ObjectType OT = new ObjectType ("user"); private String m_sLoginName; private String m_sEmailAddress; private PasswordHash m_aPasswordHash; private String m_sFirstName; private String m_sLastName; private String m_sDescription; private Locale m_aDesiredLocale; private LocalDateTime m_aLastLoginDT; private int m_nLoginCount; private int m_nConsecutiveFailedLoginCount; private boolean m_bDisabled; /** * Create a new user * * @param sLoginName * Login name of the user. May neither be <code>null</code> nor empty. * @param sEmailAddress * Email address of the user. May be <code>null</code>. * @param aPasswordHash * Password hash of the user. May not be <code>null</code>. * @param sFirstName * The first name. May be <code>null</code>. * @param sLastName * The last name. May be <code>null</code>. * @param sDescription * Optional description text. May be <code>null</code>. * @param aDesiredLocale * The desired locale. May be <code>null</code>. * @param aCustomAttrs * Custom attributes. May be <code>null</code>. * @param bDisabled * <code>true</code> if the user is disabled */ public User (@Nonnull @Nonempty final String sLoginName, @Nullable final String sEmailAddress, @Nonnull final PasswordHash aPasswordHash, @Nullable final String sFirstName, @Nullable final String sLastName, @Nullable final String sDescription, @Nullable final Locale aDesiredLocale, @Nullable final Map <String, String> aCustomAttrs, final boolean bDisabled) { this (StubObject.createForCurrentUser (aCustomAttrs), sLoginName, sEmailAddress, aPasswordHash, sFirstName, sLastName, sDescription, aDesiredLocale, (LocalDateTime) null, 0, 0, bDisabled); } /** * For deserialization only. * * @param aStubObject * Stub init object. May not be <code>null</code>. * @param sLoginName * Login name of the user. May neither be <code>null</code> nor empty. * @param sEmailAddress * Email address of the user. May be <code>null</code>. * @param aPasswordHash * Password hash of the user. May not be <code>null</code>. * @param sFirstName * The first name. May be <code>null</code>. * @param sLastName * The last name. May be <code>null</code>. * @param sDescription * Optional description text. May be <code>null</code>. * @param aDesiredLocale * The desired locale. May be <code>null</code>. * @param aLastLoginDT * The date time when the user last logged in. * @param nLoginCount * The number of times the user logged in. Must be &ge; 0. * @param nConsecutiveFailedLoginCount * The number of consecutive failed logins. Must be &ge; 0. * @param bDisabled * <code>true</code> if the user is disabled */ public User (@Nonnull final StubObject aStubObject, @Nonnull @Nonempty final String sLoginName, @Nullable final String sEmailAddress, @Nonnull final PasswordHash aPasswordHash, @Nullable final String sFirstName, @Nullable final String sLastName, @Nullable final String sDescription, @Nullable final Locale aDesiredLocale, @Nullable final LocalDateTime aLastLoginDT, @Nonnegative final int nLoginCount, @Nonnegative final int nConsecutiveFailedLoginCount, final boolean bDisabled) { super (aStubObject); ValueEnforcer.isGE0 (nLoginCount, "LoginCount"); ValueEnforcer.isGE0 (nConsecutiveFailedLoginCount, "ConsecutiveFailedLoginCount"); setLoginName (sLoginName); setEmailAddress (sEmailAddress); setPasswordHash (aPasswordHash); setFirstName (sFirstName); setLastName (sLastName); setDescription (sDescription); setDesiredLocale (aDesiredLocale); m_aLastLoginDT = aLastLoginDT; m_nLoginCount = nLoginCount; m_nConsecutiveFailedLoginCount = nConsecutiveFailedLoginCount; setDisabled (bDisabled); } @Nonnull public ObjectType getObjectType () { return User.OT; } public boolean isAdministrator () { return CSecurity.USER_ADMINISTRATOR_ID.equals (getID ()); } @Nonnull @Nonempty public String getLoginName () { return m_sLoginName; } @Nonnull public EChange setLoginName (@Nonnull @Nonempty final String sLoginName) { ValueEnforcer.notEmpty (sLoginName, "loginName"); if (sLoginName.equals (m_sLoginName)) return EChange.UNCHANGED; m_sLoginName = sLoginName; return EChange.CHANGED; } @Nullable public String getEmailAddress () { return m_sEmailAddress; } @Nonnull public EChange setEmailAddress (@Nullable final String sEmailAddress) { if (EqualsHelper.equals (sEmailAddress, m_sEmailAddress)) return EChange.UNCHANGED; m_sEmailAddress = sEmailAddress; return EChange.CHANGED; } @Nonnull @Nonempty public PasswordHash getPasswordHash () { return m_aPasswordHash; } @Nonnull public EChange setPasswordHash (@Nonnull final PasswordHash aPasswordHash) { ValueEnforcer.notNull (aPasswordHash, "PasswordHash"); if (aPasswordHash.equals (m_aPasswordHash)) return EChange.UNCHANGED; m_aPasswordHash = aPasswordHash; return EChange.CHANGED; } @Nullable public String getFirstName () { return m_sFirstName; } @Nonnull public EChange setFirstName (@Nullable final String sFirstName) { if (EqualsHelper.equals (sFirstName, m_sFirstName)) return EChange.UNCHANGED; m_sFirstName = sFirstName; return EChange.CHANGED; } @Nullable public String getLastName () { return m_sLastName; } @Nonnull public EChange setLastName (@Nullable final String sLastName) { if (EqualsHelper.equals (sLastName, m_sLastName)) return EChange.UNCHANGED; m_sLastName = sLastName; return EChange.CHANGED; } @Nullable public String getDescription () { return m_sDescription; } @Nonnull public EChange setDescription (@Nullable final String sDescription) { if (EqualsHelper.equals (sDescription, m_sDescription)) return EChange.UNCHANGED; m_sDescription = sDescription; return EChange.CHANGED; } @Nullable public Locale getDesiredLocale () { return m_aDesiredLocale; } @Nonnull public EChange setDesiredLocale (@Nullable final Locale aDesiredLocale) { if (EqualsHelper.equals (aDesiredLocale, m_aDesiredLocale)) return EChange.UNCHANGED; m_aDesiredLocale = aDesiredLocale; return EChange.CHANGED; } @Nullable public LocalDateTime getLastLoginDateTime () { return m_aLastLoginDT; } @Nonnegative public int getLoginCount () { return m_nLoginCount; } @Nonnegative public int getConsecutiveFailedLoginCount () { return m_nConsecutiveFailedLoginCount; } protected void onSuccessfulLogin () { m_aLastLoginDT = PDTFactory.getCurrentLocalDateTime (); m_nLoginCount++; m_nConsecutiveFailedLoginCount = 0; } protected void onFailedLogin () { m_nConsecutiveFailedLoginCount++; } public boolean isDisabled () { return m_bDisabled; } @Nonnull public EChange setDisabled (final boolean bDisabled) { if (bDisabled == m_bDisabled) return EChange.UNCHANGED; m_bDisabled = bDisabled; return EChange.CHANGED; } @Override public boolean equals (final Object o) { // New fields, no changes return super.equals (o); } @Override public int hashCode () { // New fields, no changes return super.hashCode (); } @Override public String toString () { return ToStringGenerator.getDerived (super.toString ()) .append ("LoginName", m_sLoginName) .appendIfNotNull ("EmailAddress", m_sEmailAddress) .append ("PasswordHash", m_aPasswordHash) .appendIfNotNull ("FirstName", m_sFirstName) .appendIfNotNull ("LastName", m_sLastName) .appendIfNotNull ("Description", m_sDescription) .appendIfNotNull ("DesiredLocale", m_aDesiredLocale) .appendIfNotNull ("LastLoginDT", m_aLastLoginDT) .append ("LoginCount", m_nLoginCount) .append ("ConsecutiveFailedLoginCount", m_nConsecutiveFailedLoginCount) .append ("Disabled", m_bDisabled) .getToString (); } // Internal use only @Nonnull public static User createdPredefinedUser (@Nonnull @Nonempty final String sID, @Nonnull @Nonempty final String sLoginName, @Nullable final String sEmailAddress, @Nonnull final PasswordHash aPasswordHash, @Nullable final String sFirstName, @Nullable final String sLastName, @Nullable final String sDescription, @Nullable final Locale aDesiredLocale, @Nullable final Map <String, String> aCustomAttrs, final boolean bDisabled) { return new User (StubObject.createForCurrentUserAndID (sID, aCustomAttrs), sLoginName, sEmailAddress, aPasswordHash, sFirstName, sLastName, sDescription, aDesiredLocale, (LocalDateTime) null, 0, 0, bDisabled); } }
/* * This file is part of Dependency-Track. * * 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. * * SPDX-License-Identifier: Apache-2.0 * Copyright (c) Steve Springett. All Rights Reserved. */ package org.dependencytrack.notification.publisher; import alpine.notification.Notification; import com.mitchellbosecke.pebble.PebbleEngine; import com.mitchellbosecke.pebble.template.PebbleTemplate; import javax.json.JsonObject; public class CsWebexPublisher extends AbstractWebhookPublisher implements Publisher { private static final PebbleEngine ENGINE = new PebbleEngine.Builder().defaultEscapingStrategy("json").build(); private static final PebbleTemplate TEMPLATE = ENGINE.getTemplate("templates/notification/publisher/cswebex.peb"); public void inform(final Notification notification, final JsonObject config) { publish(DefaultNotificationPublishers.CS_WEBEX.getPublisherName(), TEMPLATE, notification, config); } }
/* * Copyright 2017-2022 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.config.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DescribeRemediationConfigurations" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DescribeRemediationConfigurationsRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * A list of Config rule names of remediation configurations for which you want details. * </p> */ private com.amazonaws.internal.SdkInternalList<String> configRuleNames; /** * <p> * A list of Config rule names of remediation configurations for which you want details. * </p> * * @return A list of Config rule names of remediation configurations for which you want details. */ public java.util.List<String> getConfigRuleNames() { if (configRuleNames == null) { configRuleNames = new com.amazonaws.internal.SdkInternalList<String>(); } return configRuleNames; } /** * <p> * A list of Config rule names of remediation configurations for which you want details. * </p> * * @param configRuleNames * A list of Config rule names of remediation configurations for which you want details. */ public void setConfigRuleNames(java.util.Collection<String> configRuleNames) { if (configRuleNames == null) { this.configRuleNames = null; return; } this.configRuleNames = new com.amazonaws.internal.SdkInternalList<String>(configRuleNames); } /** * <p> * A list of Config rule names of remediation configurations for which you want details. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setConfigRuleNames(java.util.Collection)} or {@link #withConfigRuleNames(java.util.Collection)} if you * want to override the existing values. * </p> * * @param configRuleNames * A list of Config rule names of remediation configurations for which you want details. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeRemediationConfigurationsRequest withConfigRuleNames(String... configRuleNames) { if (this.configRuleNames == null) { setConfigRuleNames(new com.amazonaws.internal.SdkInternalList<String>(configRuleNames.length)); } for (String ele : configRuleNames) { this.configRuleNames.add(ele); } return this; } /** * <p> * A list of Config rule names of remediation configurations for which you want details. * </p> * * @param configRuleNames * A list of Config rule names of remediation configurations for which you want details. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeRemediationConfigurationsRequest withConfigRuleNames(java.util.Collection<String> configRuleNames) { setConfigRuleNames(configRuleNames); 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 (getConfigRuleNames() != null) sb.append("ConfigRuleNames: ").append(getConfigRuleNames()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DescribeRemediationConfigurationsRequest == false) return false; DescribeRemediationConfigurationsRequest other = (DescribeRemediationConfigurationsRequest) obj; if (other.getConfigRuleNames() == null ^ this.getConfigRuleNames() == null) return false; if (other.getConfigRuleNames() != null && other.getConfigRuleNames().equals(this.getConfigRuleNames()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getConfigRuleNames() == null) ? 0 : getConfigRuleNames().hashCode()); return hashCode; } @Override public DescribeRemediationConfigurationsRequest clone() { return (DescribeRemediationConfigurationsRequest) super.clone(); } }
package com.zgy.learn.springsecurity.service; import lombok.extern.slf4j.Slf4j; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; /** * @author: pray-journey.io * @despcription: * @date: created in 2021-02-21 * @modified : */ @Service @Slf4j public class LoginService implements UserDetailsService { private final PasswordEncoder passwordEncoder; public LoginService(PasswordEncoder passwordEncoder) { this.passwordEncoder = passwordEncoder; } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { log.info("正在执行登录服务..."); // 1. 根据用户名查找数据库, 不存在就抛异常, 添加了两个用户admin, zhangsan if (!"admin".equals(username) && !"zhangsan".equals(username)) { throw new UsernameNotFoundException("用户名不存在!"); } if ("admin".equals(username)) { // 2. 比较密码(注册时保存到数据库之中的已经是加密过的密码) String password = passwordEncoder.encode("123456"); return new User(username, password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin, user, ROLE_admin, insert, delete, update, select")); } else if ("zhangsan".equals(username)) { // 2. 比较密码(注册时保存到数据库之中的已经是加密过的密码) String password = passwordEncoder.encode("123456"); return new User(username, password, AuthorityUtils.commaSeparatedStringToAuthorityList("user, ROLE_vip, select")); } else { return new User("", "", AuthorityUtils.commaSeparatedStringToAuthorityList("")); } } }
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.kinesisvideosignalingchannels.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.kinesisvideosignalingchannels.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * InvalidArgumentException JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class InvalidArgumentExceptionUnmarshaller extends EnhancedJsonErrorUnmarshaller { private InvalidArgumentExceptionUnmarshaller() { super(com.amazonaws.services.kinesisvideosignalingchannels.model.InvalidArgumentException.class, "InvalidArgumentException"); } @Override public com.amazonaws.services.kinesisvideosignalingchannels.model.InvalidArgumentException unmarshallFromContext(JsonUnmarshallerContext context) throws Exception { com.amazonaws.services.kinesisvideosignalingchannels.model.InvalidArgumentException invalidArgumentException = new com.amazonaws.services.kinesisvideosignalingchannels.model.InvalidArgumentException( null); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return invalidArgumentException; } private static InvalidArgumentExceptionUnmarshaller instance; public static InvalidArgumentExceptionUnmarshaller getInstance() { if (instance == null) instance = new InvalidArgumentExceptionUnmarshaller(); return instance; } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: rpc.proto package cn.nextop.gadget.etcd.grpc; /** * Protobuf type {@code etcdserverpb.AuthEnableRequest} */ @SuppressWarnings("all") public final class AuthEnableRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:etcdserverpb.AuthEnableRequest) AuthEnableRequestOrBuilder { private static final long serialVersionUID = 0L; // Use AuthEnableRequest.newBuilder() to construct. private AuthEnableRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private AuthEnableRequest() { } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private AuthEnableRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownFieldProto3( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return cn.nextop.gadget.etcd.grpc.JetcdProto.internal_static_etcdserverpb_AuthEnableRequest_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return cn.nextop.gadget.etcd.grpc.JetcdProto.internal_static_etcdserverpb_AuthEnableRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( cn.nextop.gadget.etcd.grpc.AuthEnableRequest.class, cn.nextop.gadget.etcd.grpc.AuthEnableRequest.Builder.class); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { unknownFields.writeTo(output); } public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof cn.nextop.gadget.etcd.grpc.AuthEnableRequest)) { return super.equals(obj); } cn.nextop.gadget.etcd.grpc.AuthEnableRequest other = (cn.nextop.gadget.etcd.grpc.AuthEnableRequest) obj; boolean result = true; result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static cn.nextop.gadget.etcd.grpc.AuthEnableRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static cn.nextop.gadget.etcd.grpc.AuthEnableRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static cn.nextop.gadget.etcd.grpc.AuthEnableRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static cn.nextop.gadget.etcd.grpc.AuthEnableRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static cn.nextop.gadget.etcd.grpc.AuthEnableRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static cn.nextop.gadget.etcd.grpc.AuthEnableRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static cn.nextop.gadget.etcd.grpc.AuthEnableRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static cn.nextop.gadget.etcd.grpc.AuthEnableRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static cn.nextop.gadget.etcd.grpc.AuthEnableRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static cn.nextop.gadget.etcd.grpc.AuthEnableRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static cn.nextop.gadget.etcd.grpc.AuthEnableRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static cn.nextop.gadget.etcd.grpc.AuthEnableRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(cn.nextop.gadget.etcd.grpc.AuthEnableRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code etcdserverpb.AuthEnableRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:etcdserverpb.AuthEnableRequest) cn.nextop.gadget.etcd.grpc.AuthEnableRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return cn.nextop.gadget.etcd.grpc.JetcdProto.internal_static_etcdserverpb_AuthEnableRequest_descriptor; } protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return cn.nextop.gadget.etcd.grpc.JetcdProto.internal_static_etcdserverpb_AuthEnableRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( cn.nextop.gadget.etcd.grpc.AuthEnableRequest.class, cn.nextop.gadget.etcd.grpc.AuthEnableRequest.Builder.class); } // Construct using cn.nextop.gadget.etcd.grpc.AuthEnableRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } public Builder clear() { super.clear(); return this; } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return cn.nextop.gadget.etcd.grpc.JetcdProto.internal_static_etcdserverpb_AuthEnableRequest_descriptor; } public cn.nextop.gadget.etcd.grpc.AuthEnableRequest getDefaultInstanceForType() { return cn.nextop.gadget.etcd.grpc.AuthEnableRequest.getDefaultInstance(); } public cn.nextop.gadget.etcd.grpc.AuthEnableRequest build() { cn.nextop.gadget.etcd.grpc.AuthEnableRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public cn.nextop.gadget.etcd.grpc.AuthEnableRequest buildPartial() { cn.nextop.gadget.etcd.grpc.AuthEnableRequest result = new cn.nextop.gadget.etcd.grpc.AuthEnableRequest(this); onBuilt(); return result; } public Builder clone() { return (Builder) super.clone(); } public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof cn.nextop.gadget.etcd.grpc.AuthEnableRequest) { return mergeFrom((cn.nextop.gadget.etcd.grpc.AuthEnableRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(cn.nextop.gadget.etcd.grpc.AuthEnableRequest other) { if (other == cn.nextop.gadget.etcd.grpc.AuthEnableRequest.getDefaultInstance()) return this; this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { cn.nextop.gadget.etcd.grpc.AuthEnableRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (cn.nextop.gadget.etcd.grpc.AuthEnableRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:etcdserverpb.AuthEnableRequest) } // @@protoc_insertion_point(class_scope:etcdserverpb.AuthEnableRequest) private static final cn.nextop.gadget.etcd.grpc.AuthEnableRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new cn.nextop.gadget.etcd.grpc.AuthEnableRequest(); } public static cn.nextop.gadget.etcd.grpc.AuthEnableRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<AuthEnableRequest> PARSER = new com.google.protobuf.AbstractParser<AuthEnableRequest>() { public AuthEnableRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new AuthEnableRequest(input, extensionRegistry); } }; public static com.google.protobuf.Parser<AuthEnableRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<AuthEnableRequest> getParserForType() { return PARSER; } public cn.nextop.gadget.etcd.grpc.AuthEnableRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
package com.perfecto.reportium.model; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; public class CustomField { private String name; private String value; public CustomField() { } public CustomField(String name, String value) { this.name = name; this.value = value; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof CustomField)) return false; CustomField that = (CustomField) o; if (!getName().equals(that.getName())) return false; return getValue() != null ? getValue().equals(that.getValue()) : that.getValue() == null; } @Override public int hashCode() { int result = getName().hashCode(); result = 31 * result + (getValue() != null ? getValue().hashCode() : 0); return result; } @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) .append("name", name) .append("value", value) .toString(); } }
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.ros.android; import com.google.common.base.Preconditions; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.CheckBox; import android.widget.Toast; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.LinearLayout; import android.widget.ListView; import org.ros.exception.RosRuntimeException; import org.ros.internal.node.client.MasterClient; import org.ros.internal.node.xmlrpc.XmlRpcTimeoutException; import org.ros.namespace.GraphName; import org.ros.node.NodeConfiguration; import java.net.NetworkInterface; import java.net.SocketException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.regex.Pattern; /** * Allows the user to configue a master {@link URI} then it returns that * {@link URI} to the calling {@link Activity}. * <p> * When this {@link Activity} is started, the last used (or the default) * {@link URI} is displayed to the user. * * @author ethan.rublee@gmail.com (Ethan Rublee) * @author damonkohler@google.com (Damon Kohler) * @author munjaldesai@google.com (Munjal Desai) */ public class MasterChooser extends AppCompatActivity { /** * The key with which the last used {@link URI} will be stored as a * preference. */ private static final String PREFS_KEY_NAME = "URI_KEY"; /** * Package name of the QR code reader used to scan QR codes. */ private static final String BAR_CODE_SCANNER_PACKAGE_NAME = "com.google.zxing.client.android.SCAN"; /** * Lookup text for catching a ConnectionException when attempting to * connect to a master. */ private static final String CONNECTION_EXCEPTION_TEXT = "ECONNREFUSED"; /** * Lookup text for catching a UnknownHostException when attemping to * connect to a master. */ private static final String UNKNOW_HOST_TEXT = "UnknownHost"; /** * Default port number for master URI. Apended if the URI does not * contain a port number. */ private static final int DEFAULT_PORT = 11311; /** *The preferences key used for obtaining the number of recent Master URIs. */ private static final String RECENT_COUNT_KEY_NAME = "RECENT_MASTER_URI_COUNT"; /** * The preference key prefix used for obtaining the recent Master URIs. */ private static final String RECENT_PREFIX_KEY_NAME = "RECENT_MASTER_URI_"; /** * Number of recent Master URIs to store into preferences. */ private static final int RECENT_MASTER_HISTORY_COUNT = 5; private String selectedInterface; private AutoCompleteTextView uriText; private Button connectButton; private LinearLayout connectionLayout; private class StableArrayAdapter extends ArrayAdapter<String> { HashMap<String, Integer> idMap = new HashMap<>(); public StableArrayAdapter(Context context, int textViewResourceId, List<String> objects) { super(context, textViewResourceId, objects); for (int i = 0; i < objects.size(); ++i) { idMap.put(objects.get(i), i); } } @Override public long getItemId(int position) { String item = getItem(position); return idMap.get(item); } @Override public boolean hasStableIds() { return true; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.master_chooser); final Pattern uriPattern = RosURIPattern.URI; uriText = findViewById(R.id.master_chooser_uri); connectButton = findViewById(R.id.master_chooser_ok); uriText.setThreshold(RosURIPattern.HTTP_PROTOCOL_LENGTH); ArrayAdapter<String> uriAdapter = new ArrayAdapter<> (this,android.R.layout.select_dialog_item,getRecentMasterURIs()); uriText.setAdapter(uriAdapter); uriText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { final String uri = s.toString(); if(!uriPattern.matcher(uri).matches()) { uriText.setError("Please enter valid URI"); connectButton.setEnabled(false); } else { uriText.setError(null); connectButton.setEnabled(true); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }); ListView interfacesList = findViewById(R.id.networkInterfaces); final List<String> list = new ArrayList<>(); try { for (NetworkInterface networkInterface : Collections.list(NetworkInterface.getNetworkInterfaces())) { if (networkInterface.isUp() && !networkInterface.isLoopback()) { list.add(networkInterface.getName()); } } } catch (SocketException e) { throw new RosRuntimeException(e); } // Fallback to previous behaviour when no interface is selected. selectedInterface = ""; final StableArrayAdapter adapter = new StableArrayAdapter(this, android.R.layout.simple_list_item_1, list); interfacesList.setAdapter(adapter); interfacesList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { selectedInterface = parent.getItemAtPosition(position).toString(); toast("Using " + selectedInterface + " interface."); } }); // Get the URI from preferences and display it. Since only primitive types // can be saved in preferences the URI is stored as a string. String uri = getPreferences(MODE_PRIVATE).getString(PREFS_KEY_NAME, NodeConfiguration.DEFAULT_MASTER_URI.toString()); uriText.setText(uri); connectionLayout = (LinearLayout) findViewById(R.id.connection_layout); } @Override public void onActivityResult(int requestCode, int resultCode, Intent intent) { // If the Barcode Scanner returned a string then display that string. if (requestCode == 0) { if (resultCode == RESULT_OK) { String scanResultFormat = intent.getStringExtra("SCAN_RESULT_FORMAT"); Preconditions.checkState(scanResultFormat.equals("TEXT_TYPE") || scanResultFormat.equals("QR_CODE")); String contents = intent.getStringExtra("SCAN_RESULT"); uriText.setText(contents); } } } @Override public void onBackPressed() { //Prevent user from going back to Launcher Activity since no Master is connected. this.moveTaskToBack(true); } public void okButtonClicked(View unused) { String tmpURI = uriText.getText().toString(); // Check to see if the URI has a port. final Pattern portPattern = RosURIPattern.PORT; if(!portPattern.matcher(tmpURI).find()) { // Append the default port to the URI and update the TextView. tmpURI = String.format(Locale.getDefault(),"%s:%d/",tmpURI,DEFAULT_PORT); uriText.setText(tmpURI); } // Set the URI for connection. final String uri = tmpURI; // Prevent further edits while we verify the URI. // Note: This was placed after the URI port check due to odd behavior // with setting the connectButton to disabled. uriText.setEnabled(false); connectButton.setEnabled(false); // Make sure the URI can be parsed correctly and that the master is // reachable. new AsyncTask<Void, Void, Boolean>() { @Override protected void onPreExecute() { runOnUiThread(new Runnable() { @Override public void run() { connectionLayout.setVisibility(View.VISIBLE); } }); } @Override protected Boolean doInBackground(Void... params) { try { MasterClient masterClient = new MasterClient(new URI(uri)); masterClient.getUri(GraphName.of("android/master_chooser_activity")); toast("Connected!"); return true; } catch (URISyntaxException e) { toast("Invalid URI."); return false; } catch (XmlRpcTimeoutException e) { toast("Master unreachable!"); return false; } catch (Exception e) { String exceptionMessage = e.getMessage(); if(exceptionMessage.contains(CONNECTION_EXCEPTION_TEXT)) toast("Unable to communicate with master!"); else if(exceptionMessage.contains(UNKNOW_HOST_TEXT)) toast("Unable to resolve URI hostname!"); else toast("Communication error!"); return false; } } @Override protected void onPostExecute(Boolean result) { runOnUiThread(new Runnable() { @Override public void run() { connectionLayout.setVisibility(View.GONE); } }); if (result) { //Update Recent Master URI addRecentMasterURI(uri); // If the displayed URI is valid then pack that into the intent. // Package the intent to be consumed by the calling activity. Intent intent = createNewMasterIntent(false, true); setResult(RESULT_OK, intent); finish(); } else { connectButton.setEnabled(true); uriText.setEnabled(true); } } }.execute(); } protected void toast(final String text) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MasterChooser.this, text, Toast.LENGTH_SHORT).show(); } }); } public void qrCodeButtonClicked(View unused) { Intent intent = new Intent(BAR_CODE_SCANNER_PACKAGE_NAME); intent.putExtra("SCAN_MODE", "QR_CODE_MODE"); // Check if the Barcode Scanner is installed. if (!isQRCodeReaderInstalled(intent)) { // Open the Market and take them to the page from which they can download the Barcode Scanner // app. startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.google.zxing.client.android"))); } else { // Call the Barcode Scanner to let the user scan a QR code. startActivityForResult(intent, 0); } } public void advancedCheckboxClicked(View view) { boolean checked = ((CheckBox) view).isChecked(); LinearLayout advancedOptions = (LinearLayout) findViewById(R.id.advancedOptions); if (checked) { advancedOptions.setVisibility(View.VISIBLE); } else { advancedOptions.setVisibility(View.GONE); } } public Intent createNewMasterIntent(boolean newMaster, boolean isPrivate) { Intent intent = new Intent(); final String uri = uriText.getText().toString(); intent.putExtra("ROS_MASTER_CREATE_NEW", newMaster); intent.putExtra("ROS_MASTER_PRIVATE", isPrivate); intent.putExtra("ROS_MASTER_URI", uri); intent.putExtra("ROS_MASTER_NETWORK_INTERFACE", selectedInterface); return intent; } public void newMasterButtonClicked(View unused) { setResult(RESULT_OK, createNewMasterIntent(true, false)); finish(); } public void newPrivateMasterButtonClicked(View unused) { setResult(RESULT_OK, createNewMasterIntent(true, true)); finish(); } public void cancelButtonClicked(View unused) { setResult(RESULT_CANCELED); finish(); } /** * Check if the specified app is installed. * * @param intent * The activity that you wish to look for. * @return true if the desired activity is install on the device, false * otherwise. */ protected boolean isQRCodeReaderInstalled(Intent intent) { List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); return (list.size() > 0); } /** * Adds the given URI to the list of recent Master URIs stored in shared preferences. * This implementation does not use * {@link android.content.SharedPreferences.Editor#putStringSet(String, Set)} * since it is not available in API 10. * @param uri Master URI string to store. */ private void addRecentMasterURI(String uri) { List<String> recentURIs = getRecentMasterURIs(); if (!recentURIs.contains(uri)) { recentURIs.add(0, uri); if (recentURIs.size() > RECENT_MASTER_HISTORY_COUNT) recentURIs = recentURIs.subList(0, RECENT_MASTER_HISTORY_COUNT); } SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit(); editor.putString(PREFS_KEY_NAME, uri); for (int i = 0; i < recentURIs.size(); i++) { editor.putString(RECENT_PREFIX_KEY_NAME + String.valueOf(i), recentURIs.get(i)); } editor.putInt(RECENT_COUNT_KEY_NAME, recentURIs.size()); editor.apply(); } /** * Gets a list of recent Master URIs from shared preferences. This implementation does not use * {@link android.content.SharedPreferences.Editor#putStringSet(String, Set)} * since it is not available in API 10. * @return List of recent Master URI strings */ private List<String> getRecentMasterURIs() { List<String> recentURIs; SharedPreferences prefs = getPreferences(MODE_PRIVATE); int numRecent = prefs.getInt(RECENT_COUNT_KEY_NAME, 0); recentURIs = new ArrayList<>(numRecent); for (int i = 0; i < numRecent; i++) { String uri = prefs.getString(RECENT_PREFIX_KEY_NAME + String.valueOf(i), ""); if (!uri.isEmpty()) { recentURIs.add(uri); } } return recentURIs; } /** * Regular expressions used with ROS URIs. * * The majority of the expressions and variables were copied from * {@link android.util.Patterns}. The {@link android.util.Patterns} class could not be * utilized because the PROTOCOL regex included other web protocols besides http. The * http protocol is required by ROS. */ private static class RosURIPattern { /* A word boundary or end of input. This is to stop foo.sure from matching as foo.su */ private static final String WORD_BOUNDARY = "(?:\\b|$|^)"; /** * Valid UCS characters defined in RFC 3987. Excludes space characters. */ private static final String UCS_CHAR = "[" + "\u00A0-\uD7FF" + "\uF900-\uFDCF" + "\uFDF0-\uFFEF" + "\uD800\uDC00-\uD83F\uDFFD" + "\uD840\uDC00-\uD87F\uDFFD" + "\uD880\uDC00-\uD8BF\uDFFD" + "\uD8C0\uDC00-\uD8FF\uDFFD" + "\uD900\uDC00-\uD93F\uDFFD" + "\uD940\uDC00-\uD97F\uDFFD" + "\uD980\uDC00-\uD9BF\uDFFD" + "\uD9C0\uDC00-\uD9FF\uDFFD" + "\uDA00\uDC00-\uDA3F\uDFFD" + "\uDA40\uDC00-\uDA7F\uDFFD" + "\uDA80\uDC00-\uDABF\uDFFD" + "\uDAC0\uDC00-\uDAFF\uDFFD" + "\uDB00\uDC00-\uDB3F\uDFFD" + "\uDB44\uDC00-\uDB7F\uDFFD" + "&&[^\u00A0[\u2000-\u200A]\u2028\u2029\u202F\u3000]]"; /** * Valid characters for IRI label defined in RFC 3987. */ private static final String LABEL_CHAR = "a-zA-Z0-9" + UCS_CHAR; /** * RFC 1035 Section 2.3.4 limits the labels to a maximum 63 octets. */ private static final String IRI_LABEL = "[" + LABEL_CHAR + "](?:[" + LABEL_CHAR + "\\-]{0,61}[" + LABEL_CHAR + "]){0,1}"; private static final Pattern IP_ADDRESS = Pattern.compile( "((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4]" + "[0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]" + "[0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}" + "|[1-9][0-9]|[0-9]))"); /** * Regular expression that matches domain names without a TLD */ private static final String RELAXED_DOMAIN_NAME = "(?:" + "(?:" + IRI_LABEL + "(?:\\.(?=\\S))" +"?)+" + "|" + IP_ADDRESS + ")"; private static final String HTTP_PROTOCOL = "(?i:http):\\/\\/"; public static final int HTTP_PROTOCOL_LENGTH = ("http://").length(); private static final String PORT_NUMBER = "\\:\\d{1,5}\\/?"; /** * Regular expression pattern to match valid rosmaster URIs. * This assumes the port number and trailing "/" will be auto * populated (default port: 11311) if left out. */ public static final Pattern URI = Pattern.compile("(" + WORD_BOUNDARY + "(?:" + "(?:" + HTTP_PROTOCOL + ")" + "(?:" + RELAXED_DOMAIN_NAME + ")" + "(?:" + PORT_NUMBER + ")?" + ")" + WORD_BOUNDARY + ")"); public static final Pattern PORT = Pattern.compile(PORT_NUMBER); } }
/* Derby - Class org.apache.derby.iapi.types.CollatorSQLClob 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.derby.iapi.types; import org.apache.derby.iapi.error.StandardException; import org.apache.derby.iapi.services.sanity.SanityManager; import java.text.RuleBasedCollator; /** * CollatorSQLClob class differs from SQLClob based on how the 2 classes * use different collations to collate their data. SQLClob uses Derby's * default collation which is UCS_BASIC. Whereas, this class uses the * RuleBasedCollator object that was passed to it in it's constructor and that * RuleBasedCollator object decides the collation. * * In Derby 10.3, this class will be passed a RuleBasedCollator which is based * on the database's territory. In future releases of Derby, this class can be * used to do other kinds of collations like case-insensitive collation etc by * just passing an appropriate RuleBasedCollator object for that kind of * collation. */ class CollatorSQLClob extends SQLClob implements CollationElementsInterface { private WorkHorseForCollatorDatatypes holderForCollationSensitiveInfo; /* * constructors */ /** * Create SQL CLOB value initially set to NULL that * performs collation according to collatorForCharacterDatatypes */ CollatorSQLClob(RuleBasedCollator collatorForCharacterDatatypes) { setCollator(collatorForCharacterDatatypes); } /** * Create SQL CLOB value initially set to value that * performs collation according to collatorForCharacterDatatypes */ CollatorSQLClob(String val, RuleBasedCollator collatorForCharacterDatatypes) { super(val); setCollator(collatorForCharacterDatatypes); } /** * Set the RuleBasedCollator for this instance of CollatorSQLClob. It will * be used to do the collation. */ private void setCollator(RuleBasedCollator collatorForCharacterDatatypes) { holderForCollationSensitiveInfo = new WorkHorseForCollatorDatatypes(collatorForCharacterDatatypes, this); } /** * Get the RuleBasedCollator for this instance of CollatorSQLClob. It * will be used to do the collation. * * @return The Collator object which should be used for collation * operation on this object */ protected RuleBasedCollator getCollatorForCollation() throws StandardException { return holderForCollationSensitiveInfo.getCollatorForCollation(); } /** @see CollationElementsInterface#getCollationElementsForString */ public int[] getCollationElementsForString() throws StandardException { return holderForCollationSensitiveInfo.getCollationElementsForString(); } /** @see CollationElementsInterface#getCountOfCollationElements */ public int getCountOfCollationElements() { return holderForCollationSensitiveInfo.getCountOfCollationElements(); } /* * DataValueDescriptor interface */ /** * @see DataValueDescriptor#getClone */ public DataValueDescriptor getClone() { try { return new CollatorSQLClob(getString(), holderForCollationSensitiveInfo.getCollatorForCollation()); } catch (StandardException se) { if (SanityManager.DEBUG) SanityManager.THROWASSERT("Unexpected exception", se); return null; } } /** * @see DataValueDescriptor#getNewNull */ public DataValueDescriptor getNewNull() { CollatorSQLClob result = new CollatorSQLClob(null, holderForCollationSensitiveInfo.getCollatorForCollation()); return result; } /** * We do not anticipate this method on collation sensitive DVD to be * ever called in Derby 10.3 In future, when Derby will start supporting * SQL standard COLLATE clause, this method might get called on the * collation sensitive DVDs. * * @see StringDataValue#getValue(RuleBasedCollator) */ public StringDataValue getValue(RuleBasedCollator collatorForComparison) { if (collatorForComparison != null) { //non-null collatorForComparison means use this collator sensitive //implementation of SQLClob setCollator(collatorForComparison); return this; } else { //null collatorForComparison means use UCS_BASIC for collation. //For that, we need to use the base class SQLClob SQLClob s = new SQLClob(); s.copyState(this); return s; } } /** @see SQLChar#stringCompare(SQLChar, SQLChar) */ protected int stringCompare(SQLChar char1, SQLChar char2) throws StandardException { return holderForCollationSensitiveInfo.stringCompare(char1, char2); } /** * Return a hash code that is consistent with * {@link #stringCompare(SQLChar, SQLChar)}. * * @return hash code */ public int hashCode() { return hashCodeForCollation(); } /** * This method implements the like function for char (with no escape value). * The difference in this method and the same method in superclass is that * here we use special Collator object to do the comparison rather than * using the Collator object associated with the default jvm locale. * * @param pattern The pattern to use * * @return A SQL boolean value telling whether the first operand is * like the second operand * * @exception StandardException Thrown on error */ public BooleanDataValue like(DataValueDescriptor pattern) throws StandardException { return(holderForCollationSensitiveInfo.like(pattern)); } /** * This method implements the like function for char with an escape value. * * @param pattern The pattern to use * * @return A SQL boolean value telling whether the first operand is * like the second operand * * @exception StandardException Thrown on error */ public BooleanDataValue like(DataValueDescriptor pattern, DataValueDescriptor escape) throws StandardException { return(holderForCollationSensitiveInfo.like(pattern, escape)); } }
package org.dbsyncer.storage.util; import org.apache.lucene.document.*; import org.dbsyncer.storage.constant.ConfigConstant; import org.springframework.util.Assert; import java.util.Map; /** * <b>索引维护工具类</b> * <p/>1、使用方法: * <p/> new IntPoint(name, value); 存放int类型 * <p/> new StoredField(name, value); 要存储值,必须添加一个同名的StoredField * <p/> new NumericDocValuesField(name, value); 要排序,必须添加一个同名的SortedNumericDocValuesField * <p/> 其他FloatPoint、LongPoint、DoublePoint同上 * <p/> id使用字符串,防止更新失败 * * <p/>2、Field: * <p/>IntPoint * <p/>FloatPoint * <p/>LongPoint * <p/>DoublePoint * <p/>BinaryPoint * <p/>StringField 索引不分词,所有的字符串会作为一个整体进行索引,例如通常用于country或id等 * <p/>TextField 索引并分词,不包括term vectors,例如通常用于一个body Field * <p/>StoredField 存储Field的值,可以用 IndexSearcher.doc和IndexReader.document来获取存储的Field和存储的值 * <p/>SortedDocValuesField 存储String、Text类型排序 * <p/>NumericDocValuesField 存储Int、Long类型索引并排序,用于评分、排序和值检索 * <p/>FloatDocValuesField 存储Float类型索引并排序 * <p/>DoubleDocValuesField 存储Double类型索引并排序 * <p/>BinaryDocValuesField 只存储不共享,例如标题类字段,如果需要共享并排序,推荐使用SortedDocValuesField * * <p/>3、Lucene 6.0版本后: * <p>IntField 替换为 IntPoint</p> * <p>FloatField 替换为 FloatPoint</p> * <p>LongField 替换为 LongPoint</p> * <p>DoubleField 替换为 DoublePoint</p> * * @author AE86 * @version 1.0.0 * @date 2019/11/19 22:07 */ public abstract class ParamsUtil { private ParamsUtil(){} public static Document convertConfig2Doc(Map params) { Assert.notNull(params, "Params can not be null."); Document doc = new Document(); String id = (String) params.get(ConfigConstant.CONFIG_MODEL_ID); String type = (String) params.get(ConfigConstant.CONFIG_MODEL_TYPE); String name = (String) params.get(ConfigConstant.CONFIG_MODEL_NAME); String json = (String) params.get(ConfigConstant.CONFIG_MODEL_JSON); Long createTime = (Long) params.get(ConfigConstant.CONFIG_MODEL_CREATE_TIME); Long updateTime = (Long) params.get(ConfigConstant.CONFIG_MODEL_UPDATE_TIME); doc.add(new StringField(ConfigConstant.CONFIG_MODEL_ID, id, Field.Store.YES)); doc.add(new StringField(ConfigConstant.CONFIG_MODEL_TYPE, type, Field.Store.YES)); doc.add(new TextField(ConfigConstant.CONFIG_MODEL_NAME, name, Field.Store.YES)); // 配置信息 doc.add(new StoredField(ConfigConstant.CONFIG_MODEL_JSON, json)); // 创建时间(不需要存储) doc.add(new LongPoint(ConfigConstant.CONFIG_MODEL_CREATE_TIME, createTime)); doc.add(new NumericDocValuesField(ConfigConstant.CONFIG_MODEL_CREATE_TIME, createTime)); // 修改时间(不需要存储) doc.add(new LongPoint(ConfigConstant.CONFIG_MODEL_UPDATE_TIME, updateTime)); doc.add(new NumericDocValuesField(ConfigConstant.CONFIG_MODEL_UPDATE_TIME, updateTime)); return doc; } public static Document convertLog2Doc(Map params) { Assert.notNull(params, "Params can not be null."); Document doc = new Document(); String id = (String) params.get(ConfigConstant.CONFIG_MODEL_ID); String type = (String) params.get(ConfigConstant.CONFIG_MODEL_TYPE); String json = (String) params.get(ConfigConstant.CONFIG_MODEL_JSON); Long createTime = (Long) params.get(ConfigConstant.CONFIG_MODEL_CREATE_TIME); doc.add(new StringField(ConfigConstant.CONFIG_MODEL_ID, id, Field.Store.YES)); doc.add(new StringField(ConfigConstant.CONFIG_MODEL_TYPE, type, Field.Store.YES)); // 日志信息 doc.add(new TextField(ConfigConstant.CONFIG_MODEL_JSON, json, Field.Store.YES)); // 创建时间 doc.add(new LongPoint(ConfigConstant.CONFIG_MODEL_CREATE_TIME, createTime)); doc.add(new StoredField(ConfigConstant.CONFIG_MODEL_CREATE_TIME, createTime)); doc.add(new NumericDocValuesField(ConfigConstant.CONFIG_MODEL_CREATE_TIME, createTime)); return doc; } public static Document convertData2Doc(Map params) { Assert.notNull(params, "Params can not be null."); Document doc = new Document(); String id = (String) params.get(ConfigConstant.CONFIG_MODEL_ID); Integer success = (Integer) params.get(ConfigConstant.DATA_SUCCESS); String event = (String) params.get(ConfigConstant.DATA_EVENT); String error = (String) params.get(ConfigConstant.DATA_ERROR); String json = (String) params.get(ConfigConstant.CONFIG_MODEL_JSON); Long createTime = (Long) params.get(ConfigConstant.CONFIG_MODEL_CREATE_TIME); doc.add(new StringField(ConfigConstant.CONFIG_MODEL_ID, id, Field.Store.YES)); doc.add(new IntPoint(ConfigConstant.DATA_SUCCESS, success)); doc.add(new StoredField(ConfigConstant.DATA_SUCCESS, success)); doc.add(new StringField(ConfigConstant.DATA_EVENT, event, Field.Store.YES)); doc.add(new TextField(ConfigConstant.DATA_ERROR, error, Field.Store.YES)); doc.add(new StoredField(ConfigConstant.CONFIG_MODEL_JSON, json)); // 创建时间 doc.add(new LongPoint(ConfigConstant.CONFIG_MODEL_CREATE_TIME, createTime)); doc.add(new StoredField(ConfigConstant.CONFIG_MODEL_CREATE_TIME, createTime)); doc.add(new NumericDocValuesField(ConfigConstant.CONFIG_MODEL_CREATE_TIME, createTime)); return doc; } }
/* * 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.shardingsphere.shadow.distsql.parser.statement; import lombok.Getter; import lombok.RequiredArgsConstructor; import org.apache.shardingsphere.distsql.parser.statement.rdl.alter.AlterRuleStatement; import org.apache.shardingsphere.shadow.distsql.parser.segment.ShadowAlgorithmSegment; import java.util.Collection; /** * Alter shadow algorithm statement. */ @RequiredArgsConstructor @Getter public final class AlterShadowAlgorithmStatement extends AlterRuleStatement { private final Collection<ShadowAlgorithmSegment> algorithms; }
package ru.job4j.iterator; import org.junit.Before; import org.junit.Test; import java.util.Iterator; import java.util.NoSuchElementException; import static junit.framework.TestCase.assertTrue; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * Test. * * @author Yury Doronin (doronin.ltd@gmail.com) * @version 1.0 * @since 30.05.2019 */ public class IteratorEvenTest { private Iterator<Integer> it; @Before public void setUp() { it = new IteratorEven(new int[]{1, 2, 3, 4, 5, 6, 7}); } @Test(expected = NoSuchElementException.class) public void shouldReturnEvenNumbersSequentially() { assertThat(it.hasNext(), is(true)); assertThat(it.next(), is(2)); assertThat(it.hasNext(), is(true)); assertThat(it.next(), is(4)); assertThat(it.hasNext(), is(true)); assertThat(it.next(), is(6)); assertThat(it.hasNext(), is(false)); it.next(); } @Test public void sequentialHasNextInvocationDoesntAffectRetrievalOrder() { assertThat(it.hasNext(), is(true)); assertThat(it.hasNext(), is(true)); assertThat(it.next(), is(2)); assertThat(it.next(), is(4)); assertThat(it.next(), is(6)); } @Test public void shouldReturnFalseIfNoAnyEvenNumbers() { it = new IteratorEven(new int[]{1}); assertThat(it.hasNext(), is(false)); } @Test public void allNumbersAreEven() { it = new IteratorEven(new int[]{2, 4, 6, 8}); assertThat(it.hasNext(), is(true)); assertThat(it.next(), is(2)); assertThat(it.hasNext(), is(true)); assertThat(it.next(), is(4)); assertThat(it.hasNext(), is(true)); assertThat(it.next(), is(6)); assertThat(it.hasNext(), is(true)); assertThat(it.next(), is(8)); } @Test public void whenThen() { IteratorEven it = new IteratorEven(new int[] {4, 1, 1, 1}); assertTrue(it.hasNext()); assertTrue(it.hasNext()); assertTrue(it.hasNext()); assertTrue(it.hasNext()); } @Test public void whenIteratorNextThenEven() { IteratorEven it = new IteratorEven(new int[]{4, 2, 1, 1}); it.next(); int result = it.next(); assertThat(result, is(2)); } @Test (expected = NoSuchElementException.class) public void whenIteratorNextThenZero() { IteratorEven it = new IteratorEven(new int[]{4, 2, 1, 1}); assertThat(it.hasNext(), is(true)); assertThat(it.next(), is(4)); assertThat(it.hasNext(), is(true)); assertThat(it.next(), is(2)); assertThat(it.hasNext(), is(false)); it.next(); } @Test public void whenIteratorHasNextThenTrue() { IteratorEven it = new IteratorEven(new int[]{4, 2, 1, 1}); it.next(); boolean result = it.hasNext(); assertThat(result, is(true)); } @Test public void whenIteratorHasNextThenFalse() { IteratorEven it = new IteratorEven(new int[]{4, 2, 1, 1}); it.next(); it.next(); boolean result = it.hasNext(); assertThat(result, is(false)); } }
/* * Copyright © Red Gate Software Ltd 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.flywaydb.core.internal.resource; import org.flywaydb.core.api.resource.Resource; import org.flywaydb.core.api.ResourceProvider; import java.util.Collection; import java.util.Collections; /** * No-op resource provider. */ public enum NoopResourceProvider implements ResourceProvider { INSTANCE; @Override public Resource getResource( String name) { return null; } /** * Retrieve all resources whose name begins with this prefix and ends with any of these suffixes. * * @param prefix The prefix. * @param suffixes The suffixes. * @return The matching resources. */ public Collection<Resource> getResources(String prefix, String[] suffixes) { return Collections.emptyList(); } }
package com.oneso.service; public interface ScannerService { String scanAnswer(); void closeScanner(); }
/** * MIT License * * Copyright (c) 2018 yadong.zhang * * 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.zyd.blog.framework.config; import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer; import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer; import org.springframework.boot.web.servlet.ErrorPage; import org.springframework.context.annotation.Bean; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; /** * 自定义的异常页面配置 * * @author zhrey * @website http://www.zhrey.cn * @date 2018/4/16 16:26 */ @Component public class ErrorPagesConfig { /** * 自定义异常处理路径 * * @return */ @Bean public EmbeddedServletContainerCustomizer containerCustomizer() { return new EmbeddedServletContainerCustomizer() { @Override public void customize(ConfigurableEmbeddedServletContainer configurableEmbeddedServletContainer) { configurableEmbeddedServletContainer.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/error/400")); configurableEmbeddedServletContainer.addErrorPages(new ErrorPage(HttpStatus.UNAUTHORIZED, "/error/401")); configurableEmbeddedServletContainer.addErrorPages(new ErrorPage(HttpStatus.FORBIDDEN, "/error/403")); configurableEmbeddedServletContainer.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/error/404")); configurableEmbeddedServletContainer.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500")); configurableEmbeddedServletContainer.addErrorPages(new ErrorPage(Throwable.class, "/error/500")); } }; } }
package com.github.scribejava.core.extractors; import java.io.IOException; import java.net.URI; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.github.scribejava.core.exceptions.OAuthException; import com.github.scribejava.core.model.OAuth2AccessToken; import com.github.scribejava.core.model.OAuth2AccessTokenErrorResponse; import com.github.scribejava.core.model.Response; import com.github.scribejava.core.oauth2.OAuth2Error; import com.github.scribejava.core.utils.Preconditions; /** * JSON (default) implementation of {@link TokenExtractor} for OAuth 2.0 */ public class OAuth2AccessTokenJsonExtractor implements TokenExtractor<OAuth2AccessToken> { private static final Pattern ACCESS_TOKEN_REGEX_PATTERN = Pattern.compile("\"access_token\"\\s*:\\s*\"(\\S*?)\""); private static final Pattern TOKEN_TYPE_REGEX_PATTERN = Pattern.compile("\"token_type\"\\s*:\\s*\"(\\S*?)\""); private static final Pattern EXPIRES_IN_REGEX_PATTERN = Pattern.compile("\"expires_in\"\\s*:\\s*\"?(\\d*?)\"?\\D"); private static final Pattern REFRESH_TOKEN_REGEX_PATTERN = Pattern.compile("\"refresh_token\"\\s*:\\s*\"(\\S*?)\""); private static final Pattern SCOPE_REGEX_PATTERN = Pattern.compile("\"scope\"\\s*:\\s*\"([^\"]*?)\""); private static final Pattern ERROR_REGEX_PATTERN = Pattern.compile("\"error\"\\s*:\\s*\"(\\S*?)\""); private static final Pattern ERROR_DESCRIPTION_REGEX_PATTERN = Pattern.compile("\"error_description\"\\s*:\\s*\"([^\"]*?)\""); private static final Pattern ERROR_URI_REGEX_PATTERN = Pattern.compile("\"error_uri\"\\s*:\\s*\"(\\S*?)\""); protected OAuth2AccessTokenJsonExtractor() { } private static class InstanceHolder { private static final OAuth2AccessTokenJsonExtractor INSTANCE = new OAuth2AccessTokenJsonExtractor(); } public static OAuth2AccessTokenJsonExtractor instance() { return InstanceHolder.INSTANCE; } @Override public OAuth2AccessToken extract(Response response) throws IOException { final String body = response.getBody(); Preconditions.checkEmptyString(body, "Response body is incorrect. Can't extract a token from an empty string"); if (response.getCode() != 200) { generateError(body); } return createToken(body); } /** * Related documentation: https://tools.ietf.org/html/rfc6749#section-5.2 * * @param response response */ public void generateError(String response) { final String errorInString = extractParameter(response, ERROR_REGEX_PATTERN, true); final String errorDescription = extractParameter(response, ERROR_DESCRIPTION_REGEX_PATTERN, false); final String errorUriInString = extractParameter(response, ERROR_URI_REGEX_PATTERN, false); URI errorUri; try { errorUri = errorUriInString == null ? null : URI.create(errorUriInString); } catch (IllegalArgumentException iae) { errorUri = null; } OAuth2Error errorCode; try { errorCode = OAuth2Error.parseFrom(errorInString); } catch (IllegalArgumentException iaE) { //non oauth standard error code errorCode = null; } throw new OAuth2AccessTokenErrorResponse(errorCode, errorDescription, errorUri, response); } private OAuth2AccessToken createToken(String response) { final String accessToken = extractParameter(response, ACCESS_TOKEN_REGEX_PATTERN, true); final String tokenType = extractParameter(response, TOKEN_TYPE_REGEX_PATTERN, false); final String expiresInString = extractParameter(response, EXPIRES_IN_REGEX_PATTERN, false); Integer expiresIn; try { expiresIn = expiresInString == null ? null : Integer.valueOf(expiresInString); } catch (NumberFormatException nfe) { expiresIn = null; } final String refreshToken = extractParameter(response, REFRESH_TOKEN_REGEX_PATTERN, false); final String scope = extractParameter(response, SCOPE_REGEX_PATTERN, false); return createToken(accessToken, tokenType, expiresIn, refreshToken, scope, response); } protected OAuth2AccessToken createToken(String accessToken, String tokenType, Integer expiresIn, String refreshToken, String scope, String response) { return new OAuth2AccessToken(accessToken, tokenType, expiresIn, refreshToken, scope, response); } protected static String extractParameter(String response, Pattern regexPattern, boolean required) throws OAuthException { final Matcher matcher = regexPattern.matcher(response); if (matcher.find()) { return matcher.group(1); } if (required) { throw new OAuthException("Response body is incorrect. Can't extract a '" + regexPattern.pattern() + "' from this: '" + response + "'", null); } return null; } }
/** * Copyright 2013 Canada Health Infoway, 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. * * Author: $LastChangedBy$ * Last modified: $LastChangedDate$ * Revision: $LastChangedRevision$ */ /* This class was auto-generated by the message builder generator tools. */ package ca.infoway.messagebuilder.model.ab_mr2009_r02_04_03_imm.domainvalue; import ca.infoway.messagebuilder.Code; public interface ParticipationSubset extends Code { }
import java.io.IOException; import java.io.FileInputStream; import java.io.FileOutputStream; //Just reading bytes public class FileStreams { public static void main(String[] args) throws Exception { FileInputStream input = null; FileOutputStream output = null; //Byte per Byte try { input = new FileInputStream("listofFigures.txt"); output = new FileOutputStream("listofFigures_out.txt"); int character; while( (character = input.read()) != -1 ){ System.out.printf("0x%02X",character); System.out.print("\n"); output.write(character); } } finally { if (input != null){ input.close(); } if (output != null){ input.close(); } } } }
package com.idtk.smallchart.interfaces.iData; import android.graphics.RectF; /** * Created by Idtk on 2016/6/22. * Blog : http://www.idtkm.com * GitHub : https://github.com/Idtk * 描述 : 扇形图坐标系数据接口 */ public interface IPieAxisData extends IChartData { /** * 获取透明扇形内半径与扇形半径比 * @return 比例 */ float getInsideRadiusScale(); /** * 设置透明扇形内半径与扇形半径比 * @param insideRadiusScale 比例 */ void setInsideRadiusScale(float insideRadiusScale); /** * 获取透明扇形外半径与扇形半径比 * @return 比例 */ float getOutsideRadiusScale(); /** * 设置透明扇形外半径与扇形半径比 * @param outsideRadiusScale 比例 */ void setOutsideRadiusScale(float outsideRadiusScale); /** * 获取点击后偏移扇形的半径与扇形半径比 * @return 比例 */ float getOffsetRadiusScale(); /** * 设置点击后偏移扇形的半径与扇形半径比 * @param offsetRadiusScale 比例 */ void setOffsetRadiusScale(float offsetRadiusScale); /** * 获取扇形图的起始角度 * @return 角度 */ float getStartAngle(); /** * 设置扇形图的起始角度 * @param startAngle 角度 */ void setStartAngle(float startAngle); /** * 获取扇形图显示单个扇形区域百分比时,大于的最小角度 * @return 角度 */ float getMinAngle(); /** * 设置扇形图显示单个扇形区域百分比文本时,必须大于的最小角度 * @param minAngle 角度 */ void setMinAngle(float minAngle); /** * 获取显示百分比数值的需要设置小数位数 * @return 小数位数 */ int getDecimalPlaces(); /** * 设置显示百分比数值的需要设置小数位数 * @param decimalPlaces 小数位数 */ void setDecimalPlaces(int decimalPlaces); /** * 扇形区域的起始角度集合 * @return 集合 */ float[] getStartAngles(); /** * 扇形区域的起始角度集合 * @param startAngles 集合 */ void setStartAngles(float[] startAngles); /** * 获取正常的扇形图的矩形、透明扇形图内外矩形 * @return 矩形集合 */ RectF[] getRectFs(); /** * 设置正常的扇形图的矩形、透明扇形图内外矩形 * @param rectFs 矩形集合 */ void setRectFs(RectF[] rectFs); /** * 获取偏移的扇形图的矩形、透明扇形图内外矩形 * @return 矩形集合 */ RectF[] getOffsetRectFs(); /** * 设置偏移的扇形图的矩形、透明扇形图内外矩形 * @param offsetRectFs 矩形集合 */ void setOffsetRectFs(RectF[] offsetRectFs); /** * 获取扇形图半径 * @return 半径 */ float getAxisLength(); /** * 设置扇形图半径 * @param axisLength 半径 */ void setAxisLength(float axisLength); }
package io.github.shyrkaio.crd; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import io.fabric8.kubernetes.client.CustomResourceList; import io.quarkus.runtime.annotations.RegisterForReflection; @JsonDeserialize @RegisterForReflection public class HypnosList extends CustomResourceList<Hypnos> { /** * */ private static final long serialVersionUID = 1696633306337049795L; }
/* * 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.zookeeper; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hbase.classification.InterfaceAudience; import org.apache.hadoop.hbase.Stoppable; import org.apache.hadoop.hbase.util.Bytes; import org.apache.zookeeper.KeeperException; /** * Handles coordination of a single "leader" instance among many possible * candidates. The first {@link ZKLeaderManager} to successfully create * the given znode becomes the leader, allowing the instance to continue * with whatever processing must be protected. Other {@link ZKLeaderManager} * instances will wait to be notified of changes to the leader znode. * If the current master instance fails, the ephemeral leader znode will * be removed, and all waiting instances will be notified, with the race * to claim the leader znode beginning all over again. * @deprecated Not used */ @Deprecated @InterfaceAudience.Private public class ZKLeaderManager extends ZooKeeperListener { private static Log LOG = LogFactory.getLog(ZKLeaderManager.class); private final AtomicBoolean leaderExists = new AtomicBoolean(); private String leaderZNode; private byte[] nodeId; private Stoppable candidate; public ZKLeaderManager(ZooKeeperWatcher watcher, String leaderZNode, byte[] identifier, Stoppable candidate) { super(watcher); this.leaderZNode = leaderZNode; this.nodeId = identifier; this.candidate = candidate; } public void start() { try { watcher.registerListener(this); String parent = ZKUtil.getParent(leaderZNode); if (ZKUtil.checkExists(watcher, parent) < 0) { ZKUtil.createWithParents(watcher, parent); } } catch (KeeperException ke) { watcher.abort("Unhandled zk exception when starting", ke); candidate.stop("Unhandled zk exception starting up: "+ke.getMessage()); } } @Override public void nodeCreated(String path) { if (leaderZNode.equals(path) && !candidate.isStopped()) { handleLeaderChange(); } } @Override public void nodeDeleted(String path) { if (leaderZNode.equals(path) && !candidate.isStopped()) { handleLeaderChange(); } } private void handleLeaderChange() { try { synchronized(leaderExists) { if (ZKUtil.watchAndCheckExists(watcher, leaderZNode)) { LOG.info("Found new leader for znode: "+leaderZNode); leaderExists.set(true); } else { LOG.info("Leader change, but no new leader found"); leaderExists.set(false); leaderExists.notifyAll(); } } } catch (KeeperException ke) { watcher.abort("ZooKeeper error checking for leader znode", ke); candidate.stop("ZooKeeper error checking for leader: "+ke.getMessage()); } } /** * Blocks until this instance has claimed the leader ZNode in ZooKeeper */ public void waitToBecomeLeader() { while (!candidate.isStopped()) { try { if (ZKUtil.createEphemeralNodeAndWatch(watcher, leaderZNode, nodeId)) { // claimed the leader znode leaderExists.set(true); if (LOG.isDebugEnabled()) { LOG.debug("Claimed the leader znode as '"+ Bytes.toStringBinary(nodeId)+"'"); } return; } // if claiming the node failed, there should be another existing node byte[] currentId = ZKUtil.getDataAndWatch(watcher, leaderZNode); if (currentId != null && Bytes.equals(currentId, nodeId)) { // claimed with our ID, but we didn't grab it, possibly restarted? LOG.info("Found existing leader with our ID ("+ Bytes.toStringBinary(nodeId)+"), removing"); ZKUtil.deleteNode(watcher, leaderZNode); leaderExists.set(false); } else { LOG.info("Found existing leader with ID: "+Bytes.toStringBinary(nodeId)); leaderExists.set(true); } } catch (KeeperException ke) { watcher.abort("Unexpected error from ZK, stopping candidate", ke); candidate.stop("Unexpected error from ZK: "+ke.getMessage()); return; } // wait for next chance synchronized(leaderExists) { while (leaderExists.get() && !candidate.isStopped()) { try { leaderExists.wait(); } catch (InterruptedException ie) { LOG.debug("Interrupted waiting on leader", ie); } } } } } /** * Removes the leader znode, if it is currently claimed by this instance. */ public void stepDownAsLeader() { try { synchronized(leaderExists) { if (!leaderExists.get()) { return; } byte[] leaderId = ZKUtil.getData(watcher, leaderZNode); if (leaderId != null && Bytes.equals(nodeId, leaderId)) { LOG.info("Stepping down as leader"); ZKUtil.deleteNodeFailSilent(watcher, leaderZNode); leaderExists.set(false); } else { LOG.info("Not current leader, no need to step down"); } } } catch (KeeperException ke) { watcher.abort("Unhandled zookeeper exception removing leader node", ke); candidate.stop("Unhandled zookeeper exception removing leader node: " + ke.getMessage()); } catch (InterruptedException e) { watcher.abort("Unhandled zookeeper exception removing leader node", e); candidate.stop("Unhandled zookeeper exception removing leader node: " + e.getMessage()); } } public boolean hasLeader() { return leaderExists.get(); } }
package common.sink; import common.Constants; import common.collections.Configuration; import common.collections.OsUtils; import common.datatype.util.LRTopologyControl; import common.sink.helper.stable_sink_helper; import components.operators.api.BaseSink; import execution.ExecutionGraph; import execution.runtime.tuple.impl.Tuple; import execution.runtime.tuple.impl.msgs.GeneralMsg; import org.apache.commons.math.stat.descriptive.DescriptiveStatistics; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import utils.AppConfig; import utils.SINK_CONTROL; import java.io.*; import java.util.ArrayDeque; import java.util.HashMap; import static common.CONTROL.*; import static common.Constants.STAT_Path; import static common.IRunner.CCOption_SStore; public class MeasureSink extends BaseSink { private static final Logger LOG = LoggerFactory.getLogger(MeasureSink.class); private static final DescriptiveStatistics latency = new DescriptiveStatistics(); private static final long serialVersionUID = 6249684803036342603L; protected static String directory; protected final ArrayDeque<Long> latency_map = new ArrayDeque(); public int checkpoint_interval; protected stable_sink_helper helper; protected int ccOption; public int tthread; int cnt = 0; long start; public int totalEvents; public MeasureSink() { super(new HashMap<>()); this.input_selectivity.put(Constants.DEFAULT_STREAM_ID, 1.0); this.input_selectivity.put(LRTopologyControl.TOLL_NOTIFICATIONS_STREAM_ID, 1.0); } @Override public Integer default_scale(Configuration conf) { int numNodes = conf.getInt("num_socket", 1); return 1; } public void initialize(int task_Id_InGroup, int thisTaskId, ExecutionGraph graph) { super.initialize(task_Id_InGroup, thisTaskId, graph); int size = graph.getSink().operator.getExecutorList().size(); ccOption = config.getInt("CCOption", 0); String path = config.getString("metrics.output"); helper = new stable_sink_helper(LOG , config.getInt("runtimeInSeconds") , path , config.getDouble("predict", 0) , size , thisTaskId , config.getBoolean("measure", false)); // directory = STAT_Path // + OsUtils.OS_wrapper(configPrefix) // + OsUtils.OS_wrapper(String.valueOf(config.getInt("checkpoint"))); // File file = new File(directory); // if (!file.mkdirs()) { // } totalEvents = config.getInt("totalEvents"); tthread = config.getInt("tthread"); String statsFolderPattern = OsUtils.osWrapperPostFix(config.getString("rootFilePath")) + OsUtils.osWrapperPostFix("stats") + OsUtils.osWrapperPostFix("%s") + OsUtils.osWrapperPostFix("%s") + OsUtils.osWrapperPostFix("threads = %d") + OsUtils.osWrapperPostFix("totalEvents = %d") + OsUtils.osWrapperPostFix("%d_%d_%d_%d_%d_%d_%s_%d.latency"); String scheduler = config.getString("scheduler"); if (config.getInt("CCOption") == CCOption_SStore) { scheduler = "PAT"; } // TODO: to be refactored if (config.getString("common").equals("StreamLedger")) { directory = String.format(statsFolderPattern, config.getString("common"), scheduler, tthread, totalEvents, config.getInt("NUM_ITEMS"), config.getInt("Ratio_Of_Deposit"), config.getInt("State_Access_Skewness"), config.getInt("Ratio_of_Overlapped_Keys"), config.getInt("Ratio_of_Transaction_Aborts"), config.getInt("Transaction_Length"), AppConfig.isCyclic, config.getInt("complexity")); } else if (config.getString("common").equals("GrepSum")) { directory = String.format(statsFolderPattern, config.getString("common"), scheduler, tthread, totalEvents, config.getInt("NUM_ITEMS"), config.getInt("NUM_ACCESS"), config.getInt("State_Access_Skewness"), config.getInt("Ratio_of_Overlapped_Keys"), config.getInt("Ratio_of_Transaction_Aborts"), config.getInt("Transaction_Length"), AppConfig.isCyclic, config.getInt("complexity")); } else if (config.getString("common").equals("OnlineBiding")){ directory = String.format(statsFolderPattern, config.getString("common"), scheduler, tthread, totalEvents, config.getInt("NUM_ITEMS"), config.getInt("NUM_ACCESS"), config.getInt("State_Access_Skewness"), config.getInt("Ratio_of_Overlapped_Keys"), config.getInt("Ratio_of_Transaction_Aborts"), config.getInt("Transaction_Length"), AppConfig.isCyclic, config.getInt("complexity")); } else if (config.getString("common").equals("TollProcessing")){ directory = String.format(statsFolderPattern, config.getString("common"), scheduler, tthread, totalEvents, config.getInt("NUM_ITEMS"), config.getInt("NUM_ACCESS"), config.getInt("State_Access_Skewness"), config.getInt("Ratio_of_Overlapped_Keys"), config.getInt("Ratio_of_Transaction_Aborts"), config.getInt("Transaction_Length"), AppConfig.isCyclic, config.getInt("complexity")); } else { throw new UnsupportedOperationException(); } File file = new File(directory); file.mkdirs(); if (file.exists()) file.delete(); try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } SINK_CONTROL.getInstance().config(); tthread = this.config.getInt("tthread"); totalEvents = config.getInt("totalEvents"); if (enable_log) LOG.info("expected last events = " + totalEvents); } @Override public void execute(Tuple input) throws InterruptedException { check(cnt, input); cnt++; } protected void latency_measure(Tuple input) { cnt++; if (enable_latency_measurement) { // if (cnt == 1) { // start = System.nanoTime(); // } else { // if (cnt % checkpoint_interval == 0) { // final long end = System.nanoTime(); // final long process_latency = end - start;//ns // latency_map.add(process_latency / checkpoint_interval); // start = end; // } // } latency_map.add(System.nanoTime() - input.getLong(1)); } } protected void check(int cnt, Tuple input) { if (cnt == 0) { helper.StartMeasurement(); } else if (cnt == (totalEvents - 40 * 10 - 1)) { double results = helper.EndMeasurement(cnt); this.setResults(results); if (!enable_engine)//performance measure for TStream is different. if (enable_log) LOG.info("Received:" + cnt + " throughput:" + results); if (thisTaskId == graph.getSink().getExecutorID()) { measure_end(results); } } } /** * Only one sink will do the measure_end. * * @param results */ protected void measure_end(double results) { if (enable_log) LOG.info(Thread.currentThread().getName() + " obtains lock"); if (enable_latency_measurement) { StringBuilder sb = new StringBuilder(); for (Long entry : latency_map) { latency.addValue((entry / 1E6)); } try { FileWriter f = null; f = new FileWriter(new File(directory)); Writer w = new BufferedWriter(f); for (double percentile = 0.5; percentile <= 100.0; percentile += 0.5) { w.write(latency.getPercentile(percentile) + "\n"); } sb.append("=======Details======="); sb.append("\n" + latency.toString() + "\n"); sb.append("===99th===" + "\n"); sb.append(latency.getPercentile(99) + "\n"); w.write(sb.toString()); w.close(); f.close(); } catch (IOException e) { e.printStackTrace(); } if (enable_log) LOG.info(sb.toString()); } SINK_CONTROL.getInstance().throughput = results; if (enable_log) LOG.info("Thread:" + thisTaskId + " is going to stop all threads sequentially"); context.Sequential_stopAll(); SINK_CONTROL.getInstance().unlock(); } @Override protected Logger getLogger() { return LOG; } }
package adapter; import java.util.LinkedHashMap; import exception.AutoException; import model.*; import util.FileIO; public abstract class ProxyAutomotive { private static LinkedHashMap<String, Automobile> a1 = new LinkedHashMap<String, Automobile>();; public static synchronized Automobile getAutomobile(String carName) { return a1.get(carName); } public synchronized void updateOptionSetName(String carName, String optionSetName, String newName) throws AutoException { Automobile a1 = getAutomobile(carName); if (a1 != null) a1.updateOptionSetName(newName, optionSetName); } public synchronized void updateOptionName(String carName, String optionSetName, String optionName, String newOptionName) throws AutoException { Automobile a1 = getAutomobile(carName); if (a1 != null) a1.updateOptionName(optionSetName, optionName, newOptionName); } public synchronized void updateOptionChoice(String carName, String optionSetName, String optionChoice) throws AutoException { Automobile a1 = getAutomobile(carName); if (a1 != null) a1.updateOptionChoice(optionSetName, optionChoice); } public synchronized void chooseOption(String carName, String optionSetName, String optionName) throws AutoException { Automobile a1 = getAutomobile(carName); if (a1 != null) a1.setOptionChoice(optionSetName, optionName); } public synchronized void updateOptionPrice(String carName, String optionSetName, String optionName, double newPrice) throws AutoException { Automobile a1 = getAutomobile(carName); if (a1 != null) a1.updateOptionPrice(optionSetName, optionName, newPrice); } public synchronized void buildAuto(String fileName) throws AutoException{ FileIO IO = new FileIO(); Automobile auto = IO.buildAuto(fileName); a1.put(auto.getName(), auto); } public synchronized void buildAuto(String carName, String fileName) throws AutoException{ FileIO IO = new FileIO(); a1.put(carName,IO.buildAuto(fileName)); } /* public synchronized void buildAuto(String fileName, LinkedHashMap<String, Automobile> autoList) { FileIO f = new FileIO(); try { Automobile auto = f.buildAuto(fileName); autoList.put(auto.getName(), auto); } catch (AutoException e) { e.printStackTrace(); } } */ public synchronized void printAuto(String modelName, String fileName) { FileIO IO = new FileIO(); IO.print(a1.get(modelName), fileName); } public synchronized void printAuto(String name) { getAutomobile(name).print(); } public synchronized void printAuto() { a1.forEach((key,value) -> { System.out.println("model:" + key); value.printDetail(); }); } public synchronized void fix(int errorNo) { new AutoException(errorNo).fix(); } public synchronized void addAutomobile(Automobile auto) { a1.put(auto.getModel(), auto); } public synchronized LinkedHashMap<String, Automobile> getA1() { return a1; } public synchronized void setA1(LinkedHashMap<String, Automobile> a1) { this.a1 = a1; } }
package com.semantalytics.stardog.kibble.file; import com.complexible.common.rdf.model.Values; import com.complexible.stardog.plan.filter.ExpressionEvaluationException; import com.complexible.stardog.plan.filter.ExpressionVisitor; import com.complexible.stardog.plan.filter.functions.AbstractFunction; import com.complexible.stardog.plan.filter.functions.Function; import com.complexible.stardog.plan.filter.functions.UserDefinedFunction; import org.openrdf.model.Value; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.stream.Collectors; public final class Read extends AbstractFunction implements UserDefinedFunction { Read() { super(1, FileVocabulary.read.stringValue()); } private Read(final Read cat) { super(cat); } @Override protected Value internalEvaluate(final Value... values) throws ExpressionEvaluationException { assertIRI(values[0]); assertStringLiteral(values[1]); final URLConnection conn; final String text; try { conn = new URL(values[0].stringValue()).openConnection(); } catch(IOException e) { throw new ExpressionEvaluationException(e); } try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"))) { text = reader.lines().collect(Collectors.joining("\n")); } catch (IOException e) { throw new ExpressionEvaluationException(e); } return Values.literal(text); } @Override public Function copy() { return new Read(this); } @Override public void accept(final ExpressionVisitor expressionVisitor) { expressionVisitor.visit(this); } @Override public String toString() { return FileVocabulary.read.name(); } }
package com.feng.boot.admin.project.system.role.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.feng.boot.admin.project.system.role.model.entity.RoleDeptEntity; /** * 角色数据权限 Mapper 接口 * * @author bing_huang * @since 3.0.0 */ public interface IRoleDeptMapper extends BaseMapper<RoleDeptEntity> { }
package weixin.idea.huodong.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.jeecgframework.core.common.controller.BaseController; import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery; import org.jeecgframework.core.common.model.json.AjaxJson; import org.jeecgframework.core.common.model.json.DataGrid; import org.jeecgframework.core.constant.Globals; import org.jeecgframework.core.util.MyBeanUtils; import org.jeecgframework.core.util.ResourceUtil; import org.jeecgframework.core.util.StringUtil; import org.jeecgframework.tag.core.easyui.TagUtil; import org.jeecgframework.web.system.service.SystemService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import weixin.idea.huodong.entity.PrizeRecordEntity; import weixin.idea.huodong.service.PrizeRecordServiceI; /** * @Title: Controller * @Description: 中奖纪录 * @author zhangdaihao * @date 2014-06-08 14:28:28 * @version V1.0 * */ @Controller @RequestMapping("/prizeRecordController") public class PrizeRecordController extends BaseController { /** * Logger for this class */ private static final Logger logger = Logger.getLogger(PrizeRecordController.class); @Autowired private PrizeRecordServiceI prizeRecordService; @Autowired private SystemService systemService; private String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } /** * 中奖纪录列表 页面跳转 * * @return */ @RequestMapping(params = "goPrizeRecord") public ModelAndView goPrizeRecord(HttpServletRequest request) { String hdId = request.getParameter("hdId"); request.setAttribute("hdId", hdId); return new ModelAndView("weixin/idea/huodong/prizerecord/prizeRecordList"); } /** * easyui AJAX请求数据 * * @param request * @param response * @param dataGrid * @param user */ @RequestMapping(params = "datagrid") public void datagrid(PrizeRecordEntity prizeRecord,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) { String hdid = request.getParameter("hdid"); org.jeecgframework.core.util.LogUtil.info(".....openwin...."+hdid); CriteriaQuery cq = new CriteriaQuery(PrizeRecordEntity.class, dataGrid); cq.eq("hdid",hdid); cq.eq(ACCOUNTID, ResourceUtil.getWeiXinAccountId()); cq.add(); //查询条件组装器 org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, prizeRecord, request.getParameterMap()); this.prizeRecordService.getDataGridReturn(cq, true); TagUtil.datagrid(response, dataGrid); } /** * 删除中奖纪录 * * @return */ @RequestMapping(params = "del") @ResponseBody public AjaxJson del(PrizeRecordEntity prizeRecord, HttpServletRequest request) { AjaxJson j = new AjaxJson(); prizeRecord = systemService.getEntity(PrizeRecordEntity.class, prizeRecord.getId()); message = "中奖纪录删除成功"; prizeRecordService.delete(prizeRecord); systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO); j.setMsg(message); return j; } /** * 添加中奖纪录 * @param ids * @return */ @RequestMapping(params = "save") @ResponseBody public AjaxJson save(PrizeRecordEntity prizeRecord, HttpServletRequest request) { AjaxJson j = new AjaxJson(); if (StringUtil.isNotEmpty(prizeRecord.getId())) { message = "中奖纪录更新成功"; PrizeRecordEntity t = prizeRecordService.get(PrizeRecordEntity.class, prizeRecord.getId()); try { MyBeanUtils.copyBeanNotNull2Bean(prizeRecord, t); prizeRecordService.saveOrUpdate(t); systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO); } catch (Exception e) { e.printStackTrace(); message = "中奖纪录更新失败"; } } else { message = "中奖纪录添加成功"; prizeRecordService.save(prizeRecord); systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO); } j.setMsg(message); return j; } /** * 中奖纪录列表页面跳转 * * @return */ @RequestMapping(params = "addOrUpdate") public ModelAndView addOrUpdate(PrizeRecordEntity prizeRecord, HttpServletRequest req) { if (StringUtil.isNotEmpty(prizeRecord.getId())) { prizeRecord = prizeRecordService.getEntity(PrizeRecordEntity.class, prizeRecord.getId()); req.setAttribute("prizeRecordPage", prizeRecord); } return new ModelAndView("weixin/idea/huodong/prizerecord/prizeRecord"); } }
package com.google.android.gms.internal.ads; import android.os.Bundle; import android.os.RemoteException; import com.google.android.gms.dynamic.IObjectWrapper; /* renamed from: com.google.android.gms.internal.ads.yk */ final class C9838yk extends zzatl { /* renamed from: b */ private final /* synthetic */ zzbsv f23544b; /* renamed from: c */ private final /* synthetic */ zzbri f23545c; /* renamed from: d */ private final /* synthetic */ zzbse f23546d; /* renamed from: e */ private final /* synthetic */ zzbvj f23547e; C9838yk(zzcnw zzcnw, zzbsv zzbsv, zzbri zzbri, zzbse zzbse, zzbvj zzbvj) { this.f23544b = zzbsv; this.f23545c = zzbri; this.f23546d = zzbse; this.f23547e = zzbvj; } /* renamed from: s */ public final void mo29305s(IObjectWrapper iObjectWrapper) { this.f23544b.zzta(); } /* renamed from: E */ public final void mo29300E(IObjectWrapper iObjectWrapper) { this.f23544b.zzsz(); } /* renamed from: F */ public final void mo29301F(IObjectWrapper iObjectWrapper) { this.f23545c.onAdClicked(); } /* renamed from: z */ public final void mo29309z(IObjectWrapper iObjectWrapper) { this.f23546d.mo30883H(); } /* renamed from: a */ public final void mo29302a(IObjectWrapper iObjectWrapper, zzato zzato) { this.f23547e.mo29744a(zzato); } /* renamed from: t */ public final void mo29306t(IObjectWrapper iObjectWrapper) { this.f23547e.mo29743E(); } /* renamed from: B */ public final void mo29299B(IObjectWrapper iObjectWrapper) throws RemoteException { this.f23546d.mo30885J(); } public final void zzb(Bundle bundle) { } /* renamed from: w */ public final void mo29307w(IObjectWrapper iObjectWrapper) { } /* renamed from: y */ public final void mo29308y(IObjectWrapper iObjectWrapper) { } /* renamed from: c */ public final void mo29304c(IObjectWrapper iObjectWrapper, int i) { } /* renamed from: b */ public final void mo29303b(IObjectWrapper iObjectWrapper, int i) { } }
package org.obolibrary.robot; import static org.junit.Assert.*; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.geneontology.reasoner.ExpressionMaterializingReasonerFactory; import org.junit.Test; import org.obolibrary.robot.exceptions.InvalidReferenceException; import org.obolibrary.robot.exceptions.OntologyLogicException; import org.semanticweb.elk.owlapi.ElkReasonerFactory; import org.semanticweb.owlapi.model.AddImport; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLAxiom; import org.semanticweb.owlapi.model.OWLImportsDeclaration; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyCreationException; import org.semanticweb.owlapi.model.OWLOntologyManager; import org.semanticweb.owlapi.reasoner.OWLReasonerFactory; import uk.ac.manchester.cs.jfact.JFactFactory; /** Tests for ReasonOperation. */ public class ReasonOperationTest extends CoreTest { /** * Test reasoning with StructuralReasoner. * * @throws IOException on file problem * @throws OWLOntologyCreationException on ontology problem * @throws OntologyLogicException on logic error * @throws InvalidReferenceException if a reference is invalid */ @Test public void testStructural() throws IOException, OWLOntologyCreationException, OntologyLogicException, InvalidReferenceException { OWLOntology reasoned = loadOntology("/simple.owl"); OWLReasonerFactory reasonerFactory = new org.semanticweb.owlapi.reasoner.structural.StructuralReasonerFactory(); ReasonOperation.reason(reasoned, reasonerFactory); assertIdentical("/simple_structural.owl", reasoned); } /** * Test reasoning with ELK. * * @throws IOException on file problem * @throws OWLOntologyCreationException on ontology problem * @throws OntologyLogicException on logic error * @throws InvalidReferenceException if a reference is invalid */ @Test public void testELK() throws IOException, OWLOntologyCreationException, OntologyLogicException, InvalidReferenceException { OWLOntology reasoned = loadOntology("/simple.owl"); OWLReasonerFactory reasonerFactory = new ElkReasonerFactory(); ReasonOperation.reason(reasoned, reasonerFactory); assertIdentical("/simple_elk.owl", reasoned); } /** * Test reasoning with HermiT. * * @throws IOException on file problem * @throws OWLOntologyCreationException on ontology problem * @throws OntologyLogicException on logic error * @throws InvalidReferenceException if a reference is invalid */ @Test public void testHermit() throws IOException, OWLOntologyCreationException, OntologyLogicException, InvalidReferenceException { OWLOntology reasoned = loadOntology("/simple.owl"); OWLReasonerFactory reasonerFactory = new org.semanticweb.HermiT.Reasoner.ReasonerFactory(); ReasonOperation.reason(reasoned, reasonerFactory); assertEquals(6, reasoned.getAxiomCount()); assertIdentical("/simple_hermit.owl", reasoned); } /** * Test reasoning with JFact. * * @throws IOException on file problem * @throws OWLOntologyCreationException on ontology problem * @throws OntologyLogicException on logic error * @throws InvalidReferenceException if a reference is invalid */ @Test public void testJFact() throws IOException, OWLOntologyCreationException, OntologyLogicException, InvalidReferenceException { OWLOntology reasoned = loadOntology("/simple.owl"); OWLReasonerFactory reasonerFactory = new JFactFactory(); ReasonOperation.reason(reasoned, reasonerFactory); assertEquals(6, reasoned.getAxiomCount()); assertIdentical("/simple_jfact.owl", reasoned); } /** * Test inferring into new ontology. * * @throws IOException on file problem * @throws OWLOntologyCreationException on ontology problem * @throws OntologyLogicException on logic error * @throws InvalidReferenceException if a reference is invalid */ @Test public void testInferIntoNewOntology() throws IOException, OWLOntologyCreationException, OntologyLogicException, InvalidReferenceException { OWLOntology reasoned = loadOntology("/simple.owl"); OWLReasonerFactory reasonerFactory = new org.semanticweb.HermiT.Reasoner.ReasonerFactory(); Map<String, String> opts = new HashMap<>(); // see https://github.com/ontodev/robot/issues/80 opts.put("create-new-ontology", "true"); // see https://github.com/ontodev/robot/issues/80 opts.put("annotate-inferred-axioms", "true"); ReasonOperation.reason(reasoned, reasonerFactory, opts); assertEquals(2, reasoned.getAxiomCount()); // assertIdentical("/simple_hermit.owl", reasoned); } /** * Test inferring into new ontology. * * @throws IOException on file problem * @throws OWLOntologyCreationException on ontology problem * @throws OntologyLogicException on logic error * @throws InvalidReferenceException if a reference is invalid */ @Test public void testInferIntoNewOntologyNonTrivial() throws IOException, OWLOntologyCreationException, OntologyLogicException, InvalidReferenceException { OWLOntology reasoned = loadOntology("/relax_equivalence_axioms_test.obo"); OWLReasonerFactory reasonerFactory = new org.semanticweb.HermiT.Reasoner.ReasonerFactory(); Map<String, String> opts = new HashMap<>(); // see https://github.com/ontodev/robot/issues/80 opts.put("create-new-ontology", "true"); opts.put("annotate-inferred-axioms", "true"); ReasonOperation.reason(reasoned, reasonerFactory, opts); // note that some of the inferred axioms are trivial // involving owl:Thing assertEquals(15, reasoned.getAxiomCount()); // assertIdentical("/simple_hermit.owl", reasoned); } /** * Test inferring into new ontology, excluding duplicates. * * @throws IOException on file problem * @throws OWLOntologyCreationException on ontology problem * @throws OntologyLogicException on logic error * @throws InvalidReferenceException if a reference is invalid */ @Test public void testInferIntoNewOntologyNoDupes() throws IOException, OWLOntologyCreationException, OntologyLogicException, InvalidReferenceException { OWLOntology reasoned = loadOntology("/relax_equivalence_axioms_test.obo"); OWLReasonerFactory reasonerFactory = new org.semanticweb.HermiT.Reasoner.ReasonerFactory(); Map<String, String> opts = new HashMap<>(); opts.put("create-new-ontology", "true"); opts.put("annotate-inferred-axioms", "true"); opts.put("exclude-duplicate-axioms", "true"); ReasonOperation.reason(reasoned, reasonerFactory, opts); assertEquals(5, reasoned.getAxiomCount()); // assertIdentical("/simple_hermit.owl", reasoned); } /** * Test removing redundant subclass axioms. * * @throws IOException on file problem * @throws OWLOntologyCreationException on ontology problem * @throws OntologyLogicException on logic error * @throws InvalidReferenceException if a reference is invalid */ @Test public void testRemoveRedundantSubClassAxioms() throws IOException, OWLOntologyCreationException, OntologyLogicException, InvalidReferenceException { OWLOntology reasoned = loadOntology("/redundant_subclasses.owl"); OWLReasonerFactory reasonerFactory = new org.semanticweb.elk.owlapi.ElkReasonerFactory(); ReasonOperation.reason(reasoned, reasonerFactory, Collections.emptyMap()); assertIdentical("/redundant_subclasses.owl", reasoned); Map<String, String> options = new HashMap<>(); options.put("remove-redundant-subclass-axioms", "true"); reasoned = loadOntology("/redundant_subclasses.owl"); ReasonOperation.reason(reasoned, reasonerFactory, options); assertIdentical("/without_redundant_subclasses.owl", reasoned); } /** * Test reasoning with Expression Materializing Reasoner. * * <p>This test should return the same results as running any other reasoner * * @throws IOException on file problem * @throws OWLOntologyCreationException on ontology problem * @throws OntologyLogicException on logic error * @throws InvalidReferenceException if a reference is invalid */ @Test public void testEMRBasic() throws IOException, OWLOntologyCreationException, OntologyLogicException, InvalidReferenceException { OWLOntology reasoned = loadOntology("/simple.owl"); OWLReasonerFactory coreReasonerFactory = new ElkReasonerFactory(); OWLReasonerFactory reasonerFactory = new ExpressionMaterializingReasonerFactory(coreReasonerFactory); ReasonOperation.reason(reasoned, reasonerFactory); assertIdentical("/simple_elk.owl", reasoned); } /** * Test reasoning with Expression Materializing Reasoner. * * <p>This test effectively relaxes an equivalence axiom * * @throws IOException on file problem * @throws OWLOntologyCreationException on ontology problem * @throws OntologyLogicException on logic error * @throws InvalidReferenceException if a reference is invalid */ @Test public void testEMRRelax() throws IOException, OWLOntologyCreationException, OntologyLogicException, InvalidReferenceException { OWLOntology reasoned = loadOntology("/relax_equivalence_axioms_test.obo"); OWLReasonerFactory coreReasonerFactory = new ElkReasonerFactory(); OWLReasonerFactory reasonerFactory = new ExpressionMaterializingReasonerFactory(coreReasonerFactory); Map<String, String> opts = ReasonOperation.getDefaultOptions(); opts.put("exclude-owl-thing", "true"); ReasonOperation.reason(reasoned, reasonerFactory, opts); assertIdentical("/relax_equivalence_axioms_expressions_materialized.obo", reasoned); } /** * Test reasoning with intersection axioms * * @throws IOException on file problem * @throws OWLOntologyCreationException on ontology problem * @throws OntologyLogicException on logic error * @throws InvalidReferenceException if a reference is invalid */ @Test public void testIntersection() throws IOException, OWLOntologyCreationException, OntologyLogicException, InvalidReferenceException { OWLOntology reasoned = loadOntology("/intersection.omn"); OWLReasonerFactory reasonerFactory = new ElkReasonerFactory(); ReasonOperation.reason(reasoned, reasonerFactory); assertTrue(checkContains(reasoned, "SubClassOf(<http://x.org/XA> <http://x.org/XB>)")); } /** * Test reasoning with external ontologies. * * <p>Depending on user option, inferred axioms that refer solely to external ontology classes * (i.e. those in the import chain) should not be asserted * * @throws IOException on file problem * @throws OWLOntologyCreationException on ontology problem * @throws OntologyLogicException on logic error * @throws InvalidReferenceException if a reference is invalid */ @Test public void testExternal() throws Exception { OWLOntology importOnt1 = loadOntology("/intersection.omn"); IRI oiri = importOnt1.getOntologyID().getOntologyIRI().orNull(); if (oiri == null) { throw new Exception("Ontology 'intersection.omn' does not have an IRI"); } OWLOntology mainOnt = loadOntology("/simple.owl"); OWLOntologyManager mgr = mainOnt.getOWLOntologyManager(); OWLOntology importOnt = mgr.createOntology(oiri); mgr.addAxioms(importOnt, importOnt1.getAxioms()); OWLImportsDeclaration importsDecl = mgr.getOWLDataFactory().getOWLImportsDeclaration(oiri); AddImport ch = new AddImport(mainOnt, importsDecl); mgr.applyChange(ch); OWLReasonerFactory reasonerFactory = new ElkReasonerFactory(); Map<String, String> opts = new HashMap<>(); opts.put("exclude-external-entities", "true"); ReasonOperation.reason(mainOnt, reasonerFactory, opts); assertFalse(checkContains(mainOnt, "SubClassOf(<http://x.org/XA> <http://x.org/XB>)")); opts.put("exclude-external-entities", "false"); ReasonOperation.reason(mainOnt, reasonerFactory, opts); assertTrue(checkContains(mainOnt, "SubClassOf(<http://x.org/XA> <http://x.org/XB>)")); } private boolean checkContains(OWLOntology reasoned, String axStr) { for (OWLAxiom a : reasoned.getLogicalAxioms()) { if (a.toString().equals(axStr)) return true; } return false; } }
/* * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.plc4x.codegen.ast; public abstract class Expression extends AbstractNode { protected Expression(TypeDefinition type) { super(type); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.management.internal; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; /** * Various utility methods for open type conversion */ public class OpenTypeUtil { static <K, V> Map<K, V> newMap() { return new HashMap<>(); } static <K, V> IdentityHashMap<K, V> newIdentityHashMap() { return new IdentityHashMap<>(); } static <K, V> SortedMap<K, V> newSortedMap() { return new TreeMap<>(); } static <E> Set<E> newSet() { return new HashSet<>(); } static <E> Set<E> newSet(Collection<E> c) { return new HashSet<>(c); } static <E> List<E> newList() { return new ArrayList<>(); } static <E> List<E> newList(Collection<E> c) { return new ArrayList<>(c); } public static <T> T cast(Object x) { return (T) x; } /** * Utility method to take a string and convert it to normal Java variable name capitalization. * * @param name The string to be made in camel case. * * @return The camel case version of the string. */ static String toCamelCase(String name) { if (name == null || name.isEmpty()) { return name; } int offset1 = Character.offsetByCodePoints(name, 0, 1); if (offset1 < name.length() && Character.isUpperCase(name.codePointAt(offset1))) { return name; } return name.substring(0, offset1).toLowerCase() + name.substring(offset1); } }
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.isis.viewer.restfulobjects.rendering.domaintypes; import java.util.List; import org.apache.isis.core.metamodel.facets.actcoll.typeof.TypeOfFacet; import org.apache.isis.core.metamodel.spec.ObjectSpecification; import org.apache.isis.core.metamodel.spec.feature.ObjectAction; import org.apache.isis.core.metamodel.spec.feature.ObjectActionParameter; import org.apache.isis.viewer.restfulobjects.applib.JsonRepresentation; import org.apache.isis.viewer.restfulobjects.applib.Rel; import org.apache.isis.viewer.restfulobjects.applib.RepresentationType; import org.apache.isis.viewer.restfulobjects.rendering.LinkBuilder; import org.apache.isis.viewer.restfulobjects.rendering.LinkFollowSpecs; import org.apache.isis.viewer.restfulobjects.rendering.RendererContext; public class ActionDescriptionReprRenderer extends AbstractTypeMemberReprRenderer<ActionDescriptionReprRenderer, ObjectAction> { public static LinkBuilder newLinkToBuilder(final RendererContext resourceContext, final Rel rel, final ObjectSpecification objectSpecification, final ObjectAction objectAction) { final String domainType = objectSpecification.getSpecId().asString(); final String actionId = objectAction.getId(); final String url = "domain-types/" + domainType + "/actions/" + actionId; return LinkBuilder.newBuilder(resourceContext, rel.getName(), RepresentationType.ACTION_DESCRIPTION, url); } public ActionDescriptionReprRenderer(final RendererContext resourceContext, final LinkFollowSpecs linkFollower, final JsonRepresentation representation) { super(resourceContext, linkFollower, RepresentationType.ACTION_DESCRIPTION, representation); } @Override protected void addLinksSpecificToFeature() { addParameters(); addLinkToReturnTypeIfAny(); addLinkToElementTypeIfAny(); } private void addParameters() { final JsonRepresentation parameterList = JsonRepresentation.newArray(); final List<ObjectActionParameter> parameters = getObjectFeature().getParameters(); for (final ObjectActionParameter parameter : parameters) { final LinkBuilder linkBuilder = ActionParameterDescriptionReprRenderer.newLinkToBuilder(getRendererContext(), Rel.ACTION_PARAM, objectSpecification, parameter); parameterList.arrayAdd(linkBuilder.build()); } representation.mapPut("parameters", parameterList); } protected void addLinkToElementTypeIfAny() { final TypeOfFacet facet = getObjectFeature().getFacet(TypeOfFacet.class); if (facet == null) { return; } final ObjectSpecification typeOfSpec = facet.valueSpec(); final LinkBuilder linkBuilder = DomainTypeReprRenderer.newLinkToBuilder(getRendererContext(), Rel.ELEMENT_TYPE, typeOfSpec); getLinks().arrayAdd(linkBuilder.build()); } private void addLinkToReturnTypeIfAny() { final ObjectSpecification returnType = getObjectFeature().getReturnType(); if (returnType == null) { return; } final LinkBuilder linkBuilder = DomainTypeReprRenderer.newLinkToBuilder(getRendererContext(), Rel.RETURN_TYPE, returnType); getLinks().arrayAdd(linkBuilder.build()); } @Override protected void putExtensionsSpecificToFeature() { putExtensionsName(); putExtensionsDescriptionIfAvailable(); } }
public class Employee implements java.io.Serializable{ //serialVersionUID is getting calculated automatically //If the class has been changed with serialVersionUID automatically, //Reading the same object with some difference from other file will make an exception //private static final long serialVersionUID = 1123261121L; public String name; public String address; public int SSN; public int number; //public int a; public void mailCheck() { System.out.println("Mailing a check to " + name + ", with address: " + address); } }
package util.parser; import org.apache.commons.cli.*; import util.exceptions.InternalAnalyzerException; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.*; /** * @author Nicolas Müller * */ public class ArgParser { // flags final static String MAINCLASS_FLAG = "m"; final static String ONLY_DYNAMIC_FLAG = "onlydynamic"; final static String FORCE_MONOMORPHIC_METHODS = "forcemonomorphic"; final static String CLASSPATH = "cp"; final static String SECDOMAIN_CLASSPATH = "scp"; final static String OTHER_CLASSES_FOR_STATIC_ANALYZER = "s"; final static String JIMPLE_FLAG = "j"; final static String OUTPUT_FOLDER_FLAG = "o"; final static String ADDITIONAL_FILES_FLAG = "f"; final static String PUBLIC_TYPING_FOR_JIMPLE = "x"; final static String VERBOSE = "v"; final static String HELP = "h"; private static void printHelp(Options options) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("jgs", options); } private static String getRequiredOptionValue(CommandLine cmd, String flag) throws ParseException { if (cmd.hasOption(flag)) { return cmd.getOptionValue(flag); } else { throw new ParseException("Missing required option: -" + flag); } } // TODO: some options are unused at the moment. Clean up. public static ArgumentContainer getSootOptions(String[] args) { // locals variables to hold parsing results String mainclass; boolean toJimple; String outputFolder; Deque<String> addDirsToClasspath = new LinkedList<>(); List<URL> secDomainClasspath = new ArrayList<>(); List<String> addClasses = new ArrayList<>(); List<String> additionalFiles = new ArrayList<>(); boolean usePublicTyping; // ======== PREPARE OPTIONS ========= Options options = new Options(); Option mainopt = new Option(MAINCLASS_FLAG, "main-class", true, "the main-class of the application"); options.addOption(mainopt); Option addDirsToClasspathOption = new Option(CLASSPATH, "classpath", true, "set the classpath"); addDirsToClasspathOption.setRequired(false); addDirsToClasspathOption.setArgs(Option.UNLIMITED_VALUES); options.addOption(addDirsToClasspathOption); Option addDirsToSecdomainClasspathOption = new Option(SECDOMAIN_CLASSPATH, "secdomain-classpath", true, "set the classpath of the security domain to be used"); addDirsToSecdomainClasspathOption.setRequired(false); addDirsToSecdomainClasspathOption.setArgs(Option.UNLIMITED_VALUES); options.addOption(addDirsToSecdomainClasspathOption); // TODO: This probably can be removed Option addOtherClassesForStatic = new Option(OTHER_CLASSES_FOR_STATIC_ANALYZER, "otherClasses", true, "Add other classes for the static analyzer"); addOtherClassesForStatic.setRequired(false); addOtherClassesForStatic.setArgs(Option.UNLIMITED_VALUES); // options.addOption(addOtherClassesForStatic); Option format = new Option(JIMPLE_FLAG, "jimple", false, "Optional: Output as Jimple instead of as compiled class"); format.setRequired(false); options.addOption(format); Option output = new Option(OUTPUT_FOLDER_FLAG, "output", true, "set output folder"); options.addOption(output); Option filesToAdd = new Option(ADDITIONAL_FILES_FLAG, "files", true, "Optional: add additional files to instrumentation process"); filesToAdd.setRequired(false); filesToAdd.setArgs(Option.UNLIMITED_VALUES); // options.addOption(filesToAdd); Option verbose = new Option(VERBOSE, "verbose", false, "verbose logging"); verbose.setRequired(false); options.addOption(verbose); Option onlyDynamic = new Option(ONLY_DYNAMIC_FLAG, "ignore static types and perform pure dynamic enforcement"); onlyDynamic.setRequired(false); options.addOption(onlyDynamic); Option forceMonomorphic = new Option(FORCE_MONOMORPHIC_METHODS, "extend signatures such that all methods are monomorphic (polymorphic parameter become public parameter)"); forceMonomorphic.setRequired(false); options.addOption(forceMonomorphic); Option help = new Option(HELP, "help", false, "Print Help"); help.setRequired(false); options.addOption(help); CommandLineParser parser = new DefaultParser(); CommandLine cmd; try { cmd = parser.parse(options, args); // help flag if (cmd.hasOption("h")){ printHelp(options); System.exit(0); } // m flag mainclass = getRequiredOptionValue(cmd, MAINCLASS_FLAG); // case p flag if (cmd.hasOption(CLASSPATH)) { for ( String path : cmd.getOptionValues(CLASSPATH)) { for (String s : path.split(":")) { File tmp = new File(s); // TODO: not sure if making path elements absolut makes sense. addDirsToClasspath.add(tmp.isAbsolute() ? s : new File(System.getProperty("user.dir"), s).getAbsolutePath()); } } } // case scp flag if (cmd.hasOption(SECDOMAIN_CLASSPATH)) { for (String path : cmd.getOptionValues(SECDOMAIN_CLASSPATH)) { for (String s : path.split(":")) { File tmp = new File(s); addDirsToClasspath.addFirst(tmp.getAbsolutePath()); secDomainClasspath.add(tmp.toURI().toURL()); } } } // case s flag if (cmd.hasOption(OTHER_CLASSES_FOR_STATIC_ANALYZER)) { for (String s: cmd.getOptionValues(OTHER_CLASSES_FOR_STATIC_ANALYZER)) { File tmp = new File(s); addClasses.add(tmp.isAbsolute() ? s : new File(System.getProperty("user.dir"), s).getAbsolutePath()); } } // case j flag toJimple = cmd.hasOption(JIMPLE_FLAG); // case o flag outputFolder = getRequiredOptionValue(cmd, OUTPUT_FOLDER_FLAG); // case f flag if (cmd.hasOption(ADDITIONAL_FILES_FLAG)) { Collections.addAll(additionalFiles, cmd.getOptionValues(ADDITIONAL_FILES_FLAG)); } usePublicTyping = cmd.hasOption(PUBLIC_TYPING_FOR_JIMPLE); boolean forceMonomorphicMethods = cmd.hasOption(FORCE_MONOMORPHIC_METHODS); // return new ArgumentContainer(mainclass, addDirsToClasspath, secDomainClasspath, addClasses, toJimple, outputFolder, additionalFiles, usePublicTyping, cmd.hasOption(VERBOSE), cmd.hasOption(ONLY_DYNAMIC_FLAG), forceMonomorphicMethods); // if illegal input // TODO: handle bad options (exit) in main } catch (ParseException e) { System.err.println("Error parsing command line: " + e.getMessage()); printHelp(options); System.exit(-1); } catch (MalformedURLException e) { System.err.println("Error parsing url: " + e.getMessage()); System.exit(-1); } throw new InternalAnalyzerException("This line must never be reached"); // compiler complains if i dont put this here?! } }
/* * Copyright 2016 Skynav, Inc. All rights reserved. * Portions Copyright 2009 Extensible Formatting Systems, Inc (XFSI). * * 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. * * THIS SOFTWARE IS PROVIDED BY SKYNAV, INC. AND ITS 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 SKYNAV, INC. OR ITS CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.xfsi.xav.validation.images.png; public final class ChunkValidatorzTXt extends ChunkValidator { public static final class Spec { public static final String section = "4.2.10"; static final byte[] header = ChunkValidatorzTXt.class.getName().substring(ChunkValidatorzTXt.class.getName().length() - ChunkValidator.Spec.Props.typeSize, ChunkValidatorzTXt.class.getName().length()).getBytes(Utils.getCharset()); } void validate() throws PngValidationException { validateMultipleAllowed(Spec.header); int size = validateKeyword(); validateCompressionMethod(size, 0, Spec.section); } private int validateKeyword() throws PngValidationException { return Utils.findValidatedNameSize(data, png, true, Spec.section); } }
package org.oasis_open.contextserver.itests; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.http.HttpResponse; import org.apache.http.util.EntityUtils; import java.io.IOException; public class TestUtils { public static <T> T retrieveResourceFromResponse(HttpResponse response, Class<T> clazz) throws IOException { String jsonFromResponse = EntityUtils.toString(response.getEntity()); ObjectMapper mapper = new ObjectMapper(). configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); return mapper.readValue(jsonFromResponse, clazz); } }
package com.czl.exception; import java.io.Serializable; import static com.czl.exception.ExpPrefix.*; /** * @Author zerechen * 全局的异常状态码 和 异常描述 * * PS:异常码一共由5位组成,前两位为固定前缀,请参考{@link ExpPrefix} */ public enum ExpCodeEnum implements Serializable { /** 通用异常 */ UNKNOW_ERROR(ComExpPrefix + "000", "未知异常"), ERROR_404(ComExpPrefix + "001", "没有该接口"), PARAM_NULL(ComExpPrefix + "002", "参数为空"), NO_REPEAT(ComExpPrefix + "003", "请勿重复提交"), SESSION_NULL(ComExpPrefix + "004", "请求头中SessionId不存在"), HTTP_REQ_METHOD_ERROR(ComExpPrefix + "005", "HTTP请求方法不正确"), JSONERROR(ComExpPrefix + "006", "JSON解析异常"), /** User模块异常 */ USERNAME_NULL(UserExpPrefix + "000", "用户名为空"), PASSWD_NULL(UserExpPrefix + "001", "密码为空"), LOGIN_FAIL(UserExpPrefix + "003", "登录失败"), UNLOGIN(UserExpPrefix + "004", "尚未登录"), NO_PERMISSION(UserExpPrefix + "005", "没有权限"), USER_ID_NULL(UserExpPrefix + "006", "用户ID为空"), MAIL_NULL(UserExpPrefix + "007", "电子邮件为空"), USERTYPE_NULL(UserExpPrefix + "008", "用户类别为空"), LICENCE_NULL(UserExpPrefix + "009", "营业执照为空"), COMPANYNAME_NULL(UserExpPrefix + "010", "企业名称为空"), ROLE_NULL(UserExpPrefix + "011", "角色为空"), ROLEID_NULL(UserExpPrefix + "012", "roleId为空"), MENUIDLIST_NULL(UserExpPrefix + "013", "menuIdList为空"), PERMISSIONIDLIST_NULL(UserExpPrefix + "014", "permissionIdList为空"), NAME_NULL(UserExpPrefix + "015", "name为空"), LOCATIONID_NULL(UserExpPrefix + "016", "locationId为空"), LOCATIONUPDATEREQ_NULL(UserExpPrefix + "017", "LocationUpdateReq为空"), /** Product模块异常 */ PRODUCT_NAME_NULL(ProdExpPrefix + "000", "产品名称为空"), PRODUCT_MARKETPRICE_NULL(ProdExpPrefix + "001", "产品市场价为空"), PRODUCT_SHOPPRICE_NULL(ProdExpPrefix + "002", "产品本店价为空"), PRODUCT_STOCK_ZERO(ProdExpPrefix + "003", "产品库存为0"), PRODUCT_WEIGHT_NULL(ProdExpPrefix + "004", "产品重量为空"), PRODUCT_ID_NULL(ProdExpPrefix + "005", "产品ID为空"), PRODUCT_SUBCATEGENTITY_NULL(ProdExpPrefix + "006", "产品二级分类为空"), PRODUCT_BRANDENTITY_NULL(ProdExpPrefix + "007", "产品品牌为空"), PRODUCT_COMPANYENTITY_NULL(ProdExpPrefix + "008", "产品所属企业为空"), PRODUCT_CREATE_FAIL(ProdExpPrefix + "009", "产品新增失败"), PRODUCT_UPDATE_FAIL(ProdExpPrefix + "010", "产品更新失败"), PRODUCT_SELECT_FAIL(ProdExpPrefix + "011", "没有符合条件的查询结果,产品查询失败"), PRODUCT_DELETE_FAIL(ProdExpPrefix + "011", "产品删除失败"), PRODUCT_NO_EXISTENT(ProdExpPrefix + "025", "产品不存在,或者已下架"), /** Car异常 前缀统一使用 ProdExpPrefix */ CAR_MERGE_FAIL(ProdExpPrefix + "013","购物车产品合并失败"), CAR_CREATE_FAIL(ProdExpPrefix + "014","购物车产品新增失败"), CAR_DELETE_FAIL(ProdExpPrefix + "015","购物车产品删除失败"), CAR_UPDATE_FAIL(ProdExpPrefix + "016","购物车产品更新失败"), CAR_SELECT_FAIL(ProdExpPrefix + "017","没有符合条件的查询结果,购物车产品查询失败"), CAR_NUM_FAIL(ProdExpPrefix + "018","购物车产品数量错误"), CAR_ID_NULL(ProdExpPrefix + "019","购物车产品ID为空"), /** BUY异常 前缀统一使用 ProdExpPrefix */ BUY_SELECT_FAIL(ProdExpPrefix + "017","没有符合条件的查询结果,购买记录产品查询失败"); private String code; private String message; private ExpCodeEnum(String code, String message){ this.code = code; this.message = message; } ExpCodeEnum(){} public String getCode() { return code; } public String getMessage() { return message; } }
// Copyright 2020 Goldman Sachs // // 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.finos.legend.pure.runtime.java.compiled.generation.processors.natives.core.meta; import org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.type.Type; import org.finos.legend.pure.m3.execution.ExecutionSupport; import org.finos.legend.pure.runtime.java.compiled.generation.processors.natives.AbstractNativeFunctionGeneric; public class Generalizations extends AbstractNativeFunctionGeneric { public Generalizations() { super("Pure.getGeneralizations", new Class[]{Type.class, ExecutionSupport.class}, false, true, false, "generalizations_Type_1__Type_$1_MANY$_"); } }
/* * Home Health Grouper * Developer for the Center for Medicare and Medicaid Services CMS * by 3M Health Information Systems for CMS Home Health. * * All code is provided as is. */ package com.mmm.cms.homehealth.io.record; import com.mmm.cms.homehealth.proto.record.HomeHealthRecord_C1_IF; import com.mmm.cms.homehealth.proto.RecordType; import com.mmm.cms.util.OasisCalendarFormatter; /** * OASIS-C1 Record * * @author 3M Health Information Systems for CMS Home Health */ public class Oasis_C1_Record_2_11 extends Oasis_C_Record implements HomeHealthRecord_C1_IF { @Override public RecordType getRecordType() { return RecordType.OASIS_C1_ICD_9; } @Override public String toString() { final StringBuilder buffer = new StringBuilder(2000); buffer.append("M0030_START_CARE_DT="); OasisCalendarFormatter.format(getSTART_CARE_DT(), buffer); buffer.append(",M0090_INFO_COMPLETED_DT="); OasisCalendarFormatter.format(getINFO_COMPLETED_DT(), buffer); buffer.append(",M0100_ASSMT_REASON="); buffer.append(getASSMT_REASON()); buffer.append(",M1020_PRIMARY_DIAG_ICD="); buffer.append(getPRIMARY_DIAG_ICD()); buffer.append(",M1022_OTH_DIAG1_ICD="); buffer.append(getOTH_DIAG1_ICD()); buffer.append(",M1022_OTH_DIAG2_ICD="); buffer.append(getOTH_DIAG2_ICD()); buffer.append(",M1022_OTH_DIAG3_ICD="); buffer.append(getOTH_DIAG3_ICD()); buffer.append(",M1022_OTH_DIAG4_ICD="); buffer.append(getOTH_DIAG4_ICD()); buffer.append(",M1022_OTH_DIAG5_ICD="); buffer.append(getOTH_DIAG5_ICD()); buffer.append(",M1030_THH_IV_INFUSION="); buffer.append(getTHH_IV_INFUSION()); buffer.append(",M1030_THH_PAR_NUTRITION="); buffer.append(getTHH_PAR_NUTRITION()); buffer.append(",M1030_THH_ENT_NUTRITION="); buffer.append(getTHH_ENT_NUTRITION()); buffer.append(",M1030_THH_NONE_ABOVE="); buffer.append(getTHH_NONE_ABOVE()); buffer.append(",M1200_VISION="); buffer.append(getVISION()); buffer.append(",M1242_PAIN_FREQ_ACTVTY_MVMT="); buffer.append(getPAIN_FREQ_ACTVTY_MVMT()); buffer.append(",M1306_UNHLD_STG2_PRSR_ULCR="); buffer.append(getUNHEALED_STAGE2_PRESSURE_ULCER()); buffer.append(",M1322_NBR_PRSULC_STG1="); // fix per CMS buffer.append(getNBR_PRSULC_STG1()); buffer.append(",M1308_NBR_PRSULC_STG2="); buffer.append(getNBR_PRSULC_STG2()); buffer.append(",M1308_NBR_PRSULC_STG3="); buffer.append(getNBR_PRSULC_STG3()); buffer.append(",M1308_NBR_PRSULC_STG4="); buffer.append(getNBR_PRSULC_STG4()); buffer.append(",M1320_STUS_PRBLM_PRSR_ULCR="); buffer.append(getSTUS_PRBLM_PRSR_ULCR()); buffer.append(",M1324_STG_PRBLM_ULCER="); buffer.append(getSTG_PRBLM_ULCER()); buffer.append(",M1330_STAS_ULCR_PRSNT="); buffer.append(getSTAS_ULCR_PRSNT()); buffer.append(",M1332_NBR_STAS_ULCR="); buffer.append(getNBR_STAS_ULCR()); buffer.append(",M1334_STUS_PRBLM_STAS_ULCR="); buffer.append(getSTUS_PRBLM_STAS_ULCR()); buffer.append(",M1340_SRGCL_WND_PRSNT="); buffer.append(getSRGCL_WND_PRSNT()); buffer.append(",M1342_STAT_PRB_SURGWND="); buffer.append(getSTUS_PRBLM_SRGCL_WND()); buffer.append(",M1350_LESION_OPEN_WND="); buffer.append(getLESION_OPEN_WND()); buffer.append(",M1400_WHEN_DYSPNEIC="); buffer.append(getWHEN_DYSPNEIC()); buffer.append(",M1610_UR_INCONT="); buffer.append(getUR_INCONT()); buffer.append(",M1620_BWL_INCONT="); buffer.append(getBWL_INCONT()); buffer.append(",M1630_OSTOMY="); buffer.append(getOSTOMY()); buffer.append(",M1810_CRNT_DRESS_UPPER="); buffer.append(getCRNT_DRESS_UPPER()); buffer.append(",M1820_CRNT_DRESS_LOWER="); buffer.append(getCRNT_DRESS_LOWER()); buffer.append(",M1830_CRNT_BATHING="); buffer.append(getCRNT_BATHG()); buffer.append(",M1840_CRNT_TOILETING="); buffer.append(getCRNT_TOILTG()); buffer.append(",M1850_CRNT_TRANSFERRING="); buffer.append(getCRNT_TRNSFRNG()); buffer.append(",M1860_CRNT_AMBULATION="); buffer.append(getCRNT_AMBLTN()); buffer.append(",M2030_CRNT_MGMT_INJCTN_MDCTN="); buffer.append(getCRNT_MGMT_INJCTN_MDCTN()); buffer.append(",M0110_EPISODE_TIMING="); buffer.append(getEPISODE_TIMING()); buffer.append(",M1024_PMT_DIAG_ICD_A3="); buffer.append(getPMT_DIAG_ICD_A3()); buffer.append(",M1024_PMT_DIAG_ICD_B3="); buffer.append(getPMT_DIAG_ICD_B3()); buffer.append(",M1024_PMT_DIAG_ICD_C3="); buffer.append(getPMT_DIAG_ICD_C3()); buffer.append(",M1024_PMT_DIAG_ICD_D3="); buffer.append(getPMT_DIAG_ICD_D3()); buffer.append(",M1024_PMT_DIAG_ICD_E3="); buffer.append(getPMT_DIAG_ICD_E3()); buffer.append(",M1024_PMT_DIAG_ICD_F3="); buffer.append(getPMT_DIAG_ICD_F3()); buffer.append(",M1024_PMT_DIAG_ICD_A4="); buffer.append(getPMT_DIAG_ICD_A4()); buffer.append(",M1024_PMT_DIAG_ICD_B4="); buffer.append(getPMT_DIAG_ICD_B4()); buffer.append(",M1024_PMT_DIAG_ICD_C4="); buffer.append(getPMT_DIAG_ICD_C4()); buffer.append(",M1024_PMT_DIAG_ICD_D4="); buffer.append(getPMT_DIAG_ICD_D4()); buffer.append(",M1024_PMT_DIAG_ICD_E4="); buffer.append(getPMT_DIAG_ICD_E4()); buffer.append(",M1024_PMT_DIAG_ICD_F4="); buffer.append(getPMT_DIAG_ICD_F4()); buffer.append(",M1308_NSTG_DRSG="); buffer.append(getNSTG_DRSG()); buffer.append(",M1308_NSTG_CVRG="); buffer.append(getNSTG_CVRG()); buffer.append(",M1308_NSTG_DEEP_TISSUE="); buffer.append(getNSTG_DEEP_TISUE()); buffer.append(",M2000_DRUG_RGMN_RVW="); buffer.append(getDRUG_RGMN_RVW()); buffer.append(",M2200_THER_NEED_NUM="); buffer.append(getTHER_NEED_NBR()); buffer.append(",M2200_THER_NEED_NA="); buffer.append(getTHER_NEED_NA()); return buffer.toString(); } }
package org.springframework.mock.web; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import java.util.Collections; import javax.servlet.http.Part; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** * Mock implementation of {@code javax.servlet.http.Part}. * * * @since 4.3.12 * @see MockHttpServletRequest#addPart * @see MockMultipartFile */ public class MockPart implements Part { private final String name; @Nullable private final String filename; private final byte[] content; private final HttpHeaders headers = new HttpHeaders(); /** * Constructor for a part with byte[] content only. * @see #getHeaders() */ public MockPart(String name, @Nullable byte[] content) { this(name, null, content); } /** * Constructor for a part with a filename and byte[] content. * @see #getHeaders() */ public MockPart(String name, @Nullable String filename, @Nullable byte[] content) { Assert.hasLength(name, "'name' must not be empty"); this.name = name; this.filename = filename; this.content = (content != null ? content : new byte[0]); this.headers.setContentDispositionFormData(name, filename); } @Override public String getName() { return this.name; } @Override @Nullable public String getSubmittedFileName() { return this.filename; } @Override @Nullable public String getContentType() { MediaType contentType = this.headers.getContentType(); return (contentType != null ? contentType.toString() : null); } @Override public long getSize() { return this.content.length; } @Override public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(this.content); } @Override public void write(String fileName) throws IOException { throw new UnsupportedOperationException(); } @Override public void delete() throws IOException { throw new UnsupportedOperationException(); } @Override @Nullable public String getHeader(String name) { return this.headers.getFirst(name); } @Override public Collection<String> getHeaders(String name) { Collection<String> headerValues = this.headers.get(name); return (headerValues != null ? headerValues : Collections.emptyList()); } @Override public Collection<String> getHeaderNames() { return this.headers.keySet(); } /** * Return the {@link HttpHeaders} backing header related accessor methods, * allowing for populating selected header entries. */ public final HttpHeaders getHeaders() { return this.headers; } }
/* * 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.linkwan.model.v20181230; import java.util.List; import com.aliyuncs.AcsResponse; import com.aliyuncs.linkwan.transform.v20181230.ListGatewayTransferPacketsResponseUnmarshaller; import com.aliyuncs.transform.UnmarshallerContext; /** * @author auto create * @version */ public class ListGatewayTransferPacketsResponse extends AcsResponse { private String requestId; private Boolean success; private Data data; 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 Data getData() { return this.data; } public void setData(Data data) { this.data = data; } public static class Data { private Long totalCount; private List<Packet> list; public Long getTotalCount() { return this.totalCount; } public void setTotalCount(Long totalCount) { this.totalCount = totalCount; } public List<Packet> getList() { return this.list; } public void setList(List<Packet> list) { this.list = list; } public static class Packet { private String gwEui; private String devEui; private String logMillis; private String devAddr; private String freq; private String datr; private String classMode; private Integer rssi; private Float lsnr; private Integer fPort; private Boolean hasMacCommand; private Boolean hasData; private String base64EncodedMacPayload; private Long macPayloadSize; private String processEvent; private String messageType; private String nodeOwnerAliyunId; private List<String> macCommandCIDs; public String getGwEui() { return this.gwEui; } public void setGwEui(String gwEui) { this.gwEui = gwEui; } public String getDevEui() { return this.devEui; } public void setDevEui(String devEui) { this.devEui = devEui; } public String getLogMillis() { return this.logMillis; } public void setLogMillis(String logMillis) { this.logMillis = logMillis; } public String getDevAddr() { return this.devAddr; } public void setDevAddr(String devAddr) { this.devAddr = devAddr; } public String getFreq() { return this.freq; } public void setFreq(String freq) { this.freq = freq; } public String getDatr() { return this.datr; } public void setDatr(String datr) { this.datr = datr; } public String getClassMode() { return this.classMode; } public void setClassMode(String classMode) { this.classMode = classMode; } public Integer getRssi() { return this.rssi; } public void setRssi(Integer rssi) { this.rssi = rssi; } public Float getLsnr() { return this.lsnr; } public void setLsnr(Float lsnr) { this.lsnr = lsnr; } public Integer getFPort() { return this.fPort; } public void setFPort(Integer fPort) { this.fPort = fPort; } public Boolean getHasMacCommand() { return this.hasMacCommand; } public void setHasMacCommand(Boolean hasMacCommand) { this.hasMacCommand = hasMacCommand; } public Boolean getHasData() { return this.hasData; } public void setHasData(Boolean hasData) { this.hasData = hasData; } public String getBase64EncodedMacPayload() { return this.base64EncodedMacPayload; } public void setBase64EncodedMacPayload(String base64EncodedMacPayload) { this.base64EncodedMacPayload = base64EncodedMacPayload; } public Long getMacPayloadSize() { return this.macPayloadSize; } public void setMacPayloadSize(Long macPayloadSize) { this.macPayloadSize = macPayloadSize; } public String getProcessEvent() { return this.processEvent; } public void setProcessEvent(String processEvent) { this.processEvent = processEvent; } public String getMessageType() { return this.messageType; } public void setMessageType(String messageType) { this.messageType = messageType; } public String getNodeOwnerAliyunId() { return this.nodeOwnerAliyunId; } public void setNodeOwnerAliyunId(String nodeOwnerAliyunId) { this.nodeOwnerAliyunId = nodeOwnerAliyunId; } public List<String> getMacCommandCIDs() { return this.macCommandCIDs; } public void setMacCommandCIDs(List<String> macCommandCIDs) { this.macCommandCIDs = macCommandCIDs; } } } @Override public ListGatewayTransferPacketsResponse getInstance(UnmarshallerContext context) { return ListGatewayTransferPacketsResponseUnmarshaller.unmarshall(this, context); } @Override public boolean checkShowJsonItemName() { return false; } }
/* * 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.hudi.common.util; import org.apache.hudi.common.config.DFSPropertiesConfiguration; import org.apache.hudi.common.config.TypedProperties; import org.apache.hudi.common.minicluster.HdfsTestService; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.DistributedFileSystem; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.io.IOException; import java.io.PrintStream; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests basic functionality of {@link DFSPropertiesConfiguration}. */ public class TestDFSPropertiesConfiguration { private static String dfsBasePath; private static HdfsTestService hdfsTestService; private static MiniDFSCluster dfsCluster; private static DistributedFileSystem dfs; @BeforeAll public static void initClass() throws Exception { hdfsTestService = new HdfsTestService(); dfsCluster = hdfsTestService.start(true); // Create a temp folder as the base path dfs = dfsCluster.getFileSystem(); dfsBasePath = dfs.getWorkingDirectory().toString(); dfs.mkdirs(new Path(dfsBasePath)); // create some files. Path filePath = new Path(dfsBasePath + "/t1.props"); writePropertiesFile(filePath, new String[] {"", "#comment", "abc", // to be ignored "int.prop=123", "double.prop=113.4", "string.prop=str", "boolean.prop=true", "long.prop=1354354354"}); filePath = new Path(dfsBasePath + "/t2.props"); writePropertiesFile(filePath, new String[] {"string.prop=ignored", "include=t1.props"}); filePath = new Path(dfsBasePath + "/t3.props"); writePropertiesFile(filePath, new String[] {"double.prop=838.3", "include = t2.props", "double.prop=243.4", "string.prop=t3.value"}); filePath = new Path(dfsBasePath + "/t4.props"); writePropertiesFile(filePath, new String[] {"double.prop=838.3", "include = t4.props"}); } @AfterAll public static void cleanupClass() throws Exception { if (hdfsTestService != null) { hdfsTestService.stop(); } } private static void writePropertiesFile(Path path, String[] lines) throws IOException { PrintStream out = new PrintStream(dfs.create(path, true)); for (String line : lines) { out.println(line); } out.flush(); out.close(); } @Test public void testParsing() { DFSPropertiesConfiguration cfg = new DFSPropertiesConfiguration(dfs, new Path(dfsBasePath + "/t1.props")); TypedProperties props = cfg.getConfig(); assertEquals(5, props.size()); assertThrows(IllegalArgumentException.class, () -> { props.getString("invalid.key"); }, "Should error out here."); assertEquals(123, props.getInteger("int.prop")); assertEquals(113.4, props.getDouble("double.prop"), 0.001); assertTrue(props.getBoolean("boolean.prop")); assertEquals("str", props.getString("string.prop")); assertEquals(1354354354, props.getLong("long.prop")); assertEquals(123, props.getInteger("int.prop", 456)); assertEquals(113.4, props.getDouble("double.prop", 223.4), 0.001); assertTrue(props.getBoolean("boolean.prop", false)); assertEquals("str", props.getString("string.prop", "default")); assertEquals(1354354354, props.getLong("long.prop", 8578494434L)); assertEquals(456, props.getInteger("bad.int.prop", 456)); assertEquals(223.4, props.getDouble("bad.double.prop", 223.4), 0.001); assertFalse(props.getBoolean("bad.boolean.prop", false)); assertEquals("default", props.getString("bad.string.prop", "default")); assertEquals(8578494434L, props.getLong("bad.long.prop", 8578494434L)); } @Test public void testIncludes() { DFSPropertiesConfiguration cfg = new DFSPropertiesConfiguration(dfs, new Path(dfsBasePath + "/t3.props")); TypedProperties props = cfg.getConfig(); assertEquals(123, props.getInteger("int.prop")); assertEquals(243.4, props.getDouble("double.prop"), 0.001); assertTrue(props.getBoolean("boolean.prop")); assertEquals("t3.value", props.getString("string.prop")); assertEquals(1354354354, props.getLong("long.prop")); assertThrows(IllegalStateException.class, () -> { new DFSPropertiesConfiguration(dfs, new Path(dfsBasePath + "/t4.props")); }, "Should error out on a self-included file."); } }
/** * */ package org.rcsb.mmtf.geometric; import java.io.Serializable; import javax.vecmath.Matrix4d; import javax.vecmath.Point3d; import org.biojava.nbio.structure.symmetry.geometry.SuperPosition; /** * @author Yana Valasatava * */ public class LeastSquaresFitting implements Superposition, Serializable { /** * */ private static final long serialVersionUID = 6446827562623522934L; private Matrix4d tm; private Point3d[] supCoords; @Override public void run(Point3d[] v1, Point3d[] v2) { Point3d[] v1clone = SuperPosition.clonePoint3dArray(v1); tm = SuperPosition.superposeWithTranslation(v1clone, v2); supCoords = v1clone; } @Override public Matrix4d getTransformationMatrix() { return tm; } @Override public Point3d[] getSuperposedCoordanates() { return supCoords; } }
package org.bigbluebutton.red5.client; import java.util.HashMap; import java.util.Map; import org.bigbluebutton.common.messages.ClearWhiteboardReplyMessage; import org.bigbluebutton.common.messages.GetWhiteboardShapesReplyMessage; import org.bigbluebutton.common.messages.IsWhiteboardEnabledReplyMessage; import org.bigbluebutton.common.messages.SendWhiteboardAnnotationReplyMessage; import org.bigbluebutton.common.messages.UndoWhiteboardReplyMessage; import org.bigbluebutton.red5.client.messaging.BroadcastClientMessage; import org.bigbluebutton.red5.client.messaging.ConnectionInvokerService; import org.bigbluebutton.red5.client.messaging.DirectClientMessage; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.JsonParser; public class WhiteboardClientMessageSender { private ConnectionInvokerService service; public WhiteboardClientMessageSender(ConnectionInvokerService service) { this.service = service; } public void handleWhiteboardMessage(String message) { JsonParser parser = new JsonParser(); JsonObject obj = (JsonObject) parser.parse(message); if (obj.has("header") && obj.has("payload")) { JsonObject header = (JsonObject) obj.get("header"); if (header.has("name")) { String messageName = header.get("name").getAsString(); switch (messageName) { case UndoWhiteboardReplyMessage.UNDO_WHITEBOARD_REPLY: UndoWhiteboardReplyMessage uwrm = UndoWhiteboardReplyMessage.fromJson(message); if (uwrm != null) { processUndoWhiteboardReply(uwrm); } break; case ClearWhiteboardReplyMessage.WHITEBOARD_CLEARED_MESSAGE: ClearWhiteboardReplyMessage wcm = ClearWhiteboardReplyMessage.fromJson(message); if (wcm != null) { processClearWhiteboardReply(wcm); } break; case IsWhiteboardEnabledReplyMessage.IS_WHITEBOARD_ENABLED_REPLY: IsWhiteboardEnabledReplyMessage iwe = IsWhiteboardEnabledReplyMessage.fromJson(message); if (iwe != null) { processIsWhiteboardEnabledReply(iwe); } break; case GetWhiteboardShapesReplyMessage.GET_WHITEBOARD_SHAPES_REPLY: GetWhiteboardShapesReplyMessage gwsrm = GetWhiteboardShapesReplyMessage.fromJson(message); if (gwsrm != null) { processGetWhiteboardShapesReplyMessage(gwsrm); } break; case SendWhiteboardAnnotationReplyMessage.SEND_WHITEBOARD_ANNOTATION_REPLY: SendWhiteboardAnnotationReplyMessage swarm = SendWhiteboardAnnotationReplyMessage.fromJson(message); if (swarm != null) { processSendWhiteboardAnnotationReplyMessage(swarm); } break; } } } } private void processSendWhiteboardAnnotationReplyMessage(SendWhiteboardAnnotationReplyMessage msg) { Map<String, Object> args = new HashMap<String, Object>(); args.put("whiteboardId", msg.whiteboardId); Map<String, Object> shape = new HashMap<String, Object>(); shape.put("id", msg.shape.get("id")); shape.put("type", msg.shape.get("type")); shape.put("status", msg.shape.get("status")); shape.put("shape", msg.shape.get("shapes")); args.put("shape", shape); Map<String, Object> message = new HashMap<String, Object>(); Gson gson = new Gson(); message.put("msg", gson.toJson(args)); //broadcast message BroadcastClientMessage b = new BroadcastClientMessage(msg.meetingId, "WhiteboardNewAnnotationCommand", message); service.sendMessage(b); } private void processGetWhiteboardShapesReplyMessage(GetWhiteboardShapesReplyMessage msg) { Map<String, Object> args = new HashMap<String, Object>(); args.put("whiteboardId", msg.whiteboardId); args.put("count", msg.shapes.size()); args.put("annotations",msg.shapes); Map<String, Object> message = new HashMap<String, Object>(); Gson gson = new Gson(); message.put("msg", gson.toJson(args)); DirectClientMessage m = new DirectClientMessage(msg.meetingId, msg.requesterId, "WhiteboardRequestAnnotationHistoryReply", message); service.sendMessage(m); } private void processIsWhiteboardEnabledReply(IsWhiteboardEnabledReplyMessage msg) { Map<String, Object> args = new HashMap<String, Object>(); args.put("enabled", msg.enabled); Map<String, Object> message = new HashMap<String, Object>(); Gson gson = new Gson(); message.put("msg", gson.toJson(args)); DirectClientMessage m = new DirectClientMessage(msg.meetingId, msg.requesterId, "WhiteboardIsWhiteboardEnabledReply", message); service.sendMessage(m); // broadcast message BroadcastClientMessage b = new BroadcastClientMessage(msg.meetingId, "WhiteboardIsWhiteboardEnabledReply", message); service.sendMessage(b); } private void processClearWhiteboardReply(ClearWhiteboardReplyMessage msg) { Map<String, Object> args = new HashMap<String, Object>(); args.put("whiteboardId", msg.whiteboardId); Map<String, Object> message = new HashMap<String, Object>(); Gson gson = new Gson(); message.put("msg", gson.toJson(args)); BroadcastClientMessage m = new BroadcastClientMessage(msg.meetingId, "WhiteboardClearCommand", message); service.sendMessage(m); } private void processUndoWhiteboardReply(UndoWhiteboardReplyMessage msg) { Map<String, Object> args = new HashMap<String, Object>(); args.put("shapeId", msg.shapeId); args.put("whiteboardId", msg.whiteboardId); Map<String, Object> message = new HashMap<String, Object>(); Gson gson = new Gson(); message.put("msg", gson.toJson(args)); BroadcastClientMessage m = new BroadcastClientMessage(msg.meetingId, "WhiteboardUndoCommand", message); service.sendMessage(m); } }
package assignment_basics; // Question 18 public class Palindrome { static int reverse(int i){ if (i<0){ return 0; } else{ int num = 0; while (i!= 0){ num = (num*10)+(i%10); i = i/10; } return num; } } public static void main(String[] args){ int num = 0; if (args.length == 1){ try { num = Integer.parseInt(args[0]); } catch (NumberFormatException e) { System.err.println("Please enter valid number"); System.exit(2); } } else if (args.length == 0){ System.out.println("Please enter an integer number"); System.exit(3); } else { System.out.println("Please enter one number"); System.exit(4); } if (reverse(num) == num){ System.out.println(num+" is a palindrome"); } else { System.out.println(num+" is not a palindrome"); } } }
package com.litle.sdk; import java.util.Calendar; public class JAXBConverters { public static Calendar parseDate(String value){ if(value == null){ return null; } return (javax.xml.bind.DatatypeConverter.parseDate(value)); } public static String printDate(Calendar value){ if(value == null){ return null; } return (com.litle.sdk.CalendarPrinter.printDate(value)); } public static String parseString(String value){ if(value == null){ return null; } return (java.lang.String.valueOf(value)); } public static String printString(String value){ if(value == null){ return null; } return (java.lang.String.valueOf(value)); } public static Long parseLong(String value){ if(value == null){ return null; } return (java.lang.Long.valueOf(value)); } public static String printLong(Long value){ if(value == null){ return null; } return (java.lang.Long.toString(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.solr.update.processor; import java.io.IOException; import java.util.Date; import org.apache.solr.common.SolrException; import static org.apache.solr.common.SolrException.ErrorCode.*; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.util.NamedList; import org.apache.solr.request.SolrRequestInfo; import org.apache.solr.request.SolrQueryRequest; import org.apache.solr.response.SolrQueryResponse; import org.apache.solr.update.AddUpdateCommand; import org.apache.solr.common.params.CommonParams; // javadoc /** * <p> * An update processor that adds a newly generated <code>Date</code> value * of "NOW" to any document being added that does not already have a value * in the specified field. * </p> * * <p> * In the example configuration below, if a document does not contain a value * in the <code>timestamp</code> field, a new <code>Date</code> will be * generated and added as the value of that field. * <br> * * <pre class="prettyprint"> * &lt;processor class="solr.TimestampUpdateProcessorFactory"&gt; * &lt;str name="fieldName"&gt;timestamp&lt;/str&gt; * &lt;/processor&gt; * </pre> * * @see Date * @see CommonParams#NOW */ public class TimestampUpdateProcessorFactory extends AbstractDefaultValueUpdateProcessorFactory { @Override public UpdateRequestProcessor getInstance(SolrQueryRequest req, SolrQueryResponse rsp, UpdateRequestProcessor next ) { return new DefaultValueUpdateProcessor(fieldName, next) { @Override public Object getDefaultValue() { return SolrRequestInfo.getRequestInfo().getNOW(); } }; } }