repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
pushinginertia/pushinginertia-commons
pushinginertia-commons-core/src/test/java/com/pushinginertia/commons/core/validation/ValidateAsTest.java
4635
/* Copyright (c) 2011-2014 Pushing Inertia * All rights reserved. http://pushinginertia.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.pushinginertia.commons.core.validation; import org.junit.Assert; import org.junit.Test; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class ValidateAsTest { @Test(expected = IllegalArgumentException.class) public void notNull() { ValidateAs.notNull(null, "nullParameter"); } @Test public void notEmpty() { ValidateAs.notEmpty("abc", "emptyParameter"); } @Test(expected = IllegalArgumentException.class) public void notEmptyFail() { ValidateAs.notEmpty("", "emptyParameter"); } @Test public void trimmedNotEmpty() { Assert.assertEquals("abc", ValidateAs.trimmedNotEmpty(" abc ", "emptyParameter")); } @Test(expected = IllegalArgumentException.class) public void trimmedNotEmptyFail() { ValidateAs.trimmedNotEmpty(" ", "emptyParameter"); } @Test public void notEqual() { ValidateAs.notEqual("abc", "def", "string1", "string2"); } @Test(expected = IllegalArgumentException.class) public void notEqualFail() { ValidateAs.notEqual("abc", "abc", "string1", "string2"); } @Test public void equal() { ValidateAs.equal("abc", "abc", "string1", "string2"); } @Test(expected = IllegalArgumentException.class) public void equalFail() { ValidateAs.equal("abc", "def", "string1", "string2"); } @Test(expected = IllegalArgumentException.class) public void positive0() { ValidateAs.positive(0, "zeroParameter"); } @Test(expected = IllegalArgumentException.class) public void positiveMinus1() { ValidateAs.positive(-1, "minusOneParameter"); } @Test public void nonNegative() { ValidateAs.nonNegative(BigDecimal.ZERO, "bd1"); ValidateAs.nonNegative(BigDecimal.ONE, "bd2"); } @Test(expected = IllegalArgumentException.class) public void nonNegativeFail() { ValidateAs.nonNegative(new BigDecimal(-1), "bd1"); } @Test public void mapDoesNotContainKey() { final Map<String, String> m = new HashMap<String, String>(); // positive case ValidateAs.mapDoesNotContainKey(m, "a"); // negative case m.put("a", "1"); try { ValidateAs.mapDoesNotContainKey(m, "a"); Assert.fail("Expected IllegalArgumentException"); } catch (final IllegalArgumentException e) { // expected } } @Test public void ofLength() { ValidateAs.ofLength("abc", 3, "string1"); } @Test(expected = IllegalArgumentException.class) public void ofLengthFail() { ValidateAs.ofLength("abc", 2, "string1"); } @Test public void ofMinimumLength() { ValidateAs.ofMinimumLength("abc", 3, "string1"); ValidateAs.ofMinimumLength("abcd", 3, "string1"); } @Test(expected = IllegalArgumentException.class) public void ofMinimumLengthFail() { ValidateAs.ofMinimumLength("ab", 3, "string1"); } @Test public void allUppercase() { ValidateAs.allUppercase("ABC", "string"); } @Test(expected = IllegalArgumentException.class) public void allUppercaseFail1() { ValidateAs.allUppercase("ABc", "string"); } @Test(expected = IllegalArgumentException.class) public void allUppercaseFail2() { ValidateAs.allUppercase("ABC1", "string"); } @Test public void indexInList() { ValidateAs.indexInList(Arrays.asList(1, 2, 3), 0, "listname"); ValidateAs.indexInList(Arrays.asList(1, 2, 3), 1, "listname"); ValidateAs.indexInList(Arrays.asList(1, 2, 3), 2, "listname"); } @Test(expected = IllegalArgumentException.class) public void indexInListFailNegativeIndex() { ValidateAs.indexInList(Arrays.asList(1, 2, 3), -1, "listname"); } @Test(expected = IllegalArgumentException.class) public void indexInListFailOutOfBoundsIndex() { ValidateAs.indexInList(Arrays.asList(1, 2, 3), 3, "listname"); } @Test(expected = IllegalArgumentException.class) public void indexInListFailEmptyList() { ValidateAs.indexInList(new ArrayList(), 0, "listname"); } @Test(expected = IllegalArgumentException.class) public void indexInListFailNullList() { ValidateAs.indexInList(null, 0, "listname"); } }
apache-2.0
umangmehta12/elasticsearch-server
elasticsearch-test-integration/src/test/java/org/elasticsearch/test/integration/cluster/SimpleDataNodesTests.java
3547
/* * Licensed to ElasticSearch and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. ElasticSearch licenses this * file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.test.integration.cluster; import org.elasticsearch.action.UnavailableShardsException; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.client.AdminRequests; import org.elasticsearch.test.integration.AbstractNodesTests; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import static org.elasticsearch.client.AdminRequests.createIndexRequest; import static org.elasticsearch.client.IngestRequests.*; import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder; import static org.elasticsearch.common.unit.TimeValue.timeValueSeconds; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; /** * */ public class SimpleDataNodesTests extends AbstractNodesTests { @AfterMethod public void closeNodes() { closeAllNodes(); } @Test public void testDataNodes() throws Exception { startNode("nonData1", settingsBuilder().put("node.data", false).build()); client("nonData1").admin().indices().create(createIndexRequest("test")).actionGet(); try { client("nonData1").index(indexRequest("test").type("type1").id("1").source(source("1", "test")).timeout(timeValueSeconds(1))).actionGet(); assert false : "no allocation should happen"; } catch (UnavailableShardsException e) { // all is well } startNode("nonData2", settingsBuilder().put("node.data", false).build()); assertThat(client("nonData1").admin().cluster().prepareHealth().setWaitForNodes("2").execute().actionGet().timedOut(), equalTo(false)); // still no shard should be allocated try { client("nonData2").index(indexRequest("test").type("type1").id("1").source(source("1", "test")).timeout(timeValueSeconds(1))).actionGet(); assert false : "no allocation should happen"; } catch (UnavailableShardsException e) { // all is well } // now, start a node data, and see that it gets with shards startNode("data1", settingsBuilder().put("node.data", true).build()); assertThat(client("nonData1").admin().cluster().prepareHealth().setWaitForNodes("3").execute().actionGet().timedOut(), equalTo(false)); IndexResponse indexResponse = client("nonData2").index(indexRequest("test").type("type1").id("1").source(source("1", "test"))).actionGet(); assertThat(indexResponse.id(), equalTo("1")); assertThat(indexResponse.type(), equalTo("type1")); } private String source(String id, String nameValue) { return "{ type1 : { \"id\" : \"" + id + "\", \"name\" : \"" + nameValue + "\" } }"; } }
apache-2.0
blackbarTeam/Android-TDC-TourismGuide-2016
TourismGuide/app/src/main/java/com/edu/tdc/blackbar/tourismguide/myAdapter/MyAdapter.java
2988
package com.edu.tdc.blackbar.tourismguide.myAdapter; import android.app.Activity; import android.support.annotation.NonNull; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import com.edu.tdc.blackbar.tourismguide.R; /** * Created by Shiro on 03/12/2016. */ public class MyAdapter extends ArrayAdapter { private Activity context; private int IDLayout; private String[] keyTypesSearch = null; public MyAdapter(Activity context, int resource, String[] types) { super(context, resource, types); this.context = context; this.IDLayout = resource; this.keyTypesSearch = types; } @NonNull @Override public View getView(int position, View convertView, ViewGroup parent) { convertView = context.getLayoutInflater().inflate(this.IDLayout,null); if(keyTypesSearch.length > 0 && position >= 0){ //add key TextView keyTypes = (TextView)convertView.findViewById(R.id.txt_types_item); keyTypes.setText(keyTypesSearch[position]); //add icon ImageView ic_item = (ImageView)convertView.findViewById(R.id.ic_types_item); switch (keyTypesSearch[position]){ case "Cafe": { ic_item.setImageResource(R.drawable.cafe); break; }case "Food": { ic_item.setImageResource(R.drawable.food); break; }case "Gym": { ic_item.setImageResource(R.drawable.gym); break; }case "Park": { ic_item.setImageResource(R.drawable.park); break; }case "Bar": { ic_item.setImageResource(R.drawable.bar); break; }case "Post Office": { ic_item.setImageResource(R.drawable.office); break; }case "Airport": { ic_item.setImageResource(R.drawable.airport); break; }case "Car Repair": { ic_item.setImageResource(R.drawable.car_rp); break; }case "ATM": { ic_item.setImageResource(R.drawable.atm); break; }case "Bank": { ic_item.setImageResource(R.drawable.bank); break; }case "Police": { ic_item.setImageResource(R.drawable.police); break; }case "Hospital": { ic_item.setImageResource(R.drawable.hospital); break; }default:{ } } } return convertView; } }
apache-2.0
hmusavi/jpo-ode
jpo-ode-common/src/test/java/us/dot/its/jpo/ode/inet/InetPacketSenderTest.java
20056
package us.dot.its.jpo.ode.inet; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.util.Arrays; import org.apache.log4j.Logger; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import mockit.Capturing; import us.dot.its.jpo.ode.util.CodecUtils; public class InetPacketSenderTest { @Capturing DatagramSocket capturingDatagramSocket; @Capturing DatagramPacket capturingDatagramPacket; @Capturing Thread capturingThread; static final private boolean isDebugOutput = false; private static Logger log = Logger.getLogger(InetPacketSenderTest.class); private static final int DEFAULT_MAX_PACKET_SIZE = 65535; private static final String TRANSPORT_HOST = "localhost"; private static final int TRANSPORT_PORT = 46751; private static final String FORWARDER_HOST = "localhost"; private static final int FORWARDER_PORT = 46752; private static final String CLIENT_HOST_IPV4 = "localhost"; private static final String CLIENT_HOST_IPV6 = "::1"; private static final int CLIENT_PORT = 46753; private static final byte[] PAYLOAD = new byte[] { (byte) 0xde, (byte) 0xad, (byte) 0xbe, (byte) 0xef, (byte) 0xca, (byte) 0xfe, (byte) 0xba, (byte) 0xbe }; AssertionError assertionError = null; private enum TestCase { TestForwardPacketInbound, TestSendPacketOutbound, TestIPv6ForwardOutbound, TestIPv4ForwardOutboundForward, TestIPv4ForwardOutboundSend, TestIPv6SendOutbound, TestIPv4SendOutbound, }; @BeforeClass public static void init() { } @Test public void testForwardPacketInboundIPV4() throws UnknownHostException, InetPacketException, InterruptedException { // Use case: Forwarder forwards incoming IPV4 packet to transport testForwardPacketInbound(CLIENT_HOST_IPV4); } @Test public void testForwardPacketInboundIPV6() throws UnknownHostException, InetPacketException, InterruptedException { // Use case: Forwarder forwards incoming IPV6 packet to transport testForwardPacketInbound(CLIENT_HOST_IPV6); } public void testForwardPacketInbound(String hostname) throws UnknownHostException, InetPacketException, InterruptedException { startUdpListener(TRANSPORT_PORT, TestCase.TestForwardPacketInbound); InetPoint transport = new InetPoint(getAddressBytes(TRANSPORT_HOST), TRANSPORT_PORT); InetPacketSender sender = new InetPacketSender(transport); DatagramPacket packet = new DatagramPacket(PAYLOAD, PAYLOAD.length, InetAddress.getByName(hostname), CLIENT_PORT); sender.forward(packet); checkBackgroundThreadAssertion(); } @Test @Ignore public void testSendPacketOutboundIPv4() throws UnknownHostException, InterruptedException, InetPacketException { // Use case: Forwarder sends outgoing IPv4 packet out testSendPacketOutbound(CLIENT_HOST_IPV4); } @Test @Ignore public void testSendPacketOutboundIPv6() throws UnknownHostException, InterruptedException, InetPacketException { // Use case: Forwarder sends outgoing IPv6 packet out testSendPacketOutbound(CLIENT_HOST_IPV6); } public void testSendPacketOutbound(String hostname) throws UnknownHostException, InetPacketException, InterruptedException { startUdpListener(CLIENT_PORT, TestCase.TestSendPacketOutbound); InetPoint client = new InetPoint(getAddressBytes(hostname), CLIENT_PORT); byte[] bundle = new InetPacket(client, PAYLOAD).getBundle(); InetPacketSender sender = new InetPacketSender(); DatagramPacket packet = new DatagramPacket(bundle, bundle.length, InetAddress.getByName(FORWARDER_HOST), FORWARDER_PORT); sender.send(packet); checkBackgroundThreadAssertion(); } @Test public void testIPv6ForwardOutbound() throws UnknownHostException, InetPacketException, InterruptedException { // Use case: Transport or Data Sink send IPv6 message out via forwarder startUdpListener(FORWARDER_PORT, TestCase.TestIPv6ForwardOutbound); InetPoint forwarder = new InetPoint(getAddressBytes(FORWARDER_HOST), FORWARDER_PORT); InetPacketSender sender = new InetPacketSender(forwarder); InetPoint client = new InetPoint(getAddressBytes(CLIENT_HOST_IPV6), CLIENT_PORT); sender.forward(client, PAYLOAD); checkBackgroundThreadAssertion(); } @Test public void testIPv4ForwardOutboundForward() throws InterruptedException, UnknownHostException, InetPacketException { // Use case: Transport or Data Sink send IPv4 message out via forwarder startUdpListener(FORWARDER_PORT, TestCase.TestIPv4ForwardOutboundForward); InetPoint forwarder = new InetPoint(getAddressBytes(FORWARDER_HOST), FORWARDER_PORT); InetPacketSender sender = new InetPacketSender(forwarder); sender.setForwardAll(true); InetPoint client = new InetPoint(getAddressBytes(CLIENT_HOST_IPV4), CLIENT_PORT); sender.forward(client, PAYLOAD); checkBackgroundThreadAssertion(); } @Test public void testIPv4ForwardOutboundSend() throws InterruptedException, UnknownHostException, InetPacketException { // Use case: Transport or Data Sink send IPv4 message out via forwarder // but it's being send out directly startUdpListener(CLIENT_PORT, TestCase.TestIPv4ForwardOutboundSend); InetPoint forwarder = new InetPoint(getAddressBytes(FORWARDER_HOST), FORWARDER_PORT); InetPacketSender sender = new InetPacketSender(forwarder); InetPoint client = new InetPoint(getAddressBytes(CLIENT_HOST_IPV4), CLIENT_PORT); sender.forward(client, PAYLOAD); checkBackgroundThreadAssertion(); } @Test public void testIPv6SendOutbound() throws InterruptedException, UnknownHostException, InetPacketException { // Use case: Transport or Data Sink send IPv6 message out directly startUdpListener(CLIENT_PORT, TestCase.TestIPv6SendOutbound); InetPacketSender sender = new InetPacketSender(); InetPoint client = new InetPoint(getAddressBytes(CLIENT_HOST_IPV6), CLIENT_PORT); sender.send(client, PAYLOAD); checkBackgroundThreadAssertion(); } @Test public void testIPv4SendOutbound() throws InterruptedException, UnknownHostException, InetPacketException { // Use case: Transport or Data Sink send IPv4 message out directly startUdpListener(CLIENT_PORT, TestCase.TestIPv4SendOutbound); InetPacketSender sender = new InetPacketSender(); InetPoint client = new InetPoint(getAddressBytes(CLIENT_HOST_IPV4), CLIENT_PORT); sender.send(client, PAYLOAD); checkBackgroundThreadAssertion(); } private static byte[] getAddressBytes(String host) throws UnknownHostException { return InetAddress.getByName(host).getAddress(); } private void startUdpListener(int port, TestCase tc) { final int listenPort = port; final TestCase testCase = tc; Thread listener = new Thread(new Runnable() { @Override public void run() { DatagramSocket socket = null; try { socket = new DatagramSocket(listenPort); DatagramPacket datagramPacket = new DatagramPacket(new byte[DEFAULT_MAX_PACKET_SIZE], DEFAULT_MAX_PACKET_SIZE); socket.setSoTimeout(1000); socket.receive(datagramPacket); validatePacket(datagramPacket); } catch (SocketTimeoutException ex) { log.error( String.format("Caught socket timeout exception while recieving message on port %d. Max size is %d", listenPort, DEFAULT_MAX_PACKET_SIZE), ex); assertTrue(false); } catch (SocketException ex) { log.error(String.format("Caught socket exception while recieving message on port %d. Max size is %d", listenPort, DEFAULT_MAX_PACKET_SIZE), ex); assertTrue(false); } catch (IOException ex) { log.error( String.format("Caught IO exception exception while recieving message on port %d. Max size is %d", listenPort, DEFAULT_MAX_PACKET_SIZE), ex); assertTrue(false); } finally { if (socket != null && !socket.isClosed()) { socket.close(); socket = null; } } } private void validatePacket(DatagramPacket packet) throws UnknownHostException { assertNotNull(packet); final byte[] data = packet.getData(); assertNotNull(data); final int length = packet.getLength(); assertTrue(length > 0); final int offset = packet.getOffset(); byte[] packetData = Arrays.copyOfRange(data, offset, length); try { switch (testCase) { case TestForwardPacketInbound: validateForwardPacketInbound(packetData); validateForwardPacketInbound(packet); break; case TestSendPacketOutbound: validateSendPacketOutbound(packetData); validateSendPacketOutbound(packet); break; case TestIPv6ForwardOutbound: validateIPv6ForwardOutbound(packetData); validateIPv6ForwardOutbound(packet); break; case TestIPv4ForwardOutboundForward: validateIPv4ForwardOutboundForward(packetData); validateIPv4ForwardOutboundForward(packet); break; case TestIPv4ForwardOutboundSend: validateIPv4ForwardOutboundSend(packetData); validateIPv4ForwardOutboundSend(packet); break; case TestIPv6SendOutbound: validateIPv6SendOutbound(packetData); validateIPv6SendOutbound(packet); break; case TestIPv4SendOutbound: validateIPv4SendOutbound(packetData); validateIPv4SendOutbound(packet); break; } } catch (AssertionError ex) { assertionError = ex; } } private void validateForwardPacketInbound(byte[] payload) throws UnknownHostException { validateForwardPacketInbound("Payload", new InetPacket(payload)); } private void validateForwardPacketInbound(DatagramPacket packet) throws UnknownHostException { validateForwardPacketInbound("Packet", new InetPacket(packet)); } private void validateForwardPacketInbound(String tail, InetPacket p) throws UnknownHostException { assertNotNull(p); if (isDebugOutput) print("ForwardPacketInbound", p); assertEquals(listenPort, TRANSPORT_PORT); InetPoint point = p.getPoint(); assertNotNull(point); byte[] srcAddress = point.address; assertNotNull(srcAddress); if (point.isIPv6Address()) assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV6)); else assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV4)); assertEquals(point.port, CLIENT_PORT); assertEquals(point.forward, true); assertArrayEquals(p.getPayload(), PAYLOAD); } private void validateSendPacketOutbound(byte[] payload) throws UnknownHostException { InetPacket p = new InetPacket(payload); assertNotNull(p); if (isDebugOutput) print("SendPacketOutbound Payload", p); assertEquals(listenPort, CLIENT_PORT); InetPoint point = p.getPoint(); assertNull(point); assertArrayEquals(p.getPayload(), PAYLOAD); } private void validateSendPacketOutbound(DatagramPacket packet) throws UnknownHostException { InetPacket p = new InetPacket(packet); assertNotNull(p); if (isDebugOutput) print("SendPacketOutbound Packet", p); assertEquals(listenPort, CLIENT_PORT); InetPoint point = p.getPoint(); assertNotNull(point); byte[] srcAddress = point.address; assertNotNull(srcAddress); if (point.isIPv6Address()) assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV6)); else assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV4)); assertFalse(point.forward); assertArrayEquals(p.getPayload(), PAYLOAD); } private void validateIPv6ForwardOutbound(byte[] payload) throws UnknownHostException { validateIPv6ForwardOutbound("Payload", new InetPacket(payload)); } private void validateIPv6ForwardOutbound(DatagramPacket packet) throws UnknownHostException { validateIPv6ForwardOutbound("Packet", new InetPacket(packet)); } private void validateIPv6ForwardOutbound(String tail, InetPacket p) throws UnknownHostException { assertNotNull(p); if (isDebugOutput) print("IPv6ForwardOutbound " + tail, p); assertEquals(listenPort, FORWARDER_PORT); InetPoint point = p.getPoint(); assertNotNull(point); byte[] srcAddress = point.address; assertNotNull(srcAddress); assertTrue(point.isIPv6Address()); assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV6)); assertEquals(point.port, CLIENT_PORT); assertEquals(point.forward, true); assertArrayEquals(p.getPayload(), PAYLOAD); } private void validateIPv4ForwardOutboundForward(byte[] payload) throws UnknownHostException { validateIPv4ForwardOutboundForward("Payload", new InetPacket(payload)); } private void validateIPv4ForwardOutboundForward(DatagramPacket packet) throws UnknownHostException { validateIPv4ForwardOutboundForward("Packet", new InetPacket(packet)); } private void validateIPv4ForwardOutboundForward(String tail, InetPacket p) throws UnknownHostException { assertNotNull(p); if (isDebugOutput) print("IPv4ForwardOutboundForward " + tail, p); assertEquals(listenPort, FORWARDER_PORT); InetPoint point = p.getPoint(); assertNotNull(point); byte[] srcAddress = point.address; assertNotNull(srcAddress); assertFalse(point.isIPv6Address()); assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV4)); assertEquals(point.port, CLIENT_PORT); assertEquals(point.forward, true); assertArrayEquals(p.getPayload(), PAYLOAD); } private void validateIPv4ForwardOutboundSend(byte[] payload) throws UnknownHostException { InetPacket p = new InetPacket(payload); assertNotNull(p); if (isDebugOutput) print("IPv4ForwardOutboundSend Payload", p); assertEquals(listenPort, CLIENT_PORT); InetPoint point = p.getPoint(); assertNull(point); assertArrayEquals(p.getPayload(), PAYLOAD); } private void validateIPv4ForwardOutboundSend(DatagramPacket packet) throws UnknownHostException { InetPacket p = new InetPacket(packet); assertNotNull(p); if (isDebugOutput) print("IPv4ForwardOutboundSend Packet", p); assertEquals(listenPort, CLIENT_PORT); InetPoint point = p.getPoint(); assertNotNull(point); byte[] srcAddress = point.address; assertNotNull(srcAddress); if (point.isIPv6Address()) assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV6)); else assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV4)); assertFalse(point.forward); assertArrayEquals(p.getPayload(), PAYLOAD); } private void validateIPv6SendOutbound(byte[] payload) throws UnknownHostException { validateIPvXSendOutboundPayload(new InetPacket(payload)); } private void validateIPv4SendOutbound(byte[] payload) throws UnknownHostException { validateIPvXSendOutboundPayload(new InetPacket(payload)); } private void validateIPv6SendOutbound(DatagramPacket packet) throws UnknownHostException { validateIPvXSendOutboundPacket(new InetPacket(packet)); } private void validateIPv4SendOutbound(DatagramPacket packet) throws UnknownHostException { validateIPvXSendOutboundPacket(new InetPacket(packet)); } private void validateIPvXSendOutboundPayload(InetPacket p) throws UnknownHostException { assertNotNull(p); if (isDebugOutput) print("IPvXSendOutbound Payload", p); assertEquals(listenPort, CLIENT_PORT); InetPoint point = p.getPoint(); assertNull(point); assertArrayEquals(p.getPayload(), PAYLOAD); } private void validateIPvXSendOutboundPacket(InetPacket p) throws UnknownHostException { assertNotNull(p); if (isDebugOutput) print("IPvXSendOutbound Packet", p); assertEquals(listenPort, CLIENT_PORT); InetPoint point = p.getPoint(); assertNotNull(point); byte[] srcAddress = point.address; assertNotNull(srcAddress); if (point.isIPv6Address()) assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV6)); else assertArrayEquals(point.address, getAddressBytes(CLIENT_HOST_IPV4)); assertFalse(point.forward); assertArrayEquals(p.getPayload(), PAYLOAD); } private void print(String header, InetPacket pb) throws UnknownHostException { assertNotNull(pb); InetPoint point = pb.getPoint(); if (point != null) { System.out.printf("%s: port: %d (0x%x)\n", header, point.port, point.port); System.out.printf("%s: address size: %d value: %s ip: %s\n", header, point.address.length, CodecUtils.toHex(point.address), InetAddress.getByAddress(point.address).getHostAddress()); System.out.printf("%s: forward: %s\n", header, point.forward ? "true" : "false"); } else { System.out.printf("%s: Inet point is null\n", header); } byte[] p = pb.getPayload(); System.out.printf("%s: payload: %s\n", header, p != null && p.length > 0 ? CodecUtils.toHex(p) : "<empty>"); System.out.printf("%s: bundle: %s\n", header, pb.toHexString()); } }); listener.start(); try { Thread.sleep(500); } catch (InterruptedException e) { } } void checkBackgroundThreadAssertion() { try { Thread.sleep(1500); } catch (InterruptedException unused) { } if (assertionError != null) throw assertionError; } }
apache-2.0
NonVolatileComputing/arrow
java/vector/src/test/java/org/apache/arrow/vector/TestBitVector.java
17934
/** * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.arrow.vector; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import org.apache.arrow.memory.BufferAllocator; import org.apache.arrow.memory.RootAllocator; import org.apache.arrow.vector.util.TransferPair; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class TestBitVector { private final static String EMPTY_SCHEMA_PATH = ""; private BufferAllocator allocator; @Before public void init() { allocator = new RootAllocator(Long.MAX_VALUE); } @After public void terminate() throws Exception { allocator.close(); } @Test public void testBitVectorCopyFromSafe() { final int size = 20; try (final BitVector src = new BitVector(EMPTY_SCHEMA_PATH, allocator); final BitVector dst = new BitVector(EMPTY_SCHEMA_PATH, allocator)) { src.allocateNew(size); dst.allocateNew(10); for (int i = 0; i < size; i++) { src.getMutator().set(i, i % 2); } src.getMutator().setValueCount(size); for (int i = 0; i < size; i++) { dst.copyFromSafe(i, i, src); } dst.getMutator().setValueCount(size); for (int i = 0; i < size; i++) { assertEquals(src.getAccessor().getObject(i), dst.getAccessor().getObject(i)); } } } @Test public void testSplitAndTransfer() throws Exception { try (final BitVector sourceVector = new BitVector("bitvector", allocator)) { final BitVector.Mutator sourceMutator = sourceVector.getMutator(); final BitVector.Accessor sourceAccessor = sourceVector.getAccessor(); sourceVector.allocateNew(40); /* populate the bitvector -- 010101010101010101010101..... */ for (int i = 0; i < 40; i++) { if ((i & 1) == 1) { sourceMutator.set(i, 1); } else { sourceMutator.set(i, 0); } } sourceMutator.setValueCount(40); /* check the vector output */ for (int i = 0; i < 40; i++) { int result = sourceAccessor.get(i); if ((i & 1) == 1) { assertEquals(Integer.toString(1), Integer.toString(result)); } else { assertEquals(Integer.toString(0), Integer.toString(result)); } } try (final BitVector toVector = new BitVector("toVector", allocator)) { final TransferPair transferPair = sourceVector.makeTransferPair(toVector); final BitVector.Accessor toAccessor = toVector.getAccessor(); final BitVector.Mutator toMutator = toVector.getMutator(); /* * form test cases such that we cover: * * (1) the start index is exactly where a particular byte starts in the source bit vector * (2) the start index is randomly positioned within a byte in the source bit vector * (2.1) the length is a multiple of 8 * (2.2) the length is not a multiple of 8 */ final int[][] transferLengths = {{0, 8}, {8, 10}, {18, 0}, {18, 8}, {26, 0}, {26, 14}}; for (final int[] transferLength : transferLengths) { final int start = transferLength[0]; final int length = transferLength[1]; transferPair.splitAndTransfer(start, length); /* check the toVector output after doing splitAndTransfer */ for (int i = 0; i < length; i++) { int actual = toAccessor.get(i); int expected = sourceAccessor.get(start + i); assertEquals("different data values not expected --> sourceVector index: " + (start + i) + " toVector index: " + i, expected, actual); } } } } } @Test public void testSplitAndTransfer1() throws Exception { try (final BitVector sourceVector = new BitVector("bitvector", allocator)) { final BitVector.Mutator sourceMutator = sourceVector.getMutator(); final BitVector.Accessor sourceAccessor = sourceVector.getAccessor(); sourceVector.allocateNew(8190); /* populate the bitvector */ for (int i = 0; i < 8190; i++) { sourceMutator.set(i, 1); } sourceMutator.setValueCount(8190); /* check the vector output */ for (int i = 0; i < 8190; i++) { int result = sourceAccessor.get(i); assertEquals(Integer.toString(1), Integer.toString(result)); } try (final BitVector toVector = new BitVector("toVector", allocator)) { final TransferPair transferPair = sourceVector.makeTransferPair(toVector); final BitVector.Accessor toAccessor = toVector.getAccessor(); final BitVector.Mutator toMutator = toVector.getMutator(); final int[][] transferLengths = {{0, 4095}, {4095, 4095}}; for (final int[] transferLength : transferLengths) { final int start = transferLength[0]; final int length = transferLength[1]; transferPair.splitAndTransfer(start, length); /* check the toVector output after doing splitAndTransfer */ for (int i = 0; i < length; i++) { int actual = toAccessor.get(i); int expected = sourceAccessor.get(start + i); assertEquals("different data values not expected --> sourceVector index: " + (start + i) + " toVector index: " + i, expected, actual); } } } } } @Test public void testSplitAndTransfer2() throws Exception { try (final BitVector sourceVector = new BitVector("bitvector", allocator)) { final BitVector.Mutator sourceMutator = sourceVector.getMutator(); final BitVector.Accessor sourceAccessor = sourceVector.getAccessor(); sourceVector.allocateNew(32); /* populate the bitvector */ for (int i = 0; i < 32; i++) { if ((i & 1) == 1) { sourceMutator.set(i, 1); } else { sourceMutator.set(i, 0); } } sourceMutator.setValueCount(32); /* check the vector output */ for (int i = 0; i < 32; i++) { int result = sourceAccessor.get(i); if ((i & 1) == 1) { assertEquals(Integer.toString(1), Integer.toString(result)); } else { assertEquals(Integer.toString(0), Integer.toString(result)); } } try (final BitVector toVector = new BitVector("toVector", allocator)) { final TransferPair transferPair = sourceVector.makeTransferPair(toVector); final BitVector.Accessor toAccessor = toVector.getAccessor(); final BitVector.Mutator toMutator = toVector.getMutator(); final int[][] transferLengths = {{5,22}, {5,24}, {5,25}, {5,27}, {0,31}, {5,7}, {2,3}}; for (final int[] transferLength : transferLengths) { final int start = transferLength[0]; final int length = transferLength[1]; transferPair.splitAndTransfer(start, length); /* check the toVector output after doing splitAndTransfer */ for (int i = 0; i < length; i++) { int actual = toAccessor.get(i); int expected = sourceAccessor.get(start + i); assertEquals("different data values not expected --> sourceVector index: " + (start + i) + " toVector index: " + i, expected, actual); } } } } } @Test public void testReallocAfterVectorTransfer1() { try (final BitVector vector = new BitVector(EMPTY_SCHEMA_PATH, allocator)) { vector.allocateNew(4096); int valueCapacity = vector.getValueCapacity(); assertEquals(4096, valueCapacity); final BitVector.Mutator mutator = vector.getMutator(); final BitVector.Accessor accessor = vector.getAccessor(); for (int i = 0; i < valueCapacity; i++) { if ((i & 1) == 1) { mutator.setToOne(i); } } for (int i = 0; i < valueCapacity; i++) { int val = accessor.get(i); if ((i & 1) == 1) { assertEquals("unexpected cleared bit at index: " + i, 1, val); } else { assertEquals("unexpected set bit at index: " + i, 0, val); } } /* trigger first realloc */ mutator.setSafeToOne(valueCapacity); assertEquals(valueCapacity * 2, vector.getValueCapacity()); for (int i = valueCapacity; i < valueCapacity*2; i++) { if ((i & 1) == 1) { mutator.setToOne(i); } } for (int i = 0; i < valueCapacity*2; i++) { int val = accessor.get(i); if (((i & 1) == 1) || (i == valueCapacity)) { assertEquals("unexpected cleared bit at index: " + i, 1, val); } else { assertEquals("unexpected set bit at index: " + i, 0, val); } } /* trigger second realloc */ mutator.setSafeToOne(valueCapacity*2); assertEquals(valueCapacity * 4, vector.getValueCapacity()); for (int i = valueCapacity*2; i < valueCapacity*4; i++) { if ((i & 1) == 1) { mutator.setToOne(i); } } for (int i = 0; i < valueCapacity*4; i++) { int val = accessor.get(i); if (((i & 1) == 1) || (i == valueCapacity) || (i == valueCapacity*2)) { assertEquals("unexpected cleared bit at index: " + i, 1, val); } else { assertEquals("unexpected set bit at index: " + i, 0, val); } } /* now transfer the vector */ TransferPair transferPair = vector.getTransferPair(allocator); transferPair.transfer(); final BitVector toVector = (BitVector)transferPair.getTo(); final BitVector.Accessor toAccessor = toVector.getAccessor(); final BitVector.Mutator toMutator = toVector.getMutator(); assertEquals(valueCapacity * 4, toVector.getValueCapacity()); /* realloc the toVector */ toMutator.setSafeToOne(valueCapacity * 4); for (int i = 0; i < toVector.getValueCapacity(); i++) { int val = toAccessor.get(i); if (i <= valueCapacity * 4) { if (((i & 1) == 1) || (i == valueCapacity) || (i == valueCapacity*2) || (i == valueCapacity*4)) { assertEquals("unexpected cleared bit at index: " + i, 1, val); } else { assertEquals("unexpected set bit at index: " + i, 0, val); } } else { assertEquals("unexpected set bit at index: " + i, 0, val); } } toVector.close(); } } @Test public void testReallocAfterVectorTransfer2() { try (final NullableBitVector vector = new NullableBitVector(EMPTY_SCHEMA_PATH, allocator)) { vector.allocateNew(4096); int valueCapacity = vector.getValueCapacity(); assertEquals(4096, valueCapacity); final NullableBitVector.Mutator mutator = vector.getMutator(); final NullableBitVector.Accessor accessor = vector.getAccessor(); for (int i = 0; i < valueCapacity; i++) { if ((i & 1) == 1) { mutator.set(i, 1); } } for (int i = 0; i < valueCapacity; i++) { if ((i & 1) == 1) { assertFalse("unexpected cleared bit at index: " + i, accessor.isNull(i)); } else { assertTrue("unexpected set bit at index: " + i, accessor.isNull(i)); } } /* trigger first realloc */ mutator.setSafe(valueCapacity, 1, 1); assertEquals(valueCapacity * 2, vector.getValueCapacity()); for (int i = valueCapacity; i < valueCapacity*2; i++) { if ((i & 1) == 1) { mutator.set(i, 1); } } for (int i = 0; i < valueCapacity*2; i++) { if (((i & 1) == 1) || (i == valueCapacity)) { assertFalse("unexpected cleared bit at index: " + i, accessor.isNull(i)); } else { assertTrue("unexpected set bit at index: " + i, accessor.isNull(i)); } } /* trigger second realloc */ mutator.setSafe(valueCapacity*2, 1, 1); assertEquals(valueCapacity * 4, vector.getValueCapacity()); for (int i = valueCapacity*2; i < valueCapacity*4; i++) { if ((i & 1) == 1) { mutator.set(i, 1); } } for (int i = 0; i < valueCapacity*4; i++) { if (((i & 1) == 1) || (i == valueCapacity) || (i == valueCapacity*2)) { assertFalse("unexpected cleared bit at index: " + i, accessor.isNull(i)); } else { assertTrue("unexpected set bit at index: " + i, accessor.isNull(i)); } } /* now transfer the vector */ TransferPair transferPair = vector.getTransferPair(allocator); transferPair.transfer(); final NullableBitVector toVector = (NullableBitVector)transferPair.getTo(); final NullableBitVector.Accessor toAccessor = toVector.getAccessor(); final NullableBitVector.Mutator toMutator = toVector.getMutator(); assertEquals(valueCapacity * 4, toVector.getValueCapacity()); /* realloc the toVector */ toMutator.setSafe(valueCapacity * 4, 1, 1); for (int i = 0; i < toVector.getValueCapacity(); i++) { if (i <= valueCapacity * 4) { if (((i & 1) == 1) || (i == valueCapacity) || (i == valueCapacity*2) || (i == valueCapacity*4)) { assertFalse("unexpected cleared bit at index: " + i, toAccessor.isNull(i)); } else { assertTrue("unexpected set bit at index: " + i, toAccessor.isNull(i)); } } else { assertTrue("unexpected set bit at index: " + i, toAccessor.isNull(i)); } } toVector.close(); } } @Test public void testBitVector() { // Create a new value vector for 1024 integers try (final BitVector vector = new BitVector(EMPTY_SCHEMA_PATH, allocator)) { final BitVector.Mutator m = vector.getMutator(); vector.allocateNew(1024); m.setValueCount(1024); // Put and set a few values m.set(0, 1); m.set(1, 0); m.set(100, 0); m.set(1022, 1); m.setValueCount(1024); final BitVector.Accessor accessor = vector.getAccessor(); assertEquals(1, accessor.get(0)); assertEquals(0, accessor.get(1)); assertEquals(0, accessor.get(100)); assertEquals(1, accessor.get(1022)); assertEquals(1022, accessor.getNullCount()); // test setting the same value twice m.set(0, 1); m.set(0, 1); m.set(1, 0); m.set(1, 0); assertEquals(1, accessor.get(0)); assertEquals(0, accessor.get(1)); // test toggling the values m.set(0, 0); m.set(1, 1); assertEquals(0, accessor.get(0)); assertEquals(1, accessor.get(1)); // should not change assertEquals(1022, accessor.getNullCount()); // Ensure unallocated space returns 0 assertEquals(0, accessor.get(3)); // unset the previously set bits m.set(1, 0); m.set(1022, 0); // this should set all the array to 0 assertEquals(1024, accessor.getNullCount()); // set all the array to 1 for (int i = 0; i < 1024; ++i) { assertEquals(1024 - i, accessor.getNullCount()); m.set(i, 1); } assertEquals(0, accessor.getNullCount()); vector.allocateNew(1015); m.setValueCount(1015); // ensure it has been zeroed assertEquals(1015, accessor.getNullCount()); m.set(0, 1); m.set(1014, 1); // ensure that the last item of the last byte is allocated assertEquals(1013, accessor.getNullCount()); vector.zeroVector(); assertEquals(1015, accessor.getNullCount()); // set all the array to 1 for (int i = 0; i < 1015; ++i) { assertEquals(1015 - i, accessor.getNullCount()); m.set(i, 1); } assertEquals(0, accessor.getNullCount()); } } @Test public void testBitVectorRangeSetAllOnes() { validateRange(1000, 0, 1000); validateRange(1000, 0, 1); validateRange(1000, 1, 2); validateRange(1000, 5, 6); validateRange(1000, 5, 10); validateRange(1000, 5, 150); validateRange(1000, 5, 27); for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { validateRange(1000, 10 + i, 27 + j); validateRange(1000, i, j); } } } private void validateRange(int length, int start, int count) { String desc = "[" + start + ", " + (start + count) + ") "; try (BitVector bitVector = new BitVector("bits", allocator)) { bitVector.reset(); bitVector.allocateNew(length); bitVector.getMutator().setRangeToOne(start, count); for (int i = 0; i < start; i++) { Assert.assertEquals(desc + i, 0, bitVector.getAccessor().get(i)); } for (int i = start; i < start + count; i++) { Assert.assertEquals(desc + i, 1, bitVector.getAccessor().get(i)); } for (int i = start + count; i < length; i++) { Assert.assertEquals(desc + i, 0, bitVector.getAccessor().get(i)); } } } }
apache-2.0
m-m-m/multimedia
mmm-data/mmm-data-api/src/main/java/net/sf/mmm/data/api/repository/access/package-info.java
547
/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ /** * Provides the internal access API for the content-repository. * <a name="documentation"/><h2>Content-Repository API Access</h2> * This package contains the access interfaces used by the * {@link net.sf.mmm.data.api.repository content-repository API}. These interfaces * exist to avoid redundant signatures. They are NOT intended to be used * directly. */ package net.sf.mmm.data.api.repository.access;
apache-2.0
286470753/crtestgit
ace-auth/ace-auth-server/src/main/java/com/github/wxiaoqi/security/auth/configuration/ClientConfig.java
684
package com.github.wxiaoqi.security.auth.configuration; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; /** * Created by ace on 2017/9/12. */ @Configuration public class ClientConfig { @Value("${client.id}") private String clientId; @Value("${client.secret}") private String clientSecret; @Value("${client.token-header}") private String clientTokenHeader; public String getClientTokenHeader() { return clientTokenHeader; } public String getClientSecret() { return clientSecret; } public String getClientId() { return clientId; } }
apache-2.0
Sargul/dbeaver
plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/edit/SQLServerTableManager.java
6304
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2021 DBeaver Corp and others * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.ext.mssql.edit; import org.jkiss.code.NotNull; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.ext.mssql.model.*; import org.jkiss.dbeaver.model.DBConstants; import org.jkiss.dbeaver.model.DBPEvaluationContext; import org.jkiss.dbeaver.model.edit.DBECommandContext; import org.jkiss.dbeaver.model.edit.DBEPersistAction; import org.jkiss.dbeaver.model.exec.DBCExecutionContext; import org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistAction; import org.jkiss.dbeaver.model.impl.sql.edit.SQLObjectEditor; import org.jkiss.dbeaver.model.impl.sql.edit.SQLStructEditor; import org.jkiss.dbeaver.model.messages.ModelMessages; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.struct.rdb.DBSTableIndex; import org.jkiss.utils.CommonUtils; import java.util.Collection; import java.util.List; import java.util.Map; /** * SQLServer table manager */ public class SQLServerTableManager extends SQLServerBaseTableManager<SQLServerTableBase> { private static final Class<?>[] CHILD_TYPES = { SQLServerTableColumn.class, SQLServerTableUniqueKey.class, SQLServerTableForeignKey.class, SQLServerTableIndex.class, SQLServerTableCheckConstraint.class, SQLServerExtendedProperty.class, }; @Override protected SQLServerTable createDatabaseObject(DBRProgressMonitor monitor, DBECommandContext context, Object container, Object copyFrom, Map<String, Object> options) { SQLServerSchema schema = (SQLServerSchema) container; SQLServerTable table = new SQLServerTable(schema); setNewObjectName(monitor, schema, table); return table; //$NON-NLS-1$ } @Override protected void addObjectModifyActions(DBRProgressMonitor monitor, DBCExecutionContext executionContext, List<DBEPersistAction> actionList, ObjectChangeCommand command, Map<String, Object> options) { if (command.getProperties().size() > 1 || command.getProperty(DBConstants.PROP_ID_DESCRIPTION) == null) { StringBuilder query = new StringBuilder("ALTER TABLE "); //$NON-NLS-1$ query.append(command.getObject().getFullyQualifiedName(DBPEvaluationContext.DDL)).append(" "); //$NON-NLS-1$ appendTableModifiers(monitor, command.getObject(), command, query, true); actionList.add(new SQLDatabasePersistAction(query.toString())); } } @Override protected void appendTableModifiers(DBRProgressMonitor monitor, SQLServerTableBase table, NestedObjectCommand tableProps, StringBuilder ddl, boolean alter) { // ALTER /* if (tableProps.getProperty("tablespace") != null) { //$NON-NLS-1$ Object tablespace = table.getTablespace(); if (tablespace instanceof SQLServerTablespace) { if (table.isPersisted()) { ddl.append("\nMOVE TABLESPACE ").append(((SQLServerTablespace) tablespace).getName()); //$NON-NLS-1$ } else { ddl.append("\nTABLESPACE ").append(((SQLServerTablespace) tablespace).getName()); //$NON-NLS-1$ } } } */ } @Override protected void addObjectDeleteActions(DBRProgressMonitor monitor, DBCExecutionContext executionContext, List<DBEPersistAction> actions, ObjectDeleteCommand command, Map<String, Object> options) { SQLServerTableBase object = command.getObject(); actions.add( new SQLDatabasePersistAction( ModelMessages.model_jdbc_drop_table, "DROP " + (object.isView() ? "VIEW" : "TABLE") + //$NON-NLS-2$ " " + object.getFullyQualifiedName(DBPEvaluationContext.DDL) + (!object.isView() && CommonUtils.getOption(options, OPTION_DELETE_CASCADE) ? " CASCADE CONSTRAINTS" : "") ) ); } @NotNull @Override public Class<?>[] getChildTypes() { return CHILD_TYPES; } @Override public void renameObject(@NotNull DBECommandContext commandContext, @NotNull SQLServerTableBase object, @NotNull Map<String, Object> options, @NotNull String newName) throws DBException { processObjectRename(commandContext, object, options, newName); } @Override protected boolean isIncludeIndexInDDL(DBRProgressMonitor monitor, DBSTableIndex index) throws DBException { return !index.isPrimary() && super.isIncludeIndexInDDL(monitor, index); } protected void addExtraDDLCommands(DBRProgressMonitor monitor, SQLServerTableBase table, Map<String, Object> options, SQLStructEditor.StructCreateCommand createCommand) { SQLObjectEditor<SQLServerTableCheckConstraint, SQLServerTableBase> ccm = getObjectEditor( table.getDataSource().getContainer().getPlatform().getEditorsRegistry(), SQLServerTableCheckConstraint.class); if (ccm != null) { try { if (table instanceof SQLServerTable) { Collection<SQLServerTableCheckConstraint> checkConstraints = CommonUtils.safeCollection(((SQLServerTable) table).getCheckConstraints(monitor)); if (!CommonUtils.isEmpty(checkConstraints)) { for (SQLServerTableCheckConstraint checkConstraint : checkConstraints) { createCommand.aggregateCommand(ccm.makeCreateCommand(checkConstraint, options)); } } } } catch (DBException e) { // Ignore indexes log.debug(e); } } } }
apache-2.0
LucidWorks/solr-hadoop-common
solr-hadoop-io/src/main/java/edu/cmu/lemurproject/WarcRecord.java
17212
/* Lemur License Agreement Copyright (c) 2000-2011 The Lemur Project. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names "Lemur", "Indri", "University of Massachusetts" and "Carnegie Mellon" must not be used to endorse or promote products derived from this software without prior written permission. To obtain permission, contact license@lemurproject.org 4. Products derived from this software may not be called "Lemur" or "Indri" nor may "Lemur" or "Indri" appear in their names without prior written permission of The Lemur Project. To obtain permission, contact license@lemurproject.org. THIS SOFTWARE IS PROVIDED BY THE LEMUR PROJECT AND OTHER CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.cmu.lemurproject; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutput; import java.io.EOFException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Iterator; import java.util.Map.Entry; import java.util.Set; // import org.apache.commons.logging.Log; // import org.apache.commons.logging.LogFactory; /** * @author mhoy */ public class WarcRecord { // public static final Log LOG = LogFactory.getLog(WarcRecord.class); public static String WARC_VERSION = "WARC/"; public static String WARC_VERSION_LINE = "WARC/0.18\n"; ////public static String WARC_VERSION = "WARC/1.0"; //public static String WARC_VERSION = "WARC/0.18"; ////public static String WARC_VERSION_LINE = "WARC/1.0\n"; //public static String WARC_VERSION_LINE = "WARC/0.18\n"; private static String NEWLINE = "\n"; private static String CR_NEWLINE = "\r\n"; private static byte MASK_THREE_BYTE_CHAR = (byte) (0xE0); private static byte MASK_TWO_BYTE_CHAR = (byte) (0xC0); private static byte MASK_TOPMOST_BIT = (byte) (0x80); private static byte MASK_BOTTOM_SIX_BITS = (byte) (0x1F); private static byte MASK_BOTTOM_FIVE_BITS = (byte) (0x3F); private static byte MASK_BOTTOM_FOUR_BITS = (byte) (0x0F); private static String LINE_ENDING = "\n"; private static String readLineFromInputStream(DataInputStream in) throws IOException { StringBuilder retString = new StringBuilder(); boolean found_cr = false; boolean keepReading = true; try { do { char thisChar = 0; byte readByte = in.readByte(); // check to see if it's a multibyte character if ((readByte & MASK_THREE_BYTE_CHAR) == MASK_THREE_BYTE_CHAR) { found_cr = false; // need to read the next 2 bytes if (in.available() < 2) { // treat these all as individual characters retString.append((char) readByte); int numAvailable = in.available(); for (int i = 0; i < numAvailable; i++) { retString.append((char) (in.readByte())); } continue; } byte secondByte = in.readByte(); byte thirdByte = in.readByte(); // ensure the topmost bit is set if (((secondByte & MASK_TOPMOST_BIT) != MASK_TOPMOST_BIT) || ( (thirdByte & MASK_TOPMOST_BIT) != MASK_TOPMOST_BIT)) { //treat these as individual characters retString.append((char) readByte); retString.append((char) secondByte); retString.append((char) thirdByte); continue; } int finalVal = (thirdByte & MASK_BOTTOM_FIVE_BITS) + 64 * (secondByte & MASK_BOTTOM_FIVE_BITS) + 4096 * (readByte & MASK_BOTTOM_FOUR_BITS); thisChar = (char) finalVal; } else if ((readByte & MASK_TWO_BYTE_CHAR) == MASK_TWO_BYTE_CHAR) { found_cr = false; // need to read next byte if (in.available() < 1) { // treat this as individual characters retString.append((char) readByte); continue; } byte secondByte = in.readByte(); if ((secondByte & MASK_TOPMOST_BIT) != MASK_TOPMOST_BIT) { retString.append((char) readByte); retString.append((char) secondByte); continue; } int finalVal = (secondByte & MASK_BOTTOM_FIVE_BITS) + 64 * (readByte & MASK_BOTTOM_SIX_BITS); thisChar = (char) finalVal; } else { // interpret it as a single byte thisChar = (char) readByte; } // Look for carriage return; if found set a flag if (thisChar == '\r') { found_cr = true; } if (thisChar == '\n') { // if the linefeed is the next character after the carriage return if (found_cr) { LINE_ENDING = CR_NEWLINE; } else { LINE_ENDING = NEWLINE; } keepReading = false; } else { retString.append(thisChar); } } while (keepReading); } catch (EOFException eofEx) { return null; } if (retString.length() == 0) { return ""; } return retString.toString(); } private static byte[] readNextRecord(DataInputStream in, StringBuffer headerBuffer) throws IOException { if (in == null) { return null; } if (headerBuffer == null) { return null; } String line = null; boolean foundMark = false; byte[] retContent = null; // cannot be using a buffered reader here!!!! // just read the header // first - find our WARC header while ((!foundMark) && ((line = readLineFromInputStream(in)) != null)) { if (line.startsWith(WARC_VERSION)) { WARC_VERSION_LINE = line; foundMark = true; } } // no WARC mark? if (!foundMark) { return null; } // LOG.info("Found WARC_VERSION"); int contentLength = -1; // read until we see contentLength then an empty line // (to handle malformed ClueWeb09 headers that have blank lines) // get the content length and set our retContent for (line = readLineFromInputStream(in).trim(); line.length() > 0 || contentLength < 0; line = readLineFromInputStream(in).trim()) { if (line.length() > 0) { headerBuffer.append(line); headerBuffer.append(LINE_ENDING); // find the content length designated by Content-Length: <length> String[] parts = line.split(":", 2); if (parts.length == 2 && parts[0].equals("Content-Length")) { try { contentLength = Integer.parseInt(parts[1].trim()); // LOG.info("WARC record content length: " + contentLength); } catch (NumberFormatException nfEx) { contentLength = -1; } } } } // now read the bytes of the content retContent = new byte[contentLength]; int totalWant = contentLength; int totalRead = 0; // // LOOP TO REMOVE LEADING CR * LF // To prevent last few characters from being cut off of the content // when reading // while ((totalRead == 0) && (totalRead < contentLength)) { byte CR = in.readByte(); byte LF = in.readByte(); if ((CR != 13) && (LF != 10)) { retContent[0] = CR; retContent[1] = LF; totalRead = 2; totalWant = contentLength - totalRead; } } // // // while (totalRead < contentLength) { try { int numRead = in.read(retContent, totalRead, totalWant); if (numRead < 0) { return null; } else { totalRead += numRead; totalWant = contentLength - totalRead; } // end if (numRead < 0) / else } catch (EOFException eofEx) { // resize to what we have if (totalRead > 0) { byte[] newReturn = new byte[totalRead]; System.arraycopy(retContent, 0, newReturn, 0, totalRead); return newReturn; } else { return null; } } // end try/catch (EOFException) } // end while (totalRead < contentLength) return retContent; } public static WarcRecord readNextWarcRecord(DataInputStream in) throws IOException { // LOG.info("Starting read of WARC record"); StringBuffer recordHeader = new StringBuffer(); byte[] recordContent = readNextRecord(in, recordHeader); if (recordContent == null) { // LOG.info("WARC content is null - file is complete"); return null; } // extract out our header information String thisHeaderString = recordHeader.toString(); String[] headerLines = thisHeaderString.split(LINE_ENDING); WarcRecord retRecord = new WarcRecord(); for (int i = 0; i < headerLines.length; i++) { String[] pieces = headerLines[i].split(":", 2); if (pieces.length != 2) { retRecord.addHeaderMetadata(pieces[0], ""); continue; } String thisKey = pieces[0].trim(); String thisValue = pieces[1].trim(); // check for known keys if (thisKey.equals("WARC-Type")) { // LOG.info("Setting WARC record type: " + thisValue); retRecord.setWarcRecordType(thisValue); } else if (thisKey.equals("WARC-Date")) { retRecord.setWarcDate(thisValue); } else if (thisKey.equals("WARC-Record-ID")) { // LOG.info("Setting WARC record ID: " + thisValue); retRecord.setWarcUUID(thisValue); } else if (thisKey.equals("Content-Type")) { retRecord.setWarcContentType(thisValue); } else { retRecord.addHeaderMetadata(thisKey, thisValue); } } // set the content retRecord.setContent(recordContent); return retRecord; } public class WarcHeader { public String contentType = ""; public String UUID = ""; public String dateString = ""; public String recordType = ""; public HashMap<String, String> metadata = new HashMap<String, String>(); public int contentLength = 0; public WarcHeader() { } public WarcHeader(WarcHeader o) { this.contentType = o.contentType; this.UUID = o.UUID; this.dateString = o.dateString; this.recordType = o.recordType; this.metadata.putAll(o.metadata); this.contentLength = o.contentLength; } public void write(DataOutput out) throws IOException { out.writeUTF(contentType); out.writeUTF(UUID); out.writeUTF(dateString); out.writeUTF(recordType); out.writeInt(metadata.size()); Iterator<Entry<String, String>> metadataIterator = metadata.entrySet().iterator(); while (metadataIterator.hasNext()) { Entry<String, String> thisEntry = metadataIterator.next(); out.writeUTF(thisEntry.getKey()); out.writeUTF(thisEntry.getValue()); } out.writeInt(contentLength); } public void readFields(DataInput in) throws IOException { contentType = in.readUTF(); UUID = in.readUTF(); dateString = in.readUTF(); recordType = in.readUTF(); metadata.clear(); int numMetaItems = in.readInt(); for (int i = 0; i < numMetaItems; i++) { String thisKey = in.readUTF(); String thisValue = in.readUTF(); metadata.put(thisKey, thisValue); } contentLength = in.readInt(); } @Override public String toString() { StringBuffer retBuffer = new StringBuffer(); retBuffer.append(WARC_VERSION_LINE); retBuffer.append(LINE_ENDING); retBuffer.append("WARC-Type: " + recordType + LINE_ENDING); retBuffer.append("WARC-Date: " + dateString + LINE_ENDING); Iterator<Entry<String, String>> metadataIterator = metadata.entrySet().iterator(); while (metadataIterator.hasNext()) { Entry<String, String> thisEntry = metadataIterator.next(); retBuffer.append(thisEntry.getKey()); retBuffer.append(": "); retBuffer.append(thisEntry.getValue()); retBuffer.append(LINE_ENDING); } // Keep this as the last WARC-... retBuffer.append("WARC-Record-ID: " + UUID + LINE_ENDING); retBuffer.append("Content-Type: " + contentType + LINE_ENDING); retBuffer.append("Content-Length: " + contentLength + LINE_ENDING); return retBuffer.toString(); } } private WarcHeader warcHeader = new WarcHeader(); private byte[] warcContent = null; private String warcFilePath = ""; public WarcRecord() { } public WarcRecord(WarcRecord o) { this.warcHeader = new WarcHeader(o.warcHeader); this.warcContent = o.warcContent; } public int getTotalRecordLength() { int headerLength = warcHeader.toString().length(); return (headerLength + warcContent.length); } public void set(WarcRecord o) { this.warcHeader = new WarcHeader(o.warcHeader); this.warcContent = o.warcContent; } public String getWarcFilePath() { return warcFilePath; } public void setWarcFilePath(String path) { warcFilePath = path; } public void setWarcRecordType(String recordType) { warcHeader.recordType = recordType; } public void setWarcContentType(String contentType) { warcHeader.contentType = contentType; } public void setWarcDate(String dateString) { warcHeader.dateString = dateString; } public void setWarcUUID(String UUID) { warcHeader.UUID = UUID; } public void addHeaderMetadata(String key, String value) { // don't allow addition of known keys if (key.equals("WARC-Type")) { return; } if (key.equals("WARC-Date")) { return; } if (key.equals("WARC-Record-ID")) { return; } if (key.equals("Content-Type")) { return; } if (key.equals("Content-Length")) { return; } warcHeader.metadata.put(key, value); } public void clearHeaderMetadata() { warcHeader.metadata.clear(); } public WarcHeader getHeader() { return warcHeader; } public Set<Entry<String, String>> getHeaderMetadata() { return warcHeader.metadata.entrySet(); } public String getHeaderMetadataItem(String key) { if (key.equals("WARC-Type")) { return warcHeader.recordType; } if (key.equals("WARC-Date")) { return warcHeader.dateString; } if (key.equals("WARC-Record-ID")) { return warcHeader.UUID; } if (key.equals("Content-Type")) { return warcHeader.contentType; } if (key.equals("Content-Length")) { return Integer.toString(warcHeader.contentLength); } return warcHeader.metadata.get(key); } public void setContent(byte[] content) { warcContent = content; warcHeader.contentLength = content.length; } public void setContent(String content) { setContent(content.getBytes()); } public void setContentLength(int len) { warcHeader.contentLength = len; } public byte[] getContent() { return warcContent; } public byte[] getByteContent() { return warcContent; } public String getContentUTF8() { String retString = null; try { retString = new String(warcContent, "UTF-8"); } catch (UnsupportedEncodingException ex) { retString = new String(warcContent); } return retString; } public String getHeaderRecordType() { return warcHeader.recordType; } @Override public String toString() { StringBuffer retBuffer = new StringBuffer(); retBuffer.append(warcHeader.toString()); retBuffer.append(LINE_ENDING); retBuffer.append(new String(warcContent)); return retBuffer.toString(); } public String getHeaderString() { return warcHeader.toString(); } public void write(DataOutput out) throws IOException { warcHeader.write(out); out.write(warcContent); } public void readFields(DataInput in) throws IOException { warcHeader.readFields(in); int contentLengthBytes = warcHeader.contentLength; warcContent = new byte[contentLengthBytes]; in.readFully(warcContent); } }
apache-2.0
afs/lizard
lizard-cluster/src/main/java/lizard/conf/ConfDeploy.java
1107
/* * 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. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. */ package lizard.conf; import java.util.ArrayList; import java.util.List ; // Here : cf ConfCluster which is cluster wide. public class ConfDeploy { public ConfCluster confCluster = null ; public ConfZookeeper localZk = null ; public List<ConfNodeTableElement> ntReplicas = new ArrayList<>(); public List<ConfIndexElement> idxReplicas = new ArrayList<>(); public ConfDataset confDataset = null ; }
apache-2.0
dump247/aws-sdk-java
aws-java-sdk-kinesis/src/main/java/com/amazonaws/services/kinesis/model/transform/IncreaseStreamRetentionPeriodRequestMarshaller.java
3756
/* * Copyright 2010-2016 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.kinesis.model.transform; import static com.amazonaws.util.StringUtils.UTF8; import static com.amazonaws.util.StringUtils.COMMA_SEPARATOR; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.io.Writer; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.List; import java.util.regex.Pattern; import com.amazonaws.AmazonClientException; import com.amazonaws.Request; import com.amazonaws.DefaultRequest; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.kinesis.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.BinaryUtils; import com.amazonaws.util.StringUtils; import com.amazonaws.util.IdempotentUtils; import com.amazonaws.util.StringInputStream; import com.amazonaws.util.json.*; /** * IncreaseStreamRetentionPeriodRequest Marshaller */ public class IncreaseStreamRetentionPeriodRequestMarshaller implements Marshaller<Request<IncreaseStreamRetentionPeriodRequest>, IncreaseStreamRetentionPeriodRequest> { public Request<IncreaseStreamRetentionPeriodRequest> marshall( IncreaseStreamRetentionPeriodRequest increaseStreamRetentionPeriodRequest) { if (increaseStreamRetentionPeriodRequest == null) { throw new AmazonClientException( "Invalid argument passed to marshall(...)"); } Request<IncreaseStreamRetentionPeriodRequest> request = new DefaultRequest<IncreaseStreamRetentionPeriodRequest>( increaseStreamRetentionPeriodRequest, "AmazonKinesis"); request.addHeader("X-Amz-Target", "Kinesis_20131202.IncreaseStreamRetentionPeriod"); request.setHttpMethod(HttpMethodName.POST); request.setResourcePath(""); try { final SdkJsonGenerator jsonGenerator = new SdkJsonGenerator(); jsonGenerator.writeStartObject(); if (increaseStreamRetentionPeriodRequest.getStreamName() != null) { jsonGenerator.writeFieldName("StreamName").writeValue( increaseStreamRetentionPeriodRequest.getStreamName()); } if (increaseStreamRetentionPeriodRequest.getRetentionPeriodHours() != null) { jsonGenerator.writeFieldName("RetentionPeriodHours") .writeValue( increaseStreamRetentionPeriodRequest .getRetentionPeriodHours()); } jsonGenerator.writeEndObject(); byte[] content = jsonGenerator.getBytes(); request.setContent(new ByteArrayInputStream(content)); request.addHeader("Content-Length", Integer.toString(content.length)); request.addHeader("Content-Type", "application/x-amz-json-1.1"); } catch (Throwable t) { throw new AmazonClientException( "Unable to marshall request to JSON: " + t.getMessage(), t); } return request; } }
apache-2.0
puce77/org.ops4j.pax.cdi
pax-cdi-web-weld/src/main/java/org/ops4j/pax/cdi/web/weld/impl/WeldWebAdapter.java
1132
/* * Copyright 2012 Harald Wellmann. * * 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.ops4j.pax.cdi.web.weld.impl; import javax.servlet.ServletContextListener; import org.ops4j.pax.cdi.spi.CdiContainerListener; import org.ops4j.pax.cdi.web.CdiWebAppDependencyManager; import org.osgi.service.component.annotations.Component; @Component(property = "type=web", service = CdiContainerListener.class) public class WeldWebAdapter extends CdiWebAppDependencyManager { @Override protected ServletContextListener getServletContextListener() { return new WeldServletContextListener(); } }
apache-2.0
junkerm/specmate
tools/cause-effect-dsl/org.xtext.specmate.ui/xtend-gen/org/xtext/specmate/ui/labeling/SpecDSLLabelProvider.java
587
/** * generated by Xtext 2.17.1 */ package org.xtext.specmate.ui.labeling; import com.google.inject.Inject; import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider; import org.eclipse.xtext.ui.label.DefaultEObjectLabelProvider; /** * Provides labels for EObjects. * * See https://www.eclipse.org/Xtext/documentation/304_ide_concepts.html#label-provider */ @SuppressWarnings("all") public class SpecDSLLabelProvider extends DefaultEObjectLabelProvider { @Inject public SpecDSLLabelProvider(final AdapterFactoryLabelProvider delegate) { super(delegate); } }
apache-2.0
AungPyae/PADC-Animation-Samples
app/src/main/java/xyz/aungpyaephyo/padc/animation/components/rvset/SmartScrollListener.java
1720
package xyz.aungpyaephyo.padc.animation.components.rvset; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; /** * Created by aung on 12/12/15. */ public class SmartScrollListener extends RecyclerView.OnScrollListener { private int visibleItemCount, pastVisibleItems, totalItemCount; private ControllerSmartScroll controller; private boolean isListEndReached = false; private int previousDy, currentDy; public SmartScrollListener(ControllerSmartScroll controller) { this.controller = controller; } @Override public void onScrolled(RecyclerView rv, int dx, int dy) { super.onScrolled(rv, dx, dy); currentDy = dy; if (currentDy > previousDy) { //from top to bottom } else if (currentDy < previousDy) { //from bottom to top isListEndReached = false; } visibleItemCount = rv.getLayoutManager().getChildCount(); totalItemCount = rv.getLayoutManager().getItemCount(); pastVisibleItems = ((LinearLayoutManager) rv.getLayoutManager()).findFirstVisibleItemPosition(); previousDy = currentDy; } @Override public void onScrollStateChanged(RecyclerView recyclerView, int scrollState) { super.onScrollStateChanged(recyclerView, scrollState); if (scrollState == RecyclerView.SCROLL_STATE_IDLE) { if ((visibleItemCount + pastVisibleItems) >= totalItemCount && !isListEndReached) { isListEndReached = true; controller.onListEndReached(); } } } public interface ControllerSmartScroll { void onListEndReached(); } }
apache-2.0
weld/core
tests-arquillian/src/test/java/org/jboss/weld/tests/builtinBeans/metadata/passivation/VehicleDecoratorExtension.java
2345
/* * JBoss, Home of Professional Open Source * Copyright 2012, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.weld.tests.builtinBeans.metadata.passivation; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.Collections; import java.util.Set; import jakarta.enterprise.event.Observes; import jakarta.enterprise.inject.Any; import jakarta.enterprise.inject.spi.AfterBeanDiscovery; import jakarta.enterprise.inject.spi.AnnotatedType; import jakarta.enterprise.inject.spi.BeanAttributes; import jakarta.enterprise.inject.spi.BeanManager; import jakarta.enterprise.inject.spi.Extension; import jakarta.enterprise.inject.spi.InjectionTargetFactory; /** * Register {@link VehicleDecorator} as a decorator using {@link PassivationCapableDecoratorImpl}. * * @author Jozef Hartinger * */ public class VehicleDecoratorExtension implements Extension { void registerVehicleDecorator(@Observes AfterBeanDiscovery event, BeanManager manager) { AnnotatedType<VehicleDecorator> annotatedType = manager.createAnnotatedType(VehicleDecorator.class); BeanAttributes<VehicleDecorator> attributes = manager.createBeanAttributes(annotatedType); Set<Annotation> delegateQualifiers = Collections.<Annotation> singleton(Any.Literal.INSTANCE); Set<Type> decoratedTypes = Collections.<Type> singleton(Vehicle.class); InjectionTargetFactory<VehicleDecorator> factory = manager.getInjectionTargetFactory(annotatedType); event.addBean(new PassivationCapableDecoratorImpl<VehicleDecorator>(VehicleDecorator.class, attributes, Vehicle.class, delegateQualifiers, decoratedTypes, factory)); } }
apache-2.0
supercyc/jigsaw-redis
src/test/java/com/ericsson/jigsaw/redis/ct/replication/JedisReplicationMultiShardsCT.java
6452
package com.ericsson.jigsaw.redis.ct.replication; import static org.junit.Assert.assertEquals; import java.util.List; import org.junit.After; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.Mockito; import org.slf4j.Logger; import redis.clients.jedis.Jedis; import redis.clients.jedis.Pipeline; import com.ericsson.jigsaw.embedded.redis.RedisServer; import com.ericsson.jigsaw.redis.JedisTemplate; import com.ericsson.jigsaw.redis.JedisTemplate.PipelineActionNoResult; import com.ericsson.jigsaw.redis.pool.JedisPool; import com.ericsson.jigsaw.redis.pool.JedisPoolBuilder; import com.ericsson.jigsaw.redis.replication.JedisReplicationConstants; import com.ericsson.jigsaw.redis.replication.JedisReplicationShardedTemplate; import com.ericsson.jigsaw.redis.replication.exception.handler.JedisExceptionHandler; import com.ericsson.jigsaw.redis.shard.NormHashShardingProvider; public class JedisReplicationMultiShardsCT { private static final int Q_REDIS_PORT = 16383; private static final int DATA_REDIS_PORT = 16379; private static final String defaultShardKey = "shard1"; private static final String DATA_URL = "direct://localhost:16379?poolSize=3&poolName=traffic"; private static final String QUEUE_URL = "direct://localhost:16383?poolSize=3&poolName=dwbuffer"; private static RedisServer tServer1; private static RedisServer tServer2; private static Jedis tJedis1; private static Jedis tJedis2; private static RedisServer dwServer1; private static RedisServer dwServer2; private static Jedis dwJedis1; private static Jedis dwJedis2; private static JedisExceptionHandler exceptionHandler; private static Logger logger; private static JedisReplicationShardedTemplate jedisGeoRedTemplate; @BeforeClass public static void beforeClass() throws Exception { exceptionHandler = Mockito.mock(JedisExceptionHandler.class); logger = Mockito.mock(Logger.class); // traffic data tServer1 = new RedisServer(DATA_REDIS_PORT); tServer1.start(); tServer2 = new RedisServer(DATA_REDIS_PORT + 1); tServer2.start(); tJedis1 = new Jedis("127.0.0.1", DATA_REDIS_PORT); tJedis2 = new Jedis("127.0.0.1", DATA_REDIS_PORT + 1); // doublewrite dwServer1 = new RedisServer(Q_REDIS_PORT); dwServer1.start(); dwServer2 = new RedisServer(Q_REDIS_PORT + 1); dwServer2.start(); dwJedis1 = new Jedis("127.0.0.1", Q_REDIS_PORT); dwJedis2 = new Jedis("127.0.0.1", Q_REDIS_PORT + 1); // jedisPool List<JedisPool> tJedisPool = new JedisPoolBuilder().setUrl(DATA_URL).buildShardedPools(); List<JedisPool> qJedisPool = new JedisPoolBuilder().setUrl(QUEUE_URL).buildShardedPools(); jedisGeoRedTemplate = new JedisReplicationShardedTemplate(new NormHashShardingProvider<JedisTemplate>(true), tJedisPool, qJedisPool, exceptionHandler); } @After public void tearDown() throws InterruptedException { tJedis1.flushAll(); tJedis2.flushAll(); dwJedis1.flushAll(); dwJedis2.flushAll(); Mockito.reset(logger); } @AfterClass public static void afterClass() { tJedis1.close(); tServer1.stop(); tJedis2.close(); tServer2.stop(); dwJedis1.close(); dwServer1.stop(); dwJedis2.close(); dwServer2.stop(); } @Test public void testTemplateSetMethod() throws InterruptedException { // prepare final String key = "set"; final String value = "set-method"; createDwBuffer(); // replay jedisGeoRedTemplate.set(defaultShardKey, key, value); // verify // a) traffic data String rtnValue = jedisGeoRedTemplate.get(key); assertEquals(value, rtnValue); // b) operation log queue Thread.sleep(500); // the first element is used to create queue, pop it before verify dwJedis1.rpop(JedisReplicationConstants.DOUBLEWRITE_QUEUE); long queueLen = dwJedis1.llen(JedisReplicationConstants.DOUBLEWRITE_QUEUE); assertEquals(1, queueLen); String expectedOpLog = "{\"shardKey\":\"shard1\",\"cmd\":\"set\",\"args\":[\"set\",\"set-method\"],\"paramTypes\":[\"java.lang.String\",\"java.lang.String\"]}"; String rtnOpLog = dwJedis1.rpop(JedisReplicationConstants.DOUBLEWRITE_QUEUE); assertEquals(expectedOpLog, rtnOpLog); } @Test public void testPipelineSetex() throws InterruptedException { // prepare final String key = "pipeline"; final String value = "setex"; final int expire = 1; createDwBuffer(); // replay jedisGeoRedTemplate.execute(defaultShardKey, new PipelineActionNoResult() { @Override public void action(Pipeline pipeline) { pipeline.setex(key, expire, value); } }); // verify // a) traffic data String rtnValue = jedisGeoRedTemplate.get(defaultShardKey, key); assertEquals(value, rtnValue); // b) operation log queue Thread.sleep(500); // the first element is used to create queue, pop it before verify dwJedis1.rpop(JedisReplicationConstants.DOUBLEWRITE_QUEUE); long queueLen = dwJedis1.llen(JedisReplicationConstants.DOUBLEWRITE_QUEUE); assertEquals(1, queueLen); String expectedOpLog = "{\"shardKey\":\"shard1\",\"cmd\":\"setex\",\"args\":[\"pipeline\",1,\"setex\"],\"paramTypes\":[\"java.lang.String\",\"int\",\"java.lang.String\"]}"; String rtnOpLog = dwJedis1.rpop(JedisReplicationConstants.DOUBLEWRITE_QUEUE); assertEquals(expectedOpLog, rtnOpLog); } private void createDwBuffer() { dwJedis1.del(JedisReplicationConstants.DOUBLEWRITE_QUEUE); dwJedis1.lpush(JedisReplicationConstants.DOUBLEWRITE_QUEUE, "DoubleWriteBuffer"); long len1 = dwJedis1.llen(JedisReplicationConstants.DOUBLEWRITE_QUEUE); assertEquals(1, len1); dwJedis2.del(JedisReplicationConstants.DOUBLEWRITE_QUEUE); dwJedis2.lpush(JedisReplicationConstants.DOUBLEWRITE_QUEUE, "DoubleWriteBuffer"); long len2 = dwJedis2.llen(JedisReplicationConstants.DOUBLEWRITE_QUEUE); assertEquals(1, len2); } }
apache-2.0
projecttemp/hci-android_prototype
app/src/test/java/app/bus/project/ExampleUnitTest.java
308
package app.bus.project; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
apache-2.0
Indoqa/osgi-embedded
indoqa-osgi-embedded-services/src/main/java/com/indoqa/osgi/embedded/services/EmbeddedOSGiServiceProvider.java
1233
/* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.osgi.embedded.services; import org.osgi.framework.BundleContext; /** * A service that implements this interfaces and is registered with the Embedded OSGi container will be provided with the bundle * context in order to get access to the OSGi service infrastructure. */ public interface EmbeddedOSGiServiceProvider { void destroy(); void initialize(BundleContext bundleContext); }
apache-2.0
abesto/zipkin
zipkin/src/main/java/zipkin2/internal/Platform.java
3340
/* * Copyright 2015-2019 The OpenZipkin 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 zipkin2.internal; import java.io.IOException; import org.jvnet.animal_sniffer.IgnoreJRERequirement; /** * Provides access to platform-specific features. * * <p>Originally designed by OkHttp team, derived from {@code okhttp3.internal.platform.Platform} */ public abstract class Platform { private static final Platform PLATFORM = findPlatform(); Platform() { } static final ThreadLocal<char[]> SHORT_STRING_BUFFER = new ThreadLocal<>(); /** Maximum character length constraint of most names, IP literals and IDs. */ public static final int SHORT_STRING_LENGTH = 256; /** * Returns a {@link ThreadLocal} reused {@code char[]} for use when decoding bytes into hex, IP * literals, or {@link #SHORT_STRING_LENGTH short strings}. The buffer must never be leaked * outside the method. Most will {@link String#String(char[], int, int) copy it into a string}. */ public static char[] shortStringBuffer() { char[] shortStringBuffer = SHORT_STRING_BUFFER.get(); if (shortStringBuffer == null) { shortStringBuffer = new char[SHORT_STRING_LENGTH]; SHORT_STRING_BUFFER.set(shortStringBuffer); } return shortStringBuffer; } public RuntimeException uncheckedIOException(IOException e) { return new RuntimeException(e); } public AssertionError assertionError(String message, Throwable cause) { AssertionError error = new AssertionError(message); error.initCause(cause); throw error; } public static Platform get() { return PLATFORM; } /** Attempt to match the host runtime to a capable Platform implementation. */ static Platform findPlatform() { // Find JRE 8 new types try { Class.forName("java.io.UncheckedIOException"); return new Jre8(); // intentionally doesn't not access the type prior to the above guard } catch (ClassNotFoundException e) { // pre JRE 8 } // Find JRE 7 new types try { Class.forName("java.util.concurrent.ThreadLocalRandom"); return new Jre7(); // intentionally doesn't not access the type prior to the above guard } catch (ClassNotFoundException e) { // pre JRE 7 } // compatible with JRE 6 return Jre6.build(); } static final class Jre8 extends Jre7 { @IgnoreJRERequirement @Override public RuntimeException uncheckedIOException(IOException e) { return new java.io.UncheckedIOException(e); } } static class Jre7 extends Platform { @IgnoreJRERequirement @Override public AssertionError assertionError(String message, Throwable cause) { return new AssertionError(message, cause); } } static final class Jre6 extends Platform { static Jre6 build() { return new Jre6(); } } }
apache-2.0
SilenceDut/NBAPlus
app/src/main/java/com/me/silencedut/nbaplus/utils/DataClearManager.java
6170
package com.me.silencedut.nbaplus.utils; import android.content.Context; import android.os.Environment; import android.util.Log; import java.io.File; /** * Created by SlienceDut on 2015/12/15. */ public class DataClearManager { private static final String newsCacheurl = Environment.getExternalStorageDirectory().getAbsolutePath() + "nbaplus"; private static final String imUrl = Environment.getExternalStorageDirectory().getAbsolutePath() + ""; /** * 清除本应用内部缓存 * @param context */ public static void cleanInternalCache(Context context) { deleteFilesByDirectory(context.getCacheDir()); } public static double getInternalCacheSize(Context context) { Log.d("getApplicationDataSize", context.getCacheDir()+"kkkkk"); return getDirSize(context.getCacheDir()); } /** * 清除本应用所有数据库(/data/data/com.xxx.xxx/databases) * * @param context */ public static void cleanDatabases(Context context) { deleteFilesByDirectory(new File("/data/data/" + context.getPackageName() + "/databases")); } public static double getDatabasesSize(Context context) { return getDirSize(new File("/data/data/" + context.getPackageName() + "/databases")); } /** * 清除本应用sharedPreference保存数据 * @param context */ public static void cleanSharedPreference(Context context) { deleteFilesByDirectory(new File("/data/data/" + context.getPackageName() + "/shared_prefs")); } public static double getSharedSize (Context context) { return getDirSize(new File("/data/data/" + context.getPackageName() + "/shared_prefs")); } /** * 清除本应用数据库 * @param context * @param dbName */ public static void cleanDatabaseByName(Context context, String dbName) { context.deleteDatabase(dbName); } /** * 清除file下的内容 * * @param context */ public static void cleanFiles(Context context) { deleteFilesByDirectory(context.getFilesDir()); } public static double getFilesSize(Context context) { return getDirSize(context.getFilesDir()); } /** * 清除外部cache下的内容(/mnt/sdcard/android/data/com.xxx.xxx/cache) * * @param context */ public static void cleanExternalCache(Context context) { if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { deleteFilesByDirectory(context.getExternalCacheDir()); } } /** * 计算外部cache大小 * @param context * @return */ public static double getExternalCacheSize(Context context) { if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { return getDirSize(context.getExternalCacheDir()); } return 0; } /** * 清除自定义路径下的文件,使用需小心,请不要误删。而且只支持目录下的文件删除 * * @param filePath */ public static void cleanCustomCache(String filePath) { deleteFilesByDirectory(new File(filePath)); } public static String getCustomCacheSize(String filePath) { double size = getDirSize(new File(filePath)); return String.format("%.1f", size); } /** * 清除本应用所有的数据 * * @param context * @param filepath */ public static void cleanApplicationData(Context context, String... filepath) { cleanInternalCache(context); cleanExternalCache(context); //cleanSharedPreference(context); for (String filePath : filepath) { cleanCustomCache(filePath); } } public static void cleanApplicationData(Context context) { cleanApplicationData(context,newsCacheurl); } /** * 获得删除数据的大小,保存两位有效数字,并且返回字符串 * @param context * @param filepath * @return */ public static String getApplicationDataSize(Context context, String... filepath) { double size = 0; size += getInternalCacheSize(context); dirSizeAll = 0; getExternalCacheSize(context); size += dirSizeAll; for (String file : filepath) { dirSizeAll = 0; getCustomCacheSize(file); size += dirSizeAll; } return String.format("%.1f", size)+"M"; } // public static String getApplicationDataSize(Context context) { return getApplicationDataSize(context,newsCacheurl); } /** * 删除某文件夹下的文件,如果传入参数是个文件,酱不做处理 * @param directory */ private static void deleteFilesByDirectory(File directory) { if (directory != null && directory.exists() && directory.isDirectory()) { for (File item : directory.listFiles()) { if (item.isFile()) { item.delete(); } else if (item.isDirectory()) { deleteFilesByDirectory(item); } } // directory.delete(); } } /** * 计算文件夹大小 * @param dir * @return Mb */ public static double getDirSize(File dir) { if (dir == null || !dir.exists()) { return 0; } if (!dir.isDirectory()) { return 0; } double dirSize = 0; File[] files = dir.listFiles(); if (files != null && files.length > 0) { for (File file : files) { if (file.isFile()) { dirSize += file.length(); } else if (file.isDirectory()) { dirSize += getDirSize(file); // 如果遇到目录则通过递归调用继续统计 } } } dirSizeAll += dirSize / (1024 * 1024); return dirSizeAll; } private static double dirSizeAll = 0; }
apache-2.0
harfalm/Sakai-10.1
samigo/samigo-app/src/java/org/sakaiproject/tool/assessment/ui/listener/author/ReorderQuestionsListener.java
5224
/********************************************************************************** * $URL: https://source.sakaiproject.org/svn/sam/tags/sakai-10.1/samigo-app/src/java/org/sakaiproject/tool/assessment/ui/listener/author/ReorderQuestionsListener.java $ * $Id: ReorderQuestionsListener.java 106463 2012-04-02 12:20:09Z david.horwitz@uct.ac.za $ *********************************************************************************** * * Copyright (c) 2004, 2005, 2006, 2008, 2009 The Sakai Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ECL-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.sakaiproject.tool.assessment.ui.listener.author; import java.util.Iterator; import java.util.Set; import javax.faces.context.FacesContext; import javax.faces.event.AbortProcessingException; import javax.faces.event.ValueChangeEvent; import javax.faces.event.ValueChangeListener; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.tool.assessment.facade.AgentFacade; import org.sakaiproject.tool.assessment.facade.AssessmentFacade; import org.sakaiproject.tool.assessment.facade.ItemFacade; import org.sakaiproject.tool.assessment.facade.SectionFacade; import org.sakaiproject.tool.assessment.services.ItemService; import org.sakaiproject.tool.assessment.services.assessment.AssessmentService; import org.sakaiproject.tool.assessment.ui.bean.author.AssessmentBean; import org.sakaiproject.tool.assessment.ui.bean.author.ItemAuthorBean; import org.sakaiproject.tool.assessment.ui.listener.util.ContextUtil; /** * <p>Title: Samigo</p> * <p>Description: Sakai Assessment Manager</p> * @version $Id: ReorderQuestionsListener.java 106463 2012-04-02 12:20:09Z david.horwitz@uct.ac.za $ */ public class ReorderQuestionsListener implements ValueChangeListener { private static Log log = LogFactory.getLog(ReorderQuestionsListener.class); /** * Standard process action method. * @param ae ValueChangeEvent * @throws AbortProcessingException */ public void processValueChange(ValueChangeEvent ae) throws AbortProcessingException { log.info("ReorderQuestionsListener valueChangeLISTENER."); ItemAuthorBean itemauthorbean = (ItemAuthorBean) ContextUtil.lookupBean("itemauthor"); FacesContext context = FacesContext.getCurrentInstance(); String oldPos= ae.getOldValue().toString(); String newPos= ae.getNewValue().toString(); // String itemParam = String.valueOf( ((Integer)ae.getOldValue()).intValue()-1) + ":currItemId"; String pulldownId = ae.getComponent().getClientId(context); String itemParam = pulldownId.replaceFirst("number","currItemId"); String itemId= ContextUtil.lookupParam(itemParam); if (itemId !=null) { // somehow ae.getOldValue() keeps the old value, thus we get itemId==null ItemService delegate = new ItemService(); ItemFacade itemf = delegate.getItem(Long.valueOf(itemId), AgentFacade.getAgentString()); SectionFacade sectFacade = (SectionFacade) itemf.getSection(); reorderSequences(sectFacade, Integer.valueOf(oldPos), Integer.valueOf(newPos)); // goto editAssessment.jsp, so reset assessmentBean AssessmentService assessdelegate = new AssessmentService(); AssessmentBean assessmentBean = (AssessmentBean) ContextUtil.lookupBean("assessmentBean"); AssessmentFacade assessment = assessdelegate.getAssessment(assessmentBean.getAssessmentId()); assessmentBean.setAssessment(assessment); itemauthorbean.setOutcome("editAssessment"); } } /** ** shift sequence number down when inserting or reordering **/ private void reorderSequences(SectionFacade sectfacade, Integer oldPos, Integer newPos){ ItemService delegate = new ItemService(); Set itemset = sectfacade.getItemFacadeSet(); Iterator iter = itemset.iterator(); while (iter.hasNext()) { ItemFacade itemfacade = (ItemFacade) iter.next(); Integer itemfacadeseq = itemfacade.getSequence(); if ( (oldPos.compareTo(newPos) < 0) && (itemfacadeseq.compareTo(oldPos) > 0) && (itemfacadeseq.compareTo(newPos) <= 0) ){ itemfacade.setSequence(Integer.valueOf(itemfacadeseq.intValue()-1) ); delegate.saveItem(itemfacade); } if ( (oldPos.compareTo(newPos) > 0) && (itemfacadeseq.compareTo(newPos) >= 0) && (itemfacadeseq.compareTo(oldPos) < 0) ){ itemfacade.setSequence(Integer.valueOf(itemfacadeseq.intValue()+1) ); delegate.saveItem(itemfacade); } if ( itemfacadeseq.compareTo(oldPos) == 0) { itemfacade.setSequence(newPos); delegate.saveItem(itemfacade); } } } }
apache-2.0
astubbs/wicket.get-portals2
wicket/src/main/java/org/apache/wicket/Request.java
6655
/* * 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.wicket; import java.util.Locale; import java.util.Map; import org.apache.wicket.request.IRequestCodingStrategy; import org.apache.wicket.request.IRequestCycleProcessor; import org.apache.wicket.request.RequestParameters; /** * Base class for page request implementations allowing access to request parameters. A Request has * a URL and a parameter map. You can retrieve the URL of the request with getURL(). The entire * parameter map can be retrieved via getParameterMap(). Individual parameters can be retrieved via * getParameter(String). If multiple values are available for a given parameter, they can be * retrieved via getParameters(String). * * @author Jonathan Locke */ public abstract class Request { /** Any Page decoded for this request */ private Page page; /** the type safe request parameters object for this request. */ private RequestParameters requestParameters; /** * Construct. */ public Request() { } /** * An implementation of this method is only required if a subclass wishes to support sessions * via URL rewriting. This default implementation simply returns the URL String it is passed. * * @param url * The URL to decode * @return The decoded url */ public String decodeURL(final String url) { return url; } /** * @return The locale for this request */ public abstract Locale getLocale(); /** * @return Any Page for this request */ public Page getPage() { return page; } /** * Gets a given (query) parameter by name. * * @param key * Parameter name * @return Parameter value */ public abstract String getParameter(final String key); /** * Gets a map of (query) parameters sent with the request. * * @return Map of parameters */ public abstract Map<String, String[]> getParameterMap(); /** * Gets an array of multiple parameters by name. * * @param key * Parameter name * @return Parameter values */ public abstract String[] getParameters(final String key); /** * @return Path info for request */ public abstract String getPath(); /** * Gets a prefix to make this relative to the context root. * <p> * For example, if your context root is http://server.com/myApp/ and the request is for * /myApp/mountedPage/, then the prefix returned might be "../../". * <p> * For a particular technology, this might return either an absolute prefix or a relative one. * * @return Prefix relative to this request required to back up to context root. */ public abstract String getRelativePathPrefixToContextRoot(); /** * Gets a prefix to make this relative to the Wicket Servlet/Filter. * <p> * For example, if your context root is http://server.com/myApp/ and the request is for * /myApp/mountedPage/, then the prefix returned might be "../../". * <p> * For a particular technology, this might return either an absolute prefix or a relative one. * * @return Prefix relative to this request required to back up to context root. */ public abstract String getRelativePathPrefixToWicketHandler(); /** * Gets the relative (to some root) url (e.g. in a servlet environment, the url without the * context path and without a leading '/'). Use this method e.g. to load resources using the * servlet context. * * @return Request URL * @deprecated Use {@link #getURL()} instead. */ @Deprecated public String getRelativeURL() { return getURL(); } /** * Gets the request parameters object using the instance of {@link IRequestCodingStrategy} of * the provided request cycle processor. * * @return the request parameters object */ public final RequestParameters getRequestParameters() { // reused cached parameters if (requestParameters != null) { return requestParameters; } // get the request encoder to decode the request parameters IRequestCycleProcessor processor = RequestCycle.get().getProcessor(); final IRequestCodingStrategy encoder = processor.getRequestCodingStrategy(); if (encoder == null) { throw new WicketRuntimeException("request encoder must be not-null (provided by " + processor + ")"); } // decode the request parameters into a strongly typed parameters // object that is to be used by the target resolving try { requestParameters = encoder.decode(this); } catch (RuntimeException re) { // do set the parameters as it was parsed. // else the error page will also error again (infinite loop) requestParameters = new RequestParameters(); throw re; } if (requestParameters == null) { throw new WicketRuntimeException("request parameters must be not-null (provided by " + encoder + ")"); } return requestParameters; } /** * Retrieves the relative URL of this request for local use. This is relative to the context * root. * * @return The relative request URL for local use */ public abstract String getURL(); /** * THIS METHOD IS NOT PART OF THE WICKET PUBLIC API. DO NOT CALL IT. * * @param page * The Page for this request */ public void setPage(final Page page) { this.page = page; } /** * A request can say if the current request should generated a new version number. If this * returns true, then all the changes on a page that has versioning enabled is merged with the * latest version. Else it will just create a new version. * * @return true if the version must be merged with the previous latest. */ public boolean mergeVersion() { return false; } /** * @see java.lang.Object#toString() */ @Override public String toString() { return "Request[url=" + getURL() + "]"; } /** * Returns the query string (part after ?) of this request. * * @return request query string */ public abstract String getQueryString(); }
apache-2.0
googleads/googleads-java-lib
modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v202111/LineItemCreativeAssociationServiceInterfacepushCreativeToDevicesResponse.java
2218
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.admanager.jaxws.v202111; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for pushCreativeToDevicesResponse element declaration. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;element name="pushCreativeToDevicesResponse"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="rval" type="{https://www.google.com/apis/ads/publisher/v202111}UpdateResult" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "rval" }) @XmlRootElement(name = "pushCreativeToDevicesResponse") public class LineItemCreativeAssociationServiceInterfacepushCreativeToDevicesResponse { protected UpdateResult rval; /** * Gets the value of the rval property. * * @return * possible object is * {@link UpdateResult } * */ public UpdateResult getRval() { return rval; } /** * Sets the value of the rval property. * * @param value * allowed object is * {@link UpdateResult } * */ public void setRval(UpdateResult value) { this.rval = value; } }
apache-2.0
JuKu/libgdx-test-rpg
core/src/main/java/com/jukusoft/libgdx/rpg/game/screen/GameScreen.java
14434
package com.jukusoft.libgdx.rpg.game.screen; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.jukusoft.libgdx.rpg.engine.fightingsystem.HitboxesSystem; import com.jukusoft.libgdx.rpg.engine.projectile.ProjectileSpawner; import com.jukusoft.libgdx.rpg.engine.camera.impl.Shake2CameraModification; import com.jukusoft.libgdx.rpg.engine.camera.impl.Shake3CameraModification; import com.jukusoft.libgdx.rpg.engine.entity.Entity; import com.jukusoft.libgdx.rpg.engine.entity.EntityManager; import com.jukusoft.libgdx.rpg.engine.entity.factory.AnimatedEnvObjectFactory; import com.jukusoft.libgdx.rpg.engine.entity.factory.NPCFactory; import com.jukusoft.libgdx.rpg.engine.entity.factory.PlayerFactory; import com.jukusoft.libgdx.rpg.engine.entity.impl.ECS; import com.jukusoft.libgdx.rpg.engine.entity.impl.component.draw.LightMapComponent; import com.jukusoft.libgdx.rpg.engine.game.ScreenBasedGame; import com.jukusoft.libgdx.rpg.engine.input.impl.CameraZoomListener; import com.jukusoft.libgdx.rpg.engine.lighting.LightingSystem; import com.jukusoft.libgdx.rpg.engine.screen.impl.BaseScreen; import com.jukusoft.libgdx.rpg.engine.skybox.SimpleSkyBox; import com.jukusoft.libgdx.rpg.engine.skybox.SkyBox; import com.jukusoft.libgdx.rpg.engine.time.GameTime; import com.jukusoft.libgdx.rpg.engine.utils.DevMode; import com.jukusoft.libgdx.rpg.engine.world.SectorCoord; import com.jukusoft.libgdx.rpg.engine.entity.impl.component.collision.GameWorldCollisionComponent; import com.jukusoft.libgdx.rpg.game.data.CharacterData; import com.jukusoft.libgdx.rpg.game.shared.SharedDataConst; import com.jukusoft.libgdx.rpg.game.utils.AssetPathUtils; import com.jukusoft.libgdx.rpg.engine.world.GameWorld; /** * Created by Justin on 07.02.2017. */ public class GameScreen extends BaseScreen { protected CharacterData characterData = null; protected GameWorld gameWorld = null; protected Texture testTexture = null; protected String testTexturePath = AssetPathUtils.getImagePath("test/water.png"); protected String lightMapPath = AssetPathUtils.getLightMapPath("lightmap1/light.png"); protected Texture lightMap = null; protected String skyBoxPath = AssetPathUtils.getWallpaperPath("ocean/Ocean_large.png"); protected Texture skyBoxTexture = null; protected String characterTexturePath = AssetPathUtils.getImagePath("test/character.png"); protected Texture characterTexture = null; protected String characterTexturePath2 = AssetPathUtils.getImagePath("test/character2.png"); protected Texture characterTexture2 = null; protected String cursorPath = AssetPathUtils.getCursorPath("attack/attack.png"); protected Pixmap cursorImage = null; protected String campfireTexturePath = AssetPathUtils.getSpritesheetPath("campfire/campfire1.png"); protected Texture campfireTexture = null; protected String blackTexturePath = AssetPathUtils.getLightMapPath("blackmap/blackmap.png"); protected Texture blackTexture = null; protected String character2AtlasFile = AssetPathUtils.getSpritesheetPath("pentaquin/player_walk.atlas"); //protected String character2AtlasFile = AssetPathUtils.getSpritesheetPath("reinertilesets/T_grey_caveman/output/T_grey_caveman.atlas"); protected String fireParticleEffectFile = AssetPathUtils.getParticleEffectPath("fire1.p"); //lighting system LightingSystem lightingSystem = null; //hitboxes system HitboxesSystem hitboxesSystem = null; protected CameraZoomListener zoomListener = null; protected EntityManager ecs = null; protected Entity playerEntity = null; protected ProjectileSpawner projectileSpawner = null; @Override protected void onInit(ScreenBasedGame game, AssetManager assetManager) { game.getAssetManager().load(testTexturePath, Texture.class); game.getAssetManager().load(lightMapPath, Texture.class); game.getAssetManager().load(skyBoxPath, Texture.class); game.getAssetManager().load(blackTexturePath, Texture.class); game.getAssetManager().load(cursorPath, Pixmap.class); game.getAssetManager().load(campfireTexturePath, Texture.class); game.getAssetManager().load(characterTexturePath, Texture.class); game.getAssetManager().load(characterTexturePath2, Texture.class); game.getAssetManager().finishLoading(); this.testTexture = game.getAssetManager().get(testTexturePath, Texture.class); this.lightMap = game.getAssetManager().get(lightMapPath, Texture.class); this.skyBoxTexture = game.getAssetManager().get(skyBoxPath, Texture.class); this.cursorImage = game.getAssetManager().get(cursorPath, Pixmap.class); this.campfireTexture = game.getAssetManager().get(campfireTexturePath, Texture.class); this.characterTexture = game.getAssetManager().get(characterTexturePath, Texture.class); this.characterTexture2 = game.getAssetManager().get(characterTexturePath2, Texture.class); this.blackTexture = game.getAssetManager().get(blackTexturePath, Texture.class); if (this.campfireTexture == null) { throw new NullPointerException("campfire texture is null, path: " + campfireTexturePath); } //create new lighting system this.lightingSystem = new LightingSystem(game, blackTexture, game.getViewportWidth(), game.getViewportHeight()); //create new hitboxes system this.hitboxesSystem = new HitboxesSystem(); //create new test lighting //this.testLighting = new TextureLighting(this.lightMap, 200, 200); //this.lightingSystem.addLighting(this.testLighting); //save lighting environment to shared data, so HUD can change ambient color & intensity game.getSharedData().put(SharedDataConst.LIGHTING_ENV, this.lightingSystem); //create zoom listener to support camera zoom this.zoomListener = new CameraZoomListener(game.getCamera2D()); game.getInputManager().getGameInputProcessor().addScrollListener(this.zoomListener); //create new entity component system this.ecs = new ECS(game, this.lightingSystem, this.hitboxesSystem); } @Override public void onResume () { //TODO: maybe load data this.characterData = new CharacterData(); game.getSharedData().put("character_data", this.characterData); //get current sector SectorCoord coord = this.characterData.getCurrentSector(); //create game world this.gameWorld = new GameWorld(game, coord, this.testTexture); game.getSharedData().put(SharedDataConst.GAME_WORLD, this.gameWorld); //set correct input processor game.getInputManager().setInputProcessor(); //add hud screen overlay game.getScreenManager().push("hud"); //create skybox SkyBox skyBox = new SimpleSkyBox(this.skyBoxTexture); this.gameWorld.setSkyBox(skyBox); //initialize entity component system //create an entity for player this.playerEntity = PlayerFactory.createPlayer(this.ecs, this.character2AtlasFile, "standDown", 200, 200); this.playerEntity.addComponent(new LightMapComponent(this.lightMap, 0, 0, false), LightMapComponent.class); this.playerEntity.addComponent(new GameWorldCollisionComponent(this.gameWorld), GameWorldCollisionComponent.class); this.ecs.addEntity(this.playerEntity); game.getSharedData().put(SharedDataConst.PLAYER_ENTITY, this.playerEntity); //save current entity component system to shared data game.getSharedData().put(SharedDataConst.ENTITY_COMPONENT_SYSTEM, this.ecs); //create an entity for dummy NPC Entity npcEntity = NPCFactory.createDummyNPC(this.ecs, this.characterTexture, this.cursorImage, 400, 400); this.ecs.addEntity(npcEntity); //create an entity for dummy NPC Entity npcEntity1 = NPCFactory.createDummyWithBlobShadowNPC(this.ecs, this.characterTexture2, this.cursorImage, 300, 600); this.ecs.addEntity(npcEntity1); //create campfire Entity campfireEntity = AnimatedEnvObjectFactory.createBasicAnimatedLightingEntity(this.ecs, this.campfireTexture, this.lightMap, 300, 300, 150, 1, 5); this.ecs.addEntity(campfireEntity); //create campfire with lighting Entity campfireEntity1 = AnimatedEnvObjectFactory.createBasicAnimatedLightingEntity(this.ecs, this.campfireTexture, this.lightMap, 200, 600, 150, 1, 5); this.ecs.addEntity(campfireEntity1); //create particle effect Entity fireParticleEffectEntity = AnimatedEnvObjectFactory.createParticlesEntity(this.ecs, this.fireParticleEffectFile, this.lightMap, 100, 100); this.ecs.addEntity(fireParticleEffectEntity); //enable hitbox drawing DevMode.setDrawHitboxEnabled(true); //create projectile spawner and add to shared data this.projectileSpawner = new ProjectileSpawner(this.ecs, this.gameWorld, this.hitboxesSystem); game.getSharedData().put(SharedDataConst.PROJECTILE_SPAWNER, this.projectileSpawner); } @Override public void onPause () { //remove hud screen overlay game.getScreenManager().pop(); //remove all entitites this.ecs.removeAllEntities(); } @Override public void update(ScreenBasedGame game, GameTime time) { /*if (Gdx.input.isKeyPressed(Input.Keys.LEFT) || Gdx.input.isKeyPressed(Input.Keys.A)) { //move camera game.getCamera().translate(-5, 0, 0); //move skybox gameWorld.getSkyBox().translate(-5, 0); } if (Gdx.input.isKeyPressed(Input.Keys.RIGHT) || Gdx.input.isKeyPressed(Input.Keys.D)) { //move camera game.getCamera().translate(5, 0, 0); //move skybox gameWorld.getSkyBox().translate(5, 0); } if (Gdx.input.isKeyPressed(Input.Keys.UP) || Gdx.input.isKeyPressed(Input.Keys.W)) { //move camera game.getCamera().translate(0, 5, 0); //move skybox gameWorld.getSkyBox().translate(0, 5); } if (Gdx.input.isKeyPressed(Input.Keys.DOWN) || Gdx.input.isKeyPressed(Input.Keys.S)) { //move camera game.getCamera().translate(0, -5, 0); //move skybox gameWorld.getSkyBox().translate(0, -5); } if (Gdx.input.isKeyPressed(Input.Keys.K)) { //disable lighting lightingSystem.setLightingEnabled(false); } if (Gdx.input.isKeyPressed(Input.Keys.L)) { //enable lighting lightingSystem.setLightingEnabled(true); }*/ if (Gdx.input.isKeyPressed(Input.Keys.C)) { Shake2CameraModification mod = game.getCamera().getMod(Shake2CameraModification.class); if (!mod.isShaking()) { System.out.println("shake camera."); //shake camera 50ms mod.shake(30, 500); } } if (Gdx.input.isKeyPressed(Input.Keys.V)) { Shake3CameraModification mod = game.getCamera().getMod(Shake3CameraModification.class); if (!mod.isShaking()) { System.out.println("shake camera."); //shake camera 500ms mod.shake(10, 500); } } //update game world this.gameWorld.update(game, game.getCamera(), time); //update entities this.ecs.update(game, time); //update lighting system this.lightingSystem.update(game, game.getCamera(), time); } @Override public void draw(GameTime time, SpriteBatch batch) { //draw lighting framebuffer first this.lightingSystem.drawFBO(time, this.gameWorld, game.getCamera(), batch); batch.setProjectionMatrix(game.getCamera().getCombined()); //check, if lighting is enabled if (this.lightingSystem.isLightingEnabled()) { //set lighting shader, so lighting shader will be used this.gameWorld.setCurrentShader(this.lightingSystem.getLightingShader()); } else { //reset shader this.gameWorld.setCurrentShader(null); } lightingSystem.getFBO().getColorBufferTexture().bind(1); //this is important! bind the FBO to the 2nd texture unit this.lightMap.bind(0); //we force the binding of a texture on first texture unit to avoid artefacts //this is because our default and ambiant shader dont use multi texturing... //youc can basically bind anything, it doesnt matter //batch.draw(testTexture, 0, 0); //draw game world if (this.lightingSystem.isLightingEnabled()) { this.gameWorld.draw(time, game.getCamera(), this.lightingSystem.getLightingShader(), batch); } else { this.gameWorld.draw(time, game.getCamera(), null, batch); } batch.end(); batch.begin(); batch.setProjectionMatrix(game.getCamera().getCombined()); if (DevMode.isDrawHitboxEnabled()) { //draw hitboxes this.gameWorld.drawHitboxes(time, game.getCamera(), batch); } if (DevMode.isNoLightingHitboxEnabled()) { //draw hitboxes this.gameWorld.drawNoLightingHitboxes(time, game.getCamera(), batch); } //draw entities this.ecs.draw(time, game.getCamera(), batch); //reset shader batch.setShader(null); batch.setProjectionMatrix(game.getCamera().getCombined()); //draw abilities and son on this.ecs.drawUILayer(time, game.getCamera(), batch); //draw lightmap (only for testing purposes) //batch.draw(lightingSystem.getFBO().getColorBufferTexture(), 0, 0); batch.flush(); //reset shader, so default shader is used batch.setShader(null); } @Override public void destroy() { this.gameWorld.dispose(); this.gameWorld = null; this.lightingSystem.dispose(); this.lightingSystem = null; this.skyBoxTexture.dispose(); this.skyBoxTexture = null; } }
apache-2.0
mattec92/DesignSample
app/src/main/java/se/mattec/design/interfaces/ViewPagerHolder.java
208
package se.mattec.design.interfaces; public interface ViewPagerHolder { void registerViewPagerListener(int position, ViewPagerListener listener); void unregisterViewPagerListener(int position); }
apache-2.0
deeplearning4j/deeplearning4j
datavec/datavec-data/datavec-data-codec/src/test/java/org/datavec/codec/reader/AssertTestsExtendBaseClass.java
1683
/* ****************************************************************************** * Copyright (c) 2020 Konduit K.K. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ package org.datavec.codec.reader; import lombok.extern.slf4j.Slf4j; import org.nd4j.common.tests.AbstractAssertTestsClass; import org.nd4j.common.tests.BaseND4JTest; import java.util.*; /** * This class checks that all test classes (i.e., anything with one or more methods annotated with @Test) * extends BaseDl4jTest - either directly or indirectly. * Other than a small set of exceptions, all tests must extend this * * @author Alex Black */ @Slf4j public class AssertTestsExtendBaseClass extends AbstractAssertTestsClass { @Override protected Set<Class<?>> getExclusions() { //Set of classes that are exclusions to the rule (either run manually or have their own logging + timeouts) return new HashSet<>(); } @Override protected String getPackageName() { return "org.datavec.codec.reader"; } @Override protected Class<?> getBaseClass() { return BaseND4JTest.class; } }
apache-2.0
glustful/henjiapp
src/com/heji/henjiapp/db/SqliteHelper.java
1227
package com.heji.henjiapp.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class SqliteHelper extends SQLiteOpenHelper { private static final String DataBaseName = "henji.db"; private static final int DataBaseVersion = 1; private static final String tableSql = "CREATE TABLE IF NOT EXISTS guide_table(_id INTEGER PRIMARY KEY, link_id VARCHAR, link VARCHAR, logo VARCHAR, location VARCHAR, time VARCHAR, category_id VARCHAR,category VARCHAR,isdefault INTEGER)"; private static final String updateSql = "CREATE TABLE IF NOT EXISTS update_table(_id INTEGER PRIMARY KEY, isupdate INTEGER)"; private static SqliteHelper mInstance; public SqliteHelper(Context context) { super(context, DataBaseName, null, DataBaseVersion); } public static SqliteHelper getInstance(Context context) { if (mInstance == null) { synchronized (SqliteHelper.class) { mInstance = new SqliteHelper(context); } } return mInstance; } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(tableSql); db.execSQL(updateSql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
apache-2.0
lu4242/ext-myfaces-2.0.2-patch
trunk/myfaces-impl-2021override/src/main/java/org/apache/myfaces/ov2021/view/facelets/FaceletCompositionContext.java
17487
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.myfaces.ov2021.view.facelets; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.faces.component.UIComponent; import javax.faces.component.UIViewRoot; import javax.faces.component.UniqueIdVendor; import javax.faces.context.FacesContext; import javax.faces.view.AttachedObjectHandler; import javax.faces.view.EditableValueHolderAttachedObjectHandler; import javax.faces.view.facelets.FaceletContext; /** * @since 2.0.1 * @author Leonardo Uribe (latest modification by $Author: lu4242 $) * @version $Revision: 1424975 $ $Date: 2012-12-21 16:41:27 +0100 (Fr, 21 Dez 2012) $ */ abstract public class FaceletCompositionContext { static protected final String FACELET_COMPOSITION_CONTEXT_KEY = "oam.facelets.FACELET_COMPOSITION_CONTEXT"; protected FaceletCompositionContext() { } static public FaceletCompositionContext getCurrentInstance() { return (FaceletCompositionContext) FacesContext.getCurrentInstance().getAttributes().get(FACELET_COMPOSITION_CONTEXT_KEY); } static public FaceletCompositionContext getCurrentInstance(FaceletContext ctx) { if (ctx instanceof AbstractFaceletContext) { return ((AbstractFaceletContext)ctx).getFaceletCompositionContext(); } else { // Here we have two choices: retrieve it throught ThreadLocal var // or use the attribute value on FacesContext, but it seems better // use the FacesContext attribute map. return (FaceletCompositionContext) ctx.getFacesContext().getAttributes().get(FACELET_COMPOSITION_CONTEXT_KEY); } } static public FaceletCompositionContext getCurrentInstance(FacesContext ctx) { return (FaceletCompositionContext) ctx.getAttributes().get(FACELET_COMPOSITION_CONTEXT_KEY); } public void init(FacesContext facesContext) { facesContext.getAttributes().put( FaceletCompositionContext.FACELET_COMPOSITION_CONTEXT_KEY, this); } /** * Releases the MyFaceletContext object. This method must only * be called by the code that created the MyFaceletContext. */ public void release(FacesContext facesContext) { facesContext.getAttributes().remove(FACELET_COMPOSITION_CONTEXT_KEY); } public abstract FaceletFactory getFaceletFactory(); /** * Return the composite component being applied on the current facelet. * * Note this is different to UIComponent.getCurrentCompositeComponent, because a composite * component is added to the stack each time a composite:implementation tag handler is applied. * * This could be used by InsertChildrenHandler and InsertFacetHandler to retrieve the current * composite component to be applied. * * @since 2.0.1 * @return */ public abstract UIComponent getCompositeComponentFromStack(); /** * @since 2.0.1 * @param parent */ public abstract void pushCompositeComponentToStack(UIComponent parent); /** * @since 2.0.1 */ public abstract void popCompositeComponentToStack(); /** * Return the latest UniqueIdVendor created from stack. The reason why we need to keep * a UniqueIdVendor stack is because we need to look the closest one in ComponentTagHandlerDelegate. * Note that facelets tree is built from leafs to root, that means use UIComponent.getParent() does not * always return parent components. * * @since 2.0.1 * @return */ public abstract UniqueIdVendor getUniqueIdVendorFromStack(); /** * @since 2.0.1 * @param parent */ public abstract void pushUniqueIdVendorToStack(UniqueIdVendor parent); /** * @since 2.0.1 */ public abstract void popUniqueIdVendorToStack(); /** * Gets the top of the validationGroups stack. * @return * @since 2.0.1 */ @Deprecated public abstract String getFirstValidationGroupFromStack(); /** * Removes top of stack. * @since 2.0.1 */ @Deprecated public abstract void popValidationGroupsToStack(); /** * Pushes validationGroups to the stack. * @param validationGroups * @since 2.0.1 */ @Deprecated public abstract void pushValidationGroupsToStack(String validationGroups); /** * Gets all validationIds on the stack. * @return * @since 2.0.1 */ @Deprecated public abstract Iterator<String> getExcludedValidatorIds(); /** * Removes top of stack. * @since 2.0.1 */ @Deprecated public abstract void popExcludedValidatorIdToStack(); /** * Pushes validatorId to the stack of excluded validatorIds. * @param validatorId * @since 2.0.1 */ @Deprecated public abstract void pushExcludedValidatorIdToStack(String validatorId); /** * Gets all validationIds on the stack. * @return * @since 2.0.1 */ @Deprecated public abstract Iterator<String> getEnclosingValidatorIds(); /** * Removes top of stack. * @since 2.0.1 */ public abstract void popEnclosingValidatorIdToStack(); /** * Pushes validatorId to the stack of all enclosing validatorIds. * @param validatorId * @since 2.0.1 */ @Deprecated public abstract void pushEnclosingValidatorIdToStack(String validatorId); /** * Pushes validatorId to the stack of all enclosing validatorIds. * * @param validatorId * @param attachedObjectHandler * @since 2.0.10 */ public abstract void pushEnclosingValidatorIdToStack(String validatorId, EditableValueHolderAttachedObjectHandler attachedObjectHandler); /** * Gets all validationIds with its associated EditableValueHolderAttachedObjectHandler from the stack. * * @return * @since 2.0.10 */ public abstract Iterator<Map.Entry<String, EditableValueHolderAttachedObjectHandler>> getEnclosingValidatorIdsAndHandlers(); /** * * @param id * @return * @since 2.0.10 */ public abstract boolean containsEnclosingValidatorId(String id); /** * Check if this build is being refreshed, adding transient components * and adding/removing components under c:if or c:forEach or not. * * @return * @since 2.0.1 */ public abstract boolean isRefreshingTransientBuild(); /** * Check if this build should be marked as initial state. In other words, * all components must call UIComponent.markInitialState. * * @return * @since 2.0.1 */ public abstract boolean isMarkInitialState(); public void setMarkInitialState(boolean value) { } /** * Check if the current view will be refreshed with partial state saving. * * This param is used in two posible events: * * 1. To notify UIInstruction instances to look for instances moved by * cc:insertChildren or cc:insertFacet. * 2. To do proper actions when a tag that could change tree structure is applied * (c:if, c:forEach...) * * @return * @since 2.0.1 */ public abstract boolean isRefreshTransientBuildOnPSS(); /** * * @since 2.0.12, 2.1.6 * @return */ public boolean isRefreshTransientBuildOnPSSPreserveState() { return false; } /** * Check if we are using partial state saving on this view * * @return * @since 2.0.1 */ public abstract boolean isUsingPSSOnThisView(); /** * @since 2.0.1 * @return */ public abstract boolean isMarkInitialStateAndIsRefreshTransientBuildOnPSS(); /** * Add to the composite component parent this handler, so it will be processed later when * ViewDeclarationLanguage.retargetAttachedObjects is called. * * Tag Handlers exposing attached objects should call this method to expose them when the * parent to be applied is a composite components. * * @since 2.0.2 * @param compositeComponentParent * @param handler */ public abstract void addAttachedObjectHandler(UIComponent compositeComponentParent, AttachedObjectHandler handler); /** * Remove from the composite component parent the list of attached handlers. * * @since 2.0.2 * @param compositeComponentParent */ public abstract void removeAttachedObjectHandlers(UIComponent compositeComponentParent); /** * Retrieve the list of object handlers attached to a composite component parent. * * @since 2.0.2 * @param compositeComponentParent */ public abstract List<AttachedObjectHandler> getAttachedObjectHandlers(UIComponent compositeComponentParent); /** * Marks all direct children and Facets with an attribute for deletion. * * @since 2.0.2 * @see #finalizeForDeletion(UIComponent) * @param component * UIComponent to mark */ public abstract void markForDeletion(UIComponent component); /** * Used in conjunction with markForDeletion where any UIComponent marked will be removed. * * @since 2.0.2 * @param component * UIComponent to finalize */ public abstract void finalizeForDeletion(UIComponent component); public void removeComponentForDeletion(UIComponent component) { } /** * Marks the given resource for deletion. Is to be used for relocatable * components instead of {@link #markForDeletion(UIComponent)}. * * @since 2.0.17 2.1.11 * @param component * UIComponent to finalize */ public void markRelocatableResourceForDeletion(UIComponent component) { } /** * Used to clean up all unused relocatable components on the root component. * * @since 2.0.17 2.1.11 * @param component * UIComponent to finalize (root component) */ public void finalizeRelocatableResourcesForDeletion(UIViewRoot root) { } /** * Add a method expression as targeted for the provided composite component * * @since 2.0.3 * @param targetedComponent * @param attributeName * @param backingValue A value that could be useful to revert its effects. */ public abstract void addMethodExpressionTargeted(UIComponent targetedComponent, String attributeName, Object backingValue); /** * Check if the MethodExpression attribute has been applied using vdl.retargetMethodExpression * * @since 2.0.3 * @param compositeComponentParent * @param attributeName * @return */ public abstract boolean isMethodExpressionAttributeApplied(UIComponent compositeComponentParent, String attributeName); /** * Mark the MethodExpression attribute as applied using vdl.retargetMethodExpression * * @since 2.0.3 * @param compositeComponentParent * @param attributeName */ public abstract void markMethodExpressionAttribute(UIComponent compositeComponentParent, String attributeName); /** * Clear the MethodExpression attribute to call vdl.retargetMethodExpression again * * @since 2.0.3 * @param compositeComponentParent * @param attributeName */ public abstract void clearMethodExpressionAttribute(UIComponent compositeComponentParent, String attributeName); /** * Remove a method expression as targeted for the provided composite component * * @since 2.0.3 * @param targetedComponent * @param attributeName * @return A value that could be useful to revert its effects. */ public abstract Object removeMethodExpressionTargeted(UIComponent targetedComponent, String attributeName); /** * Indicates if a EL Expression can be or not cached by facelets vdl. * * @since 2.0.8 * @return */ public ELExpressionCacheMode getELExpressionCacheMode() { return ELExpressionCacheMode.noCache; } /** * * @since 2.0.9 * @return */ public boolean isWrapTagExceptionsAsContextAware() { return true; } /** * Start a new unique id section, which means a new counter is used to * generate unique ids to components * * @since 2.0.10, 2.1.4 * @return */ public String startComponentUniqueIdSection() { return null; } /** * Generate a unique id that will be used later to derive a unique id per tag * by FaceletContext.generateUniqueId(). This generator ensures uniqueness per * view but FaceletContext.generateUniqueId() ensures uniqueness per view and * per facelet hierarchy, so different included facelets will generate different * ids. * * @return */ public String generateUniqueId() { return null; } public void generateUniqueId(StringBuilder builderToAdd) { } /** * Generate a unique id for component instances. * * @return */ public String generateUniqueComponentId() { return null; } /** * Ends the current unique id section, so the previous counter will be used * to generate unique ids to components. */ public void endComponentUniqueIdSection() { } /** * Set the iterator used to retrieve unique ids. * * since 2.1.7, 2.0.13 * @param uniqueIdsIterator */ public void setUniqueIdsIterator(Iterator<String> uniqueIdsIterator) { } /** * Activater record unique id mode, so an structure will be * used to hold those values. * * since 2.1.7, 2.0.13 */ public void initUniqueIdRecording() { } /** * Add an unique id to the list if recording is enabled, * if recording is not enabled it has no effect. * * since 2.1.7, 2.0.13 * @param uniqueId */ public void addUniqueId(String uniqueId) { } /** * Return the unique id from the iterator if applies * * since 2.1.7, 2.0.13 * @return */ public String getUniqueIdFromIterator() { return null; } /** * Return the list of unique ids * * since 2.1.7, 2.0.13 * @return */ public List<String> getUniqueIdList() { return null; } /** * Increment the unique id without construct it. * * since 2.1.7, 2.0.13 * @return */ public void incrementUniqueId() { } /** * Check if the view * * since 2.1.7, 2.0.13 * @return */ public boolean isBuildingViewMetadata() { return FaceletViewDeclarationLanguage.isBuildingViewMetadata( FacesContext.getCurrentInstance()); } /** * Call this method to indicate a f:metadata section is about to be processed * * since 2.1.7, 2.0.13 * @return */ public void startMetadataSection() { } /** * Call this method to indicate f:metadata section has been already processed * * since 2.1.7, 2.0.13 * @return */ public void endMetadataSection() { } /** * Check if the component is created inside f:metadata section * * since 2.1.7, 2.0.13 * @return */ public boolean isInMetadataSection() { return false; } /** * Check if the section to be processed is being refreshed. * * since 2.1.7, 2.0.13 * @return */ public boolean isRefreshingSection() { return isRefreshingTransientBuild() || (!isBuildingViewMetadata() && isInMetadataSection()); } /** * * @since 2.1.8, 2.0.14 */ public void incrementUniqueComponentId() { } public StringBuilder getSharedStringBuilder() { return new StringBuilder(); } /** * Returns the current nesting level of composite components found. If * no composite component has been used returns 0. * * @since 2.1.9, 2.0.15 */ public int getCompositeComponentLevel() { return 0; } }
apache-2.0
DLR-SC/tigl
bindings/java/src/de/dlr/sc/tigl3/TixiNativeInterface.java
1078
/* * Copyright (C) 2007-2013 German Aerospace Center (DLR/SC) * * Created: 2014-10-21 Martin Siggel <martin.siggel@dlr.de> * * 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.dlr.sc.tigl3; import com.sun.jna.Native; import com.sun.jna.ptr.*; public class TixiNativeInterface { static { Native.register("tixi3"); } static native int tixiOpenDocument (String xmlFilename, IntByReference handle); static native int tixiImportFromString(String xmlImportString, IntByReference handle); static native int tixiCloseDocument (int handle); }
apache-2.0
anttribe/zookeeper-console
src/main/java/org/anttribe/zookeeper/console/core/ZkData.java
1139
package org.anttribe.zookeeper.console.core; import java.nio.charset.Charset; import java.util.Arrays; import java.util.List; import org.apache.zookeeper.data.Stat; /** * 抽象Zookeeper数据 * * @author zhaoyong * @version 2015年10月9日 */ public class ZkData { private byte[] data; private Stat stat; /** * 子路径 */ private List<String> children; @Override public String toString() { return "ZkData [data=" + Arrays.toString(getData()) + ", stat=" + getStat() + "]"; } public String getDataString() { return new String(getData(), Charset.forName("UTF-8")); } public byte[] getData() { return data; } public void setData(byte[] data) { this.data = data; } public Stat getStat() { return stat; } public void setStat(Stat stat) { this.stat = stat; } public List<String> getChildren() { return children; } public void setChildren(List<String> children) { this.children = children; } }
apache-2.0
xaioyi/yidongyiljwj
src/main/java/com/sectong/repository/MessageRepository.java
347
package com.sectong.repository; import com.sectong.domain.UserMessages; import org.springframework.data.mongodb.repository.MongoRepository; import java.util.List; /** * UserMessage类的CRUD操作 */ public interface MessageRepository extends MongoRepository<UserMessages, Long> { List<UserMessages> findByTargetid(String mytargetid); }
apache-2.0
berict/Tapad
app/src/main/java/com/bedrock/padder/api/ApiClient.java
602
package com.bedrock.padder.api; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class ApiClient { static Retrofit retrofit = null; public static String BASE_URL = "http://berict.com/api/"; public static void setRetrofit() { retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); } public static Retrofit getClient() { if (retrofit == null) { setRetrofit(); } return retrofit; } }
apache-2.0
jetblack87/cs576
KWIC/src/main/java/edu/drexel/cs/cs576/mwa29/KwicGenerator.java
2590
/** * */ package edu.drexel.cs.cs576.mwa29; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; /** * @author mark * */ public class KwicGenerator { private static final String tokenDelimiter = "[\\s.,;:?!]+"; private final Scanner inputFileScanner; private final List<String> stopWordList; public KwicGenerator(final String inputFile, final String stopWordFile) throws FileNotFoundException { inputFileScanner = getInputScanner(inputFile); stopWordList = getStopWordList(stopWordFile); } public KwicIndex generateKwicIndex() { final KwicIndex kwicIndex = new KwicIndex(); while (inputFileScanner.hasNext()) { String line = inputFileScanner.nextLine(); List<String> tokenizedLine = Arrays.asList(line .split(tokenDelimiter)); for (int i = 0; i < tokenizedLine.size(); i++) { final String nextWord = tokenizedLine.get(i); if (!stopWordList.contains(nextWord.toLowerCase())) { final int beforeLength = i < Constants.MAX_BEFORE_ENTRY ? i : Constants.MAX_BEFORE_ENTRY; final int afterLength = (tokenizedLine.size() - i < Constants.MAX_AFTER_ENTRY + 1) ? (tokenizedLine .size() - i) : Constants.MAX_AFTER_ENTRY + 1; final List<String> beforeKeywordList = new ArrayList<String>( tokenizedLine.subList(i - beforeLength, i)); if (i > Constants.MAX_BEFORE_ENTRY) { beforeKeywordList.add(0,"..."); } final List<String> afterKeywordList = new ArrayList<String>( tokenizedLine.subList(i + 1, i + afterLength)); if (tokenizedLine.size() - i > Constants.MAX_AFTER_ENTRY + 1) { afterKeywordList.add("..."); } kwicIndex.add(new KwicEntry(nextWord, beforeKeywordList, afterKeywordList)); } } } return kwicIndex; } protected Scanner getInputScanner(final String inputFile) throws FileNotFoundException { if (Constants.STDIN.equals(inputFile.toLowerCase())) { return new Scanner(System.in, "UTF-8"); } else { return new Scanner(new File(inputFile), "UTF-8"); } } protected List<String> getStopWordList(final String stopWordFile) throws FileNotFoundException { final List<String> stopWordList = new ArrayList<String>(); final File file = new File(stopWordFile); if (file.exists()) { final Scanner stopWordScanner = new Scanner(file, "UTF-8"); while (stopWordScanner.hasNext()) { stopWordList.add(stopWordScanner.next().toLowerCase()); } stopWordScanner.close(); } return stopWordList; } }
apache-2.0
shaolinwu/uimaster
modules/designtime/src/main/java/org/shaolin/bmdp/designtime/andriod/datamodel/ObjectFactory.java
24055
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.6 // 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.08.28 at 04:10:22 PM CST // package org.shaolin.bmdp.designtime.andriod.datamodel; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the generated package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { private final static QName _ViewGroup_QNAME = new QName("", "ViewGroup"); private final static QName _TextureView_QNAME = new QName("", "TextureView"); private final static QName _AdapterViewAnimator_QNAME = new QName("", "AdapterViewAnimator"); private final static QName _ListView_QNAME = new QName("", "ListView"); private final static QName _View_QNAME = new QName("", "View"); private final static QName _Button_QNAME = new QName("", "Button"); private final static QName _SurfaceView_QNAME = new QName("", "SurfaceView"); private final static QName _FrameLayout_QNAME = new QName("", "FrameLayout"); private final static QName _ImageButton_QNAME = new QName("", "ImageButton"); private final static QName _RelativeLayout_QNAME = new QName("", "RelativeLayout"); private final static QName _AutoCompleteTextView_QNAME = new QName("", "AutoCompleteTextView"); private final static QName _AbsSpinner_QNAME = new QName("", "AbsSpinner"); private final static QName _ViewSwitcher_QNAME = new QName("", "ViewSwitcher"); private final static QName _LinearLayout_QNAME = new QName("", "LinearLayout"); private final static QName _EditText_QNAME = new QName("", "EditText"); private final static QName _ViewAnimator_QNAME = new QName("", "ViewAnimator"); private final static QName _TextView_QNAME = new QName("", "TextView"); private final static QName _AbsListView_QNAME = new QName("", "AbsListView"); private final static QName _AbsoluteLayout_QNAME = new QName("", "AbsoluteLayout"); private final static QName _AbsSeekBar_QNAME = new QName("", "AbsSeekBar"); private final static QName _AdapterView_QNAME = new QName("", "AdapterView"); private final static QName _CompoundButton_QNAME = new QName("", "CompoundButton"); private final static QName _ImageView_QNAME = new QName("", "ImageView"); private final static QName _ProgressBar_QNAME = new QName("", "ProgressBar"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: generated * */ public ObjectFactory() { } /** * Create an instance of {@link AdapterViewFlipper } * */ public AdapterViewFlipper createAdapterViewFlipper() { return new AdapterViewFlipper(); } /** * Create an instance of {@link AdapterViewAnimator } * */ public AdapterViewAnimator createAdapterViewAnimator() { return new AdapterViewAnimator(); } /** * Create an instance of {@link AdapterView } * */ public AdapterView createAdapterView() { return new AdapterView(); } /** * Create an instance of {@link ViewGroup } * */ public ViewGroup createViewGroup() { return new ViewGroup(); } /** * Create an instance of {@link View } * */ public View createView() { return new View(); } /** * Create an instance of {@link GLSurfaceView } * */ public GLSurfaceView createGLSurfaceView() { return new GLSurfaceView(); } /** * Create an instance of {@link SurfaceView } * */ public SurfaceView createSurfaceView() { return new SurfaceView(); } /** * Create an instance of {@link AutoCompleteTextView } * */ public AutoCompleteTextView createAutoCompleteTextView() { return new AutoCompleteTextView(); } /** * Create an instance of {@link MediaController } * */ public MediaController createMediaController() { return new MediaController(); } /** * Create an instance of {@link FrameLayout } * */ public FrameLayout createFrameLayout() { return new FrameLayout(); } /** * Create an instance of {@link TextView } * */ public TextView createTextView() { return new TextView(); } /** * Create an instance of {@link FragmentBreadCrumbs } * */ public FragmentBreadCrumbs createFragmentBreadCrumbs() { return new FragmentBreadCrumbs(); } /** * Create an instance of {@link AppWidgetHostView } * */ public AppWidgetHostView createAppWidgetHostView() { return new AppWidgetHostView(); } /** * Create an instance of {@link GestureOverlayView } * */ public GestureOverlayView createGestureOverlayView() { return new GestureOverlayView(); } /** * Create an instance of {@link ExtractEditText } * */ public ExtractEditText createExtractEditText() { return new ExtractEditText(); } /** * Create an instance of {@link EditText } * */ public EditText createEditText() { return new EditText(); } /** * Create an instance of {@link KeyboardView } * */ public KeyboardView createKeyboardView() { return new KeyboardView(); } /** * Create an instance of {@link RSSurfaceView } * */ public RSSurfaceView createRSSurfaceView() { return new RSSurfaceView(); } /** * Create an instance of {@link RSTextureView } * */ public RSTextureView createRSTextureView() { return new RSTextureView(); } /** * Create an instance of {@link TextureView } * */ public TextureView createTextureView() { return new TextureView(); } /** * Create an instance of {@link ViewStub } * */ public ViewStub createViewStub() { return new ViewStub(); } /** * Create an instance of {@link WebView } * */ public WebView createWebView() { return new WebView(); } /** * Create an instance of {@link AbsoluteLayout } * */ public AbsoluteLayout createAbsoluteLayout() { return new AbsoluteLayout(); } /** * Create an instance of {@link AbsListView } * */ public AbsListView createAbsListView() { return new AbsListView(); } /** * Create an instance of {@link AbsSeekBar } * */ public AbsSeekBar createAbsSeekBar() { return new AbsSeekBar(); } /** * Create an instance of {@link AbsSpinner } * */ public AbsSpinner createAbsSpinner() { return new AbsSpinner(); } /** * Create an instance of {@link AnalogClock } * */ public AnalogClock createAnalogClock() { return new AnalogClock(); } /** * Create an instance of {@link Button } * */ public Button createButton() { return new Button(); } /** * Create an instance of {@link CalendarView } * */ public CalendarView createCalendarView() { return new CalendarView(); } /** * Create an instance of {@link CheckBox } * */ public CheckBox createCheckBox() { return new CheckBox(); } /** * Create an instance of {@link CompoundButton } * */ public CompoundButton createCompoundButton() { return new CompoundButton(); } /** * Create an instance of {@link CheckedTextView } * */ public CheckedTextView createCheckedTextView() { return new CheckedTextView(); } /** * Create an instance of {@link Chronometer } * */ public Chronometer createChronometer() { return new Chronometer(); } /** * Create an instance of {@link DatePicker } * */ public DatePicker createDatePicker() { return new DatePicker(); } /** * Create an instance of {@link DialerFilter } * */ public DialerFilter createDialerFilter() { return new DialerFilter(); } /** * Create an instance of {@link RelativeLayout } * */ public RelativeLayout createRelativeLayout() { return new RelativeLayout(); } /** * Create an instance of {@link DigitalClock } * */ public DigitalClock createDigitalClock() { return new DigitalClock(); } /** * Create an instance of {@link ExpandableListView } * */ public ExpandableListView createExpandableListView() { return new ExpandableListView(); } /** * Create an instance of {@link ListView } * */ public ListView createListView() { return new ListView(); } /** * Create an instance of {@link Gallery } * */ public Gallery createGallery() { return new Gallery(); } /** * Create an instance of {@link GridLayout } * */ public GridLayout createGridLayout() { return new GridLayout(); } /** * Create an instance of {@link GridView } * */ public GridView createGridView() { return new GridView(); } /** * Create an instance of {@link HorizontalScrollView } * */ public HorizontalScrollView createHorizontalScrollView() { return new HorizontalScrollView(); } /** * Create an instance of {@link ImageButton } * */ public ImageButton createImageButton() { return new ImageButton(); } /** * Create an instance of {@link ImageSwitcher } * */ public ImageSwitcher createImageSwitcher() { return new ImageSwitcher(); } /** * Create an instance of {@link ViewSwitcher } * */ public ViewSwitcher createViewSwitcher() { return new ViewSwitcher(); } /** * Create an instance of {@link ViewAnimator } * */ public ViewAnimator createViewAnimator() { return new ViewAnimator(); } /** * Create an instance of {@link ImageView } * */ public ImageView createImageView() { return new ImageView(); } /** * Create an instance of {@link LinearLayout } * */ public LinearLayout createLinearLayout() { return new LinearLayout(); } /** * Create an instance of {@link MultiAutoCompleteTextView } * */ public MultiAutoCompleteTextView createMultiAutoCompleteTextView() { return new MultiAutoCompleteTextView(); } /** * Create an instance of {@link NumberPicker } * */ public NumberPicker createNumberPicker() { return new NumberPicker(); } /** * Create an instance of {@link ProgressBar } * */ public ProgressBar createProgressBar() { return new ProgressBar(); } /** * Create an instance of {@link QuickContactBadge } * */ public QuickContactBadge createQuickContactBadge() { return new QuickContactBadge(); } /** * Create an instance of {@link RadioButton } * */ public RadioButton createRadioButton() { return new RadioButton(); } /** * Create an instance of {@link RadioGroup } * */ public RadioGroup createRadioGroup() { return new RadioGroup(); } /** * Create an instance of {@link RatingBar } * */ public RatingBar createRatingBar() { return new RatingBar(); } /** * Create an instance of {@link ScrollView } * */ public ScrollView createScrollView() { return new ScrollView(); } /** * Create an instance of {@link SearchView } * */ public SearchView createSearchView() { return new SearchView(); } /** * Create an instance of {@link SeekBar } * */ public SeekBar createSeekBar() { return new SeekBar(); } /** * Create an instance of {@link SlidingDrawer } * */ public SlidingDrawer createSlidingDrawer() { return new SlidingDrawer(); } /** * Create an instance of {@link Space } * */ public Space createSpace() { return new Space(); } /** * Create an instance of {@link Spinner } * */ public Spinner createSpinner() { return new Spinner(); } /** * Create an instance of {@link StackView } * */ public StackView createStackView() { return new StackView(); } /** * Create an instance of {@link Switch } * */ public Switch createSwitch() { return new Switch(); } /** * Create an instance of {@link TabHost } * */ public TabHost createTabHost() { return new TabHost(); } /** * Create an instance of {@link TabWidget } * */ public TabWidget createTabWidget() { return new TabWidget(); } /** * Create an instance of {@link TableLayout } * */ public TableLayout createTableLayout() { return new TableLayout(); } /** * Create an instance of {@link TableRow } * */ public TableRow createTableRow() { return new TableRow(); } /** * Create an instance of {@link TextSwitcher } * */ public TextSwitcher createTextSwitcher() { return new TextSwitcher(); } /** * Create an instance of {@link TimePicker } * */ public TimePicker createTimePicker() { return new TimePicker(); } /** * Create an instance of {@link ToggleButton } * */ public ToggleButton createToggleButton() { return new ToggleButton(); } /** * Create an instance of {@link TwoLineListItem } * */ public TwoLineListItem createTwoLineListItem() { return new TwoLineListItem(); } /** * Create an instance of {@link VideoView } * */ public VideoView createVideoView() { return new VideoView(); } /** * Create an instance of {@link ViewFlipper } * */ public ViewFlipper createViewFlipper() { return new ViewFlipper(); } /** * Create an instance of {@link ZoomButton } * */ public ZoomButton createZoomButton() { return new ZoomButton(); } /** * Create an instance of {@link ZoomControls } * */ public ZoomControls createZoomControls() { return new ZoomControls(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link ViewGroup }{@code >}} * */ @XmlElementDecl(namespace = "", name = "ViewGroup") public JAXBElement<ViewGroup> createViewGroup(ViewGroup value) { return new JAXBElement<ViewGroup>(_ViewGroup_QNAME, ViewGroup.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link TextureView }{@code >}} * */ @XmlElementDecl(namespace = "", name = "TextureView") public JAXBElement<TextureView> createTextureView(TextureView value) { return new JAXBElement<TextureView>(_TextureView_QNAME, TextureView.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link AdapterViewAnimator }{@code >}} * */ @XmlElementDecl(namespace = "", name = "AdapterViewAnimator") public JAXBElement<AdapterViewAnimator> createAdapterViewAnimator(AdapterViewAnimator value) { return new JAXBElement<AdapterViewAnimator>(_AdapterViewAnimator_QNAME, AdapterViewAnimator.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link ListView }{@code >}} * */ @XmlElementDecl(namespace = "", name = "ListView") public JAXBElement<ListView> createListView(ListView value) { return new JAXBElement<ListView>(_ListView_QNAME, ListView.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link View }{@code >}} * */ @XmlElementDecl(namespace = "", name = "View") public JAXBElement<View> createView(View value) { return new JAXBElement<View>(_View_QNAME, View.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link Button }{@code >}} * */ @XmlElementDecl(namespace = "", name = "Button") public JAXBElement<Button> createButton(Button value) { return new JAXBElement<Button>(_Button_QNAME, Button.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link SurfaceView }{@code >}} * */ @XmlElementDecl(namespace = "", name = "SurfaceView") public JAXBElement<SurfaceView> createSurfaceView(SurfaceView value) { return new JAXBElement<SurfaceView>(_SurfaceView_QNAME, SurfaceView.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link FrameLayout }{@code >}} * */ @XmlElementDecl(namespace = "", name = "FrameLayout") public JAXBElement<FrameLayout> createFrameLayout(FrameLayout value) { return new JAXBElement<FrameLayout>(_FrameLayout_QNAME, FrameLayout.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link ImageButton }{@code >}} * */ @XmlElementDecl(namespace = "", name = "ImageButton") public JAXBElement<ImageButton> createImageButton(ImageButton value) { return new JAXBElement<ImageButton>(_ImageButton_QNAME, ImageButton.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link RelativeLayout }{@code >}} * */ @XmlElementDecl(namespace = "", name = "RelativeLayout") public JAXBElement<RelativeLayout> createRelativeLayout(RelativeLayout value) { return new JAXBElement<RelativeLayout>(_RelativeLayout_QNAME, RelativeLayout.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link AutoCompleteTextView }{@code >}} * */ @XmlElementDecl(namespace = "", name = "AutoCompleteTextView") public JAXBElement<AutoCompleteTextView> createAutoCompleteTextView(AutoCompleteTextView value) { return new JAXBElement<AutoCompleteTextView>(_AutoCompleteTextView_QNAME, AutoCompleteTextView.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link AbsSpinner }{@code >}} * */ @XmlElementDecl(namespace = "", name = "AbsSpinner") public JAXBElement<AbsSpinner> createAbsSpinner(AbsSpinner value) { return new JAXBElement<AbsSpinner>(_AbsSpinner_QNAME, AbsSpinner.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link ViewSwitcher }{@code >}} * */ @XmlElementDecl(namespace = "", name = "ViewSwitcher") public JAXBElement<ViewSwitcher> createViewSwitcher(ViewSwitcher value) { return new JAXBElement<ViewSwitcher>(_ViewSwitcher_QNAME, ViewSwitcher.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link LinearLayout }{@code >}} * */ @XmlElementDecl(namespace = "", name = "LinearLayout") public JAXBElement<LinearLayout> createLinearLayout(LinearLayout value) { return new JAXBElement<LinearLayout>(_LinearLayout_QNAME, LinearLayout.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link EditText }{@code >}} * */ @XmlElementDecl(namespace = "", name = "EditText") public JAXBElement<EditText> createEditText(EditText value) { return new JAXBElement<EditText>(_EditText_QNAME, EditText.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link ViewAnimator }{@code >}} * */ @XmlElementDecl(namespace = "", name = "ViewAnimator") public JAXBElement<ViewAnimator> createViewAnimator(ViewAnimator value) { return new JAXBElement<ViewAnimator>(_ViewAnimator_QNAME, ViewAnimator.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link TextView }{@code >}} * */ @XmlElementDecl(namespace = "", name = "TextView") public JAXBElement<TextView> createTextView(TextView value) { return new JAXBElement<TextView>(_TextView_QNAME, TextView.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link AbsListView }{@code >}} * */ @XmlElementDecl(namespace = "", name = "AbsListView") public JAXBElement<AbsListView> createAbsListView(AbsListView value) { return new JAXBElement<AbsListView>(_AbsListView_QNAME, AbsListView.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link AbsoluteLayout }{@code >}} * */ @XmlElementDecl(namespace = "", name = "AbsoluteLayout") public JAXBElement<AbsoluteLayout> createAbsoluteLayout(AbsoluteLayout value) { return new JAXBElement<AbsoluteLayout>(_AbsoluteLayout_QNAME, AbsoluteLayout.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link AbsSeekBar }{@code >}} * */ @XmlElementDecl(namespace = "", name = "AbsSeekBar") public JAXBElement<AbsSeekBar> createAbsSeekBar(AbsSeekBar value) { return new JAXBElement<AbsSeekBar>(_AbsSeekBar_QNAME, AbsSeekBar.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link AdapterView }{@code >}} * */ @XmlElementDecl(namespace = "", name = "AdapterView") public JAXBElement<AdapterView> createAdapterView(AdapterView value) { return new JAXBElement<AdapterView>(_AdapterView_QNAME, AdapterView.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link CompoundButton }{@code >}} * */ @XmlElementDecl(namespace = "", name = "CompoundButton") public JAXBElement<CompoundButton> createCompoundButton(CompoundButton value) { return new JAXBElement<CompoundButton>(_CompoundButton_QNAME, CompoundButton.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link ImageView }{@code >}} * */ @XmlElementDecl(namespace = "", name = "ImageView") public JAXBElement<ImageView> createImageView(ImageView value) { return new JAXBElement<ImageView>(_ImageView_QNAME, ImageView.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link ProgressBar }{@code >}} * */ @XmlElementDecl(namespace = "", name = "ProgressBar") public JAXBElement<ProgressBar> createProgressBar(ProgressBar value) { return new JAXBElement<ProgressBar>(_ProgressBar_QNAME, ProgressBar.class, null, value); } }
apache-2.0
watson-developer-cloud/java-sdk
discovery/src/test/java/com/ibm/watson/discovery/v1/model/DeleteTrainingExampleOptionsTest.java
2108
/* * (C) Copyright IBM Corp. 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 com.ibm.watson.discovery.v1.model; import static org.testng.Assert.*; import com.ibm.cloud.sdk.core.service.model.FileWithMetadata; import com.ibm.watson.discovery.v1.utils.TestUtilities; import java.io.InputStream; import java.util.HashMap; import java.util.List; import org.testng.annotations.Test; /** Unit test class for the DeleteTrainingExampleOptions model. */ public class DeleteTrainingExampleOptionsTest { final HashMap<String, InputStream> mockStreamMap = TestUtilities.createMockStreamMap(); final List<FileWithMetadata> mockListFileWithMetadata = TestUtilities.creatMockListFileWithMetadata(); @Test public void testDeleteTrainingExampleOptions() throws Throwable { DeleteTrainingExampleOptions deleteTrainingExampleOptionsModel = new DeleteTrainingExampleOptions.Builder() .environmentId("testString") .collectionId("testString") .queryId("testString") .exampleId("testString") .build(); assertEquals(deleteTrainingExampleOptionsModel.environmentId(), "testString"); assertEquals(deleteTrainingExampleOptionsModel.collectionId(), "testString"); assertEquals(deleteTrainingExampleOptionsModel.queryId(), "testString"); assertEquals(deleteTrainingExampleOptionsModel.exampleId(), "testString"); } @Test(expectedExceptions = IllegalArgumentException.class) public void testDeleteTrainingExampleOptionsError() throws Throwable { new DeleteTrainingExampleOptions.Builder().build(); } }
apache-2.0
xiaomozhang/druid
druid-1.0.9/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowMasterStatusStatement.java
969
/* * Copyright 1999-2011 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; public class MySqlShowMasterStatusStatement extends MySqlStatementImpl implements MySqlShowStatement { public void accept0(MySqlASTVisitor visitor) { visitor.visit(this); visitor.endVisit(this); } }
apache-2.0
CognizantOneDevOps/Insights
PlatformEngine/src/main/java/com/cognizant/devops/engines/platformengine/modules/correlation/model/Correlation.java
2572
/******************************************************************************* * Copyright 2017 Cognizant Technology Solutions * * 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.cognizant.devops.engines.platformengine.modules.correlation.model; *//** * @author Vishal Ganjare (vganjare) *//* public class Correlation { private CorrelationNode source; private CorrelationNode destination; private String relationName; public CorrelationNode getSource() { return source; } public void setSource(CorrelationNode source) { this.source = source; } public CorrelationNode getDestination() { return destination; } public void setDestination(CorrelationNode destination) { this.destination = destination; } public String getRelationName() { return relationName; } public void setRelationName(String relationName) { this.relationName = relationName; } }*/ package com.cognizant.devops.engines.platformengine.modules.correlation.model; public class Correlation { private CorrelationNode source; private CorrelationNode destination; private String relationName; public CorrelationNode getSource() { return source; } public void setSource(CorrelationNode source) { this.source = source; } public CorrelationNode getDestination() { return destination; } public void setDestination(CorrelationNode destination) { this.destination = destination; } public String getRelationName() { return relationName; } public void setRelationName(String relationName) { this.relationName = relationName; } @Override public String toString() { return "CorrelationJson [source=" + source + ", destination=" + destination + ", relationName=" + relationName + ", getSource()=" + getSource() + ", getDestination()=" + getDestination() + ", getRelationName()=" + getRelationName() + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()=" + super.toString() + "]"; } }
apache-2.0
duck1123/java-xmltooling
src/main/java/org/opensaml/xml/signature/impl/RSAKeyValueBuilder.java
1611
/* * Copyright [2006] [University Corporation for Advanced Internet Development, 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.opensaml.xml.signature.impl; import org.opensaml.xml.AbstractXMLObjectBuilder; import org.opensaml.xml.signature.RSAKeyValue; import org.opensaml.xml.signature.XMLSignatureBuilder; import org.opensaml.xml.util.XMLConstants; /** * Builder of {@link org.opensaml.xml.signature.RSAKeyValue} */ public class RSAKeyValueBuilder extends AbstractXMLObjectBuilder<RSAKeyValue> implements XMLSignatureBuilder<RSAKeyValue> { /** * Constructor * */ public RSAKeyValueBuilder() { } /** {@inheritDoc} */ public RSAKeyValue buildObject(String namespaceURI, String localName, String namespacePrefix) { return new RSAKeyValueImpl(namespaceURI, localName, namespacePrefix); } /** {@inheritDoc} */ public RSAKeyValue buildObject() { return buildObject(XMLConstants.XMLSIG_NS, RSAKeyValue.DEFAULT_ELEMENT_LOCAL_NAME, XMLConstants.XMLSIG_PREFIX); } }
apache-2.0
GeorgeTea/practice
design-patterns/src/factory/abstractFactory/ingredients/sauce/MarinaraSouce.java
201
package factory.abstractFactory.ingredients.sauce; import factory.abstractFactory.framework.ingredient.Sauce; /** * Created by george on 28/2/15. */ public class MarinaraSouce implements Sauce { }
apache-2.0
maheshika/carbon4-kernel
core/org.wso2.carbon.user.core/src/test/java/org/wso2/carbon/user/core/jdbc/JDBCConfigurationTest.java
2227
/* * Copyright 2009-2010 WSO2, Inc. (http://wso2.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.carbon.user.core.jdbc; import org.wso2.carbon.user.api.RealmConfiguration; import org.wso2.carbon.user.core.BaseTestCase; import org.wso2.carbon.user.core.UserStoreException; import org.wso2.carbon.user.core.config.RealmConfigXMLProcessor; import org.wso2.carbon.user.core.util.JDBCRealmUtil; import java.io.IOException; import java.io.InputStream; /** Test case for getSQL function */ public class JDBCConfigurationTest extends BaseTestCase { private RealmConfiguration realmConfig = null; public void setUp() throws Exception { super.setUp(); } public void testStuff() throws Exception { doSQLQueryStuff(); } public void doSQLQueryStuff() throws IOException, UserStoreException { InputStream inStream = this.getClass().getClassLoader().getResource(JDBCRealmTest.JDBC_TEST_USERMGT_XML).openStream(); RealmConfigXMLProcessor realmConfigProcessor = new RealmConfigXMLProcessor(); realmConfig = realmConfigProcessor.buildRealmConfiguration(inStream); assertEquals(realmConfig.getUserStoreProperty(JDBCRealmConstants.ADD_ROLE), null); assertEquals(realmConfig.getUserStoreProperty(JDBCRealmConstants.SELECT_USER), JDBCRealmConstants.SELECT_USER_SQL); realmConfig.setUserStoreProperties(JDBCRealmUtil.getSQL(realmConfig.getUserStoreProperties())); assertEquals(realmConfig.getUserStoreProperty(JDBCRealmConstants.ADD_ROLE), JDBCRealmConstants.ADD_ROLE_SQL); assertEquals(realmConfig.getUserStoreProperty(JDBCRealmConstants.SELECT_USER), JDBCRealmConstants.SELECT_USER_SQL); } }
apache-2.0
sluk3r/lucene-3.0.2-src-study
contrib/benchmark/src/test/org/apache/lucene/benchmark/quality/TestQualityRun.java
7028
package org.apache.lucene.benchmark.quality; /** * 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. */ import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.PrintWriter; import org.apache.lucene.benchmark.byTask.TestPerfTasksLogic; import org.apache.lucene.benchmark.byTask.feeds.ReutersContentSource; import org.apache.lucene.benchmark.quality.Judge; import org.apache.lucene.benchmark.quality.QualityQuery; import org.apache.lucene.benchmark.quality.QualityQueryParser; import org.apache.lucene.benchmark.quality.QualityBenchmark; import org.apache.lucene.benchmark.quality.trec.TrecJudge; import org.apache.lucene.benchmark.quality.trec.TrecTopicsReader; import org.apache.lucene.benchmark.quality.utils.SimpleQQParser; import org.apache.lucene.benchmark.quality.utils.SubmissionReport; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.store.FSDirectory; import junit.framework.TestCase; /** * Test that quality run does its job. */ public class TestQualityRun extends TestCase { private static boolean DEBUG = Boolean.getBoolean("tests.verbose"); /** * @param arg0 */ public TestQualityRun(String name) { super(name); } public void testTrecQuality() throws Exception { // first create the complete reuters index createReutersIndex(); File workDir = new File(System.getProperty("benchmark.work.dir","work")); assertTrue("Bad workDir: "+workDir, workDir.exists()&& workDir.isDirectory()); int maxResults = 1000; String docNameField = "docid"; PrintWriter logger = DEBUG ? new PrintWriter(System.out,true) : null; // <tests src dir> for topics/qrels files - src/test/org/apache/lucene/benchmark/quality File srcTestDir = new File(new File(new File(new File(new File( new File(new File(workDir.getAbsoluteFile().getParentFile(), "src"),"test"),"org"),"apache"),"lucene"),"benchmark"),"quality"); // prepare topics File topicsFile = new File(srcTestDir, "trecTopics.txt"); assertTrue("Bad topicsFile: "+topicsFile, topicsFile.exists()&& topicsFile.isFile()); TrecTopicsReader qReader = new TrecTopicsReader(); QualityQuery qqs[] = qReader.readQueries(new BufferedReader(new FileReader(topicsFile))); // prepare judge File qrelsFile = new File(srcTestDir, "trecQRels.txt"); assertTrue("Bad qrelsFile: "+qrelsFile, qrelsFile.exists()&& qrelsFile.isFile()); Judge judge = new TrecJudge(new BufferedReader(new FileReader(qrelsFile))); // validate topics & judgments match each other judge.validateData(qqs, logger); IndexSearcher searcher = new IndexSearcher(FSDirectory.open(new File(workDir,"index")), true); QualityQueryParser qqParser = new SimpleQQParser("title","body"); QualityBenchmark qrun = new QualityBenchmark(qqs, qqParser, searcher, docNameField); SubmissionReport submitLog = DEBUG ? new SubmissionReport(logger, "TestRun") : null; qrun.setMaxResults(maxResults); QualityStats stats[] = qrun.execute(judge, submitLog, logger); // --------- verify by the way judgments were altered for this test: // for some queries, depending on m = qnum % 8 // m==0: avg_precision and recall are hurt, by marking fake docs as relevant // m==1: precision_at_n and avg_precision are hurt, by unmarking relevant docs // m==2: all precision, precision_at_n and recall are hurt. // m>=3: these queries remain perfect for (int i = 0; i < stats.length; i++) { QualityStats s = stats[i]; switch (i%8) { case 0: assertTrue("avg-p should be hurt: "+s.getAvp(), 1.0 > s.getAvp()); assertTrue("recall should be hurt: "+s.getRecall(), 1.0 > s.getRecall()); for (int j = 1; j <= QualityStats.MAX_POINTS; j++) { assertEquals("p_at_"+j+" should be perfect: "+s.getPrecisionAt(j), 1.0, s.getPrecisionAt(j), 1E-9); } break; case 1: assertTrue("avg-p should be hurt", 1.0 > s.getAvp()); assertEquals("recall should be perfect: "+s.getRecall(), 1.0, s.getRecall(), 1E-9); for (int j = 1; j <= QualityStats.MAX_POINTS; j++) { assertTrue("p_at_"+j+" should be hurt: "+s.getPrecisionAt(j), 1.0 > s.getPrecisionAt(j)); } break; case 2: assertTrue("avg-p should be hurt: "+s.getAvp(), 1.0 > s.getAvp()); assertTrue("recall should be hurt: "+s.getRecall(), 1.0 > s.getRecall()); for (int j = 1; j <= QualityStats.MAX_POINTS; j++) { assertTrue("p_at_"+j+" should be hurt: "+s.getPrecisionAt(j), 1.0 > s.getPrecisionAt(j)); } break; default: { assertEquals("avg-p should be perfect: "+s.getAvp(), 1.0, s.getAvp(), 1E-9); assertEquals("recall should be perfect: "+s.getRecall(), 1.0, s.getRecall(), 1E-9); for (int j = 1; j <= QualityStats.MAX_POINTS; j++) { assertEquals("p_at_"+j+" should be perfect: "+s.getPrecisionAt(j), 1.0, s.getPrecisionAt(j), 1E-9); } } } } QualityStats avg = QualityStats.average(stats); if (logger!=null) { avg.log("Average statistis:",1,logger," "); } assertTrue("mean avg-p should be hurt: "+avg.getAvp(), 1.0 > avg.getAvp()); assertTrue("avg recall should be hurt: "+avg.getRecall(), 1.0 > avg.getRecall()); for (int j = 1; j <= QualityStats.MAX_POINTS; j++) { assertTrue("avg p_at_"+j+" should be hurt: "+avg.getPrecisionAt(j), 1.0 > avg.getPrecisionAt(j)); } } // use benchmark logic to create the full Reuters index private void createReutersIndex() throws Exception { // 1. alg definition String algLines[] = { "# ----- properties ", "content.source="+ReutersContentSource.class.getName(), "content.source.log.step=2500", "doc.term.vector=false", "content.source.forever=false", "directory=FSDirectory", "doc.stored=true", "doc.tokenized=true", "# ----- alg ", "ResetSystemErase", "CreateIndex", "{ AddDoc } : *", "CloseIndex", }; // 2. execute the algorithm (required in every "logic" test) TestPerfTasksLogic.execBenchmark(algLines); } }
apache-2.0
jfernandosf/phoenix
phoenix-core/src/main/java/org/apache/phoenix/schema/PTable.java
28929
/* * 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; import static com.google.common.base.Preconditions.checkArgument; import static org.apache.phoenix.query.QueryConstants.ENCODED_CQ_COUNTER_INITIAL_VALUE; import static org.apache.phoenix.util.EncodedColumnsUtil.isReservedColumnQualifier; import java.io.DataOutputStream; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.annotation.Nullable; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.hadoop.hbase.util.Bytes; import org.apache.phoenix.hbase.index.util.KeyValueBuilder; import org.apache.phoenix.index.IndexMaintainer; import org.apache.phoenix.jdbc.PhoenixConnection; import org.apache.phoenix.schema.types.PArrayDataType; import org.apache.phoenix.schema.types.PArrayDataTypeDecoder; import org.apache.phoenix.schema.types.PArrayDataTypeEncoder; import org.apache.phoenix.schema.types.PDataType; import org.apache.phoenix.schema.types.PVarbinary; import org.apache.phoenix.util.TrustedByteArrayOutputStream; import com.google.common.annotations.VisibleForTesting; /** * Definition of a Phoenix table * * * @since 0.1 */ public interface PTable extends PMetaDataEntity { public static final long INITIAL_SEQ_NUM = 0; public static final String IS_IMMUTABLE_ROWS_PROP_NAME = "IMMUTABLE_ROWS"; public static final boolean DEFAULT_DISABLE_WAL = false; public enum ViewType { MAPPED((byte)1), READ_ONLY((byte)2), UPDATABLE((byte)3); private final byte[] byteValue; private final byte serializedValue; ViewType(byte serializedValue) { this.serializedValue = serializedValue; this.byteValue = Bytes.toBytes(this.name()); } public byte[] getBytes() { return byteValue; } public boolean isReadOnly() { return this != UPDATABLE; } public byte getSerializedValue() { return this.serializedValue; } public static ViewType fromSerializedValue(byte serializedValue) { if (serializedValue < 1 || serializedValue > ViewType.values().length) { throw new IllegalArgumentException("Invalid ViewType " + serializedValue); } return ViewType.values()[serializedValue-1]; } public ViewType combine(ViewType otherType) { if (otherType == null) { return this; } if (this == UPDATABLE && otherType == UPDATABLE) { return UPDATABLE; } return READ_ONLY; } } public enum IndexType { GLOBAL((byte)1), LOCAL((byte)2); private final byte[] byteValue; private final byte serializedValue; IndexType(byte serializedValue) { this.serializedValue = serializedValue; this.byteValue = Bytes.toBytes(this.name()); } public byte[] getBytes() { return byteValue; } public byte getSerializedValue() { return this.serializedValue; } public static IndexType getDefault() { return GLOBAL; } public static IndexType fromToken(String token) { return IndexType.valueOf(token.trim().toUpperCase()); } public static IndexType fromSerializedValue(byte serializedValue) { if (serializedValue < 1 || serializedValue > IndexType.values().length) { throw new IllegalArgumentException("Invalid IndexType " + serializedValue); } return IndexType.values()[serializedValue-1]; } } public enum LinkType { /** * Link from a table to its index table */ INDEX_TABLE((byte)1), /** * Link from a view or index to its physical table */ PHYSICAL_TABLE((byte)2), /** * Link from a view to its parent table */ PARENT_TABLE((byte)3), /** * Link from a parent table to its child view */ CHILD_TABLE((byte)4); private final byte[] byteValue; private final byte serializedValue; LinkType(byte serializedValue) { this.serializedValue = serializedValue; this.byteValue = Bytes.toBytes(this.name()); } public byte[] getBytes() { return byteValue; } public byte getSerializedValue() { return this.serializedValue; } public static LinkType fromSerializedValue(byte serializedValue) { if (serializedValue < 1 || serializedValue > LinkType.values().length) { return null; } return LinkType.values()[serializedValue-1]; } } public enum ImmutableStorageScheme implements ColumnValueEncoderDecoderSupplier { ONE_CELL_PER_COLUMN((byte)1) { @Override public ColumnValueEncoder getEncoder(int numElements) { throw new UnsupportedOperationException(); } @Override public ColumnValueDecoder getDecoder() { throw new UnsupportedOperationException(); } }, // stores a single cell per column family that contains all serialized column values SINGLE_CELL_ARRAY_WITH_OFFSETS((byte)2, PArrayDataType.IMMUTABLE_SERIALIZATION_V2) { @Override public ColumnValueEncoder getEncoder(int numElements) { PDataType type = PVarbinary.INSTANCE; int estimatedSize = PArrayDataType.estimateSize(numElements, type); TrustedByteArrayOutputStream byteStream = new TrustedByteArrayOutputStream(estimatedSize); DataOutputStream oStream = new DataOutputStream(byteStream); return new PArrayDataTypeEncoder(byteStream, oStream, numElements, type, SortOrder.ASC, false, getSerializationVersion()); } @Override public ColumnValueDecoder getDecoder() { return new PArrayDataTypeDecoder(); } }; private final byte serializedValue; private byte serializationVersion; private ImmutableStorageScheme(byte serializedValue) { this.serializedValue = serializedValue; } private ImmutableStorageScheme(byte serializedValue, byte serializationVersion) { this.serializedValue = serializedValue; this.serializationVersion = serializationVersion; } public byte getSerializedMetadataValue() { return this.serializedValue; } public byte getSerializationVersion() { return this.serializationVersion; } @VisibleForTesting void setSerializationVersion(byte serializationVersion) { this.serializationVersion = serializationVersion; } public static ImmutableStorageScheme fromSerializedValue(byte serializedValue) { if (serializedValue < 1 || serializedValue > ImmutableStorageScheme.values().length) { return null; } return ImmutableStorageScheme.values()[serializedValue-1]; } } interface ColumnValueEncoderDecoderSupplier { ColumnValueEncoder getEncoder(int numElements); ColumnValueDecoder getDecoder(); } public enum QualifierEncodingScheme implements QualifierEncoderDecoder { NON_ENCODED_QUALIFIERS((byte)0, null) { @Override public byte[] encode(int value) { throw new UnsupportedOperationException(); } @Override public int decode(byte[] bytes) { throw new UnsupportedOperationException(); } @Override public int decode(byte[] bytes, int offset, int length) { throw new UnsupportedOperationException(); } @Override public String toString() { return name(); } }, ONE_BYTE_QUALIFIERS((byte)1, 255) { private final int c = Math.abs(Byte.MIN_VALUE); @Override public byte[] encode(int value) { if (isReservedColumnQualifier(value)) { return FOUR_BYTE_QUALIFIERS.encode(value); } if (value < 0 || value > maxQualifier) { throw new QualifierOutOfRangeException(0, maxQualifier); } return new byte[]{(byte)(value - c)}; } @Override public int decode(byte[] bytes) { if (bytes.length == 4) { return getReservedQualifier(bytes); } if (bytes.length != 1) { throw new InvalidQualifierBytesException(1, bytes.length); } return bytes[0] + c; } @Override public int decode(byte[] bytes, int offset, int length) { if (length == 4) { return getReservedQualifier(bytes, offset, length); } if (length != 1) { throw new InvalidQualifierBytesException(1, length); } return bytes[offset] + c; } @Override public String toString() { return name(); } }, TWO_BYTE_QUALIFIERS((byte)2, 65535) { private final int c = Math.abs(Short.MIN_VALUE); @Override public byte[] encode(int value) { if (isReservedColumnQualifier(value)) { return FOUR_BYTE_QUALIFIERS.encode(value); } if (value < 0 || value > maxQualifier) { throw new QualifierOutOfRangeException(0, maxQualifier); } return Bytes.toBytes((short)(value - c)); } @Override public int decode(byte[] bytes) { if (bytes.length == 4) { return getReservedQualifier(bytes); } if (bytes.length != 2) { throw new InvalidQualifierBytesException(2, bytes.length); } return Bytes.toShort(bytes) + c; } @Override public int decode(byte[] bytes, int offset, int length) { if (length == 4) { return getReservedQualifier(bytes, offset, length); } if (length != 2) { throw new InvalidQualifierBytesException(2, length); } return Bytes.toShort(bytes, offset, length) + c; } @Override public String toString() { return name(); } }, THREE_BYTE_QUALIFIERS((byte)3, 16777215) { @Override public byte[] encode(int value) { if (isReservedColumnQualifier(value)) { return FOUR_BYTE_QUALIFIERS.encode(value); } if (value < 0 || value > maxQualifier) { throw new QualifierOutOfRangeException(0, maxQualifier); } byte[] arr = Bytes.toBytes(value); return new byte[]{arr[1], arr[2], arr[3]}; } @Override public int decode(byte[] bytes) { if (bytes.length == 4) { return getReservedQualifier(bytes); } if (bytes.length != 3) { throw new InvalidQualifierBytesException(2, bytes.length); } byte[] toReturn = new byte[4]; toReturn[1] = bytes[0]; toReturn[2] = bytes[1]; toReturn[3] = bytes[2]; return Bytes.toInt(toReturn); } @Override public int decode(byte[] bytes, int offset, int length) { if (length == 4) { return getReservedQualifier(bytes, offset, length); } if (length != 3) { throw new InvalidQualifierBytesException(3, length); } byte[] toReturn = new byte[4]; toReturn[1] = bytes[offset]; toReturn[2] = bytes[offset + 1]; toReturn[3] = bytes[offset + 2]; return Bytes.toInt(toReturn); } @Override public String toString() { return name(); } }, FOUR_BYTE_QUALIFIERS((byte)4, Integer.MAX_VALUE) { @Override public byte[] encode(int value) { if (value < 0) { throw new QualifierOutOfRangeException(0, maxQualifier); } return Bytes.toBytes(value); } @Override public int decode(byte[] bytes) { if (bytes.length != 4) { throw new InvalidQualifierBytesException(4, bytes.length); } return Bytes.toInt(bytes); } @Override public int decode(byte[] bytes, int offset, int length) { if (length != 4) { throw new InvalidQualifierBytesException(4, length); } return Bytes.toInt(bytes, offset, length); } @Override public String toString() { return name(); } }; final byte metadataValue; final Integer maxQualifier; public byte getSerializedMetadataValue() { return this.metadataValue; } public static QualifierEncodingScheme fromSerializedValue(byte serializedValue) { if (serializedValue < 0 || serializedValue >= QualifierEncodingScheme.values().length) { return null; } return QualifierEncodingScheme.values()[serializedValue]; } @Override public Integer getMaxQualifier() { return maxQualifier; } private QualifierEncodingScheme(byte serializedMetadataValue, Integer maxQualifier) { this.metadataValue = serializedMetadataValue; this.maxQualifier = maxQualifier; } @VisibleForTesting public static class QualifierOutOfRangeException extends RuntimeException { public QualifierOutOfRangeException(int minQualifier, int maxQualifier) { super("Qualifier out of range (" + minQualifier + ", " + maxQualifier + ")"); } } @VisibleForTesting public static class InvalidQualifierBytesException extends RuntimeException { public InvalidQualifierBytesException(int expectedLength, int actualLength) { super("Invalid number of qualifier bytes. Expected length: " + expectedLength + ". Actual: " + actualLength); } } /** * We generate our column qualifiers in the reserved range 0-10 using the FOUR_BYTE_QUALIFIERS * encoding. When adding Cells corresponding to the reserved qualifiers to the * EncodedColumnQualifierCells list, we need to make sure that we use the FOUR_BYTE_QUALIFIERS * scheme to decode the correct int value. */ private static int getReservedQualifier(byte[] bytes) { checkArgument(bytes.length == 4); int number = FOUR_BYTE_QUALIFIERS.decode(bytes); if (!isReservedColumnQualifier(number)) { throw new InvalidQualifierBytesException(4, bytes.length); } return number; } /** * We generate our column qualifiers in the reserved range 0-10 using the FOUR_BYTE_QUALIFIERS * encoding. When adding Cells corresponding to the reserved qualifiers to the * EncodedColumnQualifierCells list, we need to make sure that we use the FOUR_BYTE_QUALIFIERS * scheme to decode the correct int value. */ private static int getReservedQualifier(byte[] bytes, int offset, int length) { checkArgument(length == 4); int number = FOUR_BYTE_QUALIFIERS.decode(bytes, offset, length); if (!isReservedColumnQualifier(number)) { throw new InvalidQualifierBytesException(4, length); } return number; } } interface QualifierEncoderDecoder { byte[] encode(int value); int decode(byte[] bytes); int decode(byte[] bytes, int offset, int length); Integer getMaxQualifier(); } long getTimeStamp(); long getSequenceNumber(); long getIndexDisableTimestamp(); /** * @return table name */ PName getName(); PName getSchemaName(); PName getTableName(); PName getTenantId(); /** * @return the table type */ PTableType getType(); PName getPKName(); /** * Get the PK columns ordered by position. * @return a list of the PK columns */ List<PColumn> getPKColumns(); /** * Get all columns ordered by position. * @return a list of all columns */ List<PColumn> getColumns(); /** * @return A list of the column families of this table * ordered by position. */ List<PColumnFamily> getColumnFamilies(); /** * Get the column family with the given name * @param family the column family name * @return the PColumnFamily with the given name * @throws ColumnFamilyNotFoundException if the column family cannot be found */ PColumnFamily getColumnFamily(byte[] family) throws ColumnFamilyNotFoundException; PColumnFamily getColumnFamily(String family) throws ColumnFamilyNotFoundException; /** * Get the column with the given string name. * @param name the column name * @return the PColumn with the given name * @throws ColumnNotFoundException if no column with the given name * can be found * @throws AmbiguousColumnException if multiple columns are found with the given name */ PColumn getColumnForColumnName(String name) throws ColumnNotFoundException, AmbiguousColumnException; /** * Get the column with the given column qualifier. * @param column qualifier bytes * @return the PColumn with the given column qualifier * @throws ColumnNotFoundException if no column with the given column qualifier can be found * @throws AmbiguousColumnException if multiple columns are found with the given column qualifier */ PColumn getColumnForColumnQualifier(byte[] cf, byte[] cq) throws ColumnNotFoundException, AmbiguousColumnException; /** * Get the PK column with the given name. * @param name the column name * @return the PColumn with the given name * @throws ColumnNotFoundException if no PK column with the given name * can be found * @throws ColumnNotFoundException */ PColumn getPKColumn(String name) throws ColumnNotFoundException; /** * Creates a new row at the specified timestamp using the key * for the PK values (from {@link #newKey(ImmutableBytesWritable, byte[][])} * and the optional key values specified using values. * @param ts the timestamp that the key value will have when committed * @param key the row key of the key value * @param hasOnDupKey true if row has an ON DUPLICATE KEY clause and false otherwise. * @param values the optional key values * @return the new row. Use {@link org.apache.phoenix.schema.PRow#toRowMutations()} to * generate the Row to send to the HBase server. * @throws ConstraintViolationException if row data violates schema * constraint */ PRow newRow(KeyValueBuilder builder, long ts, ImmutableBytesWritable key, boolean hasOnDupKey, byte[]... values); /** * Creates a new row for the PK values (from {@link #newKey(ImmutableBytesWritable, byte[][])} * and the optional key values specified using values. The timestamp of the key value * will be set by the HBase server. * @param key the row key of the key value * @param hasOnDupKey true if row has an ON DUPLICATE KEY clause and false otherwise. * @param values the optional key values * @return the new row. Use {@link org.apache.phoenix.schema.PRow#toRowMutations()} to * generate the row to send to the HBase server. * @throws ConstraintViolationException if row data violates schema * constraint */ PRow newRow(KeyValueBuilder builder, ImmutableBytesWritable key, boolean hasOnDupKey, byte[]... values); /** * Formulates a row key using the values provided. The values must be in * the same order as {@link #getPKColumns()}. * @param key bytes pointer that will be filled in with the row key * @param values the PK column values * @return the number of values that were used from values to set * the row key */ int newKey(ImmutableBytesWritable key, byte[][] values); RowKeySchema getRowKeySchema(); /** * Return the number of buckets used by this table for salting. If the table does * not use salting, returns null. * @return number of buckets used by this table for salting, or null if salting is not used. */ Integer getBucketNum(); /** * Return the list of indexes defined on this table. * @return the list of indexes. */ List<PTable> getIndexes(); /** * For a table of index type, return the state of the table. * @return the state of the index. */ PIndexState getIndexState(); /** * @return the full name of the parent view for a view or data table for an index table * or null if this is not a view or index table. Also returns null for a view of a data table * (use @getPhysicalName for this case) */ PName getParentName(); /** * @return the table name of the parent view for a view or data table for an index table * or null if this is not a view or index table. Also returns null for a view of a data table * (use @getPhysicalTableName for this case) */ PName getParentTableName(); /** * @return the schema name of the parent view for a view or data table for an index table * or null if this is not a view or index table. Also returns null for view of a data table * (use @getPhysicalSchemaName for this case) */ PName getParentSchemaName(); /** * For a view, return the name of table in Phoenix that physically stores data. * Currently a single name, but when views are allowed over multiple tables, will become multi-valued. * @return the name of the physical table storing the data. */ public List<PName> getPhysicalNames(); /** * For a view, return the name of table in HBase that physically stores data. * @return the name of the physical HBase table storing the data. */ PName getPhysicalName(); boolean isImmutableRows(); boolean getIndexMaintainers(ImmutableBytesWritable ptr, PhoenixConnection connection); IndexMaintainer getIndexMaintainer(PTable dataTable, PhoenixConnection connection); PName getDefaultFamilyName(); boolean isWALDisabled(); boolean isMultiTenant(); boolean getStoreNulls(); boolean isTransactional(); ViewType getViewType(); String getViewStatement(); Short getViewIndexId(); PTableKey getKey(); IndexType getIndexType(); int getBaseColumnCount(); /** * Determines whether or not we may optimize out an ORDER BY or do a GROUP BY * in-place when the optimizer tells us it's possible. This is due to PHOENIX-2067 * and only applicable for tables using DESC primary key column(s) which have * not been upgraded. * @return true if optimizations row key order optimizations are possible */ boolean rowKeyOrderOptimizable(); /** * @return Position of the column with {@link PColumn#isRowTimestamp()} as true. * -1 if there is no such column. */ int getRowTimestampColPos(); long getUpdateCacheFrequency(); boolean isNamespaceMapped(); /** * @return The sequence name used to get the unique identifier for views * that are automatically partitioned. */ String getAutoPartitionSeqName(); /** * @return true if the you can only add (and never delete) columns to the table, * you are also not allowed to delete the table */ boolean isAppendOnlySchema(); ImmutableStorageScheme getImmutableStorageScheme(); QualifierEncodingScheme getEncodingScheme(); EncodedCQCounter getEncodedCQCounter(); Boolean useStatsForParallelization(); /** * Class to help track encoded column qualifier counters per column family. */ public class EncodedCQCounter { private final Map<String, Integer> familyCounters = new HashMap<>(); /** * Copy constructor * @param counterToCopy * @return copy of the passed counter */ public static EncodedCQCounter copy(EncodedCQCounter counterToCopy) { EncodedCQCounter cqCounter = new EncodedCQCounter(); for (Entry<String, Integer> e : counterToCopy.values().entrySet()) { cqCounter.setValue(e.getKey(), e.getValue()); } return cqCounter; } public static final EncodedCQCounter NULL_COUNTER = new EncodedCQCounter() { @Override public Integer getNextQualifier(String columnFamily) { return null; } @Override public void setValue(String columnFamily, Integer value) { } @Override public boolean increment(String columnFamily) { return false; } @Override public Map<String, Integer> values() { return Collections.emptyMap(); } }; /** * Get the next qualifier to be used for the column family. * This method also ends up initializing the counter if the * column family already doesn't have one. */ @Nullable public Integer getNextQualifier(String columnFamily) { Integer counter = familyCounters.get(columnFamily); if (counter == null) { counter = ENCODED_CQ_COUNTER_INITIAL_VALUE; familyCounters.put(columnFamily, counter); } return counter; } public void setValue(String columnFamily, Integer value) { familyCounters.put(columnFamily, value); } /** * * @param columnFamily * @return true if the counter was incremented, false otherwise. */ public boolean increment(String columnFamily) { if (columnFamily == null) { return false; } Integer counter = familyCounters.get(columnFamily); if (counter == null) { counter = ENCODED_CQ_COUNTER_INITIAL_VALUE; } counter++; familyCounters.put(columnFamily, counter); return true; } public Map<String, Integer> values() { return Collections.unmodifiableMap(familyCounters); } } }
apache-2.0
shapesecurity/shift-java
generated-sources/main/java/com/shapesecurity/shift/es2018/path/Branch.java
62241
// Generated by branch.js /** * Copyright 2018 Shape Security, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.shapesecurity.shift.es2018.path; import com.shapesecurity.functional.data.Maybe; import com.shapesecurity.shift.es2018.ast.*; import java.util.Objects; public abstract class Branch { abstract public Maybe<? extends Node> step(Node node); abstract public String propertyName(); @Override public boolean equals(Object o) { if (this == o) return true; return o != null && getClass() == o.getClass(); } @Override public int hashCode() { return Objects.hash(getClass()); } public static ArrayAssignmentTargetElements ArrayAssignmentTargetElements_(int index) { return new ArrayAssignmentTargetElements(index); } public static ArrayAssignmentTargetRest ArrayAssignmentTargetRest_() { return new ArrayAssignmentTargetRest(); } public static ArrayBindingElements ArrayBindingElements_(int index) { return new ArrayBindingElements(index); } public static ArrayBindingRest ArrayBindingRest_() { return new ArrayBindingRest(); } public static ArrayExpressionElements ArrayExpressionElements_(int index) { return new ArrayExpressionElements(index); } public static ArrowExpressionParams ArrowExpressionParams_() { return new ArrowExpressionParams(); } public static ArrowExpressionBody ArrowExpressionBody_() { return new ArrowExpressionBody(); } public static AssignmentExpressionBinding AssignmentExpressionBinding_() { return new AssignmentExpressionBinding(); } public static AssignmentExpressionExpression AssignmentExpressionExpression_() { return new AssignmentExpressionExpression(); } public static AssignmentTargetPropertyIdentifierBinding AssignmentTargetPropertyIdentifierBinding_() { return new AssignmentTargetPropertyIdentifierBinding(); } public static AssignmentTargetPropertyIdentifierInit AssignmentTargetPropertyIdentifierInit_() { return new AssignmentTargetPropertyIdentifierInit(); } public static AssignmentTargetPropertyPropertyName AssignmentTargetPropertyPropertyName_() { return new AssignmentTargetPropertyPropertyName(); } public static AssignmentTargetPropertyPropertyBinding AssignmentTargetPropertyPropertyBinding_() { return new AssignmentTargetPropertyPropertyBinding(); } public static AssignmentTargetWithDefaultBinding AssignmentTargetWithDefaultBinding_() { return new AssignmentTargetWithDefaultBinding(); } public static AssignmentTargetWithDefaultInit AssignmentTargetWithDefaultInit_() { return new AssignmentTargetWithDefaultInit(); } public static AwaitExpressionExpression AwaitExpressionExpression_() { return new AwaitExpressionExpression(); } public static BinaryExpressionLeft BinaryExpressionLeft_() { return new BinaryExpressionLeft(); } public static BinaryExpressionRight BinaryExpressionRight_() { return new BinaryExpressionRight(); } public static BindingPropertyIdentifierBinding BindingPropertyIdentifierBinding_() { return new BindingPropertyIdentifierBinding(); } public static BindingPropertyIdentifierInit BindingPropertyIdentifierInit_() { return new BindingPropertyIdentifierInit(); } public static BindingPropertyPropertyName BindingPropertyPropertyName_() { return new BindingPropertyPropertyName(); } public static BindingPropertyPropertyBinding BindingPropertyPropertyBinding_() { return new BindingPropertyPropertyBinding(); } public static BindingWithDefaultBinding BindingWithDefaultBinding_() { return new BindingWithDefaultBinding(); } public static BindingWithDefaultInit BindingWithDefaultInit_() { return new BindingWithDefaultInit(); } public static BlockStatements BlockStatements_(int index) { return new BlockStatements(index); } public static BlockStatementBlock BlockStatementBlock_() { return new BlockStatementBlock(); } public static CallExpressionCallee CallExpressionCallee_() { return new CallExpressionCallee(); } public static CallExpressionArguments CallExpressionArguments_(int index) { return new CallExpressionArguments(index); } public static CatchClauseBinding CatchClauseBinding_() { return new CatchClauseBinding(); } public static CatchClauseBody CatchClauseBody_() { return new CatchClauseBody(); } public static ClassDeclarationName ClassDeclarationName_() { return new ClassDeclarationName(); } public static ClassDeclarationSuper ClassDeclarationSuper_() { return new ClassDeclarationSuper(); } public static ClassDeclarationElements ClassDeclarationElements_(int index) { return new ClassDeclarationElements(index); } public static ClassElementMethod ClassElementMethod_() { return new ClassElementMethod(); } public static ClassExpressionName ClassExpressionName_() { return new ClassExpressionName(); } public static ClassExpressionSuper ClassExpressionSuper_() { return new ClassExpressionSuper(); } public static ClassExpressionElements ClassExpressionElements_(int index) { return new ClassExpressionElements(index); } public static CompoundAssignmentExpressionBinding CompoundAssignmentExpressionBinding_() { return new CompoundAssignmentExpressionBinding(); } public static CompoundAssignmentExpressionExpression CompoundAssignmentExpressionExpression_() { return new CompoundAssignmentExpressionExpression(); } public static ComputedMemberAssignmentTargetObject ComputedMemberAssignmentTargetObject_() { return new ComputedMemberAssignmentTargetObject(); } public static ComputedMemberAssignmentTargetExpression ComputedMemberAssignmentTargetExpression_() { return new ComputedMemberAssignmentTargetExpression(); } public static ComputedMemberExpressionObject ComputedMemberExpressionObject_() { return new ComputedMemberExpressionObject(); } public static ComputedMemberExpressionExpression ComputedMemberExpressionExpression_() { return new ComputedMemberExpressionExpression(); } public static ComputedPropertyNameExpression ComputedPropertyNameExpression_() { return new ComputedPropertyNameExpression(); } public static ConditionalExpressionTest ConditionalExpressionTest_() { return new ConditionalExpressionTest(); } public static ConditionalExpressionConsequent ConditionalExpressionConsequent_() { return new ConditionalExpressionConsequent(); } public static ConditionalExpressionAlternate ConditionalExpressionAlternate_() { return new ConditionalExpressionAlternate(); } public static DataPropertyName DataPropertyName_() { return new DataPropertyName(); } public static DataPropertyExpression DataPropertyExpression_() { return new DataPropertyExpression(); } public static DoWhileStatementBody DoWhileStatementBody_() { return new DoWhileStatementBody(); } public static DoWhileStatementTest DoWhileStatementTest_() { return new DoWhileStatementTest(); } public static ExportDeclaration ExportDeclaration_() { return new ExportDeclaration(); } public static ExportDefaultBody ExportDefaultBody_() { return new ExportDefaultBody(); } public static ExportFromNamedExports ExportFromNamedExports_(int index) { return new ExportFromNamedExports(index); } public static ExportLocalSpecifierName ExportLocalSpecifierName_() { return new ExportLocalSpecifierName(); } public static ExportLocalsNamedExports ExportLocalsNamedExports_(int index) { return new ExportLocalsNamedExports(index); } public static ExpressionStatementExpression ExpressionStatementExpression_() { return new ExpressionStatementExpression(); } public static ForAwaitStatementLeft ForAwaitStatementLeft_() { return new ForAwaitStatementLeft(); } public static ForAwaitStatementRight ForAwaitStatementRight_() { return new ForAwaitStatementRight(); } public static ForAwaitStatementBody ForAwaitStatementBody_() { return new ForAwaitStatementBody(); } public static ForInStatementLeft ForInStatementLeft_() { return new ForInStatementLeft(); } public static ForInStatementRight ForInStatementRight_() { return new ForInStatementRight(); } public static ForInStatementBody ForInStatementBody_() { return new ForInStatementBody(); } public static ForOfStatementLeft ForOfStatementLeft_() { return new ForOfStatementLeft(); } public static ForOfStatementRight ForOfStatementRight_() { return new ForOfStatementRight(); } public static ForOfStatementBody ForOfStatementBody_() { return new ForOfStatementBody(); } public static ForStatementInit ForStatementInit_() { return new ForStatementInit(); } public static ForStatementTest ForStatementTest_() { return new ForStatementTest(); } public static ForStatementUpdate ForStatementUpdate_() { return new ForStatementUpdate(); } public static ForStatementBody ForStatementBody_() { return new ForStatementBody(); } public static FormalParametersItems FormalParametersItems_(int index) { return new FormalParametersItems(index); } public static FormalParametersRest FormalParametersRest_() { return new FormalParametersRest(); } public static FunctionBodyDirectives FunctionBodyDirectives_(int index) { return new FunctionBodyDirectives(index); } public static FunctionBodyStatements FunctionBodyStatements_(int index) { return new FunctionBodyStatements(index); } public static FunctionDeclarationName FunctionDeclarationName_() { return new FunctionDeclarationName(); } public static FunctionDeclarationParams FunctionDeclarationParams_() { return new FunctionDeclarationParams(); } public static FunctionDeclarationBody FunctionDeclarationBody_() { return new FunctionDeclarationBody(); } public static FunctionExpressionName FunctionExpressionName_() { return new FunctionExpressionName(); } public static FunctionExpressionParams FunctionExpressionParams_() { return new FunctionExpressionParams(); } public static FunctionExpressionBody FunctionExpressionBody_() { return new FunctionExpressionBody(); } public static GetterName GetterName_() { return new GetterName(); } public static GetterBody GetterBody_() { return new GetterBody(); } public static IfStatementTest IfStatementTest_() { return new IfStatementTest(); } public static IfStatementConsequent IfStatementConsequent_() { return new IfStatementConsequent(); } public static IfStatementAlternate IfStatementAlternate_() { return new IfStatementAlternate(); } public static ImportDefaultBinding ImportDefaultBinding_() { return new ImportDefaultBinding(); } public static ImportNamedImports ImportNamedImports_(int index) { return new ImportNamedImports(index); } public static ImportNamespaceDefaultBinding ImportNamespaceDefaultBinding_() { return new ImportNamespaceDefaultBinding(); } public static ImportNamespaceNamespaceBinding ImportNamespaceNamespaceBinding_() { return new ImportNamespaceNamespaceBinding(); } public static ImportSpecifierBinding ImportSpecifierBinding_() { return new ImportSpecifierBinding(); } public static LabeledStatementBody LabeledStatementBody_() { return new LabeledStatementBody(); } public static MethodName MethodName_() { return new MethodName(); } public static MethodParams MethodParams_() { return new MethodParams(); } public static MethodBody MethodBody_() { return new MethodBody(); } public static ModuleDirectives ModuleDirectives_(int index) { return new ModuleDirectives(index); } public static ModuleItems ModuleItems_(int index) { return new ModuleItems(index); } public static NewExpressionCallee NewExpressionCallee_() { return new NewExpressionCallee(); } public static NewExpressionArguments NewExpressionArguments_(int index) { return new NewExpressionArguments(index); } public static ObjectAssignmentTargetProperties ObjectAssignmentTargetProperties_(int index) { return new ObjectAssignmentTargetProperties(index); } public static ObjectAssignmentTargetRest ObjectAssignmentTargetRest_() { return new ObjectAssignmentTargetRest(); } public static ObjectBindingProperties ObjectBindingProperties_(int index) { return new ObjectBindingProperties(index); } public static ObjectBindingRest ObjectBindingRest_() { return new ObjectBindingRest(); } public static ObjectExpressionProperties ObjectExpressionProperties_(int index) { return new ObjectExpressionProperties(index); } public static ReturnStatementExpression ReturnStatementExpression_() { return new ReturnStatementExpression(); } public static ScriptDirectives ScriptDirectives_(int index) { return new ScriptDirectives(index); } public static ScriptStatements ScriptStatements_(int index) { return new ScriptStatements(index); } public static SetterName SetterName_() { return new SetterName(); } public static SetterParam SetterParam_() { return new SetterParam(); } public static SetterBody SetterBody_() { return new SetterBody(); } public static ShorthandPropertyName ShorthandPropertyName_() { return new ShorthandPropertyName(); } public static SpreadElementExpression SpreadElementExpression_() { return new SpreadElementExpression(); } public static SpreadPropertyExpression SpreadPropertyExpression_() { return new SpreadPropertyExpression(); } public static StaticMemberAssignmentTargetObject StaticMemberAssignmentTargetObject_() { return new StaticMemberAssignmentTargetObject(); } public static StaticMemberExpressionObject StaticMemberExpressionObject_() { return new StaticMemberExpressionObject(); } public static SwitchCaseTest SwitchCaseTest_() { return new SwitchCaseTest(); } public static SwitchCaseConsequent SwitchCaseConsequent_(int index) { return new SwitchCaseConsequent(index); } public static SwitchDefaultConsequent SwitchDefaultConsequent_(int index) { return new SwitchDefaultConsequent(index); } public static SwitchStatementDiscriminant SwitchStatementDiscriminant_() { return new SwitchStatementDiscriminant(); } public static SwitchStatementCases SwitchStatementCases_(int index) { return new SwitchStatementCases(index); } public static SwitchStatementWithDefaultDiscriminant SwitchStatementWithDefaultDiscriminant_() { return new SwitchStatementWithDefaultDiscriminant(); } public static SwitchStatementWithDefaultPreDefaultCases SwitchStatementWithDefaultPreDefaultCases_(int index) { return new SwitchStatementWithDefaultPreDefaultCases(index); } public static SwitchStatementWithDefaultDefaultCase SwitchStatementWithDefaultDefaultCase_() { return new SwitchStatementWithDefaultDefaultCase(); } public static SwitchStatementWithDefaultPostDefaultCases SwitchStatementWithDefaultPostDefaultCases_(int index) { return new SwitchStatementWithDefaultPostDefaultCases(index); } public static TemplateExpressionTag TemplateExpressionTag_() { return new TemplateExpressionTag(); } public static TemplateExpressionElements TemplateExpressionElements_(int index) { return new TemplateExpressionElements(index); } public static ThrowStatementExpression ThrowStatementExpression_() { return new ThrowStatementExpression(); } public static TryCatchStatementBody TryCatchStatementBody_() { return new TryCatchStatementBody(); } public static TryCatchStatementCatchClause TryCatchStatementCatchClause_() { return new TryCatchStatementCatchClause(); } public static TryFinallyStatementBody TryFinallyStatementBody_() { return new TryFinallyStatementBody(); } public static TryFinallyStatementCatchClause TryFinallyStatementCatchClause_() { return new TryFinallyStatementCatchClause(); } public static TryFinallyStatementFinalizer TryFinallyStatementFinalizer_() { return new TryFinallyStatementFinalizer(); } public static UnaryExpressionOperand UnaryExpressionOperand_() { return new UnaryExpressionOperand(); } public static UpdateExpressionOperand UpdateExpressionOperand_() { return new UpdateExpressionOperand(); } public static VariableDeclarationDeclarators VariableDeclarationDeclarators_(int index) { return new VariableDeclarationDeclarators(index); } public static VariableDeclarationStatementDeclaration VariableDeclarationStatementDeclaration_() { return new VariableDeclarationStatementDeclaration(); } public static VariableDeclaratorBinding VariableDeclaratorBinding_() { return new VariableDeclaratorBinding(); } public static VariableDeclaratorInit VariableDeclaratorInit_() { return new VariableDeclaratorInit(); } public static WhileStatementTest WhileStatementTest_() { return new WhileStatementTest(); } public static WhileStatementBody WhileStatementBody_() { return new WhileStatementBody(); } public static WithStatementObject WithStatementObject_() { return new WithStatementObject(); } public static WithStatementBody WithStatementBody_() { return new WithStatementBody(); } public static YieldExpressionExpression YieldExpressionExpression_() { return new YieldExpressionExpression(); } public static YieldGeneratorExpressionExpression YieldGeneratorExpressionExpression_() { return new YieldGeneratorExpressionExpression(); } } abstract class IndexedBranch extends Branch { public final int index; protected IndexedBranch(int index) { this.index = index; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; IndexedBranch that = (IndexedBranch) o; return index == that.index; } @Override public int hashCode() { return Objects.hash(getClass(), index); } } class ArrayAssignmentTargetElements extends IndexedBranch { protected ArrayAssignmentTargetElements(int index) { super(index); } @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ArrayAssignmentTarget)) return Maybe.empty(); return ((ArrayAssignmentTarget) node).elements.index(index).orJust(Maybe.empty()); } public String propertyName() { return "elements[" + Integer.toString(index) + "]"; } } class ArrayAssignmentTargetRest extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ArrayAssignmentTarget)) return Maybe.empty(); return ((ArrayAssignmentTarget) node).rest; } public String propertyName() { return "rest"; } } class ArrayBindingElements extends IndexedBranch { protected ArrayBindingElements(int index) { super(index); } @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ArrayBinding)) return Maybe.empty(); return ((ArrayBinding) node).elements.index(index).orJust(Maybe.empty()); } public String propertyName() { return "elements[" + Integer.toString(index) + "]"; } } class ArrayBindingRest extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ArrayBinding)) return Maybe.empty(); return ((ArrayBinding) node).rest; } public String propertyName() { return "rest"; } } class ArrayExpressionElements extends IndexedBranch { protected ArrayExpressionElements(int index) { super(index); } @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ArrayExpression)) return Maybe.empty(); return ((ArrayExpression) node).elements.index(index).orJust(Maybe.empty()); } public String propertyName() { return "elements[" + Integer.toString(index) + "]"; } } class ArrowExpressionParams extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ArrowExpression)) return Maybe.empty(); return Maybe.of(((ArrowExpression) node).params); } public String propertyName() { return "params"; } } class ArrowExpressionBody extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ArrowExpression)) return Maybe.empty(); return Maybe.of(((ArrowExpression) node).body); } public String propertyName() { return "body"; } } class AssignmentExpressionBinding extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof AssignmentExpression)) return Maybe.empty(); return Maybe.of(((AssignmentExpression) node).binding); } public String propertyName() { return "binding"; } } class AssignmentExpressionExpression extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof AssignmentExpression)) return Maybe.empty(); return Maybe.of(((AssignmentExpression) node).expression); } public String propertyName() { return "expression"; } } class AssignmentTargetPropertyIdentifierBinding extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof AssignmentTargetPropertyIdentifier)) return Maybe.empty(); return Maybe.of(((AssignmentTargetPropertyIdentifier) node).binding); } public String propertyName() { return "binding"; } } class AssignmentTargetPropertyIdentifierInit extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof AssignmentTargetPropertyIdentifier)) return Maybe.empty(); return ((AssignmentTargetPropertyIdentifier) node).init; } public String propertyName() { return "init"; } } class AssignmentTargetPropertyPropertyName extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof AssignmentTargetPropertyProperty)) return Maybe.empty(); return Maybe.of(((AssignmentTargetPropertyProperty) node).name); } public String propertyName() { return "name"; } } class AssignmentTargetPropertyPropertyBinding extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof AssignmentTargetPropertyProperty)) return Maybe.empty(); return Maybe.of(((AssignmentTargetPropertyProperty) node).binding); } public String propertyName() { return "binding"; } } class AssignmentTargetWithDefaultBinding extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof AssignmentTargetWithDefault)) return Maybe.empty(); return Maybe.of(((AssignmentTargetWithDefault) node).binding); } public String propertyName() { return "binding"; } } class AssignmentTargetWithDefaultInit extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof AssignmentTargetWithDefault)) return Maybe.empty(); return Maybe.of(((AssignmentTargetWithDefault) node).init); } public String propertyName() { return "init"; } } class AwaitExpressionExpression extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof AwaitExpression)) return Maybe.empty(); return Maybe.of(((AwaitExpression) node).expression); } public String propertyName() { return "expression"; } } class BinaryExpressionLeft extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof BinaryExpression)) return Maybe.empty(); return Maybe.of(((BinaryExpression) node).left); } public String propertyName() { return "left"; } } class BinaryExpressionRight extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof BinaryExpression)) return Maybe.empty(); return Maybe.of(((BinaryExpression) node).right); } public String propertyName() { return "right"; } } class BindingPropertyIdentifierBinding extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof BindingPropertyIdentifier)) return Maybe.empty(); return Maybe.of(((BindingPropertyIdentifier) node).binding); } public String propertyName() { return "binding"; } } class BindingPropertyIdentifierInit extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof BindingPropertyIdentifier)) return Maybe.empty(); return ((BindingPropertyIdentifier) node).init; } public String propertyName() { return "init"; } } class BindingPropertyPropertyName extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof BindingPropertyProperty)) return Maybe.empty(); return Maybe.of(((BindingPropertyProperty) node).name); } public String propertyName() { return "name"; } } class BindingPropertyPropertyBinding extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof BindingPropertyProperty)) return Maybe.empty(); return Maybe.of(((BindingPropertyProperty) node).binding); } public String propertyName() { return "binding"; } } class BindingWithDefaultBinding extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof BindingWithDefault)) return Maybe.empty(); return Maybe.of(((BindingWithDefault) node).binding); } public String propertyName() { return "binding"; } } class BindingWithDefaultInit extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof BindingWithDefault)) return Maybe.empty(); return Maybe.of(((BindingWithDefault) node).init); } public String propertyName() { return "init"; } } class BlockStatements extends IndexedBranch { protected BlockStatements(int index) { super(index); } @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof Block)) return Maybe.empty(); return ((Block) node).statements.index(index); } public String propertyName() { return "statements[" + Integer.toString(index) + "]"; } } class BlockStatementBlock extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof BlockStatement)) return Maybe.empty(); return Maybe.of(((BlockStatement) node).block); } public String propertyName() { return "block"; } } class CallExpressionCallee extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof CallExpression)) return Maybe.empty(); return Maybe.of(((CallExpression) node).callee); } public String propertyName() { return "callee"; } } class CallExpressionArguments extends IndexedBranch { protected CallExpressionArguments(int index) { super(index); } @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof CallExpression)) return Maybe.empty(); return ((CallExpression) node).arguments.index(index); } public String propertyName() { return "arguments[" + Integer.toString(index) + "]"; } } class CatchClauseBinding extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof CatchClause)) return Maybe.empty(); return Maybe.of(((CatchClause) node).binding); } public String propertyName() { return "binding"; } } class CatchClauseBody extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof CatchClause)) return Maybe.empty(); return Maybe.of(((CatchClause) node).body); } public String propertyName() { return "body"; } } class ClassDeclarationName extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ClassDeclaration)) return Maybe.empty(); return Maybe.of(((ClassDeclaration) node).name); } public String propertyName() { return "name"; } } class ClassDeclarationSuper extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ClassDeclaration)) return Maybe.empty(); return ((ClassDeclaration) node)._super; } public String propertyName() { return "super"; } } class ClassDeclarationElements extends IndexedBranch { protected ClassDeclarationElements(int index) { super(index); } @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ClassDeclaration)) return Maybe.empty(); return ((ClassDeclaration) node).elements.index(index); } public String propertyName() { return "elements[" + Integer.toString(index) + "]"; } } class ClassElementMethod extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ClassElement)) return Maybe.empty(); return Maybe.of(((ClassElement) node).method); } public String propertyName() { return "method"; } } class ClassExpressionName extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ClassExpression)) return Maybe.empty(); return ((ClassExpression) node).name; } public String propertyName() { return "name"; } } class ClassExpressionSuper extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ClassExpression)) return Maybe.empty(); return ((ClassExpression) node)._super; } public String propertyName() { return "super"; } } class ClassExpressionElements extends IndexedBranch { protected ClassExpressionElements(int index) { super(index); } @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ClassExpression)) return Maybe.empty(); return ((ClassExpression) node).elements.index(index); } public String propertyName() { return "elements[" + Integer.toString(index) + "]"; } } class CompoundAssignmentExpressionBinding extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof CompoundAssignmentExpression)) return Maybe.empty(); return Maybe.of(((CompoundAssignmentExpression) node).binding); } public String propertyName() { return "binding"; } } class CompoundAssignmentExpressionExpression extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof CompoundAssignmentExpression)) return Maybe.empty(); return Maybe.of(((CompoundAssignmentExpression) node).expression); } public String propertyName() { return "expression"; } } class ComputedMemberAssignmentTargetObject extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ComputedMemberAssignmentTarget)) return Maybe.empty(); return Maybe.of(((ComputedMemberAssignmentTarget) node).object); } public String propertyName() { return "object"; } } class ComputedMemberAssignmentTargetExpression extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ComputedMemberAssignmentTarget)) return Maybe.empty(); return Maybe.of(((ComputedMemberAssignmentTarget) node).expression); } public String propertyName() { return "expression"; } } class ComputedMemberExpressionObject extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ComputedMemberExpression)) return Maybe.empty(); return Maybe.of(((ComputedMemberExpression) node).object); } public String propertyName() { return "object"; } } class ComputedMemberExpressionExpression extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ComputedMemberExpression)) return Maybe.empty(); return Maybe.of(((ComputedMemberExpression) node).expression); } public String propertyName() { return "expression"; } } class ComputedPropertyNameExpression extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ComputedPropertyName)) return Maybe.empty(); return Maybe.of(((ComputedPropertyName) node).expression); } public String propertyName() { return "expression"; } } class ConditionalExpressionTest extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ConditionalExpression)) return Maybe.empty(); return Maybe.of(((ConditionalExpression) node).test); } public String propertyName() { return "test"; } } class ConditionalExpressionConsequent extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ConditionalExpression)) return Maybe.empty(); return Maybe.of(((ConditionalExpression) node).consequent); } public String propertyName() { return "consequent"; } } class ConditionalExpressionAlternate extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ConditionalExpression)) return Maybe.empty(); return Maybe.of(((ConditionalExpression) node).alternate); } public String propertyName() { return "alternate"; } } class DataPropertyName extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof DataProperty)) return Maybe.empty(); return Maybe.of(((DataProperty) node).name); } public String propertyName() { return "name"; } } class DataPropertyExpression extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof DataProperty)) return Maybe.empty(); return Maybe.of(((DataProperty) node).expression); } public String propertyName() { return "expression"; } } class DoWhileStatementBody extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof DoWhileStatement)) return Maybe.empty(); return Maybe.of(((DoWhileStatement) node).body); } public String propertyName() { return "body"; } } class DoWhileStatementTest extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof DoWhileStatement)) return Maybe.empty(); return Maybe.of(((DoWhileStatement) node).test); } public String propertyName() { return "test"; } } class ExportDeclaration extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof Export)) return Maybe.empty(); return Maybe.of(((Export) node).declaration); } public String propertyName() { return "declaration"; } } class ExportDefaultBody extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ExportDefault)) return Maybe.empty(); return Maybe.of(((ExportDefault) node).body); } public String propertyName() { return "body"; } } class ExportFromNamedExports extends IndexedBranch { protected ExportFromNamedExports(int index) { super(index); } @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ExportFrom)) return Maybe.empty(); return ((ExportFrom) node).namedExports.index(index); } public String propertyName() { return "namedExports[" + Integer.toString(index) + "]"; } } class ExportLocalSpecifierName extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ExportLocalSpecifier)) return Maybe.empty(); return Maybe.of(((ExportLocalSpecifier) node).name); } public String propertyName() { return "name"; } } class ExportLocalsNamedExports extends IndexedBranch { protected ExportLocalsNamedExports(int index) { super(index); } @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ExportLocals)) return Maybe.empty(); return ((ExportLocals) node).namedExports.index(index); } public String propertyName() { return "namedExports[" + Integer.toString(index) + "]"; } } class ExpressionStatementExpression extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ExpressionStatement)) return Maybe.empty(); return Maybe.of(((ExpressionStatement) node).expression); } public String propertyName() { return "expression"; } } class ForAwaitStatementLeft extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ForAwaitStatement)) return Maybe.empty(); return Maybe.of(((ForAwaitStatement) node).left); } public String propertyName() { return "left"; } } class ForAwaitStatementRight extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ForAwaitStatement)) return Maybe.empty(); return Maybe.of(((ForAwaitStatement) node).right); } public String propertyName() { return "right"; } } class ForAwaitStatementBody extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ForAwaitStatement)) return Maybe.empty(); return Maybe.of(((ForAwaitStatement) node).body); } public String propertyName() { return "body"; } } class ForInStatementLeft extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ForInStatement)) return Maybe.empty(); return Maybe.of(((ForInStatement) node).left); } public String propertyName() { return "left"; } } class ForInStatementRight extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ForInStatement)) return Maybe.empty(); return Maybe.of(((ForInStatement) node).right); } public String propertyName() { return "right"; } } class ForInStatementBody extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ForInStatement)) return Maybe.empty(); return Maybe.of(((ForInStatement) node).body); } public String propertyName() { return "body"; } } class ForOfStatementLeft extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ForOfStatement)) return Maybe.empty(); return Maybe.of(((ForOfStatement) node).left); } public String propertyName() { return "left"; } } class ForOfStatementRight extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ForOfStatement)) return Maybe.empty(); return Maybe.of(((ForOfStatement) node).right); } public String propertyName() { return "right"; } } class ForOfStatementBody extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ForOfStatement)) return Maybe.empty(); return Maybe.of(((ForOfStatement) node).body); } public String propertyName() { return "body"; } } class ForStatementInit extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ForStatement)) return Maybe.empty(); return ((ForStatement) node).init; } public String propertyName() { return "init"; } } class ForStatementTest extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ForStatement)) return Maybe.empty(); return ((ForStatement) node).test; } public String propertyName() { return "test"; } } class ForStatementUpdate extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ForStatement)) return Maybe.empty(); return ((ForStatement) node).update; } public String propertyName() { return "update"; } } class ForStatementBody extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ForStatement)) return Maybe.empty(); return Maybe.of(((ForStatement) node).body); } public String propertyName() { return "body"; } } class FormalParametersItems extends IndexedBranch { protected FormalParametersItems(int index) { super(index); } @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof FormalParameters)) return Maybe.empty(); return ((FormalParameters) node).items.index(index); } public String propertyName() { return "items[" + Integer.toString(index) + "]"; } } class FormalParametersRest extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof FormalParameters)) return Maybe.empty(); return ((FormalParameters) node).rest; } public String propertyName() { return "rest"; } } class FunctionBodyDirectives extends IndexedBranch { protected FunctionBodyDirectives(int index) { super(index); } @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof FunctionBody)) return Maybe.empty(); return ((FunctionBody) node).directives.index(index); } public String propertyName() { return "directives[" + Integer.toString(index) + "]"; } } class FunctionBodyStatements extends IndexedBranch { protected FunctionBodyStatements(int index) { super(index); } @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof FunctionBody)) return Maybe.empty(); return ((FunctionBody) node).statements.index(index); } public String propertyName() { return "statements[" + Integer.toString(index) + "]"; } } class FunctionDeclarationName extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof FunctionDeclaration)) return Maybe.empty(); return Maybe.of(((FunctionDeclaration) node).name); } public String propertyName() { return "name"; } } class FunctionDeclarationParams extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof FunctionDeclaration)) return Maybe.empty(); return Maybe.of(((FunctionDeclaration) node).params); } public String propertyName() { return "params"; } } class FunctionDeclarationBody extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof FunctionDeclaration)) return Maybe.empty(); return Maybe.of(((FunctionDeclaration) node).body); } public String propertyName() { return "body"; } } class FunctionExpressionName extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof FunctionExpression)) return Maybe.empty(); return ((FunctionExpression) node).name; } public String propertyName() { return "name"; } } class FunctionExpressionParams extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof FunctionExpression)) return Maybe.empty(); return Maybe.of(((FunctionExpression) node).params); } public String propertyName() { return "params"; } } class FunctionExpressionBody extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof FunctionExpression)) return Maybe.empty(); return Maybe.of(((FunctionExpression) node).body); } public String propertyName() { return "body"; } } class GetterName extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof Getter)) return Maybe.empty(); return Maybe.of(((Getter) node).name); } public String propertyName() { return "name"; } } class GetterBody extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof Getter)) return Maybe.empty(); return Maybe.of(((Getter) node).body); } public String propertyName() { return "body"; } } class IfStatementTest extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof IfStatement)) return Maybe.empty(); return Maybe.of(((IfStatement) node).test); } public String propertyName() { return "test"; } } class IfStatementConsequent extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof IfStatement)) return Maybe.empty(); return Maybe.of(((IfStatement) node).consequent); } public String propertyName() { return "consequent"; } } class IfStatementAlternate extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof IfStatement)) return Maybe.empty(); return ((IfStatement) node).alternate; } public String propertyName() { return "alternate"; } } class ImportDefaultBinding extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof Import)) return Maybe.empty(); return ((Import) node).defaultBinding; } public String propertyName() { return "defaultBinding"; } } class ImportNamedImports extends IndexedBranch { protected ImportNamedImports(int index) { super(index); } @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof Import)) return Maybe.empty(); return ((Import) node).namedImports.index(index); } public String propertyName() { return "namedImports[" + Integer.toString(index) + "]"; } } class ImportNamespaceDefaultBinding extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ImportNamespace)) return Maybe.empty(); return ((ImportNamespace) node).defaultBinding; } public String propertyName() { return "defaultBinding"; } } class ImportNamespaceNamespaceBinding extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ImportNamespace)) return Maybe.empty(); return Maybe.of(((ImportNamespace) node).namespaceBinding); } public String propertyName() { return "namespaceBinding"; } } class ImportSpecifierBinding extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ImportSpecifier)) return Maybe.empty(); return Maybe.of(((ImportSpecifier) node).binding); } public String propertyName() { return "binding"; } } class LabeledStatementBody extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof LabeledStatement)) return Maybe.empty(); return Maybe.of(((LabeledStatement) node).body); } public String propertyName() { return "body"; } } class MethodName extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof Method)) return Maybe.empty(); return Maybe.of(((Method) node).name); } public String propertyName() { return "name"; } } class MethodParams extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof Method)) return Maybe.empty(); return Maybe.of(((Method) node).params); } public String propertyName() { return "params"; } } class MethodBody extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof Method)) return Maybe.empty(); return Maybe.of(((Method) node).body); } public String propertyName() { return "body"; } } class ModuleDirectives extends IndexedBranch { protected ModuleDirectives(int index) { super(index); } @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof Module)) return Maybe.empty(); return ((Module) node).directives.index(index); } public String propertyName() { return "directives[" + Integer.toString(index) + "]"; } } class ModuleItems extends IndexedBranch { protected ModuleItems(int index) { super(index); } @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof Module)) return Maybe.empty(); return ((Module) node).items.index(index); } public String propertyName() { return "items[" + Integer.toString(index) + "]"; } } class NewExpressionCallee extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof NewExpression)) return Maybe.empty(); return Maybe.of(((NewExpression) node).callee); } public String propertyName() { return "callee"; } } class NewExpressionArguments extends IndexedBranch { protected NewExpressionArguments(int index) { super(index); } @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof NewExpression)) return Maybe.empty(); return ((NewExpression) node).arguments.index(index); } public String propertyName() { return "arguments[" + Integer.toString(index) + "]"; } } class ObjectAssignmentTargetProperties extends IndexedBranch { protected ObjectAssignmentTargetProperties(int index) { super(index); } @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ObjectAssignmentTarget)) return Maybe.empty(); return ((ObjectAssignmentTarget) node).properties.index(index); } public String propertyName() { return "properties[" + Integer.toString(index) + "]"; } } class ObjectAssignmentTargetRest extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ObjectAssignmentTarget)) return Maybe.empty(); return ((ObjectAssignmentTarget) node).rest; } public String propertyName() { return "rest"; } } class ObjectBindingProperties extends IndexedBranch { protected ObjectBindingProperties(int index) { super(index); } @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ObjectBinding)) return Maybe.empty(); return ((ObjectBinding) node).properties.index(index); } public String propertyName() { return "properties[" + Integer.toString(index) + "]"; } } class ObjectBindingRest extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ObjectBinding)) return Maybe.empty(); return ((ObjectBinding) node).rest; } public String propertyName() { return "rest"; } } class ObjectExpressionProperties extends IndexedBranch { protected ObjectExpressionProperties(int index) { super(index); } @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ObjectExpression)) return Maybe.empty(); return ((ObjectExpression) node).properties.index(index); } public String propertyName() { return "properties[" + Integer.toString(index) + "]"; } } class ReturnStatementExpression extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ReturnStatement)) return Maybe.empty(); return ((ReturnStatement) node).expression; } public String propertyName() { return "expression"; } } class ScriptDirectives extends IndexedBranch { protected ScriptDirectives(int index) { super(index); } @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof Script)) return Maybe.empty(); return ((Script) node).directives.index(index); } public String propertyName() { return "directives[" + Integer.toString(index) + "]"; } } class ScriptStatements extends IndexedBranch { protected ScriptStatements(int index) { super(index); } @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof Script)) return Maybe.empty(); return ((Script) node).statements.index(index); } public String propertyName() { return "statements[" + Integer.toString(index) + "]"; } } class SetterName extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof Setter)) return Maybe.empty(); return Maybe.of(((Setter) node).name); } public String propertyName() { return "name"; } } class SetterParam extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof Setter)) return Maybe.empty(); return Maybe.of(((Setter) node).param); } public String propertyName() { return "param"; } } class SetterBody extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof Setter)) return Maybe.empty(); return Maybe.of(((Setter) node).body); } public String propertyName() { return "body"; } } class ShorthandPropertyName extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ShorthandProperty)) return Maybe.empty(); return Maybe.of(((ShorthandProperty) node).name); } public String propertyName() { return "name"; } } class SpreadElementExpression extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof SpreadElement)) return Maybe.empty(); return Maybe.of(((SpreadElement) node).expression); } public String propertyName() { return "expression"; } } class SpreadPropertyExpression extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof SpreadProperty)) return Maybe.empty(); return Maybe.of(((SpreadProperty) node).expression); } public String propertyName() { return "expression"; } } class StaticMemberAssignmentTargetObject extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof StaticMemberAssignmentTarget)) return Maybe.empty(); return Maybe.of(((StaticMemberAssignmentTarget) node).object); } public String propertyName() { return "object"; } } class StaticMemberExpressionObject extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof StaticMemberExpression)) return Maybe.empty(); return Maybe.of(((StaticMemberExpression) node).object); } public String propertyName() { return "object"; } } class SwitchCaseTest extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof SwitchCase)) return Maybe.empty(); return Maybe.of(((SwitchCase) node).test); } public String propertyName() { return "test"; } } class SwitchCaseConsequent extends IndexedBranch { protected SwitchCaseConsequent(int index) { super(index); } @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof SwitchCase)) return Maybe.empty(); return ((SwitchCase) node).consequent.index(index); } public String propertyName() { return "consequent[" + Integer.toString(index) + "]"; } } class SwitchDefaultConsequent extends IndexedBranch { protected SwitchDefaultConsequent(int index) { super(index); } @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof SwitchDefault)) return Maybe.empty(); return ((SwitchDefault) node).consequent.index(index); } public String propertyName() { return "consequent[" + Integer.toString(index) + "]"; } } class SwitchStatementDiscriminant extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof SwitchStatement)) return Maybe.empty(); return Maybe.of(((SwitchStatement) node).discriminant); } public String propertyName() { return "discriminant"; } } class SwitchStatementCases extends IndexedBranch { protected SwitchStatementCases(int index) { super(index); } @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof SwitchStatement)) return Maybe.empty(); return ((SwitchStatement) node).cases.index(index); } public String propertyName() { return "cases[" + Integer.toString(index) + "]"; } } class SwitchStatementWithDefaultDiscriminant extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof SwitchStatementWithDefault)) return Maybe.empty(); return Maybe.of(((SwitchStatementWithDefault) node).discriminant); } public String propertyName() { return "discriminant"; } } class SwitchStatementWithDefaultPreDefaultCases extends IndexedBranch { protected SwitchStatementWithDefaultPreDefaultCases(int index) { super(index); } @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof SwitchStatementWithDefault)) return Maybe.empty(); return ((SwitchStatementWithDefault) node).preDefaultCases.index(index); } public String propertyName() { return "preDefaultCases[" + Integer.toString(index) + "]"; } } class SwitchStatementWithDefaultDefaultCase extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof SwitchStatementWithDefault)) return Maybe.empty(); return Maybe.of(((SwitchStatementWithDefault) node).defaultCase); } public String propertyName() { return "defaultCase"; } } class SwitchStatementWithDefaultPostDefaultCases extends IndexedBranch { protected SwitchStatementWithDefaultPostDefaultCases(int index) { super(index); } @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof SwitchStatementWithDefault)) return Maybe.empty(); return ((SwitchStatementWithDefault) node).postDefaultCases.index(index); } public String propertyName() { return "postDefaultCases[" + Integer.toString(index) + "]"; } } class TemplateExpressionTag extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof TemplateExpression)) return Maybe.empty(); return ((TemplateExpression) node).tag; } public String propertyName() { return "tag"; } } class TemplateExpressionElements extends IndexedBranch { protected TemplateExpressionElements(int index) { super(index); } @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof TemplateExpression)) return Maybe.empty(); return ((TemplateExpression) node).elements.index(index); } public String propertyName() { return "elements[" + Integer.toString(index) + "]"; } } class ThrowStatementExpression extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof ThrowStatement)) return Maybe.empty(); return Maybe.of(((ThrowStatement) node).expression); } public String propertyName() { return "expression"; } } class TryCatchStatementBody extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof TryCatchStatement)) return Maybe.empty(); return Maybe.of(((TryCatchStatement) node).body); } public String propertyName() { return "body"; } } class TryCatchStatementCatchClause extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof TryCatchStatement)) return Maybe.empty(); return Maybe.of(((TryCatchStatement) node).catchClause); } public String propertyName() { return "catchClause"; } } class TryFinallyStatementBody extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof TryFinallyStatement)) return Maybe.empty(); return Maybe.of(((TryFinallyStatement) node).body); } public String propertyName() { return "body"; } } class TryFinallyStatementCatchClause extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof TryFinallyStatement)) return Maybe.empty(); return ((TryFinallyStatement) node).catchClause; } public String propertyName() { return "catchClause"; } } class TryFinallyStatementFinalizer extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof TryFinallyStatement)) return Maybe.empty(); return Maybe.of(((TryFinallyStatement) node).finalizer); } public String propertyName() { return "finalizer"; } } class UnaryExpressionOperand extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof UnaryExpression)) return Maybe.empty(); return Maybe.of(((UnaryExpression) node).operand); } public String propertyName() { return "operand"; } } class UpdateExpressionOperand extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof UpdateExpression)) return Maybe.empty(); return Maybe.of(((UpdateExpression) node).operand); } public String propertyName() { return "operand"; } } class VariableDeclarationDeclarators extends IndexedBranch { protected VariableDeclarationDeclarators(int index) { super(index); } @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof VariableDeclaration)) return Maybe.empty(); return ((VariableDeclaration) node).declarators.index(index); } public String propertyName() { return "declarators[" + Integer.toString(index) + "]"; } } class VariableDeclarationStatementDeclaration extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof VariableDeclarationStatement)) return Maybe.empty(); return Maybe.of(((VariableDeclarationStatement) node).declaration); } public String propertyName() { return "declaration"; } } class VariableDeclaratorBinding extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof VariableDeclarator)) return Maybe.empty(); return Maybe.of(((VariableDeclarator) node).binding); } public String propertyName() { return "binding"; } } class VariableDeclaratorInit extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof VariableDeclarator)) return Maybe.empty(); return ((VariableDeclarator) node).init; } public String propertyName() { return "init"; } } class WhileStatementTest extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof WhileStatement)) return Maybe.empty(); return Maybe.of(((WhileStatement) node).test); } public String propertyName() { return "test"; } } class WhileStatementBody extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof WhileStatement)) return Maybe.empty(); return Maybe.of(((WhileStatement) node).body); } public String propertyName() { return "body"; } } class WithStatementObject extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof WithStatement)) return Maybe.empty(); return Maybe.of(((WithStatement) node).object); } public String propertyName() { return "object"; } } class WithStatementBody extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof WithStatement)) return Maybe.empty(); return Maybe.of(((WithStatement) node).body); } public String propertyName() { return "body"; } } class YieldExpressionExpression extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof YieldExpression)) return Maybe.empty(); return ((YieldExpression) node).expression; } public String propertyName() { return "expression"; } } class YieldGeneratorExpressionExpression extends Branch { @Override public Maybe<? extends Node> step(Node node) { if (!(node instanceof YieldGeneratorExpression)) return Maybe.empty(); return Maybe.of(((YieldGeneratorExpression) node).expression); } public String propertyName() { return "expression"; } }
apache-2.0
yuzhiping/jeeplus
jeeplus-blog/src/main/java/com/jeeplus/blog/service/system/SysUrlValidationService.java
607
package com.jeeplus.blog.service.system; /** * @author:yuzp17311 * @version:v1.0 * @date: 2017-02-24 14:41. */ public interface SysUrlValidationService { /** * validate category url sample :// xxx.51so.info/category/keyword * @param websiteId * @param urlPath * @return * @throws Exception */ boolean validateCategory(String websiteId,String urlPath); /** * validate lable url sample :/tags/xxxx * @param websiteId * @param urlPath * @return * @throws Exception */ boolean validateLable(String websiteId,String urlPath); }
apache-2.0
mikeleishen/bacosys
frame/frame-domain/src/main/java/com/xinyou/frame/domain/biz/EMP_BIZ.java
13096
package com.xinyou.frame.domain.biz; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.UUID; import com.xinyou.frame.domain.entities.ADDR_MAIN; import com.xinyou.frame.domain.entities.CITY_MAIN; import com.xinyou.frame.domain.entities.COUNTRY_MAIN; import com.xinyou.frame.domain.entities.EMP_MAIN; import com.xinyou.frame.domain.entities.NATION_MAIN; import com.xinyou.frame.domain.entities.STATE_MAIN; import com.xinyou.frame.domain.models.EMP_DM; import com.xinyou.frame.domain.models.EMP_MAIN_VIEW; import com.xinyou.frame.domain.models.EntityListDM; import com.xinyou.util.StringUtil; public class EMP_BIZ extends StringUtil { public List<NATION_MAIN> getSlNations(Connection conn) throws Exception { List<NATION_MAIN> returnList = new ArrayList<NATION_MAIN>(); PreparedStatement pstmt = null; ResultSet rs = null; try{ pstmt = conn.prepareStatement("select NATION_MAIN_GUID, NATION_MAIN_ID, NATION_NAME from NATION_MAIN where IS_DELETED=0"); rs = pstmt.executeQuery(); while(rs.next()){ NATION_MAIN entity = new NATION_MAIN(); entity.setNation_main_guid(rs.getString(1)); entity.setNation_main_id(rs.getString(2)); entity.setNation_name(rs.getString(3)); returnList.add(entity); } }catch(Exception e){ throw e; }finally{ if(pstmt!=null) pstmt.close(); } return returnList; } public List<STATE_MAIN> getSlStates(String nation_guid, Connection conn) throws Exception { List<STATE_MAIN> returnList = new ArrayList<STATE_MAIN>(); PreparedStatement pstmt = null; ResultSet rs = null; try{ pstmt = conn.prepareStatement("select STATE_MAIN_GUID, STATE_MAIN_ID, STATE_NAME from STATE_MAIN where IS_DELETED=0 and NATION_GUID=?"); pstmt.setString(1, nation_guid); rs = pstmt.executeQuery(); while(rs.next()){ STATE_MAIN entity = new STATE_MAIN(); entity.setState_main_guid(rs.getString(1)); entity.setState_main_id(rs.getString(2)); entity.setState_name(rs.getString(3)); returnList.add(entity); } }catch(Exception e){ throw e; }finally{ if(pstmt!=null) pstmt.close(); } return returnList; } public List<CITY_MAIN> getSlCitys(String state_guid, Connection conn) throws Exception { List<CITY_MAIN> returnList = new ArrayList<CITY_MAIN>(); PreparedStatement pstmt = null; ResultSet rs = null; try{ pstmt = conn.prepareStatement("select CITY_MAIN_GUID, CITY_MAIN_ID, CITY_NAME from CITY_MAIN where IS_DELETED=0 and STATE_GUID=?"); pstmt.setString(1, state_guid); rs = pstmt.executeQuery(); while(rs.next()){ CITY_MAIN entity = new CITY_MAIN(); entity.setCity_main_guid(rs.getString(1)); entity.setCity_main_id(rs.getString(2)); entity.setCity_name(rs.getString(3)); returnList.add(entity); } }catch(Exception e){ throw e; }finally{ if(pstmt!=null) pstmt.close(); } return returnList; } public List<COUNTRY_MAIN> getSlCountrys(String city_guid, Connection conn) throws Exception { List<COUNTRY_MAIN> returnList = new ArrayList<COUNTRY_MAIN>(); PreparedStatement pstmt = null; ResultSet rs = null; try{ pstmt = conn.prepareStatement("select COUNTRY_MAIN_GUID, COUNTRY_MAIN_ID, COUNTRY_NAME from COUNTRY_MAIN where IS_DELETED=0 and CITY_GUID=?"); pstmt.setString(1, city_guid); rs = pstmt.executeQuery(); while(rs.next()){ COUNTRY_MAIN entity = new COUNTRY_MAIN(); entity.setCountry_main_guid(rs.getString(1)); entity.setCountry_main_id(rs.getString(2)); entity.setCountry_name(rs.getString(3)); returnList.add(entity); } }catch(Exception e){ throw e; }finally{ if(pstmt!=null) pstmt.close(); } return returnList; } public static void addEmp(EMP_MAIN emp_main, Connection conn) throws Exception { PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt=conn.prepareStatement("SELECT EMP_MAIN_ID FROM EMP_MAIN WHERE EMP_MAIN_ID=?"); pstmt.setString(1, emp_main.getEmp_main_id()); rs=pstmt.executeQuery(); boolean exist = false; if (rs.next()) { exist=true; } rs.close(); pstmt.close(); if (exist) { throw new Exception("员工编号 " + emp_main.getEmp_main_id()+ " 已存在"); } pstmt=conn.prepareStatement("SELECT EMP_BACO FROM EMP_MAIN WHERE EMP_BACO=?"); pstmt.setString(1, emp_main.getEmp_baco()); rs=pstmt.executeQuery(); exist = false; if (rs.next()) { exist=true; } rs.close(); pstmt.close(); if (exist) { throw new Exception("员工条码 " + emp_main.getEmp_baco()+ " 已存在"); } pstmt=conn.prepareStatement("INSERT INTO EMP_MAIN (EMP_MAIN_GUID, EMP_MAIN_ID, CREATED_DT, CREATED_BY, UPDATED_DT, UPDATED_BY, IS_DELETED, CLIENT_GUID, DATA_VER, EMP_NAME, EMP_TYPE, EMP_LP, EMP_SP, EMP_STATUS, EMP_MEMO, EMP_SYS_ID,EMP_BACO)VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); String empguid = UUID.randomUUID().toString(); pstmt.setString(1, empguid); pstmt.setString(2, emp_main.getEmp_main_id()); long ldate = new Date().getTime(); pstmt.setLong(3, ldate); pstmt.setString(4, emp_main.getCreated_by()); pstmt.setLong(5, ldate); pstmt.setString(6, emp_main.getUpdated_by()); pstmt.setInt(7, 0); pstmt.setString(8, emp_main.getClient_guid()); pstmt.setString(9, emp_main.getData_ver()); pstmt.setString(10, emp_main.getEmp_name()); if(emp_main.getEmp_type()>4){ emp_main.setEmp_type(3); } pstmt.setInt(11, emp_main.getEmp_type()); pstmt.setString(12, emp_main.getEmp_lp()); pstmt.setString(13, emp_main.getEmp_sp()); if(emp_main.getEmp_status()!=1){ emp_main.setEmp_status(0); } pstmt.setInt(14, emp_main.getEmp_status()); pstmt.setString(15, emp_main.getEmp_memo()); pstmt.setString(16, emp_main.getEmp_sys_id()); pstmt.setString(17, emp_main.getEmp_baco()); pstmt.execute(); pstmt.close(); } catch (Exception e) { throw e; } finally { if (pstmt != null && !pstmt.isClosed())pstmt.close(); } } public static void delEmp(String emp_guid, Connection conn) throws Exception { PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = conn.prepareStatement("SELECT TOP 1 USR_MAIN_GUID FROM USR_MAIN WHERE EMP_GUID=?"); pstmt.setString(1, emp_guid); rs = pstmt.executeQuery(); boolean exist = false; if (rs.next()) { exist = true; } rs.close(); pstmt.close(); if (exist) { throw new Exception("员工已绑定系统用户,不能删除"); } pstmt = conn.prepareStatement("DELETE FROM EMP_MAIN WHERE EMP_MAIN_GUID=?"); pstmt.setString(1, emp_guid); pstmt.execute(); pstmt.close(); conn.commit(); } catch (Exception e) { throw e; } finally { if (pstmt != null && !pstmt.isClosed())pstmt.close(); } } public static void updateEmp(EMP_MAIN emp_main, Connection conn) throws Exception { PreparedStatement pstmt = null; pstmt = conn.prepareStatement("UPDATE EMP_MAIN SET UPDATED_DT=?, UPDATED_BY=?, EMP_NAME=?, EMP_TYPE=?, EMP_STATUS=?, EMP_MEMO=?,EMP_BACO=? WHERE EMP_MAIN_ID=?"); pstmt.setLong(1, new Date().getTime()); pstmt.setString(2, emp_main.getUpdated_by()); pstmt.setString(3, emp_main.getEmp_name()); if(emp_main.getEmp_type()>4){ emp_main.setEmp_type(3); } pstmt.setInt(4, emp_main.getEmp_type()); if(emp_main.getEmp_status()!=1){ emp_main.setEmp_status(0); } pstmt.setInt(5, emp_main.getEmp_status()); pstmt.setString(6, emp_main.getEmp_memo()); pstmt.setString(7, emp_main.getEmp_baco()); pstmt.setString(8, emp_main.getEmp_main_id()); pstmt.execute(); pstmt.close(); } public static EntityListDM getEmps(String emp_name,String emp_id, int page_no, int page_size, Connection conn) throws Exception { if (page_no <= 0)page_no = 1; if (page_size <= 0)page_size = 10; int iRowStart = (page_no - 1) * page_size + 1; int iRowEnd = iRowStart + page_size - 1; EntityListDM returnDM = new EntityListDM(); List<Object> returnList = new ArrayList<Object>(); PreparedStatement pstmt = null; ResultSet rs = null; String subSQL = "SELECT T.EMP_MAIN_GUID, T.EMP_MAIN_ID, T.EMP_NAME, T.EMP_TYPE, T.EMP_STATUS, T.EMP_MEMO, T.EMP_BACO, T.CREATED_DT FROM EMP_MAIN T"; String subSQLWhere = " WHERE 1=1"; String subOrderby = "ORDER BY EMP_MAIN_ID DESC"; if (emp_name != null && !emp_name.isEmpty()) { subSQLWhere += " AND T.EMP_NAME LIKE ?"; } if (emp_id != null && !emp_id.isEmpty()) { subSQLWhere += " AND T.EMP_MAIN_ID=?"; } subSQL = subSQL + subSQLWhere; String sSQL = "SELECT B.* FROM (SELECT A.*, ROW_NUMBER() OVER("+ subOrderby + ") AS RN FROM (" + subSQL+ ") A) B WHERE B.RN>=? AND B.RN <=?"; pstmt = conn.prepareStatement(sSQL); int index = 0; if (emp_name != null && !emp_name.isEmpty()) { pstmt.setString(++index, "%" + emp_name + "%"); } if (emp_id != null && !emp_id.isEmpty()) { pstmt.setString(++index, emp_id ); } pstmt.setInt(++index, iRowStart); pstmt.setInt(++index, iRowEnd); rs = pstmt.executeQuery(); while (rs.next()) { EMP_MAIN_VIEW entity = new EMP_MAIN_VIEW(); entity.setEmp_main_guid(rs.getString(1)); entity.setEmp_main_id(rs.getString(2)); entity.setEmp_name(rs.getString(3)); entity.setEmp_type(rs.getInt(4)); entity.setEmp_status(rs.getInt(5)); entity.setEmp_memo(rs.getString(6)); entity.setEmp_baco(rs.getString(7)); returnList.add(entity); } rs.close(); pstmt.close(); returnDM.setDataList(returnList); subSQLWhere = " WHERE 1=1"; if (emp_name != null && !emp_name.isEmpty()) { subSQLWhere += " AND EMP_NAME LIKE ?"; } if (emp_id != null && !emp_id.isEmpty()) { subSQLWhere += " AND EMP_MAIN_ID=?"; } pstmt = conn.prepareStatement("SELECT COUNT(*) FROM EMP_MAIN"+ subSQLWhere); index = 0; if (emp_name != null && !emp_name.isEmpty()) { pstmt.setString(++index, "%" + emp_name + "%"); } if (emp_id != null && !emp_id.isEmpty()) { pstmt.setString(++index, emp_id); } rs = pstmt.executeQuery(); if (rs.next()) { returnDM.setCount(rs.getInt(1)); } else { returnDM.setCount(0); } rs.close(); pstmt.close(); return returnDM; } public EMP_DM getEmp(String emp_guid, Connection conn) throws Exception { EMP_DM returnDM = new EMP_DM(); PreparedStatement pstmt = null; ResultSet rs = null; try{ pstmt = conn.prepareStatement("select EMP_MAIN_GUID, EMP_MAIN_ID, EMP_FULLNAME, POST_GUID, ORG_GUID, FIRST_NAME, LAST_NAME, OFFICE_PHONE, CELL_PHONE, HOME_PHONE, EMP_EMAIL, EMP_PHOTO, EMP_DESC, EMP_GENDER_ID, EMP_BIRTH_DT, BIRTH_NATION_GUID, MARITAL_STATUS_ID, ID_NO, NATIONALITY_GUID, CHILD_NUM, PASSPORT_NO, PASSPORT_END_DT from EMP_MAIN where IS_DELETED=0 and EMP_MAIN_GUID=?"); pstmt.setString(1, emp_guid); rs = pstmt.executeQuery(); while(rs.next()){ EMP_MAIN entity = new EMP_MAIN(); entity.setEmp_main_guid(rs.getString(1)); entity.setEmp_main_id(rs.getString(2)); returnDM.setEmpData(entity); } pstmt.close(); pstmt = conn.prepareStatement("select t.ADDR_TYPE_ID, t1.ADDR_STREET, t1.ADDR_BLOCK, t1.ADDR_BUILDING, t1.ADDR_FLOOR, t1.ADDR_ROOM, t1.ADDR_ZIP_CODE, t1.ADDR_NATION_GUID, t1.ADDR_STATE_GUID, t1.ADDR_CITY_GUID, t1.ADDR_COUNTRY_GUID from EMP_ADDR t left join ADDR_MAIN t1 on t.ADDR_GUID = t1.ADDR_MAIN_GUID where t.EMP_GUID=?"); pstmt.setString(1, emp_guid); rs = pstmt.executeQuery(); List<ADDR_MAIN> returnList = new ArrayList<ADDR_MAIN>(); while(rs.next()){ ADDR_MAIN entity = new ADDR_MAIN(); entity.setAddr_type_id(rs.getString(1)); entity.setAddr_street(Encode(rs.getString(2))); entity.setAddr_block(Encode(rs.getString(3))); entity.setAddr_building(Encode(rs.getString(4))); entity.setAddr_floor(Encode(rs.getString(5))); entity.setAddr_room(Encode(rs.getString(6))); entity.setAddr_zip_code(rs.getString(7)); entity.setAddr_nation_guid(rs.getString(8)); entity.setAddr_state_guid(rs.getString(9)); entity.setAddr_city_guid(rs.getString(10)); entity.setAddr_country_guid(rs.getString(11)); returnList.add(entity); } pstmt.close(); returnDM.setAddrListData(returnList); }catch(Exception e){ throw e; }finally{ if(pstmt!=null&&!pstmt.isClosed()){ pstmt.close(); } } return returnDM; } public static EMP_MAIN_VIEW getEmpById(String emp_id, Connection conn) throws Exception { EMP_MAIN_VIEW result = new EMP_MAIN_VIEW(); PreparedStatement pstmt = null; ResultSet rs = null; try{ pstmt = conn.prepareStatement("SELECT EMP_MAIN_GUID, EMP_MAIN_ID, EMP_NAME FROM EMP_MAIN WHERE IS_DELETED=0 AND EMP_STATUS=1 AND EMP_MAIN_ID=?"); pstmt.setString(1, emp_id); rs = pstmt.executeQuery(); if(rs.next()){ result.setEmp_main_guid(rs.getString(1)); result.setEmp_main_id(rs.getString(2)); result.setEmp_name(rs.getString(3)); } pstmt.close(); }catch(Exception e){ throw e; }finally{ if(pstmt!=null&&!pstmt.isClosed()){ pstmt.close(); } } return result; } }
apache-2.0
consulo/consulo-napile
src/org/napile/idea/plugin/psi/impl/NapilePackageSupportProvider.java
1088
package org.napile.idea.plugin.psi.impl; import org.consulo.module.extension.ModuleExtension; import org.consulo.psi.PsiPackage; import org.consulo.psi.PsiPackageManager; import org.consulo.psi.PsiPackageSupportProvider; import org.jetbrains.annotations.NotNull; import org.napile.idea.plugin.module.extension.NapileModuleExtension; import com.intellij.openapi.module.Module; import com.intellij.psi.PsiManager; /** * @author VISTALL * @since 12:37/27.05.13 */ public class NapilePackageSupportProvider implements PsiPackageSupportProvider { @Override public boolean isSupported(@NotNull ModuleExtension moduleExtension) { return moduleExtension instanceof NapileModuleExtension; } @Override public boolean isValidPackageName(@NotNull Module module, @NotNull String packageName) { return true; } @NotNull @Override public PsiPackage createPackage(@NotNull PsiManager psiManager, @NotNull PsiPackageManager packageManager, @NotNull Class<? extends ModuleExtension> aClass, @NotNull String s) { return new NapilePackage(psiManager, packageManager, aClass, s); } }
apache-2.0
Dhandapani/gluster-ovirt
backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/GetVdsByVdsIdQuery.java
903
package org.ovirt.engine.core.bll; import org.ovirt.engine.core.common.businessentities.VDS; import org.ovirt.engine.core.common.queries.GetVdsByVdsIdParameters; import org.ovirt.engine.core.dal.dbbroker.DbFacade; public class GetVdsByVdsIdQuery<P extends GetVdsByVdsIdParameters> extends QueriesCommandBase<P> { public GetVdsByVdsIdQuery(P parameters) { super(parameters); } @Override protected void executeQueryCommand() { VDS vds = DbFacade.getInstance() .getVdsDAO() .get(getParameters().getVdsId(), getUserID(), getParameters().isFiltered()); if (vds != null) { vds.setCpuName(CpuFlagsManagerHandler.FindMaxServerCpuByFlags(vds.getcpu_flags(), vds.getvds_group_compatibility_version())); } getQueryReturnValue().setReturnValue(vds); } }
apache-2.0
NLeSC/Aether
src/nl/esciencecenter/aether/ReceivePortIdentifier.java
1784
/* $Id: ReceivePortIdentifier.java 12055 2010-05-19 11:19:16Z ceriel $ */ package nl.esciencecenter.aether; /** * Identifies a {@link nl.esciencecenter.aether.ReceivePort ReceivePort}. */ public interface ReceivePortIdentifier extends java.io.Serializable { /** * Returns the name of the {@link nl.esciencecenter.aether.ReceivePort ReceivePort} * corresponding to this identifier. * @return * the name of the receiveport. */ public String name(); /** * Returns the {@link nl.esciencecenter.aether.AetherIdentifier IbisIdentifier} of the * {@link nl.esciencecenter.aether.ReceivePort ReceivePort} corresponding * to this identifier. * @return * the ibis identifier. */ public AetherIdentifier ibisIdentifier(); /** * The hashCode method is mentioned here just as a reminder that an * implementation must probably redefine it, because two objects * representing the same <code>ReceivePortIdentifier</code> must * result in the same hashcode (and compare equal). * To explicitly specify it in the interface does not help, because * java.lang.Object already implements it, but, anyway, here it is. * * {@inheritDoc} */ public int hashCode(); /** * The equals method is mentioned here just as a reminder that an * implementation must probably redefine it, because two objects * representing the same <code>ReceivePortIdentifier</code> must * compare equal (and result in the same hashcode). * To explicitly specify it in the interface does not help, because * java.lang.Object already implements it, but, anyway, here it is. * * {@inheritDoc} */ public boolean equals(Object other); }
apache-2.0
weijiancai/metaui
core/src/main/java/com/metaui/core/meta/action/MUActionConfig.java
811
package com.metaui.core.meta.action; import com.metaui.core.meta.model.Meta; import java.util.HashMap; import java.util.Map; /** * @author wei_jc * @since 1.0.0 */ public class MUActionConfig { private static MUActionConfig instance = new MUActionConfig(); private Map<String, MUAction> cache = new HashMap<String, MUAction>(); public static MUActionConfig getInstance() { return instance; } private MUActionConfig() { } public void addAction(MUAction action) { String key = String.format("%s.%s", action.getMeta().getName(), action.getName()); cache.put(key, action); } public MUAction getAction(Meta meta, String actionName) { String key = String.format("%s.%s", meta.getName(), actionName); return cache.get(key); } }
apache-2.0
kiddot/Record
app/src/main/java/com/android/record/base/thread/ThreadPoolInterface.java
775
package com.android.record.base.thread; /** * Created by kiddo on 17-1-10. */ public interface ThreadPoolInterface { /** * 往线程池中增加一个线程任务 * @param tasker 线程任务 */ public <T> void addTask(Tasker<T> tasker); /** * * @description:获取指定类型的线程池,如果不存在则创建 * @param @param ThreadPoolType * @return BaseThreadPool * @throws */ public BaseThreadPool getThreadPool(int threadPoolType); /** * 从线程队列中移除一个线程任务 * @param tasker 线程任务 * @return 是否移除成功 */ public <T> boolean removeTask(Tasker<T> tasker); /** * 停止所有任务 */ public void stopAllTask(); }
apache-2.0
quarkusio/quarkus
integration-tests/jpa-postgresql/src/test/java/io/quarkus/it/jpa/postgresql/OverrideJdbcUrlBuildTimeConfigSource.java
1274
package io.quarkus.it.jpa.postgresql; import java.util.HashMap; import javax.annotation.Priority; import org.eclipse.microprofile.config.ConfigProvider; import org.eclipse.microprofile.config.spi.ConfigSource; import io.smallrye.config.Priorities; import io.smallrye.config.common.MapBackedConfigSource; // To test https://github.com/quarkusio/quarkus/issues/16123 @Priority(Priorities.APPLICATION + 100) public class OverrideJdbcUrlBuildTimeConfigSource extends MapBackedConfigSource { public OverrideJdbcUrlBuildTimeConfigSource() { super(OverrideJdbcUrlBuildTimeConfigSource.class.getName(), new HashMap<>(), 1000); } @Override public String getValue(final String propertyName) { if (!propertyName.equals("quarkus.datasource.jdbc.url")) { return super.getValue(propertyName); } boolean isBuildTime = false; for (ConfigSource configSource : ConfigProvider.getConfig().getConfigSources()) { if (configSource.getClass().getSimpleName().equals("BuildTimeEnvConfigSource")) { isBuildTime = true; break; } } if (isBuildTime) { return "${postgres.url}"; } return super.getValue(propertyName); } }
apache-2.0
liuyuxiao/GoogleGlass
src/com/gdkdemo/camera/common/Config.java
285
package com.gdkdemo.camera.common; public final class Config { private Config() {} // Log level. public static int LOGLEVEL = android.util.Log.VERBOSE; //static final int LOGLEVEL = android.util.Log.DEBUG; //static final int LOGLEVEL = android.util.Log.INFO; }
apache-2.0
emembrives/dispotrains
Dispotrains/app/src/main/java/fr/membrives/dispotrains/MainActivity.java
308
package fr.membrives.dispotrains; import android.app.Activity; import android.os.Bundle; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
apache-2.0
goinstant/dagger
compiler/src/main/java/dagger2/internal/codegen/writer/TypeNames.java
3513
/* * Copyright (C) 2014 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 dagger2.internal.codegen.writer; import com.google.common.base.Function; import com.google.common.collect.FluentIterable; import javax.lang.model.element.TypeElement; import javax.lang.model.type.ArrayType; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.NoType; import javax.lang.model.type.NullType; import javax.lang.model.type.PrimitiveType; import javax.lang.model.type.TypeMirror; import javax.lang.model.type.TypeVariable; import javax.lang.model.type.WildcardType; import javax.lang.model.util.SimpleTypeVisitor6; public final class TypeNames { static final Function<TypeMirror, TypeName> FOR_TYPE_MIRROR = new Function<TypeMirror, TypeName>() { @Override public TypeName apply(TypeMirror input) { return forTypeMirror(input); } }; public static TypeName forClass(Class<?> clazz) { if (clazz.isPrimitive()) { return PrimitiveName.forClass(clazz); } else if (void.class.equals(clazz)) { return VoidName.VOID; } else if (clazz.isArray()) { return new ArrayTypeName(forClass(clazz.getComponentType())); } else { return ClassName.fromClass(clazz); } } public static TypeName forTypeMirror(TypeMirror mirror) { return mirror.accept(new SimpleTypeVisitor6<TypeName, Void>() { @Override protected TypeName defaultAction(TypeMirror e, Void p) { throw new IllegalArgumentException(e.toString()); } @Override public TypeName visitTypeVariable(TypeVariable t, Void p) { return TypeVariableName.fromTypeVariable(t); } @Override public ArrayTypeName visitArray(ArrayType t, Void p) { return new ArrayTypeName(t.getComponentType().accept(this, null)); } @Override public TypeName visitDeclared(DeclaredType t, Void p) { return t.getTypeArguments().isEmpty() ? ClassName.fromTypeElement((TypeElement) t.asElement()) : new ParameterizedTypeName( ClassName.fromTypeElement((TypeElement) t.asElement()), FluentIterable.from(t.getTypeArguments()).transform(FOR_TYPE_MIRROR)); } @Override public PrimitiveName visitPrimitive(PrimitiveType t, Void p) { return PrimitiveName.forTypeMirror(t); } @Override public WildcardName visitWildcard(WildcardType t, Void p) { return WildcardName.forTypeMirror(t); } @Override public NullName visitNull(NullType t, Void p) { return NullName.NULL; } @Override public TypeName visitNoType(NoType t, Void p) { switch (t.getKind()) { case VOID: return VoidName.VOID; case PACKAGE: throw new IllegalArgumentException(); default: throw new IllegalStateException(); } } }, null); } private TypeNames() { } }
apache-2.0
codefollower/Open-Source-Research
Douyu-0.7.1/douyu-http/src/main/java/com/codefollower/douyu/http/DouyuHttpRequestDecoder.java
762
package com.codefollower.douyu.http; public class DouyuHttpRequestDecoder extends HttpMessageDecoder { /** * Creates a new instance with the default * {@code maxInitialLineLength (4096}}, {@code maxHeaderSize (8192)}, and * {@code maxChunkSize (8192)}. */ public DouyuHttpRequestDecoder() { super(); } /** * Creates a new instance with the specified parameters. */ public DouyuHttpRequestDecoder(int maxInitialLineLength, int maxHeaderSize, int maxChunkSize) { super(maxInitialLineLength, maxHeaderSize, maxChunkSize); } @Override protected HttpMessage createMessage(String[] initialLine) throws Exception { return new DouyuHttpRequest(HttpVersion.valueOf(initialLine[2]), HttpMethod.valueOf(initialLine[0]), initialLine[1]); } }
apache-2.0
adligo/fabricate.adligo.org
src/org/adligo/fabricate/models/common/RoutineBriefMutant.java
23404
package org.adligo.fabricate.models.common; import org.adligo.fabricate.xml.io_v1.common_v1_0.ParamsType; import org.adligo.fabricate.xml.io_v1.common_v1_0.RoutineParentType; import org.adligo.fabricate.xml.io_v1.common_v1_0.RoutineType; import org.adligo.fabricate.xml.io_v1.fabricate_v1_0.StageType; import org.adligo.fabricate.xml.io_v1.project_v1_0.ProjectRoutineType; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * This is the description of a routine class, * in memory which came from the fabricate.xml file. * @author scott * */ public class RoutineBriefMutant implements I_RoutineBrief { private static final String NULL = "null"; public static Map<String, I_RoutineBrief> convert(List<RoutineParentType> types, RoutineBriefOrigin origin) throws ClassNotFoundException { Map<String, I_RoutineBrief> toRet = new HashMap<String, I_RoutineBrief>(); if (types != null) { for (RoutineParentType type: types) { if (type != null) { toRet.put( type.getName(), new RoutineBriefMutant(type, origin)); } } } return toRet; } public static Map<String, I_RoutineBrief> convertStages(List<StageType> types, RoutineBriefOrigin origin) throws ClassNotFoundException { Map<String, I_RoutineBrief> toRet = new HashMap<String, I_RoutineBrief>(); if (types != null) { for (StageType type: types) { if (type != null) { toRet.put(type.getName(), new RoutineBriefMutant(type, origin)); } } } return toRet; } /** * Note parameters and nested routines must be in * identical order to have equal return true. * @param me * @param obj * @return */ public static boolean equals(I_RoutineBrief me, Object obj) { if (me == obj) { return true; } if (obj instanceof I_RoutineBrief) { I_RoutineBrief other = (I_RoutineBrief) obj; String name = me.getName(); String oName = other.getName(); if (name == null) { if (oName != null) { return false; } } else if (!name.equals(oName)) { return false; } Class<?> clazz = me.getClazz(); Class<?> oClazz = other.getClazz(); if (clazz == null) { if (oClazz != null) { return false; } } else if (oClazz == null) { return false; } else if ( !clazz.getName().equals(oClazz.getName())) { return false; } boolean optional = me.isOptional(); boolean oOptional = other.isOptional(); if (optional != oOptional) { return false; } RoutineBriefOrigin origin = me.getOrigin(); RoutineBriefOrigin oOrigin = other.getOrigin(); if (origin == null) { if (oOrigin != null) { return false; } } else if (!origin.equals(oOrigin)) { return false; } List<I_Parameter> params = me.getParameters(); List<I_Parameter> oParams = other.getParameters(); if (params == null) { if (oParams != null) { return false; } } else if (oParams == null) { return false; } else if (params.size() != oParams.size()){ return false; } else { for (int i = 0; i < params.size(); i++) { I_Parameter param = params.get(i); I_Parameter oParam = oParams.get(i); if (param == null) { if (oParam != null) { return false; } } else if ( !param.equals(oParam)) { return false; } } } List<I_RoutineBrief> nests = me.getNestedRoutines(); List<I_RoutineBrief> oNests = other.getNestedRoutines(); if (nests == null) { if (oNests != null) { return false; } } else if (oNests == null) { return false; } else if (nests.size() != oNests.size()){ return false; } else { for (int i = 0; i < nests.size(); i++) { I_RoutineBrief nest = nests.get(i); I_RoutineBrief oNest = oNests.get(i); if (nest == null) { if (oNest != null) { return false; } } else if ( !nest.equals(oNest)) { return false; } } } return true; } return false; } public static I_Parameter getParameter(List<I_Parameter> params, String key) { if (params == null) { return null; } for (I_Parameter rbm: params) { if (rbm != null) { if (key.equals(rbm.getKey())) { return rbm; } } } return null; } public static List<I_Parameter> getParameters(List<I_Parameter> params, String key) { if (params == null) { return Collections.emptyList(); } List<I_Parameter> toRet = new ArrayList<I_Parameter>(); for (I_Parameter rbm: params) { if (rbm != null) { if (key.equals(rbm.getKey())) { toRet.add(rbm); } } } return toRet; } public static int hashCode(I_RoutineBrief in) { final int prime = 31; int result = 1; Class<?> clazz = in.getClazz(); result = prime * result + ((clazz == null) ? 0 : clazz.hashCode()); String name = in.getName(); result = prime * result + ((name == null) ? 0 : name.hashCode()); boolean optional = in.isOptional(); result = prime * result + ((optional) ? 1 : 0); RoutineBriefOrigin origin = in.getOrigin(); result = prime * result + ((origin == null) ? 0 : origin.hashCode()); List<I_Parameter> params = in.getParameters(); if (params != null) { for (I_Parameter param: params) { result = prime * result + ((param == null) ? 0 : param.hashCode()); } } List<I_RoutineBrief> nests = in.getNestedRoutines(); if (nests != null) { for (I_RoutineBrief nest: nests) { result = prime * result + ((nest == null) ? 0 : nest.hashCode()); } } return result; } public static boolean hasNested(String key, List<I_RoutineBrief> briefs) { if (briefs == null || key == null) { return false; } for (I_RoutineBrief rbm: briefs) { if (rbm != null) { if (key.equals(rbm.getName())) { return true; } } } return false; } public static String toString(I_RoutineBrief me) { StringBuilder sb = new StringBuilder(); StringBuilder indent = new StringBuilder(); toString(me, sb, indent); return sb.toString(); } public static void toString(I_RoutineBrief me, StringBuilder sb, StringBuilder indent) { String currentIndent = indent.toString(); sb.append(currentIndent); sb.append(me.getClass().getSimpleName()); sb.append(" [name="); sb.append(me.getName()); sb.append(", class="); Class<?> clazz = me.getClazz(); if (clazz == null) { sb.append(NULL); } else { sb.append(clazz.getName()); } boolean listSubs = false; List<I_Parameter> children = me.getParameters(); if (children.size() >= 1) { listSubs = true; sb.append(","); for (I_Parameter child: children) { sb.append(System.lineSeparator()); indent.append("\t"); ParameterMutant.toString(child, sb, indent); String newIndent = indent.toString(); indent.delete(0,newIndent.length()); indent.append(currentIndent); } } List<I_RoutineBrief> nests = me.getNestedRoutines(); if (nests.size() >= 1) { if (!listSubs) { sb.append(","); listSubs = true; } for (I_RoutineBrief child: nests) { sb.append(System.lineSeparator()); indent.append("\t"); toString(child, sb, indent); String newIndent = indent.toString(); indent.delete(0,newIndent.length()); indent.append(currentIndent); } } if (!listSubs) { sb.append("]"); } else { sb.append(System.lineSeparator()); sb.append(currentIndent); sb.append("]"); } } private String name_; private Class<? extends I_FabricationRoutine> clazz_; private RoutineBriefOrigin origin_; /** * actually only ParameterMutant instances. */ private List<I_Parameter> parameters_; /** * actually only RoutineBriefMutant instances. */ private List<I_RoutineBrief> nestedRoutines_; /** * This is the setting from xml, or null */ private Boolean optional_; public RoutineBriefMutant() {} /** * * @param name * @param className * @param origin * @throws IllegalArgumentException * Note these are internal exceptions and should never show to the user. * @throws IOException with the message the name * of the class that couldn't be loaded. */ @SuppressWarnings("unchecked") public RoutineBriefMutant(String name, String className, RoutineBriefOrigin origin) throws IllegalArgumentException, ClassNotFoundException { if (name == null) { throw new IllegalArgumentException("name"); } name_ = name; if (origin == null) { throw new IllegalArgumentException("origin"); } origin_ = origin; if (className != null) { ClassLoader cl = ClassLoader.getSystemClassLoader(); clazz_ = (Class<? extends I_FabricationRoutine>) Class.forName(className, true, cl); } } /** * * @param brief */ @SuppressWarnings("boxing") public RoutineBriefMutant(I_RoutineBrief brief) { name_ = brief.getName(); clazz_ = brief.getClazz(); origin_ = brief.getOrigin(); List<I_RoutineBrief> nested = brief.getNestedRoutines(); if (nested != null) { setNestedRoutines(nested); } optional_ = brief.isOptional(); origin_ = brief.getOrigin(); List<I_Parameter> parameters = brief.getParameters(); if (parameters != null) { setParameters(parameters); } } public RoutineBriefMutant(RoutineParentType routine, RoutineBriefOrigin origin) throws IllegalArgumentException, ClassNotFoundException { this(routine.getName(), routine.getClazz(), origin); ParamsType params = routine.getParams(); if (params != null) { List<I_Parameter> ps = ParameterMutant.convert(params); if (ps.size() >= 1) { setParameters(ps); } } List<RoutineType> nested = routine.getTask(); if (nested != null) { if (nested.size() >= 1) { addNested(origin, nested); } } } /** * * @param routine * @param origin a STAGE_TASK, or COMMAND_TASK * this constructor doesn't do nestedRoutines. * @throws a exception when the class couldn't be located, * or there was some other problem paramter. */ public RoutineBriefMutant(RoutineType routine, RoutineBriefOrigin origin) throws IllegalArgumentException, ClassNotFoundException { this(routine.getName(), routine.getClazz(), origin); ParamsType params = routine.getParams(); List<I_Parameter> ps = ParameterMutant.convert(params); setParameters(ps); } public RoutineBriefMutant(StageType stage, RoutineBriefOrigin origin) throws IllegalArgumentException, ClassNotFoundException { this(stage.getName(), stage.getClazz(), origin); ParamsType params = stage.getParams(); if (params != null) { List<I_Parameter> ps = ParameterMutant.convert(params); if (ps.size() >= 1) { setParameters(ps); } } optional_ = stage.isOptional(); List<? extends RoutineType> nested = stage.getTask(); if (nested != null) { if (nested.size() >= 1) { switch (origin) { case ARCHIVE_STAGE: addNested(nested, RoutineBriefOrigin.ARCHIVE_STAGE_TASK); break; case FABRICATE_ARCHIVE_STAGE: addNested(nested, RoutineBriefOrigin.FABRICATE_ARCHIVE_STAGE_TASK); break; case FABRICATE_STAGE: addNested(nested, RoutineBriefOrigin.FABRICATE_STAGE_TASK); break; case IMPLICIT_ARCHIVE_STAGE: addNested(nested, RoutineBriefOrigin.IMPLICIT_ARCHIVE_STAGE_TASK); break; case IMPLICIT_STAGE: addNested(nested, RoutineBriefOrigin.IMPLICIT_STAGE_TASK); break; case PROJECT_STAGE: addNested(nested, RoutineBriefOrigin.PROJECT_STAGE_TASK); break; case STAGE: default: addNested(nested, RoutineBriefOrigin.STAGE_TASK); } } } } public RoutineBriefMutant(ProjectRoutineType stage, RoutineBriefOrigin origin) throws IllegalArgumentException, ClassNotFoundException { this(stage.getName(), null, origin); ParamsType params = stage.getParams(); if (params != null) { List<I_Parameter> ps = ParameterMutant.convert(params); if (ps.size() >= 1) { setParameters(ps); } } List<? extends RoutineType> nested = stage.getTask(); if (nested != null) { if (nested.size() >= 1) { switch (origin) { case PROJECT_COMMAND: addNested(nested, RoutineBriefOrigin.PROJECT_COMMAND_TASK); break; case PROJECT_STAGE: default: addNested(nested, RoutineBriefOrigin.PROJECT_STAGE_TASK); } } } } public void addNestedRoutine(I_RoutineBrief nested) { String name = nested.getName(); if (hasNested(name, nestedRoutines_)) { DuplicateRoutineException dre = new DuplicateRoutineException(); dre.setName(name); dre.setOrigin(nested.getOrigin()); dre.setParentName(name_); dre.setParentOrigin(origin_); throw dre; } if (nestedRoutines_ == null) { nestedRoutines_ = new ArrayList<I_RoutineBrief>(); } if (nested instanceof RoutineBriefMutant) { nestedRoutines_.add((RoutineBriefMutant) nested); } else { //should throw a npe for null input nestedRoutines_.add(new RoutineBriefMutant(nested)); } } public void addParameter(I_Parameter param) { if (parameters_ == null) { parameters_ = new ArrayList<I_Parameter>(); } if (param instanceof ParameterMutant) { parameters_.add((ParameterMutant) param); } else { //should throw a npe for null input parameters_.add(new ParameterMutant(param)); } } @Override public boolean equals(Object obj) { return equals(this, obj); } /* (non-Javadoc) * @see org.adligo.fabricate.models.routines.I_RoutineBrief#getClazz() */ @Override public Class<? extends I_FabricationRoutine> getClazz() { return clazz_; } /* (non-Javadoc) * @see org.adligo.fabricate.models.routines.I_RoutineBrief#getName() */ @Override public String getName() { return name_; } @Override public boolean hasParameter(String key) { if (parameters_ == null) { return false; } for (I_Parameter rbm: parameters_) { if (rbm != null) { if (key.equals(rbm.getKey())) { return true; } } } return false; } @Override public boolean isCommand() { if (origin_ == null) { return false; } switch (origin_) { case COMMAND: case FABRICATE_COMMAND: case IMPLICIT_COMMAND: case PROJECT_COMMAND: return true; default: break; } return false; } /* (non-Javadoc) * @see org.adligo.fabricate.models.routines.I_RoutineBrief#isOptional() */ @Override public boolean isOptional() { if (optional_ == null) { return false; } return optional_; } @Override public boolean isStage() { if (origin_ == null) { return false; } switch (origin_) { case FABRICATE_STAGE: case PROJECT_STAGE: case IMPLICIT_STAGE: case STAGE: return true; default: break; } return false; } @Override public boolean isArchivalStage() { if (origin_ == null) { return false; } switch (origin_) { case FABRICATE_ARCHIVE_STAGE: case PROJECT_ARCHIVE_STAGE: case IMPLICIT_ARCHIVE_STAGE: case ARCHIVE_STAGE: return true; default: break; } return false; } /* (non-Javadoc) * @see org.adligo.fabricate.models.routines.I_RoutineBrief#getOrigin() */ @Override public RoutineBriefOrigin getOrigin() { return origin_; } @Override public I_Parameter getParameter(String key) { return getParameter(parameters_, key); } @Override public List<I_Parameter> getParameters(String key) { return getParameters(parameters_, key); } /* (non-Javadoc) * @see org.adligo.fabricate.models.routines.I_RoutineBrief#getParameters() */ @Override public List<I_Parameter> getParameters() { if (parameters_ == null) { return Collections.emptyList(); } return new ArrayList<I_Parameter>(parameters_); } /* (non-Javadoc) * @see org.adligo.fabricate.models.routines.I_RoutineBrief#getNestedRoutines() */ @Override public List<I_RoutineBrief> getNestedRoutines() { if (nestedRoutines_ == null) { return Collections.emptyList(); } return new ArrayList<I_RoutineBrief>(nestedRoutines_); } public boolean removeNestedRoutine(String name) { if (nestedRoutines_ == null) { return false; } Iterator<I_RoutineBrief> nestedIt = nestedRoutines_.iterator(); while(nestedIt.hasNext()) { I_RoutineBrief next = nestedIt.next(); if (name.equals(next.getName())) { nestedIt.remove(); return true; } } return false; } public void removeParameters(String key) { if (parameters_ == null) { return; } Iterator<I_Parameter> it = parameters_.iterator(); while (it.hasNext()) { I_Parameter pm = it.next(); if (key.equals(pm.getKey())) { it.remove(); } } } public void setClazz(Class<? extends I_FabricationRoutine> clazz) { this.clazz_ = clazz; } public void setName(String name) { this.name_ = name; } public void setOptional(Boolean optional) { this.optional_ = optional; } public void setOrigin(RoutineBriefOrigin origin) { this.origin_ = origin; } public void setNestedRoutines(List<I_RoutineBrief> nestedRoutines) { if (nestedRoutines_ != null) { nestedRoutines_.clear(); } if (nestedRoutines != null) { for (I_RoutineBrief brief: nestedRoutines) { addNestedRoutine(brief); } } } public void setParameters(Collection<I_Parameter> parameters) { if (parameters_ != null) {parameters_.clear(); } if (parameters != null) { for (I_Parameter param: parameters) { addParameter(param); } } } private void addNested(RoutineBriefOrigin origin, List<RoutineType> nested) throws ClassNotFoundException { switch (origin) { case ARCHIVE_STAGE: addNested(nested, RoutineBriefOrigin.ARCHIVE_STAGE_TASK); break; case COMMAND: addNested(nested, RoutineBriefOrigin.COMMAND_TASK); break; case FABRICATE_ARCHIVE_STAGE: addNested(nested, RoutineBriefOrigin.FABRICATE_ARCHIVE_STAGE_TASK); break; case FABRICATE_COMMAND: addNested(nested, RoutineBriefOrigin.FABRICATE_COMMAND_TASK); break; case FABRICATE_FACET: addNested(nested, RoutineBriefOrigin.FABRICATE_FACET_TASK); break; case FABRICATE_STAGE: addNested(nested, RoutineBriefOrigin.FABRICATE_STAGE_TASK); break; case FABRICATE_TRAIT: addNested(nested, RoutineBriefOrigin.FABRICATE_TRAIT_TASK); break; case FACET: addNested(nested, RoutineBriefOrigin.FACET_TASK); break; case IMPLICIT_ARCHIVE_STAGE: addNested(nested, RoutineBriefOrigin.IMPLICIT_ARCHIVE_STAGE_TASK); break; case IMPLICIT_COMMAND: addNested(nested, RoutineBriefOrigin.IMPLICIT_COMMAND_TASK); break; case IMPLICIT_FACET: addNested(nested, RoutineBriefOrigin.IMPLICIT_FACET_TASK); break; case IMPLICIT_STAGE: addNested(nested, RoutineBriefOrigin.IMPLICIT_STAGE_TASK); break; case IMPLICIT_TRAIT: addNested(nested, RoutineBriefOrigin.IMPLICIT_TRAIT_TASK); break; case PROJECT_COMMAND: addNested(nested, RoutineBriefOrigin.PROJECT_COMMAND_TASK); break; case PROJECT_STAGE: addNested(nested, RoutineBriefOrigin.PROJECT_STAGE_TASK); break; case PROJECT_TRAIT: addNested(nested, RoutineBriefOrigin.PROJECT_TRAIT_TASK); break; case STAGE: addNested(nested, RoutineBriefOrigin.STAGE_TASK); break; case TRAIT: addNested(nested, RoutineBriefOrigin.TRAIT_TASK); break; default: addNested(nested, RoutineBriefOrigin.TRAIT_TASK); } } private void addNested(List<? extends RoutineType> nested, RoutineBriefOrigin origin) throws IllegalArgumentException, ClassNotFoundException { if (nested != null) { List<I_RoutineBrief> nestedMuts = new ArrayList<I_RoutineBrief>(); for (RoutineType type: nested) { RoutineBriefMutant mut = new RoutineBriefMutant(type, origin); String name = mut.getName(); if (hasNested(name, nestedMuts)) { DuplicateRoutineException dre = new DuplicateRoutineException(); dre.setName(name); dre.setOrigin(mut.getOrigin()); dre.setParentName(name_); dre.setParentOrigin(origin_); throw dre; } nestedMuts.add(mut); } nestedRoutines_ = nestedMuts; } } @Override public I_RoutineBrief getNestedRoutine(String name) { if (nestedRoutines_ == null) { return null; } for (I_RoutineBrief rbm: nestedRoutines_) { if (rbm != null) { if (name.equals(rbm.getName())) { return rbm; } } } return null; } @Override public List<String> getParameterValues(String key) { if (parameters_ == null) { return Collections.emptyList(); } List<String> toRet = new ArrayList<String>(); for (I_Parameter rbm: parameters_) { if (rbm != null) { if (key.equals(rbm.getKey())) { toRet.add(rbm.getValue()); } } } return toRet; } @Override public String getParameterValue(String key) { if (parameters_ == null) { return null; } for (I_Parameter rbm: parameters_) { if (rbm != null) { if (key.equals(rbm.getKey())) { return rbm.getValue(); } } } return null; } public ParameterMutant getParameterMutant(String key) { if (parameters_ == null) { return null; } for (I_Parameter rbm: parameters_) { if (rbm != null) { if (key.equals(rbm.getKey())) { return (ParameterMutant) rbm; } } } return null; } @Override public int hashCode() { return hashCode(this); } @Override public String toString() { return toString(this); } }
apache-2.0
Erician/s3client-v2.0.0
src/main/java/run/DialogRun.java
822
package run; import java.awt.Toolkit; import javax.swing.*; public class DialogRun { public static void run(final JDialog d,final int width,final int height){ //不再单独开线程 // TODO Auto-generated method stub try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(Exception e){ throw new RuntimeException(e); } //d.setDefaultCloseOperation(JDialog.EXIT_ON_CLOSE); d.setSize(width, height); Toolkit toolkit = Toolkit.getDefaultToolkit(); int x = (int)(toolkit.getScreenSize().getWidth()-d.getWidth())/2; int y = (int)(toolkit.getScreenSize().getHeight()-d.getHeight())/2; //d.setTitle(d.getClass().getSimpleName()); d.setLocation(x, y); //父窗口不可点击 d.setModal(true); d.setVisible(true); } }
apache-2.0
google/webauthndemo
src/main/java/com/google/webauthn/gaedemo/servlets/GetSession.java
2274
// Copyright 2017 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 com.google.webauthn.gaedemo.servlets; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; import com.google.webauthn.gaedemo.storage.SessionData; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class GetSession */ public class GetSession extends HttpServlet { private static final long serialVersionUID = 1L; private final UserService userService = UserServiceFactory.getUserService(); /** * @see HttpServlet#HttpServlet() */ public GetSession() {} /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("id"); System.out.println(Long.valueOf(id)); SessionData session = SessionData.load(userService.getCurrentUser().getEmail(), Long.valueOf(id)); response.setContentType("application/json"); if (session != null) { response.getWriter().println(session.getJsonObject().toString()); } else { throw new ServletException("Session not found"); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
apache-2.0
pilhuhn/rhq-metrics
core/metrics-core-service/src/test/java/org/hawkular/metrics/core/jobs/CompressDataJobITest.java
12718
/* * Copyright 2014-2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.hawkular.metrics.core.jobs; import static java.util.Arrays.asList; import static org.hawkular.metrics.model.MetricType.AVAILABILITY; import static org.hawkular.metrics.model.MetricType.COUNTER; import static org.hawkular.metrics.model.MetricType.GAUGE; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.lang.reflect.Method; import java.nio.ByteBuffer; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.hawkular.metrics.core.service.BaseITest; import org.hawkular.metrics.core.service.DataAccess; import org.hawkular.metrics.core.service.DataAccessImpl; import org.hawkular.metrics.core.service.MetricsServiceImpl; import org.hawkular.metrics.core.service.Order; import org.hawkular.metrics.core.service.transformers.DataPointDecompressTransformer; import org.hawkular.metrics.datetime.DateTimeService; import org.hawkular.metrics.model.AvailabilityType; import org.hawkular.metrics.model.DataPoint; import org.hawkular.metrics.model.Metric; import org.hawkular.metrics.model.MetricId; import org.hawkular.metrics.model.MetricType; import org.hawkular.metrics.model.Tenant; import org.hawkular.metrics.scheduler.api.JobDetails; import org.hawkular.metrics.scheduler.impl.TestScheduler; import org.hawkular.metrics.sysconfig.ConfigurationService; import org.jboss.logging.Logger; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.Duration; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.codahale.metrics.MetricRegistry; import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.Row; import com.google.common.collect.ImmutableMap; import rx.Observable; import rx.observers.TestSubscriber; /** * Test the compression ETL jobs * * @author Michael Burman */ public class CompressDataJobITest extends BaseITest { private static Logger logger = Logger.getLogger(CompressDataJobITest.class); private static AtomicInteger tenantCounter = new AtomicInteger(); private MetricsServiceImpl metricsService; private DataAccess dataAccess; private JobsServiceImpl jobsService; private ConfigurationService configurationService; private TestScheduler jobScheduler; private PreparedStatement resetConfig; @BeforeClass public void initClass() { dataAccess = new DataAccessImpl(session); resetConfig = session.prepare("DELETE FROM sys_config WHERE config_id = 'org.hawkular.metrics.jobs." + CompressData.JOB_NAME + "'"); configurationService = new ConfigurationService() ; configurationService.init(rxSession); metricsService = new MetricsServiceImpl(); metricsService.setDataAccess(dataAccess); metricsService.setConfigurationService(configurationService); metricsService.startUp(session, getKeyspace(), true, new MetricRegistry()); } @BeforeMethod public void initTest(Method method) { logger.debug("Starting [" + method.getName() + "]"); session.execute(resetConfig.bind()); jobScheduler = new TestScheduler(rxSession); long nextStart = LocalDateTime.now(ZoneOffset.UTC) .with(DateTimeService.startOfNextOddHour()) .toInstant(ZoneOffset.UTC).toEpochMilli() - 60000; jobScheduler.advanceTimeTo(nextStart); jobScheduler.truncateTables(getKeyspace()); jobsService = new JobsServiceImpl(); jobsService.setSession(rxSession); jobsService.setScheduler(jobScheduler); jobsService.setMetricsService(metricsService); jobsService.setConfigurationService(configurationService); jobsService.start(); } @AfterMethod(alwaysRun = true) public void tearDown() { jobsService.shutdown(); } @Test public void testCompressJob() throws Exception { long now = jobScheduler.now(); DateTime start = DateTimeService.getTimeSlice(new DateTime(now, DateTimeZone.UTC).minusHours(2), Duration.standardHours(2)).plusMinutes(30); DateTime end = start.plusMinutes(20); String tenantId = nextTenantId() + now; MetricId<Double> mId = new MetricId<>(tenantId, GAUGE, "m1"); doAction(() -> metricsService.createTenant(new Tenant(tenantId), false)); Metric<Double> m1 = new Metric<>(mId, asList( new DataPoint<>(start.getMillis(), 1.1), new DataPoint<>(start.plusMinutes(2).getMillis(), 2.2), new DataPoint<>(start.plusMinutes(4).getMillis(), 3.3), new DataPoint<>(end.getMillis(), 4.4))); doAction(() -> metricsService.addDataPoints(GAUGE, Observable.just(m1))); CountDownLatch latch = new CountDownLatch(1); jobScheduler.onJobFinished(jobDetails -> { latch.countDown(); }); for (JobDetails jobDetails : jobsService.getJobDetails().toBlocking().toIterable()) { if(CompressData.JOB_NAME.equals(jobDetails.getJobName())) { jobScheduler.advanceTimeTo(jobDetails.getTrigger().getTriggerTime()); jobScheduler.advanceTimeBy(1); break; } } assertTrue(latch.await(25, TimeUnit.SECONDS)); long startSlice = DateTimeService.getTimeSlice(start.getMillis(), Duration.standardHours(2)); long endSlice = DateTimeService.getTimeSlice(jobScheduler.now(), Duration.standardHours(2)); Observable<Row> compressedRows = dataAccess.findCompressedData(mId, startSlice, endSlice, 0, Order.ASC); TestSubscriber<Row> testSubscriber = new TestSubscriber<>(); compressedRows.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(5, TimeUnit.SECONDS); testSubscriber.assertNoErrors(); testSubscriber.assertCompleted(); List<Row> rows = testSubscriber.getOnNextEvents(); assertEquals(1, rows.size()); ByteBuffer c_value = rows.get(0).getBytes("c_value"); ByteBuffer tags = rows.get(0).getBytes("tags"); assertNotNull(c_value); assertNull(tags); } @SuppressWarnings("unchecked") private <T> void testCompressResults(MetricType<T> type, Metric<T> metric, DateTime start) throws Exception { doAction(() -> metricsService.addDataPoints(type, Observable.just(metric))); CountDownLatch latch = new CountDownLatch(1); jobScheduler.onJobFinished(jobDetails -> { latch.countDown(); }); for (JobDetails jobDetails : jobsService.getJobDetails().toBlocking().toIterable()) { if(CompressData.JOB_NAME.equals(jobDetails.getJobName())) { jobScheduler.advanceTimeTo(jobDetails.getTrigger().getTriggerTime()); break; } } assertTrue(latch.await(25, TimeUnit.SECONDS)); long startSlice = DateTimeService.getTimeSlice(start.getMillis(), Duration.standardHours(2)); long endSlice = DateTimeService.getTimeSlice(jobScheduler.now(), Duration.standardHours(2)); DataPointDecompressTransformer decompressor = new DataPointDecompressTransformer(type, Order.ASC, 0, start .getMillis(), start.plusMinutes(30).getMillis()); Observable<DataPoint<T>> dataPoints = dataAccess.findCompressedData(metric.getMetricId(), startSlice, endSlice, 0, Order.ASC).compose(decompressor); TestSubscriber<DataPoint<T>> pointTestSubscriber = new TestSubscriber<>(); dataPoints.subscribe(pointTestSubscriber); pointTestSubscriber.awaitTerminalEvent(5, TimeUnit.SECONDS); pointTestSubscriber.assertCompleted(); List<DataPoint<T>> compressedPoints = pointTestSubscriber.getOnNextEvents(); assertEquals(metric.getDataPoints(), compressedPoints); } @Test public void testGaugeCompress() throws Exception { long now = jobScheduler.now(); DateTime start = DateTimeService.getTimeSlice(new DateTime(now, DateTimeZone.UTC).minusHours(2), Duration.standardHours(2)).plusMinutes(30); DateTime end = start.plusMinutes(20); String tenantId = nextTenantId() + now; MetricId<Double> mId = new MetricId<>(tenantId, GAUGE, "m1"); doAction(() -> metricsService.createTenant(new Tenant(tenantId), false)); Metric<Double> m1 = new Metric<>(mId, asList( new DataPoint<>(start.getMillis(), 1.1), new DataPoint<>(start.plusMinutes(2).getMillis(), 2.2), new DataPoint<>(start.plusMinutes(4).getMillis(), 3.3), new DataPoint<>(end.getMillis(), 4.4))); testCompressResults(GAUGE, m1, start); } @Test public void testCounterCompress() throws Exception { long now = jobScheduler.now(); DateTime start = DateTimeService.getTimeSlice(new DateTime(now, DateTimeZone.UTC).minusHours(2), Duration.standardHours(2)).plusMinutes(30); DateTime end = start.plusMinutes(20); String tenantId = nextTenantId() + now; MetricId<Long> mId = new MetricId<>(tenantId, COUNTER, "m2"); doAction(() -> metricsService.createTenant(new Tenant(tenantId), false)); Metric<Long> m1 = new Metric<>(mId, asList( new DataPoint<>(start.getMillis(), 1L), new DataPoint<>(start.plusMinutes(2).getMillis(), 2L), new DataPoint<>(start.plusMinutes(4).getMillis(), 3L), new DataPoint<>(end.getMillis(), 4L))); testCompressResults(COUNTER, m1, start); } @Test public void testAvailabilityCompress() throws Exception { long now = jobScheduler.now(); DateTime start = DateTimeService.getTimeSlice(new DateTime(now, DateTimeZone.UTC).minusHours(2), Duration.standardHours(2)).plusMinutes(30); DateTime end = start.plusMinutes(20); String tenantId = nextTenantId() + now; MetricId<AvailabilityType> mId = new MetricId<>(tenantId, AVAILABILITY, "m3"); doAction(() -> metricsService.createTenant(new Tenant(tenantId), false)); Metric<AvailabilityType> m1 = new Metric<>(mId, asList( new DataPoint<>(start.getMillis(), AvailabilityType.UP), new DataPoint<>(start.plusMinutes(2).getMillis(), AvailabilityType.DOWN), new DataPoint<>(start.plusMinutes(4).getMillis(), AvailabilityType.DOWN), new DataPoint<>(end.getMillis(), AvailabilityType.UP))); testCompressResults(AVAILABILITY, m1, start); } @Test public void testGaugeWithTags() throws Exception { long now = jobScheduler.now(); DateTime start = DateTimeService.getTimeSlice(new DateTime(now, DateTimeZone.UTC).minusHours(2), Duration.standardHours(2)).plusMinutes(30); DateTime end = start.plusMinutes(20); String tenantId = nextTenantId() + now; MetricId<Double> mId = new MetricId<>(tenantId, GAUGE, "m1"); doAction(() -> metricsService.createTenant(new Tenant(tenantId), false)); Metric<Double> m1 = new Metric<>(mId, asList( new DataPoint<>(start.getMillis(), 1.1, ImmutableMap.of("a", "b")), new DataPoint<>(start.plusMinutes(2).getMillis(), 2.2), new DataPoint<>(start.plusMinutes(4).getMillis(), 3.3, ImmutableMap.of("d", "e")), new DataPoint<>(end.getMillis(), 4.4))); testCompressResults(GAUGE, m1, start); } private String nextTenantId() { return "T" + tenantCounter.getAndIncrement(); } }
apache-2.0
jvasileff/ceylon-dart
ceylon-dart-compiler/source/com/vasileff/ceylon/dart/compiler/Warning.java
733
package com.vasileff.ceylon.dart.compiler; public enum Warning { filenameNonAscii, filenameCaselessCollision, deprecation, disjointEquals, disjointContainment, compilerAnnotation, doclink, expressionTypeNothing, unusedDeclaration, unusedImport, ceylonNamespace, javaNamespace, suppressedAlready, suppressesNothing, unknownWarning, ambiguousAnnotation, similarModule, importsOtherJdk, javaAnnotationElement, syntaxDeprecation, smallIgnored, literalNotSmall, redundantNarrowing, redundantIteration, missingImportPrefix, uncheckedTypeArguments, expressionTypeCallable, uncheckedType, unsupported, inferredNotNull }
apache-2.0
jgrandja/spring-security-oauth
spring-security-oauth2/src/main/java/org/springframework/security/oauth2/config/annotation/configurers/ClientDetailsServiceConfigurer.java
2258
/* * Copyright 2002-2013 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.security.oauth2.config.annotation.configurers; import javax.sql.DataSource; import org.springframework.security.config.annotation.SecurityConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.builders.ClientDetailsServiceBuilder; import org.springframework.security.oauth2.config.annotation.builders.InMemoryClientDetailsServiceBuilder; import org.springframework.security.oauth2.config.annotation.builders.JdbcClientDetailsServiceBuilder; import org.springframework.security.oauth2.provider.ClientDetailsService; /** * @author Rob Winch * */ public class ClientDetailsServiceConfigurer extends SecurityConfigurerAdapter<ClientDetailsService, ClientDetailsServiceBuilder<?>> { public ClientDetailsServiceConfigurer(ClientDetailsServiceBuilder<?> builder) { setBuilder(builder); } public ClientDetailsServiceBuilder<?> withClientDetails(ClientDetailsService clientDetailsService) throws Exception { setBuilder(getBuilder().clients(clientDetailsService)); return this.and(); } public InMemoryClientDetailsServiceBuilder inMemory() throws Exception { InMemoryClientDetailsServiceBuilder next = getBuilder().inMemory(); setBuilder(next); return next; } public JdbcClientDetailsServiceBuilder jdbc(DataSource dataSource) throws Exception { JdbcClientDetailsServiceBuilder next = getBuilder().jdbc().dataSource(dataSource); setBuilder(next); return next; } @Override public void init(ClientDetailsServiceBuilder<?> builder) throws Exception { } @Override public void configure(ClientDetailsServiceBuilder<?> builder) throws Exception { } }
apache-2.0
HuangLS/neo4j
enterprise/kernel/src/main/java/org/neo4j/graphdb/factory/EnterpriseGraphDatabaseFactory.java
1696
/* * Copyright (c) 2002-2018 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.graphdb.factory; import java.io.File; import java.util.Map; import org.neo4j.graphdb.EnterpriseGraphDatabase; import org.neo4j.graphdb.GraphDatabaseService; public class EnterpriseGraphDatabaseFactory extends GraphDatabaseFactory { @Override protected GraphDatabaseBuilder.DatabaseCreator createDatabaseCreator( final File storeDir, final GraphDatabaseFactoryState state ) { return new GraphDatabaseBuilder.DatabaseCreator() { @Override public GraphDatabaseService newDatabase( Map<String,String> config ) { config.put( "ephemeral", "false" ); return new EnterpriseGraphDatabase( storeDir, config, state.databaseDependencies() ); } }; } @Override public String getEdition() { return "Enterprise"; } }
apache-2.0
McLeodMoores/starling
projects/financial/src/main/java/com/opengamma/financial/analytics/model/volatility/surface/black/pure/PureBlackVolatilitySurfaceDividendCorrectionFunction.java
4358
/** * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.analytics.model.volatility.surface.black.pure; import static com.opengamma.engine.value.ValuePropertyNames.CURVE; import static com.opengamma.engine.value.ValuePropertyNames.CURVE_CALCULATION_CONFIG; import static com.opengamma.engine.value.ValuePropertyNames.CURVE_CURRENCY; import static com.opengamma.engine.value.ValuePropertyNames.SURFACE; import java.util.Set; import com.opengamma.OpenGammaRuntimeException; import com.opengamma.analytics.financial.equity.variance.pricing.AffineDividends; import com.opengamma.engine.ComputationTarget; import com.opengamma.engine.function.FunctionCompilationContext; import com.opengamma.engine.function.FunctionInputs; import com.opengamma.engine.value.ValueProperties; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.engine.value.ValueRequirementNames; import com.opengamma.financial.analytics.model.volatility.surface.black.BlackVolatilitySurfacePropertyUtils; /** * */ public abstract class PureBlackVolatilitySurfaceDividendCorrectionFunction extends PureBlackVolatilitySurfaceFunction { /** Affine dividends. */ public static final String AFFINE_DIVIDENDS = "Affine"; /** * Spline interpolator function for pure Black volatility surfaces. */ public static class Spline extends PureBlackVolatilitySurfaceDividendCorrectionFunction { @Override public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) { final Set<ValueRequirement> specificRequirements = BlackVolatilitySurfacePropertyUtils .ensureSplineVolatilityInterpolatorProperties(desiredValue.getConstraints()); if (specificRequirements == null) { return null; } final Set<ValueRequirement> requirements = super.getRequirements(context, target, desiredValue); if (requirements == null) { return null; } requirements.addAll(specificRequirements); return requirements; } @Override protected ValueProperties getResultProperties() { return BlackVolatilitySurfacePropertyUtils.addSplineVolatilityInterpolatorProperties(createValueProperties().get()) .withAny(SURFACE) .withAny(CURVE) .withAny(CURVE_CURRENCY) .withAny(CURVE_CALCULATION_CONFIG) .with(PROPERTY_DIVIDEND_TREATMENT, AFFINE_DIVIDENDS).get(); } @Override protected ValueProperties getResultProperties(final ValueRequirement desiredValue) { final String surfaceName = desiredValue.getConstraint(SURFACE); final String curveName = desiredValue.getConstraint(CURVE); final String currency = desiredValue.getConstraint(CURVE_CURRENCY); final String curveCalculationConfig = desiredValue.getConstraint(CURVE_CALCULATION_CONFIG); return BlackVolatilitySurfacePropertyUtils.addSplineVolatilityInterpolatorProperties(desiredValue.getConstraints(), desiredValue) .with(SURFACE, surfaceName) .with(CURVE, curveName) .with(CURVE_CURRENCY, currency) .with(CURVE_CALCULATION_CONFIG, curveCalculationConfig) .with(PROPERTY_DIVIDEND_TREATMENT, AFFINE_DIVIDENDS).get(); } } @Override public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) { final Set<ValueRequirement> requirements = super.getRequirements(context, target, desiredValue); if (requirements == null) { return null; } requirements.add(getDividendRequirement(target)); return requirements; } @Override protected AffineDividends getDividends(final FunctionInputs inputs) { final Object dividendsObject = inputs.getValue(ValueRequirementNames.AFFINE_DIVIDENDS); if (dividendsObject == null) { throw new OpenGammaRuntimeException("Dividends object was null"); } return (AffineDividends) dividendsObject; } private ValueRequirement getDividendRequirement(final ComputationTarget target) { return new ValueRequirement(ValueRequirementNames.AFFINE_DIVIDENDS, target.toSpecification(), ValueProperties.none()); } }
apache-2.0
AtanasTsankov/BGT
BoardGamesTimer/app/src/main/java/tsankov/atanas/boardgamestimer/StartScreent.java
840
package tsankov.atanas.boardgamestimer; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class StartScreent extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_start_screent); Button btn = (Button)this.findViewById(R.id.newTmplBtn); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(StartScreent.this, TemplateSetup.class); intent.putExtra("test", 1); StartScreent.this.startActivity(intent); } }); } }
apache-2.0
VHAINNOVATIONS/AVS
ll-javaUtils/src/main/java/gov/va/med/lom/javaUtils/config/ConfigParserConstants.java
745
/* Generated By:JavaCC: Do not edit this line. ConfigParserConstants.java */ package gov.va.med.lom.javaUtils.config; public interface ConfigParserConstants { int EOF = 0; int KEYWORD = 3; int WHITESPACE = 4; int COMMENT = 5; int WS_CHAR = 6; int EOL = 7; int QSTRING = 8; int STRING = 9; int QCHAR = 10; int PLUS = 11; int COMMA = 12; int KW_CHAR = 13; int ASSIGN = 14; int DEFAULT = 0; int RHS = 1; String[] tokenImage = { "<EOF>", "\"[\"", "\"]\"", "<KEYWORD>", "<WHITESPACE>", "<COMMENT>", "<WS_CHAR>", "<EOL>", "<QSTRING>", "<STRING>", "<QCHAR>", "<PLUS>", "<COMMA>", "<KW_CHAR>", "<ASSIGN>", }; }
apache-2.0
avafanasiev/groovy
subprojects/parser-antlr4/src/main/java/org/apache/groovy/parser/antlr4/ModifierNode.java
4978
/* * 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.groovy.parser.antlr4; import org.apache.groovy.util.Maps; import org.codehaus.groovy.ast.ASTNode; import org.codehaus.groovy.ast.AnnotationNode; import org.objectweb.asm.Opcodes; import java.util.Map; import java.util.Objects; import static org.apache.groovy.parser.antlr4.GroovyParser.*; import static org.codehaus.groovy.runtime.DefaultGroovyMethods.asBoolean; /** * Represents a modifier, which is better to place in the package org.codehaus.groovy.ast * <p> * Created by Daniel.Sun on 2016/08/23. */ public class ModifierNode extends ASTNode { private Integer type; private Integer opcode; // ASM opcode private String text; private AnnotationNode annotationNode; private boolean repeatable; public static final int ANNOTATION_TYPE = -999; public static final Map<Integer, Integer> MODIFIER_OPCODE_MAP = Maps.of( ANNOTATION_TYPE, 0, DEF, 0, NATIVE, Opcodes.ACC_NATIVE, SYNCHRONIZED, Opcodes.ACC_SYNCHRONIZED, TRANSIENT, Opcodes.ACC_TRANSIENT, VOLATILE, Opcodes.ACC_VOLATILE, PUBLIC, Opcodes.ACC_PUBLIC, PROTECTED, Opcodes.ACC_PROTECTED, PRIVATE, Opcodes.ACC_PRIVATE, STATIC, Opcodes.ACC_STATIC, ABSTRACT, Opcodes.ACC_ABSTRACT, FINAL, Opcodes.ACC_FINAL, STRICTFP, Opcodes.ACC_STRICT, DEFAULT, 0 // no flag for specifying a default method in the JVM spec, hence no ACC_DEFAULT flag in ASM ); public ModifierNode(Integer type) { this.type = type; this.opcode = MODIFIER_OPCODE_MAP.get(type); this.repeatable = ANNOTATION_TYPE == type; // Only annotations are repeatable if (!asBoolean((Object) this.opcode)) { throw new IllegalArgumentException("Unsupported modifier type: " + type); } } /** * @param type the modifier type, which is same as the token type * @param text text of the ast node */ public ModifierNode(Integer type, String text) { this(type); this.text = text; } /** * @param annotationNode the annotation node * @param text text of the ast node */ public ModifierNode(AnnotationNode annotationNode, String text) { this(ModifierNode.ANNOTATION_TYPE, text); this.annotationNode = annotationNode; if (!asBoolean(annotationNode)) { throw new IllegalArgumentException("annotationNode can not be null"); } } /** * Check whether the modifier is not an imagined modifier(annotation, def) */ public boolean isModifier() { return !this.isAnnotation() && !this.isDef(); } public boolean isVisibilityModifier() { return Objects.equals(PUBLIC, this.type) || Objects.equals(PROTECTED, this.type) || Objects.equals(PRIVATE, this.type); } public boolean isNonVisibilityModifier() { return this.isModifier() && !this.isVisibilityModifier(); } public boolean isAnnotation() { return Objects.equals(ANNOTATION_TYPE, this.type); } public boolean isDef() { return Objects.equals(DEF, this.type); } public Integer getType() { return type; } public Integer getOpcode() { return opcode; } public boolean isRepeatable() { return repeatable; } @Override public String getText() { return text; } public AnnotationNode getAnnotationNode() { return annotationNode; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ModifierNode that = (ModifierNode) o; return Objects.equals(type, that.type) && Objects.equals(text, that.text) && Objects.equals(annotationNode, that.annotationNode); } @Override public int hashCode() { return Objects.hash(type, text, annotationNode); } @Override public String toString() { return this.text; } }
apache-2.0
mread/buck
src/com/facebook/buck/apple/AppleLibraryDescription.java
2337
/* * Copyright 2013-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.apple; import com.facebook.buck.cxx.CxxPlatform; import com.facebook.buck.model.Flavor; import com.facebook.buck.model.Flavored; import com.facebook.buck.rules.BuildRuleParams; import com.facebook.buck.rules.BuildRuleResolver; import com.facebook.buck.rules.BuildRuleType; import com.facebook.buck.rules.Description; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; public class AppleLibraryDescription implements Description<AppleNativeTargetDescriptionArg>, Flavored { public static final BuildRuleType TYPE = new BuildRuleType("apple_library"); public static final Flavor DYNAMIC_LIBRARY = new Flavor("dynamic"); private final CxxPlatform cxxPlatform; public AppleLibraryDescription(CxxPlatform cxxPlatform) { this.cxxPlatform = Preconditions.checkNotNull(cxxPlatform); } @Override public BuildRuleType getBuildRuleType() { return TYPE; } @Override public AppleNativeTargetDescriptionArg createUnpopulatedConstructorArg() { return new AppleNativeTargetDescriptionArg(); } @Override public boolean hasFlavors(ImmutableSet<Flavor> flavors) { boolean match = true; for (Flavor flavor : flavors) { match &= DYNAMIC_LIBRARY.equals(flavor) || Flavor.DEFAULT.equals(flavor); } return match; } @Override public <A extends AppleNativeTargetDescriptionArg> AppleLibrary createBuildRule( BuildRuleParams params, BuildRuleResolver resolver, A args) { return new AppleLibrary( params, args, TargetSources.ofAppleSources(args.srcs.get()), cxxPlatform.getAr(), params.getBuildTarget().getFlavors().contains(DYNAMIC_LIBRARY)); } }
apache-2.0
NSAmelchev/ignite
modules/indexing/src/main/java/org/apache/ignite/internal/processors/query/h2/sql/GridSqlQueryParser.java
89869
/* * 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.ignite.internal.processors.query.h2.sql; import java.lang.reflect.Field; import java.sql.PreparedStatement; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import javax.cache.CacheException; import org.apache.ignite.IgniteException; import org.apache.ignite.IgniteLogger; import org.apache.ignite.cache.CacheAtomicityMode; import org.apache.ignite.cache.CacheWriteSynchronizationMode; import org.apache.ignite.cache.QueryIndex; import org.apache.ignite.cache.QueryIndexType; import org.apache.ignite.internal.processors.cache.GridCacheContext; import org.apache.ignite.internal.processors.cache.query.IgniteQueryErrorCode; import org.apache.ignite.internal.processors.query.IgniteSQLException; import org.apache.ignite.internal.processors.query.QueryUtils; import org.apache.ignite.internal.processors.query.h2.opt.GridH2Table; import org.apache.ignite.internal.util.typedef.F; import org.h2.command.Command; import org.h2.command.CommandContainer; import org.h2.command.CommandInterface; import org.h2.command.Prepared; import org.h2.command.ddl.AlterTableAddConstraint; import org.h2.command.ddl.AlterTableAlterColumn; import org.h2.command.ddl.CommandWithColumns; import org.h2.command.ddl.CreateIndex; import org.h2.command.ddl.CreateTable; import org.h2.command.ddl.CreateTableData; import org.h2.command.ddl.DefineCommand; import org.h2.command.ddl.DropIndex; import org.h2.command.ddl.DropTable; import org.h2.command.ddl.SchemaCommand; import org.h2.command.dml.Delete; import org.h2.command.dml.Explain; import org.h2.command.dml.Insert; import org.h2.command.dml.Merge; import org.h2.command.dml.Query; import org.h2.command.dml.Select; import org.h2.command.dml.SelectOrderBy; import org.h2.command.dml.SelectUnion; import org.h2.command.dml.Update; import org.h2.engine.Constants; import org.h2.engine.FunctionAlias; import org.h2.expression.Aggregate; import org.h2.expression.Alias; import org.h2.expression.CompareLike; import org.h2.expression.Comparison; import org.h2.expression.ConditionAndOr; import org.h2.expression.ConditionExists; import org.h2.expression.ConditionIn; import org.h2.expression.ConditionInConstantSet; import org.h2.expression.ConditionInSelect; import org.h2.expression.ConditionNot; import org.h2.expression.Expression; import org.h2.expression.ExpressionColumn; import org.h2.expression.ExpressionList; import org.h2.expression.Function; import org.h2.expression.JavaFunction; import org.h2.expression.Operation; import org.h2.expression.Parameter; import org.h2.expression.Subquery; import org.h2.expression.TableFunction; import org.h2.expression.ValueExpression; import org.h2.index.ViewIndex; import org.h2.jdbc.JdbcPreparedStatement; import org.h2.result.SortOrder; import org.h2.schema.Schema; import org.h2.table.Column; import org.h2.table.FunctionTable; import org.h2.table.IndexColumn; import org.h2.table.MetaTable; import org.h2.table.RangeTable; import org.h2.table.Table; import org.h2.table.TableBase; import org.h2.table.TableFilter; import org.h2.table.TableView; import org.h2.value.DataType; import org.h2.value.Value; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import static org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperationType.AND; import static org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperationType.BIGGER; import static org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperationType.BIGGER_EQUAL; import static org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperationType.EQUAL; import static org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperationType.EQUAL_NULL_SAFE; import static org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperationType.EXISTS; import static org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperationType.IN; import static org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperationType.IS_NOT_NULL; import static org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperationType.IS_NULL; import static org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperationType.LIKE; import static org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperationType.NOT; import static org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperationType.NOT_EQUAL; import static org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperationType.NOT_EQUAL_NULL_SAFE; import static org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperationType.OR; import static org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperationType.REGEXP; import static org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperationType.SMALLER; import static org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperationType.SMALLER_EQUAL; import static org.apache.ignite.internal.processors.query.h2.sql.GridSqlOperationType.SPATIAL_INTERSECTS; import static org.apache.ignite.internal.processors.query.h2.sql.GridSqlType.fromColumn; import static org.apache.ignite.internal.processors.query.h2.sql.GridSqlType.fromExpression; /** * H2 Query parser. */ public class GridSqlQueryParser { /** */ private static final GridSqlOperationType[] COMPARISON_TYPES = {EQUAL, BIGGER_EQUAL, BIGGER, SMALLER_EQUAL, SMALLER, NOT_EQUAL, IS_NULL, IS_NOT_NULL, null, null, null, SPATIAL_INTERSECTS /* 11 */, null, null, null, null, EQUAL_NULL_SAFE /* 16 */, null, null, null, null, NOT_EQUAL_NULL_SAFE /* 21 */}; /** */ private static final Getter<Select, Expression> CONDITION = getter(Select.class, "condition"); /** */ private static final Getter<Select, int[]> GROUP_INDEXES = getter(Select.class, "groupIndex"); /** */ private static final Getter<Select, Boolean> SELECT_IS_FOR_UPDATE = getter(Select.class, "isForUpdate"); /** */ private static final Getter<Select, Boolean> SELECT_IS_GROUP_QUERY = getter(Select.class, "isGroupQuery"); /** */ private static final Getter<SelectUnion, Boolean> UNION_IS_FOR_UPDATE = getter(SelectUnion.class, "isForUpdate"); /** */ private static final Getter<Operation, Operation.OpType> OPERATION_TYPE = getter(Operation.class, "opType"); /** */ private static final Getter<Operation, Expression> OPERATION_LEFT = getter(Operation.class, "left"); /** */ private static final Getter<Operation, Expression> OPERATION_RIGHT = getter(Operation.class, "right"); /** */ private static final Getter<Comparison, Integer> COMPARISON_TYPE = getter(Comparison.class, "compareType"); /** */ private static final Getter<Comparison, Expression> COMPARISON_LEFT = getter(Comparison.class, "left"); /** */ private static final Getter<Comparison, Expression> COMPARISON_RIGHT = getter(Comparison.class, "right"); /** */ private static final Getter<ConditionAndOr, Integer> ANDOR_TYPE = getter(ConditionAndOr.class, "andOrType"); /** */ private static final Getter<ConditionAndOr, Expression> ANDOR_LEFT = getter(ConditionAndOr.class, "left"); /** */ private static final Getter<ConditionAndOr, Expression> ANDOR_RIGHT = getter(ConditionAndOr.class, "right"); /** */ public static final Getter<TableView, Query> VIEW_QUERY = getter(TableView.class, "viewQuery"); /** */ private static final Getter<TableFilter, String> ALIAS = getter(TableFilter.class, "alias"); /** */ private static final Getter<Select, Integer> HAVING_INDEX = getter(Select.class, "havingIndex"); /** */ private static final Getter<ConditionIn, Expression> LEFT_CI = getter(ConditionIn.class, "left"); /** */ private static final Getter<ConditionIn, List<Expression>> VALUE_LIST_CI = getter(ConditionIn.class, "valueList"); /** */ private static final Getter<ConditionInConstantSet, Expression> LEFT_CICS = getter(ConditionInConstantSet.class, "left"); /** */ private static final Getter<ConditionInConstantSet, List<Expression>> VALUE_LIST_CICS = getter(ConditionInConstantSet.class, "valueList"); /** */ private static final Getter<ExpressionList, Expression[]> EXPR_LIST = getter(ExpressionList.class, "list"); /** */ private static final Getter<ConditionInSelect, Expression> LEFT_CIS = getter(ConditionInSelect.class, "left"); /** */ private static final Getter<ConditionInSelect, Boolean> ALL = getter(ConditionInSelect.class, "all"); /** */ private static final Getter<ConditionInSelect, Integer> COMPARE_TYPE = getter(ConditionInSelect.class, "compareType"); /** */ private static final Getter<ConditionInSelect, Query> QUERY_IN = getter(ConditionInSelect.class, "query"); /** */ private static final Getter<ConditionExists, Query> QUERY_EXISTS = getter(ConditionExists.class, "query"); /** */ private static final Getter<CompareLike, Expression> LEFT = getter(CompareLike.class, "left"); /** */ private static final Getter<CompareLike, Expression> RIGHT = getter(CompareLike.class, "right"); /** */ private static final Getter<CompareLike, Expression> ESCAPE = getter(CompareLike.class, "escape"); /** */ private static final Getter<CompareLike, Boolean> REGEXP_CL = getter(CompareLike.class, "regexp"); /** */ private static final Getter<Aggregate, Boolean> DISTINCT = getter(Aggregate.class, "distinct"); /** */ private static final Getter<Aggregate, Aggregate.AggregateType> TYPE = getter(Aggregate.class, "type"); /** */ private static final Getter<Aggregate, Expression> ON = getter(Aggregate.class, "on"); /** */ private static final Getter<Aggregate, Expression> GROUP_CONCAT_SEPARATOR = getter(Aggregate.class, "groupConcatSeparator"); /** */ private static final Getter<Aggregate, ArrayList<SelectOrderBy>> GROUP_CONCAT_ORDER_LIST = getter(Aggregate.class, "groupConcatOrderList"); /** */ private static final Getter<RangeTable, Expression> RANGE_MIN = getter(RangeTable.class, "min"); /** */ private static final Getter<RangeTable, Expression> RANGE_MAX = getter(RangeTable.class, "max"); /** */ private static final Getter<FunctionTable, Expression> FUNC_EXPR = getter(FunctionTable.class, "functionExpr"); /** */ private static final Getter<TableFunction, Column[]> FUNC_TBL_COLS = getter(TableFunction.class, "columnList"); /** */ private static final Getter<JavaFunction, FunctionAlias> FUNC_ALIAS = getter(JavaFunction.class, "functionAlias"); /** */ private static final Getter<ExpressionColumn, String> SCHEMA_NAME = getter(ExpressionColumn.class, "schemaName"); /** */ private static final Getter<JdbcPreparedStatement, Command> COMMAND = getter(JdbcPreparedStatement.class, "command"); /** */ private static final Getter<SelectUnion, SortOrder> UNION_SORT = getter(SelectUnion.class, "sort"); /** */ private static final Getter<Explain, Prepared> EXPLAIN_COMMAND = getter(Explain.class, "command"); /** */ private static final Getter<Merge, Table> MERGE_TABLE = getter(Merge.class, "targetTable"); /** */ private static final Getter<Merge, Column[]> MERGE_COLUMNS = getter(Merge.class, "columns"); /** */ private static final Getter<Merge, Column[]> MERGE_KEYS = getter(Merge.class, "keys"); /** */ private static final Getter<Merge, List<Expression[]>> MERGE_ROWS = getter(Merge.class, "valuesExpressionList"); /** */ private static final Getter<Merge, Query> MERGE_QUERY = getter(Merge.class, "query"); /** */ private static final Getter<Insert, Table> INSERT_TABLE = getter(Insert.class, "table"); /** */ private static final Getter<Insert, Column[]> INSERT_COLUMNS = getter(Insert.class, "columns"); /** */ private static final Getter<Insert, List<Expression[]>> INSERT_ROWS = getter(Insert.class, "list"); /** */ private static final Getter<Insert, Query> INSERT_QUERY = getter(Insert.class, "query"); /** */ private static final Getter<Insert, Boolean> INSERT_DIRECT = getter(Insert.class, "insertFromSelect"); /** */ private static final Getter<Insert, Boolean> INSERT_SORTED = getter(Insert.class, "sortedInsertMode"); /** */ private static final Getter<Delete, TableFilter> DELETE_FROM = getter(Delete.class, "targetTableFilter"); /** */ private static final Getter<Delete, Expression> DELETE_WHERE = getter(Delete.class, "condition"); /** */ private static final Getter<Delete, Expression> DELETE_LIMIT = getter(Delete.class, "limitExpr"); /** */ private static final Getter<Update, TableFilter> UPDATE_TARGET = getter(Update.class, "targetTableFilter"); /** */ private static final Getter<Update, ArrayList<Column>> UPDATE_COLUMNS = getter(Update.class, "columns"); /** */ private static final Getter<Update, HashMap<Column, Expression>> UPDATE_SET = getter(Update.class, "expressionMap"); /** */ private static final Getter<Update, Expression> UPDATE_WHERE = getter(Update.class, "condition"); /** */ private static final Getter<Update, Expression> UPDATE_LIMIT = getter(Update.class, "limitExpr"); /** */ private static final Getter<Command, Prepared> PREPARED = GridSqlQueryParser.<Command, Prepared>getter(CommandContainer.class, "prepared"); /** */ private static final Getter<CreateIndex, String> CREATE_INDEX_NAME = getter(CreateIndex.class, "indexName"); /** */ private static final Getter<CreateIndex, String> CREATE_INDEX_TABLE_NAME = getter(CreateIndex.class, "tableName"); /** */ private static final Getter<CreateIndex, IndexColumn[]> CREATE_INDEX_COLUMNS = getter(CreateIndex.class, "indexColumns"); /** */ private static final Getter<CreateIndex, Boolean> CREATE_INDEX_SPATIAL = getter(CreateIndex.class, "spatial"); /** */ private static final Getter<CreateIndex, Boolean> CREATE_INDEX_PRIMARY_KEY = getter(CreateIndex.class, "primaryKey"); /** */ private static final Getter<CreateIndex, Boolean> CREATE_INDEX_UNIQUE = getter(CreateIndex.class, "unique"); /** */ private static final Getter<CreateIndex, Boolean> CREATE_INDEX_HASH = getter(CreateIndex.class, "hash"); /** */ private static final Getter<CreateIndex, Boolean> CREATE_INDEX_IF_NOT_EXISTS = getter(CreateIndex.class, "ifNotExists"); /** */ private static final Getter<IndexColumn, String> INDEX_COLUMN_NAME = getter(IndexColumn.class, "columnName"); /** */ private static final Getter<IndexColumn, Integer> INDEX_COLUMN_SORT_TYPE = getter(IndexColumn.class, "sortType"); /** */ private static final Getter<DropIndex, String> DROP_INDEX_NAME = getter(DropIndex.class, "indexName"); /** */ private static final Getter<DropIndex, Boolean> DROP_INDEX_IF_EXISTS = getter(DropIndex.class, "ifExists"); /** */ private static final Getter<SchemaCommand, Schema> SCHEMA_COMMAND_SCHEMA = getter(SchemaCommand.class, "schema"); /** */ private static final Getter<CreateTable, CreateTableData> CREATE_TABLE_DATA = getter(CreateTable.class, "data"); /** */ private static final Getter<CommandWithColumns, ArrayList<DefineCommand>> CREATE_TABLE_CONSTRAINTS = getter(CommandWithColumns.class, "constraintCommands"); /** */ private static final Getter<CommandWithColumns, IndexColumn[]> CREATE_TABLE_PK = getter(CommandWithColumns.class, "pkColumns"); /** */ private static final Getter<CreateTable, Boolean> CREATE_TABLE_IF_NOT_EXISTS = getter(CreateTable.class, "ifNotExists"); /** */ private static final Getter<CreateTable, Query> CREATE_TABLE_QUERY = getter(CreateTable.class, "asQuery"); /** */ private static final Getter<DropTable, Boolean> DROP_TABLE_IF_EXISTS = getter(DropTable.class, "ifExists"); /** */ private static final Getter<DropTable, String> DROP_TABLE_NAME = getter(DropTable.class, "tableName"); /** */ private static final Getter<Column, Boolean> COLUMN_IS_COMPUTED = getter(Column.class, "isComputed"); /** */ private static final Getter<Column, Expression> COLUMN_CHECK_CONSTRAINT = getter(Column.class, "checkConstraint"); /** Class for private class: 'org.h2.command.CommandList'. */ private static final Class<? extends Command> CLS_COMMAND_LIST; /** */ private static final Getter<Command, Command> LIST_COMMAND; /** */ private static final Getter<Command, String> REMAINING; /** */ public static final String ORG_H2_COMMAND_COMMAND_LIST = "org.h2.command.CommandList"; static { try { CLS_COMMAND_LIST = (Class<? extends Command>)CommandContainer.class.getClassLoader() .loadClass(ORG_H2_COMMAND_COMMAND_LIST); LIST_COMMAND = getter(CLS_COMMAND_LIST, "command"); REMAINING = getter(CLS_COMMAND_LIST, "remaining"); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } /** */ private static final Getter<AlterTableAlterColumn, String> ALTER_COLUMN_TBL_NAME = getter(AlterTableAlterColumn.class, "tableName"); /** */ private static final Getter<AlterTableAlterColumn, ArrayList<Column>> ALTER_COLUMN_NEW_COLS = getter(AlterTableAlterColumn.class, "columnsToAdd"); /** */ private static final Getter<AlterTableAlterColumn, ArrayList<Column>> ALTER_COLUMN_REMOVE_COLS = getter(AlterTableAlterColumn.class, "columnsToRemove"); /** */ private static final Getter<AlterTableAlterColumn, Boolean> ALTER_COLUMN_IF_NOT_EXISTS = getter(AlterTableAlterColumn.class, "ifNotExists"); /** */ private static final Getter<AlterTableAlterColumn, Boolean> ALTER_COLUMN_IF_TBL_EXISTS = getter(AlterTableAlterColumn.class, "ifTableExists"); /** */ private static final Getter<AlterTableAlterColumn, String> ALTER_COLUMN_BEFORE_COL = getter(AlterTableAlterColumn.class, "addBefore"); /** */ private static final Getter<AlterTableAlterColumn, Boolean> ALTER_COLUMN_FIRST = getter(AlterTableAlterColumn.class, "addFirst"); /** */ private static final Getter<AlterTableAlterColumn, String> ALTER_COLUMN_AFTER_COL = getter(AlterTableAlterColumn.class, "addAfter"); /** */ private static final String PARAM_NAME_VALUE_SEPARATOR = "="; /** */ private static final String PARAM_TEMPLATE = "TEMPLATE"; /** */ private static final String PARAM_BACKUPS = "BACKUPS"; /** */ private static final String PARAM_ATOMICITY = "ATOMICITY"; /** */ private static final String PARAM_CACHE_GROUP_OLD = "CACHEGROUP"; /** */ private static final String PARAM_AFFINITY_KEY_OLD = "AFFINITYKEY"; /** */ private static final String PARAM_CACHE_GROUP = "CACHE_GROUP"; /** */ private static final String PARAM_AFFINITY_KEY = "AFFINITY_KEY"; /** */ private static final String PARAM_WRITE_SYNC = "WRITE_SYNCHRONIZATION_MODE"; /** */ private static final String PARAM_CACHE_NAME = "CACHE_NAME"; /** */ private static final String PARAM_KEY_TYPE = "KEY_TYPE"; /** */ private static final String PARAM_VAL_TYPE = "VALUE_TYPE"; /** */ private static final String PARAM_WRAP_KEY = "WRAP_KEY"; /** */ public static final String PARAM_WRAP_VALUE = "WRAP_VALUE"; /** Data region name. */ public static final String PARAM_DATA_REGION = "DATA_REGION"; /** */ private static final String PARAM_ENCRYPTED = "ENCRYPTED"; /** Query parallelism value of cache configuration. */ private static final String PARAM_PARALLELISM = "PARALLELISM"; /** */ private final IdentityHashMap<Object, Object> h2ObjToGridObj = new IdentityHashMap<>(); /** */ private final Map<String, Integer> optimizedTableFilterOrder; /** */ private final IgniteLogger log; /** * We have a counter instead of a simple flag, because * a flag can be reset earlier than needed in case of * deep subquery expression nesting. */ private int parsingSubQryExpression; /** Whether this is SELECT FOR UPDATE. */ private boolean selectForUpdate; /** * @param useOptimizedSubqry If we have to find correct order for table filters in FROM clause. * Relies on uniqueness of table filter aliases. * @param log Logger. */ public GridSqlQueryParser(boolean useOptimizedSubqry, IgniteLogger log) { assert Objects.nonNull(log); optimizedTableFilterOrder = useOptimizedSubqry ? new HashMap<>() : null; this.log = log; } /** * @param stmt Prepared statement to check. * @return {@code true} in case of multiple statements. */ public static boolean checkMultipleStatements(PreparedStatement stmt) { Command cmd = extractCommand(stmt); return ORG_H2_COMMAND_COMMAND_LIST.equals(cmd.getClass().getName()); } /** * @param stmt Prepared statement. * @return Parsed select. */ public static Prepared prepared(PreparedStatement stmt) { Command cmd = extractCommand(stmt); assert cmd instanceof CommandContainer; return PREPARED.get(cmd); } /** * @param stmt Prepared statement. * @return Parsed select. */ public static PreparedWithRemaining preparedWithRemaining(PreparedStatement stmt) { Command cmd = extractCommand(stmt); if (cmd instanceof CommandContainer) return new PreparedWithRemaining(PREPARED.get(cmd), null); else { Class<?> cmdCls = cmd.getClass(); if (cmdCls.getName().equals(ORG_H2_COMMAND_COMMAND_LIST)) return new PreparedWithRemaining(PREPARED.get(LIST_COMMAND.get(cmd)), REMAINING.get(cmd)); else throw new IgniteSQLException("Unexpected statement command"); } } /** */ private static Command extractCommand(PreparedStatement stmt) { return COMMAND.get((JdbcPreparedStatement)stmt); } /** * @param p Prepared. * @return Whether {@code p} is an {@code SELECT FOR UPDATE} query. */ public static boolean isForUpdateQuery(Prepared p) { boolean union; if (p.getClass() == Select.class) union = false; else if (p.getClass() == SelectUnion.class) union = true; else return false; boolean forUpdate = (!union && SELECT_IS_FOR_UPDATE.get((Select)p)) || (union && UNION_IS_FOR_UPDATE.get((SelectUnion)p)); if (union && forUpdate) { throw new IgniteSQLException("SELECT UNION FOR UPDATE is not supported.", IgniteQueryErrorCode.UNSUPPORTED_OPERATION); } return forUpdate; } /** * @param qry Query expression to parse. * @return Subquery AST. */ private GridSqlSubquery parseQueryExpression(Query qry) { parsingSubQryExpression++; GridSqlQuery subQry = parseQuery(qry); parsingSubQryExpression--; return new GridSqlSubquery(subQry); } /** * @param filter Filter. */ private GridSqlElement parseTableFilter(TableFilter filter) { GridSqlElement res = (GridSqlElement)h2ObjToGridObj.get(filter); if (res == null) { res = parseTable(filter.getTable()); // Setup index hints. if (res instanceof GridSqlTable && filter.getIndexHints() != null) ((GridSqlTable)res).useIndexes(new ArrayList<>(filter.getIndexHints().getAllowedIndexes())); String alias = ALIAS.get(filter); if (alias != null) res = new GridSqlAlias(alias, res, false); h2ObjToGridObj.put(filter, res); } return res; } /** * @param tbl Table. */ private GridSqlElement parseTable(Table tbl) { GridSqlElement res = (GridSqlElement)h2ObjToGridObj.get(tbl); if (res == null) { // We can't cache simple tables because otherwise it will be the same instance for all // table filters. Thus we will not be able to distinguish one table filter from another. // Table here is semantically equivalent to a table filter. if (tbl instanceof TableBase || tbl instanceof MetaTable) return new GridSqlTable(tbl); // Other stuff can be cached because we will have separate instances in // different table filters anyways. Thus the semantics will be correct. if (tbl instanceof TableView) { if (((TableView)tbl).isRecursive()) { throw new IgniteSQLException("Recursive CTE ('WITH RECURSIVE (...)') is not supported.", IgniteQueryErrorCode.UNSUPPORTED_OPERATION); } Query qry = VIEW_QUERY.get((TableView)tbl); res = new GridSqlSubquery(parseQuery(qry)); } else if (tbl instanceof FunctionTable) res = parseExpression(FUNC_EXPR.get((FunctionTable)tbl), false); else if (tbl instanceof RangeTable) { res = new GridSqlFunction(GridSqlFunctionType.SYSTEM_RANGE); res.addChild(parseExpression(RANGE_MIN.get((RangeTable)tbl), false)); res.addChild(parseExpression(RANGE_MAX.get((RangeTable)tbl), false)); } else if (tbl instanceof MetaTable) res = new GridSqlTable(tbl); else assert0(false, "Unexpected Table implementation [cls=" + tbl.getClass().getSimpleName() + ']'); h2ObjToGridObj.put(tbl, res); } return res; } /** * @param select Select. */ private GridSqlSelect parseSelect(Select select) { GridSqlSelect res = (GridSqlSelect)h2ObjToGridObj.get(select); if (res != null) return res; res = new GridSqlSelect(); h2ObjToGridObj.put(select, res); res.distinct(select.isDistinct()); Expression where = CONDITION.get(select); res.where(parseExpression(where, true)); ArrayList<TableFilter> tableFilters = new ArrayList<>(); TableFilter filter = select.getTopTableFilter(); boolean isForUpdate = SELECT_IS_FOR_UPDATE.get(select); do { assert0(filter != null, select); assert0(filter.getNestedJoin() == null, select); // Can use optimized join order only if we are not inside of an expression. if (parsingSubQryExpression == 0 && optimizedTableFilterOrder != null) { String tblAlias = filter.getTableAlias(); int idx = optimizedTableFilterOrder.get(tblAlias); setElementAt(tableFilters, idx, filter); } else tableFilters.add(filter); filter = filter.getJoin(); } while (filter != null); // Build FROM clause from correctly ordered table filters. GridSqlElement from = null; for (int i = 0; i < tableFilters.size(); i++) { TableFilter f = tableFilters.get(i); GridSqlElement gridFilter = parseTableFilter(f); from = from == null ? gridFilter : new GridSqlJoin(from, gridFilter, f.isJoinOuter(), parseExpression(f.getJoinCondition(), true)); } res.from(from); if (isForUpdate) { if (!(from instanceof GridSqlTable || (from instanceof GridSqlAlias && from.size() == 1 && from.child() instanceof GridSqlTable))) { throw new IgniteSQLException("SELECT FOR UPDATE with joins is not supported.", IgniteQueryErrorCode.UNSUPPORTED_OPERATION); } GridSqlTable gridTbl = from instanceof GridSqlTable ? (GridSqlTable)from : ((GridSqlAlias)from).child(); GridH2Table tbl = gridTbl.dataTable(); if (tbl == null) { throw new IgniteSQLException("SELECT FOR UPDATE query must involve Ignite table.", IgniteQueryErrorCode.UNSUPPORTED_OPERATION); } if (select.getLimit() != null || select.getOffset() != null) { throw new IgniteSQLException("LIMIT/OFFSET clauses are not supported for SELECT FOR UPDATE.", IgniteQueryErrorCode.UNSUPPORTED_OPERATION); } if (SELECT_IS_GROUP_QUERY.get(select)) { throw new IgniteSQLException("SELECT FOR UPDATE with aggregates and/or GROUP BY is not supported.", IgniteQueryErrorCode.UNSUPPORTED_OPERATION); } if (select.isDistinct()) throw new IgniteSQLException("DISTINCT clause is not supported for SELECT FOR UPDATE.", IgniteQueryErrorCode.UNSUPPORTED_OPERATION); if (SplitterUtils.hasSubQueries(res)) throw new IgniteSQLException("Sub queries are not supported for SELECT FOR UPDATE.", IgniteQueryErrorCode.UNSUPPORTED_OPERATION); } ArrayList<Expression> expressions = select.getExpressions(); for (int i = 0; i < expressions.size(); i++) res.addColumn(parseExpression(expressions.get(i), true), i < select.getColumnCount()); int[] grpIdx = GROUP_INDEXES.get(select); if (grpIdx != null) res.groupColumns(grpIdx); int havingIdx = HAVING_INDEX.get(select); if (havingIdx >= 0) res.havingColumn(havingIdx); res.forUpdate(isForUpdate); processSortOrder(select.getSortOrder(), res); res.limit(parseExpression(select.getLimit(), false)); res.offset(parseExpression(select.getOffset(), false)); return res; } /** * @param list List. * @param idx Index. * @param x Element. */ private static <Z> void setElementAt(List<Z> list, int idx, Z x) { while (list.size() <= idx) list.add(null); assert0(list.get(idx) == null, "Element already set: " + idx); list.set(idx, x); } /** * @param merge Merge. * @see <a href="http://h2database.com/html/grammar.html#merge">H2 merge spec</a> */ private GridSqlMerge parseMerge(Merge merge) { GridSqlMerge res = (GridSqlMerge)h2ObjToGridObj.get(merge); if (res != null) return res; res = new GridSqlMerge(); h2ObjToGridObj.put(merge, res); Table srcTbl = MERGE_TABLE.get(merge); GridSqlElement tbl = parseTable(srcTbl); res.into(tbl); Column[] srcCols = MERGE_COLUMNS.get(merge); GridSqlColumn[] cols = new GridSqlColumn[srcCols.length]; for (int i = 0; i < srcCols.length; i++) { cols[i] = new GridSqlColumn(srcCols[i], tbl, null, null, srcCols[i].getName()); cols[i].resultType(fromColumn(srcCols[i])); } res.columns(cols); if (!F.isEmpty(MERGE_KEYS.get(merge))) { log.warning("The search row by explicit KEY isn't supported. The primary key is always used to search row " + "[sql=" + merge.getSQL() + ']'); } List<Expression[]> srcRows = MERGE_ROWS.get(merge); if (!srcRows.isEmpty()) { List<GridSqlElement[]> rows = new ArrayList<>(srcRows.size()); for (Expression[] srcRow : srcRows) { GridSqlElement[] row = new GridSqlElement[srcRow.length]; for (int i = 0; i < srcRow.length; i++) { row[i] = parseExpression(srcRow[i], false); if (row[i] == null) { throw new IgniteSQLException("Explicit DEFAULT values are unsupported for MERGE.", IgniteQueryErrorCode.UNSUPPORTED_OPERATION); } } rows.add(row); } res.rows(rows); } else { res.rows(Collections.emptyList()); res.query(parseQuery(MERGE_QUERY.get(merge))); } return res; } /** * @param insert Insert. * @see <a href="http://h2database.com/html/grammar.html#insert">H2 insert spec</a> */ private GridSqlInsert parseInsert(Insert insert) { GridSqlInsert res = (GridSqlInsert)h2ObjToGridObj.get(insert); if (res != null) return res; res = new GridSqlInsert(); h2ObjToGridObj.put(insert, res); Table srcTbl = INSERT_TABLE.get(insert); GridSqlElement tbl = parseTable(srcTbl); res.into(tbl). direct(INSERT_DIRECT.get(insert)). sorted(INSERT_SORTED.get(insert)); Column[] srcCols = INSERT_COLUMNS.get(insert); GridSqlColumn[] cols = new GridSqlColumn[srcCols.length]; for (int i = 0; i < srcCols.length; i++) { cols[i] = new GridSqlColumn(srcCols[i], tbl, null, null, srcCols[i].getName()); cols[i].resultType(fromColumn(srcCols[i])); } res.columns(cols); List<Expression[]> srcRows = INSERT_ROWS.get(insert); if (!srcRows.isEmpty()) { List<GridSqlElement[]> rows = new ArrayList<>(srcRows.size()); for (Expression[] srcRow : srcRows) { GridSqlElement[] row = new GridSqlElement[srcRow.length]; for (int i = 0; i < srcRow.length; i++) { row[i] = parseExpression(srcRow[i], false); if (row[i] == null) { throw new IgniteSQLException("Explicit DEFAULT values are unsupported for INSERT.", IgniteQueryErrorCode.UNSUPPORTED_OPERATION); } } rows.add(row); } res.rows(rows); } else { res.rows(Collections.<GridSqlElement[]>emptyList()); res.query(parseQuery(INSERT_QUERY.get(insert))); } return res; } /** * @param del Delete. * @see <a href="http://h2database.com/html/grammar.html#delete">H2 delete spec</a> */ private GridSqlDelete parseDelete(Delete del) { GridSqlDelete res = (GridSqlDelete)h2ObjToGridObj.get(del); if (res != null) return res; res = new GridSqlDelete(); h2ObjToGridObj.put(del, res); GridSqlElement tbl = parseTableFilter(DELETE_FROM.get(del)); GridSqlElement where = parseExpression(DELETE_WHERE.get(del), true); GridSqlElement limit = parseExpression(DELETE_LIMIT.get(del), true); res.from(tbl).where(where).limit(limit); return res; } /** * @param update Update. * @see <a href="http://h2database.com/html/grammar.html#update">H2 update spec</a> */ private GridSqlUpdate parseUpdate(Update update) { GridSqlUpdate res = (GridSqlUpdate)h2ObjToGridObj.get(update); if (res != null) return res; res = new GridSqlUpdate(); h2ObjToGridObj.put(update, res); GridSqlElement tbl = parseTableFilter(UPDATE_TARGET.get(update)); List<Column> srcCols = UPDATE_COLUMNS.get(update); Map<Column, Expression> srcSet = UPDATE_SET.get(update); ArrayList<GridSqlColumn> cols = new ArrayList<>(srcCols.size()); LinkedHashMap<String, GridSqlElement> set = new LinkedHashMap<>(srcSet.size()); for (Column c : srcCols) { GridSqlColumn col = new GridSqlColumn(c, tbl, null, null, c.getName()); col.resultType(fromColumn(c)); cols.add(col); GridSqlElement setVal = parseExpression(srcSet.get(c), true); if (containsDefaultKeyword(setVal)) { throw new IgniteSQLException("DEFAULT values are unsupported for UPDATE.", IgniteQueryErrorCode.UNSUPPORTED_OPERATION); } set.put(col.columnName(), setVal); } GridSqlElement where = parseExpression(UPDATE_WHERE.get(update), true); GridSqlElement limit = parseExpression(UPDATE_LIMIT.get(update), true); res.target(tbl).cols(cols).set(set).where(where).limit(limit); return res; } /** * @param val SQL expression. * @return {@code true} if the expression contains DEFAULT keyword. */ private boolean containsDefaultKeyword(GridSqlAst val) { if (val == GridSqlKeyword.DEFAULT) return true; for (int i = 0; i < val.size(); ++i) { if (containsDefaultKeyword(val.child(i))) return true; } return false; } /** * Parse {@code DROP INDEX} statement. * * @param dropIdx {@code DROP INDEX} statement. * @see <a href="http://h2database.com/html/grammar.html#drop_index">H2 {@code DROP INDEX} spec.</a> */ private GridSqlDropIndex parseDropIndex(DropIndex dropIdx) { GridSqlDropIndex res = new GridSqlDropIndex(); res.indexName(DROP_INDEX_NAME.get(dropIdx)); res.schemaName(SCHEMA_COMMAND_SCHEMA.get(dropIdx).getName()); res.ifExists(DROP_INDEX_IF_EXISTS.get(dropIdx)); return res; } /** * Parse {@code CREATE INDEX} statement. * * @param createIdx {@code CREATE INDEX} statement. * @see <a href="http://h2database.com/html/grammar.html#create_index">H2 {@code CREATE INDEX} spec.</a> */ private GridSqlCreateIndex parseCreateIndex(CreateIndex createIdx) { if (CREATE_INDEX_HASH.get(createIdx) || CREATE_INDEX_PRIMARY_KEY.get(createIdx) || CREATE_INDEX_UNIQUE.get(createIdx)) { throw new IgniteSQLException("Only SPATIAL modifier is supported for CREATE INDEX", IgniteQueryErrorCode.UNSUPPORTED_OPERATION); } GridSqlCreateIndex res = new GridSqlCreateIndex(); Schema schema = SCHEMA_COMMAND_SCHEMA.get(createIdx); String tblName = CREATE_INDEX_TABLE_NAME.get(createIdx); res.schemaName(schema.getName()); res.tableName(tblName); res.ifNotExists(CREATE_INDEX_IF_NOT_EXISTS.get(createIdx)); QueryIndex idx = new QueryIndex(); idx.setName(CREATE_INDEX_NAME.get(createIdx)); idx.setIndexType(CREATE_INDEX_SPATIAL.get(createIdx) ? QueryIndexType.GEOSPATIAL : QueryIndexType.SORTED); IndexColumn[] cols = CREATE_INDEX_COLUMNS.get(createIdx); LinkedHashMap<String, Boolean> flds = new LinkedHashMap<>(cols.length); for (IndexColumn col : CREATE_INDEX_COLUMNS.get(createIdx)) { int sortType = INDEX_COLUMN_SORT_TYPE.get(col); if ((sortType & SortOrder.NULLS_FIRST) != 0 || (sortType & SortOrder.NULLS_LAST) != 0) { throw new IgniteSQLException("NULLS FIRST and NULLS LAST modifiers are not supported for index columns", IgniteQueryErrorCode.UNSUPPORTED_OPERATION); } Boolean prev = flds.put(INDEX_COLUMN_NAME.get(col), (sortType & SortOrder.DESCENDING) == 0); if (prev != null) { String prevCol = INDEX_COLUMN_NAME.get(col) + " " + (prev ? "ASC" : "DESC"); throw new IgniteSQLException("Already defined column in index: " + prevCol, IgniteQueryErrorCode.COLUMN_ALREADY_EXISTS); } } idx.setFields(flds); res.index(idx); return res; } /** * Parse {@code CREATE TABLE} statement. * * @param createTbl {@code CREATE TABLE} statement. * @see <a href="http://h2database.com/html/grammar.html#create_table">H2 {@code CREATE TABLE} spec.</a> */ private GridSqlCreateTable parseCreateTable(CreateTable createTbl) { GridSqlCreateTable res = new GridSqlCreateTable(); res.templateName(QueryUtils.TEMPLATE_PARTITIONED); Query qry = CREATE_TABLE_QUERY.get(createTbl); if (qry != null) { throw new IgniteSQLException("CREATE TABLE ... AS ... syntax is not supported", IgniteQueryErrorCode.UNSUPPORTED_OPERATION); } List<DefineCommand> constraints = CREATE_TABLE_CONSTRAINTS.get(createTbl); if (F.isEmpty(constraints)) { throw new IgniteSQLException("No PRIMARY KEY defined for CREATE TABLE", IgniteQueryErrorCode.PARSING); } if (constraints.size() > 1) { throw new IgniteSQLException("Too many constraints - only PRIMARY KEY is supported for CREATE TABLE", IgniteQueryErrorCode.UNSUPPORTED_OPERATION); } DefineCommand constraint = constraints.get(0); if (!(constraint instanceof AlterTableAddConstraint)) { throw new IgniteSQLException("Unsupported type of constraint for CREATE TABLE - only PRIMARY KEY " + "is supported", IgniteQueryErrorCode.UNSUPPORTED_OPERATION); } AlterTableAddConstraint alterTbl = (AlterTableAddConstraint)constraint; if (alterTbl.getType() != Command.ALTER_TABLE_ADD_CONSTRAINT_PRIMARY_KEY) { throw new IgniteSQLException("Unsupported type of constraint for CREATE TABLE - only PRIMARY KEY " + "is supported", IgniteQueryErrorCode.UNSUPPORTED_OPERATION); } Schema schema = SCHEMA_COMMAND_SCHEMA.get(createTbl); res.schemaName(schema.getName()); CreateTableData data = CREATE_TABLE_DATA.get(createTbl); if (data.globalTemporary) { throw new IgniteSQLException("GLOBAL TEMPORARY keyword is not supported", IgniteQueryErrorCode.UNSUPPORTED_OPERATION); } if (data.temporary) { throw new IgniteSQLException("TEMPORARY keyword is not supported", IgniteQueryErrorCode.UNSUPPORTED_OPERATION); } if (data.isHidden) { throw new IgniteSQLException("HIDDEN keyword is not supported", IgniteQueryErrorCode.UNSUPPORTED_OPERATION); } if (!data.persistIndexes) { throw new IgniteSQLException("MEMORY and NOT PERSISTENT keywords are not supported", IgniteQueryErrorCode.UNSUPPORTED_OPERATION); } LinkedHashMap<String, GridSqlColumn> cols = new LinkedHashMap<>(data.columns.size()); for (Column col : data.columns) { if (cols.put(col.getName(), parseColumn(col)) != null) throw new IgniteSQLException("Duplicate column name: " + col.getName(), IgniteQueryErrorCode.PARSING); } if (cols.containsKey(QueryUtils.KEY_FIELD_NAME.toUpperCase()) || cols.containsKey(QueryUtils.VAL_FIELD_NAME.toUpperCase())) { throw new IgniteSQLException("Direct specification of _KEY and _VAL columns is forbidden", IgniteQueryErrorCode.PARSING); } IndexColumn[] pkIdxCols = CREATE_TABLE_PK.get(createTbl); if (F.isEmpty(pkIdxCols)) throw new AssertionError("No PRIMARY KEY columns specified"); LinkedHashSet<String> pkCols = new LinkedHashSet<>(); for (IndexColumn pkIdxCol : pkIdxCols) { GridSqlColumn gridCol = cols.get(pkIdxCol.columnName); if (gridCol == null) { throw new IgniteSQLException("PRIMARY KEY column is not defined: " + pkIdxCol.columnName, IgniteQueryErrorCode.PARSING); } pkCols.add(gridCol.columnName()); } int keyColsNum = pkCols.size(); int valColsNum = cols.size() - keyColsNum; if (valColsNum == 0) { throw new IgniteSQLException("Table must have at least one non PRIMARY KEY column.", IgniteQueryErrorCode.UNSUPPORTED_OPERATION); } res.columns(cols); res.primaryKeyColumns(pkCols); res.tableName(data.tableName); res.ifNotExists(CREATE_TABLE_IF_NOT_EXISTS.get(createTbl)); List<String> extraParams = data.tableEngineParams != null ? new ArrayList<String>() : null; if (data.tableEngineParams != null) for (String s : data.tableEngineParams) extraParams.addAll(F.asList(s.split(","))); res.params(extraParams); if (!F.isEmpty(extraParams)) { Map<String, String> params = new HashMap<>(); for (String p : extraParams) { String[] parts = p.split(PARAM_NAME_VALUE_SEPARATOR); if (parts.length > 2) { throw new IgniteSQLException("Invalid parameter (key[=value] expected): " + p, IgniteQueryErrorCode.PARSING); } String name = parts[0].trim().toUpperCase(); String val = parts.length > 1 ? parts[1].trim() : null; if (F.isEmpty(name)) { throw new IgniteSQLException("Invalid parameter (key[=value] expected): " + p, IgniteQueryErrorCode.PARSING); } if (params.put(name, val) != null) throw new IgniteSQLException("Duplicate parameter: " + p, IgniteQueryErrorCode.PARSING); } for (Map.Entry<String, String> e : params.entrySet()) processExtraParam(e.getKey(), e.getValue(), res); } // Process key wrapping. Boolean wrapKey = res.wrapKey(); if (wrapKey != null && !wrapKey) { if (keyColsNum > 1) { throw new IgniteSQLException(PARAM_WRAP_KEY + " cannot be false when composite primary key exists.", IgniteQueryErrorCode.PARSING); } if (!F.isEmpty(res.keyTypeName())) { throw new IgniteSQLException(PARAM_WRAP_KEY + " cannot be false when " + PARAM_KEY_TYPE + " is set.", IgniteQueryErrorCode.PARSING); } } boolean wrapKey0 = (res.wrapKey() != null && res.wrapKey()) || !F.isEmpty(res.keyTypeName()) || keyColsNum > 1; res.wrapKey(wrapKey0); // Process value wrapping. Boolean wrapVal = res.wrapValue(); if (wrapVal != null && !wrapVal) { if (valColsNum > 1) { throw new IgniteSQLException(PARAM_WRAP_VALUE + " cannot be false when multiple non-primary key " + "columns exist.", IgniteQueryErrorCode.PARSING); } if (!F.isEmpty(res.valueTypeName())) { throw new IgniteSQLException(PARAM_WRAP_VALUE + " cannot be false when " + PARAM_VAL_TYPE + " is set.", IgniteQueryErrorCode.PARSING); } res.wrapValue(false); } else res.wrapValue(true); // By default value is always wrapped to allow for ALTER TABLE ADD COLUMN commands. if (!F.isEmpty(res.valueTypeName()) && F.eq(res.keyTypeName(), res.valueTypeName())) { throw new IgniteSQLException("Key and value type names " + "should be different for CREATE TABLE: " + res.valueTypeName(), IgniteQueryErrorCode.PARSING); } if (res.affinityKey() == null) { LinkedHashSet<String> pkCols0 = res.primaryKeyColumns(); if (!F.isEmpty(pkCols0) && pkCols0.size() == 1 && wrapKey0) res.affinityKey(pkCols0.iterator().next()); } return res; } /** * Parse {@code DROP TABLE} statement. * * @param dropTbl {@code DROP TABLE} statement. * @see <a href="http://h2database.com/html/grammar.html#drop_table">H2 {@code DROP TABLE} spec.</a> */ private GridSqlDropTable parseDropTable(DropTable dropTbl) { GridSqlDropTable res = new GridSqlDropTable(); Schema schema = SCHEMA_COMMAND_SCHEMA.get(dropTbl); res.schemaName(schema.getName()); res.ifExists(DROP_TABLE_IF_EXISTS.get(dropTbl)); res.tableName(DROP_TABLE_NAME.get(dropTbl)); return res; } /** * Parse {@code ALTER TABLE} statement. * @param stmt H2 statement. */ private GridSqlStatement parseAlterColumn(AlterTableAlterColumn stmt) { switch (stmt.getType()) { case CommandInterface.ALTER_TABLE_ADD_COLUMN: return parseAddColumn(stmt); case CommandInterface.ALTER_TABLE_DROP_COLUMN: return parseDropColumn(stmt); default: { String stmtName = null; switch (stmt.getType()) { case CommandInterface.ALTER_TABLE_ALTER_COLUMN_CHANGE_TYPE: case CommandInterface.ALTER_TABLE_ALTER_COLUMN_DEFAULT: case CommandInterface.ALTER_TABLE_ALTER_COLUMN_NOT_NULL: case CommandInterface.ALTER_TABLE_ALTER_COLUMN_RENAME: case CommandInterface.ALTER_TABLE_ALTER_COLUMN_NULL: case CommandInterface.ALTER_TABLE_ALTER_COLUMN_SELECTIVITY: case CommandInterface.ALTER_TABLE_ALTER_COLUMN_VISIBILITY: stmtName = "ALTER COLUMN"; break; } if (stmtName == null) { throw new IgniteSQLException("Unsupported operation: " + stmt.getSQL(), IgniteQueryErrorCode.UNSUPPORTED_OPERATION); } else { throw new IgniteSQLException(stmtName + " is not supported", IgniteQueryErrorCode.UNSUPPORTED_OPERATION); } } } } /** * Turn H2 column to grid column and check requested features. * @param col H2 column. * @return Grid column. */ private static GridSqlColumn parseColumn(Column col) { if (col.isAutoIncrement()) { throw new IgniteSQLException("AUTO_INCREMENT columns are not supported [colName=" + col.getName() + ']', IgniteQueryErrorCode.UNSUPPORTED_OPERATION); } if (COLUMN_IS_COMPUTED.get(col)) { throw new IgniteSQLException("Computed columns are not supported [colName=" + col.getName() + ']', IgniteQueryErrorCode.UNSUPPORTED_OPERATION); } checkTypeSupported(col.getType(), "[colName=" + col.getName() + ']'); if (col.getDefaultExpression() != null) { if (!col.getDefaultExpression().isConstant()) { throw new IgniteSQLException("Non-constant DEFAULT expressions are not supported [colName=" + col.getName() + ']', IgniteQueryErrorCode.UNSUPPORTED_OPERATION); } DataType colType = DataType.getDataType(col.getType()); DataType dfltType = DataType.getDataType(col.getDefaultExpression().getType()); if ((DataType.isStringType(colType.type) && !DataType.isStringType(dfltType.type)) || (DataType.supportsAdd(colType.type) && !DataType.supportsAdd(dfltType.type))) { throw new IgniteSQLException("Invalid default value for column. [colName=" + col.getName() + ", colType=" + colType.name + ", dfltValueType=" + dfltType.name + ']', IgniteQueryErrorCode.UNEXPECTED_ELEMENT_TYPE); } } if (col.getSequence() != null) throw new IgniteSQLException("SEQUENCE columns are not supported [colName=" + col.getName() + ']', IgniteQueryErrorCode.UNSUPPORTED_OPERATION); if (col.getSelectivity() != Constants.SELECTIVITY_DEFAULT) { throw new IgniteSQLException("SELECTIVITY column attribute is not supported [colName=" + col.getName() + ']', IgniteQueryErrorCode.UNSUPPORTED_OPERATION); } if (COLUMN_CHECK_CONSTRAINT.get(col) != null) { throw new IgniteSQLException("Column CHECK constraints are not supported [colName=" + col.getName() + ']', IgniteQueryErrorCode.UNSUPPORTED_OPERATION); } GridSqlColumn gridCol = new GridSqlColumn(col, null, col.getName()); gridCol.resultType(GridSqlType.fromColumn(col)); return gridCol; } /** * Parse {@code ALTER TABLE ... ADD COLUMN} statement. * @param addCol H2 statement. * @return Grid SQL statement. * * @see <a href="http://www.h2database.com/html/grammar.html#alter_table_add"></a> */ private GridSqlStatement parseAddColumn(AlterTableAlterColumn addCol) { assert addCol.getType() == CommandInterface.ALTER_TABLE_ADD_COLUMN; if (ALTER_COLUMN_BEFORE_COL.get(addCol) != null ) throw new IgniteSQLException("BEFORE keyword is not supported", IgniteQueryErrorCode.UNSUPPORTED_OPERATION); if (ALTER_COLUMN_AFTER_COL.get(addCol) != null) throw new IgniteSQLException("AFTER keyword is not supported", IgniteQueryErrorCode.UNSUPPORTED_OPERATION); if (ALTER_COLUMN_FIRST.get(addCol)) throw new IgniteSQLException("FIRST keyword is not supported", IgniteQueryErrorCode.UNSUPPORTED_OPERATION); GridSqlAlterTableAddColumn res = new GridSqlAlterTableAddColumn(); ArrayList<Column> h2NewCols = ALTER_COLUMN_NEW_COLS.get(addCol); GridSqlColumn[] gridNewCols = new GridSqlColumn[h2NewCols.size()]; for (int i = 0; i < h2NewCols.size(); i++) { Column col = h2NewCols.get(i); if (col.getDefaultExpression() != null) { throw new IgniteSQLException("ALTER TABLE ADD COLUMN with DEFAULT value is not supported " + "[col=" + col.getName() + ']', IgniteQueryErrorCode.UNSUPPORTED_OPERATION); } gridNewCols[i] = parseColumn(h2NewCols.get(i)); } res.columns(gridNewCols); if (gridNewCols.length == 1) res.ifNotExists(ALTER_COLUMN_IF_NOT_EXISTS.get(addCol)); res.ifTableExists(ALTER_COLUMN_IF_TBL_EXISTS.get(addCol)); Schema schema = SCHEMA_COMMAND_SCHEMA.get(addCol); res.schemaName(schema.getName()); res.tableName(ALTER_COLUMN_TBL_NAME.get(addCol)); return res; } /** * Parse {@code ALTER TABLE ... DROP COLUMN} statement. * @param dropCol H2 statement. * @see <a href="http://www.h2database.com/html/grammar.html#alter_table_add"></a> */ private GridSqlStatement parseDropColumn(AlterTableAlterColumn dropCol) { assert dropCol.getType() == CommandInterface.ALTER_TABLE_DROP_COLUMN; GridSqlAlterTableDropColumn res = new GridSqlAlterTableDropColumn(); ArrayList<Column> h2DropCols = ALTER_COLUMN_REMOVE_COLS.get(dropCol); String[] gridDropCols = new String[h2DropCols.size()]; for (int i = 0; i < h2DropCols.size(); i++) gridDropCols[i] = h2DropCols.get(i).getName(); res.columns(gridDropCols); if (gridDropCols.length == 1) res.ifExists(!ALTER_COLUMN_IF_NOT_EXISTS.get(dropCol)); res.ifTableExists(ALTER_COLUMN_IF_TBL_EXISTS.get(dropCol)); Schema schema = SCHEMA_COMMAND_SCHEMA.get(dropCol); res.schemaName(schema.getName()); res.tableName(ALTER_COLUMN_TBL_NAME.get(dropCol)); return res; } /** * @param name Param name. * @param val Param value. * @param res Table params to update. */ private static void processExtraParam(String name, String val, GridSqlCreateTable res) { assert !F.isEmpty(name); switch (name) { case PARAM_TEMPLATE: ensureNotEmpty(name, val); res.templateName(val); break; case PARAM_BACKUPS: ensureNotEmpty(name, val); int backups = parseIntParam(PARAM_BACKUPS, val); if (backups < 0) { throw new IgniteSQLException("\"" + PARAM_BACKUPS + "\" cannot be negative: " + backups, IgniteQueryErrorCode.PARSING); } res.backups(backups); break; case PARAM_PARALLELISM: ensureNotEmpty(name, val); int qryPar = parseIntParam(PARAM_PARALLELISM, val); if (qryPar <= 0) throw new IgniteSQLException("\"" + PARAM_PARALLELISM + "\" must be positive: " + qryPar, IgniteQueryErrorCode.PARSING); res.parallelism(qryPar); break; case PARAM_ATOMICITY: ensureNotEmpty(name, val); try { res.atomicityMode(CacheAtomicityMode.valueOf(val.toUpperCase())); } catch (IllegalArgumentException e) { String validVals = Arrays.stream(CacheAtomicityMode.values()) .map(Enum::name) .collect(Collectors.joining(", ")); throw new IgniteSQLException("Invalid value of \"" + PARAM_ATOMICITY + "\" parameter " + "(should be either " + validVals + "): " + val, IgniteQueryErrorCode.PARSING, e); } break; case PARAM_CACHE_NAME: ensureNotEmpty(name, val); res.cacheName(val); break; case PARAM_KEY_TYPE: ensureNotEmpty(name, val); res.keyTypeName(val); break; case PARAM_VAL_TYPE: ensureNotEmpty(name, val); res.valueTypeName(val); break; case PARAM_CACHE_GROUP_OLD: case PARAM_CACHE_GROUP: ensureNotEmpty(name, val); res.cacheGroup(val); break; case PARAM_AFFINITY_KEY_OLD: case PARAM_AFFINITY_KEY: ensureNotEmpty(name, val); String affColName = null; // Either strip column name off its quotes, or uppercase it. if (val.startsWith("'")) { if (val.length() == 1 || !val.endsWith("'")) { throw new IgniteSQLException("Affinity key column name does not have trailing quote: " + val, IgniteQueryErrorCode.PARSING); } val = val.substring(1, val.length() - 1); ensureNotEmpty(name, val); affColName = val; } else { for (String colName : res.columns().keySet()) { if (val.equalsIgnoreCase(colName)) { if (affColName != null) { throw new IgniteSQLException("Ambiguous affinity column name, use single quotes " + "for case sensitivity: " + val, IgniteQueryErrorCode.PARSING); } affColName = colName; } } } if (affColName == null || !res.columns().containsKey(affColName)) { throw new IgniteSQLException("Affinity key column with given name not found: " + val, IgniteQueryErrorCode.PARSING); } if (!res.primaryKeyColumns().contains(affColName)) { throw new IgniteSQLException("Affinity key column must be one of key columns: " + affColName, IgniteQueryErrorCode.PARSING); } res.affinityKey(affColName); break; case PARAM_WRITE_SYNC: ensureNotEmpty(name, val); CacheWriteSynchronizationMode writeSyncMode; if (CacheWriteSynchronizationMode.FULL_ASYNC.name().equalsIgnoreCase(val)) writeSyncMode = CacheWriteSynchronizationMode.FULL_ASYNC; else if (CacheWriteSynchronizationMode.FULL_SYNC.name().equalsIgnoreCase(val)) writeSyncMode = CacheWriteSynchronizationMode.FULL_SYNC; else if (CacheWriteSynchronizationMode.PRIMARY_SYNC.name().equalsIgnoreCase(val)) writeSyncMode = CacheWriteSynchronizationMode.PRIMARY_SYNC; else { throw new IgniteSQLException("Invalid value of \"" + PARAM_WRITE_SYNC + "\" parameter " + "(should be FULL_SYNC, FULL_ASYNC, or PRIMARY_SYNC): " + val, IgniteQueryErrorCode.PARSING); } res.writeSynchronizationMode(writeSyncMode); break; case PARAM_WRAP_KEY: { res.wrapKey(F.isEmpty(val) || Boolean.parseBoolean(val)); break; } case PARAM_WRAP_VALUE: res.wrapValue(F.isEmpty(val) || Boolean.parseBoolean(val)); break; case PARAM_DATA_REGION: ensureNotEmpty(name, val); res.dataRegionName(val); break; case PARAM_ENCRYPTED: res.encrypted(F.isEmpty(val) || Boolean.parseBoolean(val)); break; default: throw new IgniteSQLException("Unsupported parameter: " + name, IgniteQueryErrorCode.PARSING); } } /** * Check that param with mandatory value has it specified. * @param name Param name. * @param val Param value to check. */ private static void ensureNotEmpty(String name, String val) { if (F.isEmpty(val)) throw new IgniteSQLException("Parameter value cannot be empty: " + name, IgniteQueryErrorCode.PARSING); } /** * Parse given value as integer, or throw an {@link IgniteSQLException} if it's not of matching format. * @param name param name. * @param val param value. * @return parsed int value. */ private static int parseIntParam(String name, String val) { try { return Integer.parseInt(val); } catch (NumberFormatException ignored) { throw new IgniteSQLException("Parameter value must be an integer [name=" + name + ", value=" + val + ']', IgniteQueryErrorCode.PARSING); } } /** * @param sortOrder Sort order. * @param qry Query. */ private void processSortOrder(SortOrder sortOrder, GridSqlQuery qry) { if (sortOrder == null) return; int[] indexes = sortOrder.getQueryColumnIndexes(); int[] sortTypes = sortOrder.getSortTypes(); for (int i = 0; i < indexes.length; i++) { int colIdx = indexes[i]; int type = sortTypes[i]; qry.addSort(new GridSqlSortColumn(colIdx, (type & SortOrder.DESCENDING) == 0, (type & SortOrder.NULLS_FIRST) != 0, (type & SortOrder.NULLS_LAST) != 0)); } } /** * @param qry Prepared. * @return Query. */ public static Query query(Prepared qry) { if (qry instanceof Query) return (Query)qry; if (qry instanceof Explain) return query(EXPLAIN_COMMAND.get((Explain)qry)); throw new CacheException("Unsupported query: " + qry); } /** * Check whether statement is DML statement. * * @param stmt Statement. * @return {@code True} if this is DML. */ public static boolean isDml(Prepared stmt) { return stmt instanceof Merge || stmt instanceof Insert || stmt instanceof Update || stmt instanceof Delete; } /** * @param stmt Prepared. * @return Target table. */ @NotNull public static GridH2Table dmlTable(@NotNull Prepared stmt) { Table table; if (stmt.getClass() == Insert.class) table = INSERT_TABLE.get((Insert)stmt); else if (stmt.getClass() == Merge.class) table = MERGE_TABLE.get((Merge)stmt); else if (stmt.getClass() == Delete.class) table = DELETE_FROM.get((Delete)stmt).getTable(); else if (stmt.getClass() == Update.class) table = UPDATE_TARGET.get((Update)stmt).getTable(); else throw new IgniteException("Unsupported statement: " + stmt); assert table instanceof GridH2Table : table; return (GridH2Table)table; } /** * Check if query may be run locally on all caches mentioned in the query. * * @return {@code true} if query may be run locally on all caches mentioned in the query, i.e. there's no need * to run distributed query. */ public boolean isLocalQuery() { if (selectForUpdate) return false; for (Object o : h2ObjToGridObj.values()) { if (o instanceof GridSqlAlias) o = GridSqlAlias.unwrap((GridSqlAst)o); if (o instanceof GridSqlTable) { GridH2Table tbl = ((GridSqlTable)o).dataTable(); if (tbl != null) { GridCacheContext<?, ?> cctx = tbl.cacheContext(); //It's not affinity cache. Can't be local. if (cctx == null) return false; if (cctx.mvccEnabled()) return false; if (cctx.isPartitioned()) return false; if (isReplicatedLocalExecutionImpossible(cctx)) return false; } } } return true; } /** */ private static boolean isReplicatedLocalExecutionImpossible(GridCacheContext<?, ?> cctx) { // Improvement is possible: // MOVING partitions check inspects full partition map, but possibly only local node check is sufficient. return cctx.isReplicated() && (!cctx.affinityNode() || cctx.topology().hasMovingPartitions()); } /** * Get first (i.e. random, as we need any one) partitioned cache from parsed query * to determine expected query parallelism. * @return Context for the first of partitioned caches mentioned in the query, * or {@code null} if it does not involve partitioned caches. */ public GridCacheContext getFirstPartitionedCache() { for (Object o : h2ObjToGridObj.values()) { if (o instanceof GridSqlAlias) o = GridSqlAlias.unwrap((GridSqlAst)o); if (o instanceof GridSqlTable) { GridH2Table tbl = ((GridSqlTable)o).dataTable(); if (tbl != null && tbl.cacheContext().isPartitioned()) return tbl.cacheContext(); } } return null; } /** * @return All known cache IDs. */ public List<Integer> cacheIds() { ArrayList<Integer> res = new ArrayList<>(1); for (Object o : h2ObjToGridObj.values()) { if (o instanceof GridSqlAlias) o = GridSqlAlias.unwrap((GridSqlAst)o); if (o instanceof GridSqlTable) { GridH2Table tbl = ((GridSqlTable)o).dataTable(); if (tbl != null) res.add(tbl.cacheId()); } } return res; } /** * Extract all tables participating in DML statement. * * @return List of tables participate at query. * @throws IgniteSQLException in case query contains virtual tables. */ public List<GridH2Table> tablesForDml() throws IgniteSQLException { Collection<?> parserObjects = h2ObjToGridObj.values(); List<GridH2Table> tbls = new ArrayList<>(parserObjects.size()); // check all involved caches for (Object o : parserObjects) { if (o instanceof GridSqlMerge) o = ((GridSqlMerge)o).into(); else if (o instanceof GridSqlInsert) o = ((GridSqlInsert)o).into(); else if (o instanceof GridSqlUpdate) o = ((GridSqlUpdate)o).target(); else if (o instanceof GridSqlDelete) o = ((GridSqlDelete)o).from(); if (o instanceof GridSqlAlias) o = GridSqlAlias.unwrap((GridSqlAst)o); if (o instanceof GridSqlTable) { GridH2Table h2tbl = ((GridSqlTable)o).dataTable(); if (h2tbl == null) { // Check for virtual tables. throw new IgniteSQLException("Operation not supported for table '" + ((GridSqlTable)o).tableName() + "'", IgniteQueryErrorCode.UNSUPPORTED_OPERATION); } tbls.add(h2tbl); } } return tbls; } /** * Parse query. * * @param prepared Prepared statement. * @param useOptimizedSubqry Whether to user optimized subquery. * @return Parsed query. */ public static GridSqlQuery parseQuery(Prepared prepared, boolean useOptimizedSubqry, IgniteLogger log) { return (GridSqlQuery)new GridSqlQueryParser(useOptimizedSubqry, log).parse(prepared); } /** * @param stmt Prepared statement. * @return Parsed AST. */ public final GridSqlStatement parse(Prepared stmt) { if (stmt instanceof Query) { if (optimizedTableFilterOrder != null) collectOptimizedTableFiltersOrder((Query)stmt); selectForUpdate = isForUpdateQuery(stmt); return parseQuery((Query)stmt); } if (stmt instanceof Merge) return parseMerge((Merge)stmt); if (stmt instanceof Insert) return parseInsert((Insert)stmt); if (stmt instanceof Delete) return parseDelete((Delete)stmt); if (stmt instanceof Update) return parseUpdate((Update)stmt); if (stmt instanceof Explain) return parse(EXPLAIN_COMMAND.get((Explain)stmt)).explain(true); if (stmt instanceof CreateIndex) return parseCreateIndex((CreateIndex)stmt); if (stmt instanceof DropIndex) return parseDropIndex((DropIndex)stmt); if (stmt instanceof CreateTable) return parseCreateTable((CreateTable)stmt); if (stmt instanceof DropTable) return parseDropTable((DropTable)stmt); if (stmt instanceof AlterTableAlterColumn) return parseAlterColumn((AlterTableAlterColumn)stmt); throw new IgniteSQLException("Unsupported statement: " + stmt, IgniteQueryErrorCode.UNSUPPORTED_OPERATION); } /** * @return H2 to Grid objects map. */ public Map<Object, Object> objectsMap() { return h2ObjToGridObj; } /** * @param qry Query. * @return Parsed query AST. */ private GridSqlQuery parseQuery(Query qry) { if (qry instanceof Select) return parseSelect((Select)qry); if (qry instanceof SelectUnion) return parseUnion((SelectUnion)qry); throw new UnsupportedOperationException("Unknown query type: " + qry); } /** * @param union Select. * @return Parsed AST. */ private GridSqlUnion parseUnion(SelectUnion union) { if (UNION_IS_FOR_UPDATE.get(union)) throw new IgniteSQLException("SELECT UNION FOR UPDATE is not supported.", IgniteQueryErrorCode.UNSUPPORTED_OPERATION); GridSqlUnion res = (GridSqlUnion)h2ObjToGridObj.get(union); if (res != null) return res; res = new GridSqlUnion(); res.right(parseQuery(union.getRight())); res.left(parseQuery(union.getLeft())); res.unionType(union.getUnionType()); res.limit(parseExpression(union.getLimit(), false)); res.offset(parseExpression(union.getOffset(), false)); processSortOrder(UNION_SORT.get(union), res); h2ObjToGridObj.put(union, res); return res; } /** * @param expression Expression. * @param calcTypes Calculate types for all the expressions. * @return Parsed expression. */ private GridSqlElement parseExpression(@Nullable Expression expression, boolean calcTypes) { if (expression == null) return null; GridSqlElement res = (GridSqlElement)h2ObjToGridObj.get(expression); if (res == null) { res = parseExpression0(expression, calcTypes); if (calcTypes) res.resultType(fromExpression(expression)); h2ObjToGridObj.put(expression, res); } return res; } /** * @param qry Query. */ private void collectOptimizedTableFiltersOrder(Query qry) { if (qry instanceof SelectUnion) { collectOptimizedTableFiltersOrder(((SelectUnion)qry).getLeft()); collectOptimizedTableFiltersOrder(((SelectUnion)qry).getRight()); } else { Select select = (Select)qry; TableFilter filter = select.getTopTableFilter(); int i = 0; do { assert0(filter != null, select); assert0(filter.getNestedJoin() == null, select); // Here all the table filters must have generated unique aliases, // thus we can store them in the same map for all the subqueries. optimizedTableFilterOrder.put(filter.getTableAlias(), i++); Table tbl = filter.getTable(); // Go down and collect inside of optimized subqueries. if (tbl instanceof TableView) { ViewIndex viewIdx = (ViewIndex)filter.getIndex(); collectOptimizedTableFiltersOrder(viewIdx.getQuery()); } filter = filter.getJoin(); } while (filter != null); } } /** * Map operation type. * * @param opType H2 operation type. * @return Ignite operation type. */ private static GridSqlOperationType mapOperationType(Operation.OpType opType) { switch (opType) { case CONCAT: return GridSqlOperationType.CONCAT; case PLUS: return GridSqlOperationType.PLUS; case MINUS: return GridSqlOperationType.MINUS; case MULTIPLY: return GridSqlOperationType.MULTIPLY; case DIVIDE: return GridSqlOperationType.DIVIDE; case NEGATE: // NB: Was set to null in original code for some reason; left unchanged during 1.4.197 migration. return null; case MODULUS: return GridSqlOperationType.MODULUS; default: throw new IllegalStateException("Unsupported operation type: " + opType); } } /** * @param expression Expression. * @param calcTypes Calculate types for all the expressions. * @return Parsed expression. */ private GridSqlElement parseExpression0(Expression expression, boolean calcTypes) { if (expression instanceof ExpressionColumn) { ExpressionColumn expCol = (ExpressionColumn)expression; return new GridSqlColumn(expCol.getColumn(), parseTableFilter(expCol.getTableFilter()), SCHEMA_NAME.get(expCol), expCol.getOriginalTableAliasName(), expCol.getColumnName()); } if (expression instanceof Alias) return new GridSqlAlias(expression.getAlias(), parseExpression(expression.getNonAliasExpression(), calcTypes), true); if (expression instanceof ValueExpression) // == comparison is legit, see ValueExpression#getSQL() return expression == ValueExpression.getDefault() ? GridSqlKeyword.DEFAULT : new GridSqlConst(expression.getValue(null)); if (expression instanceof Operation) { Operation operation = (Operation)expression; Operation.OpType type = OPERATION_TYPE.get(operation); if (type == Operation.OpType.NEGATE) { assert OPERATION_RIGHT.get(operation) == null; return new GridSqlOperation(GridSqlOperationType.NEGATE, parseExpression(OPERATION_LEFT.get(operation), calcTypes)); } return new GridSqlOperation(mapOperationType(type), parseExpression(OPERATION_LEFT.get(operation), calcTypes), parseExpression(OPERATION_RIGHT.get(operation), calcTypes)); } if (expression instanceof Comparison) { Comparison cmp = (Comparison)expression; GridSqlOperationType opType = COMPARISON_TYPES[COMPARISON_TYPE.get(cmp)]; assert opType != null : COMPARISON_TYPE.get(cmp); Expression leftExp = COMPARISON_LEFT.get(cmp); GridSqlElement left = parseExpression(leftExp, calcTypes); if (opType.childrenCount() == 1) return new GridSqlOperation(opType, left); Expression rightExp = COMPARISON_RIGHT.get(cmp); GridSqlElement right = parseExpression(rightExp, calcTypes); return new GridSqlOperation(opType, left, right); } if (expression instanceof ConditionNot) return new GridSqlOperation(NOT, parseExpression(expression.getNotIfPossible(null), calcTypes)); if (expression instanceof ConditionAndOr) { ConditionAndOr andOr = (ConditionAndOr)expression; int type = ANDOR_TYPE.get(andOr); assert type == ConditionAndOr.AND || type == ConditionAndOr.OR; return new GridSqlOperation(type == ConditionAndOr.AND ? AND : OR, parseExpression(ANDOR_LEFT.get(andOr), calcTypes), parseExpression(ANDOR_RIGHT.get(andOr), calcTypes)); } if (expression instanceof Subquery) { Query qry = ((Subquery)expression).getQuery(); return parseQueryExpression(qry); } if (expression instanceof ConditionIn) { GridSqlOperation res = new GridSqlOperation(IN); res.addChild(parseExpression(LEFT_CI.get((ConditionIn)expression), calcTypes)); List<Expression> vals = VALUE_LIST_CI.get((ConditionIn)expression); for (Expression val : vals) res.addChild(parseExpression(val, calcTypes)); return res; } if (expression instanceof ConditionInConstantSet) { GridSqlOperation res = new GridSqlOperation(IN); res.addChild(parseExpression(LEFT_CICS.get((ConditionInConstantSet)expression), calcTypes)); List<Expression> vals = VALUE_LIST_CICS.get((ConditionInConstantSet)expression); for (Expression val : vals) res.addChild(parseExpression(val, calcTypes)); return res; } if (expression instanceof ConditionInSelect) { GridSqlOperation res = new GridSqlOperation(IN); boolean all = ALL.get((ConditionInSelect)expression); int compareType = COMPARE_TYPE.get((ConditionInSelect)expression); assert0(!all, expression); assert0(compareType == Comparison.EQUAL, expression); res.addChild(parseExpression(LEFT_CIS.get((ConditionInSelect)expression), calcTypes)); Query qry = QUERY_IN.get((ConditionInSelect)expression); res.addChild(parseQueryExpression(qry)); return res; } if (expression instanceof CompareLike) { assert0(ESCAPE.get((CompareLike)expression) == null, expression); boolean regexp = REGEXP_CL.get((CompareLike)expression); return new GridSqlOperation(regexp ? REGEXP : LIKE, parseExpression(LEFT.get((CompareLike)expression), calcTypes), parseExpression(RIGHT.get((CompareLike)expression), calcTypes)); } if (expression instanceof Function) { Function f = (Function)expression; GridSqlFunction res = new GridSqlFunction(null, f.getName()); if (f.getArgs() != null) { if (f.getFunctionType() == Function.TABLE || f.getFunctionType() == Function.TABLE_DISTINCT) { Column[] cols = FUNC_TBL_COLS.get((TableFunction)f); Expression[] args = f.getArgs(); assert cols.length == args.length; for (int i = 0; i < cols.length; i++) { GridSqlElement arg = parseExpression(args[i], calcTypes); GridSqlAlias alias = new GridSqlAlias(cols[i].getName(), arg, false); alias.resultType(fromColumn(cols[i])); res.addChild(alias); } } else { for (Expression arg : f.getArgs()) { if (arg == null) { if (f.getFunctionType() != Function.CASE) throw new IllegalStateException("Function type with null arg: " + f.getFunctionType()); res.addChild(GridSqlPlaceholder.EMPTY); } else res.addChild(parseExpression(arg, calcTypes)); } } } if (f.getFunctionType() == Function.CAST || f.getFunctionType() == Function.CONVERT) { checkTypeSupported(f.getType(), "[expSql=" + f.getSQL() + ']'); res.resultType(fromExpression(f)); } return res; } if (expression instanceof JavaFunction) { JavaFunction f = (JavaFunction)expression; FunctionAlias alias = FUNC_ALIAS.get(f); GridSqlFunction res = new GridSqlFunction(alias.getSchema().getName(), f.getName()); if (f.getArgs() != null) { for (Expression arg : f.getArgs()) res.addChild(parseExpression(arg, calcTypes)); } return res; } if (expression instanceof Parameter) return new GridSqlParameter(((Parameter)expression).getIndex()); if (expression instanceof Aggregate) { Aggregate.AggregateType type = TYPE.get((Aggregate)expression); if (GridSqlAggregateFunction.isValidType(type)) { GridSqlAggregateFunction res = new GridSqlAggregateFunction( DISTINCT.get((Aggregate)expression), type); Expression on = ON.get((Aggregate)expression); if (on != null) res.addChild(parseExpression(on, calcTypes)); ArrayList<SelectOrderBy> orders = GROUP_CONCAT_ORDER_LIST.get((Aggregate)expression); if (!F.isEmpty(orders)) parseGroupConcatOrder(res, orders, calcTypes); Expression separator = GROUP_CONCAT_SEPARATOR.get((Aggregate)expression); if (separator != null) res.setGroupConcatSeparator(parseExpression(separator, calcTypes)); return res; } } if (expression instanceof ExpressionList) { Expression[] exprs = EXPR_LIST.get((ExpressionList)expression); GridSqlArray res = new GridSqlArray(exprs.length); for (Expression expr : exprs) res.addChild(parseExpression(expr, calcTypes)); return res; } if (expression instanceof ConditionExists) { Query qry = QUERY_EXISTS.get((ConditionExists)expression); GridSqlOperation res = new GridSqlOperation(EXISTS); res.addChild(parseQueryExpression(qry)); return res; } throw new IgniteException("Unsupported expression: " + expression + " [type=" + expression.getClass().getSimpleName() + ']'); } /** * Check if passed statement is insert statement eligible for streaming. * * @param prep Prepared statement. * @return {@code True} if streamable insert. */ public static boolean isStreamableInsertStatement(Prepared prep) { return prep instanceof Insert && INSERT_QUERY.get((Insert)prep) == null; } /** * @param f Aggregate function. * @param orders Orders. * @param calcTypes Calculate types for all the expressions. */ private void parseGroupConcatOrder(GridSqlAggregateFunction f, ArrayList<SelectOrderBy> orders, boolean calcTypes) { GridSqlElement[] grpConcatOrderExpression = new GridSqlElement[orders.size()]; boolean[] grpConcatOrderDesc = new boolean[orders.size()]; for (int i = 0; i < orders.size(); ++i) { SelectOrderBy o = orders.get(i); grpConcatOrderExpression[i] = parseExpression(o.expression, calcTypes); grpConcatOrderDesc[i] = o.descending; } f.setGroupConcatOrder(grpConcatOrderExpression, grpConcatOrderDesc); } /** * @param cond Condition. * @param o Object. */ private static void assert0(boolean cond, Object o) { if (!cond) throw new IgniteException("Unsupported query: " + o); } /** * Determines if specified prepared statement is an EXPLAIN of update operation: UPDATE, DELETE, etc. * (e.g. not a SELECT query). * * @param statement statement to probe. * @return {@code True} if statement is EXPLAIN UPDATE, EXPLAIN DELETE or etc.; {@code false} otherwise. */ public static boolean isExplainUpdate(Prepared statement) { if (!(statement instanceof Explain)) return false; return !EXPLAIN_COMMAND.get((Explain)statement).isQuery(); } /** */ public static void checkTypeSupported(int type, String errMsg) { if (type == Value.TIMESTAMP_TZ) { throw new IgniteSQLException("TIMESTAMP WITH TIMEZONE type is not supported " + errMsg, IgniteQueryErrorCode.UNSUPPORTED_OPERATION); } if (type == Value.ENUM) { throw new IgniteSQLException("ENUM type is not supported " + errMsg, IgniteQueryErrorCode.UNSUPPORTED_OPERATION); } } /** * @param cls Class. * @param fldName Fld name. */ private static <T, R> Getter<T, R> getter(Class<? extends T> cls, String fldName) { Field field; try { field = cls.getDeclaredField(fldName); } catch (NoSuchFieldException e) { throw new RuntimeException(e); } field.setAccessible(true); return new Getter<>(field); } /** * Field getter. */ public static class Getter<T, R> { /** */ private final Field fld; /** * @param fld Fld. */ private Getter(Field fld) { this.fld = fld; } /** * @param obj Object. * @return Result. */ public R get(T obj) { try { return (R)fld.get(obj); } catch (IllegalAccessException e) { throw new IgniteException(e); } } } /** * */ public static class PreparedWithRemaining { /** Prepared. */ private Prepared prepared; /** Remaining sql. */ private String remainingSql; /** * @param prepared Prepared. * @param sql Remaining SQL. */ public PreparedWithRemaining(Prepared prepared, String sql) { this.prepared = prepared; if (sql != null) sql = sql.trim(); remainingSql = !F.isEmpty(sql) ? sql : null; } /** * @return Prepared. */ public Prepared prepared() { return prepared; } /** * @return Remaining SQL. */ public String remainingSql() { return remainingSql; } } }
apache-2.0
barchart/fixio
core/src/main/java/fixio/netty/pipeline/client/ClientSessionHandler.java
5582
/* * Copyright 2014 The FIX.io Project * * The FIX.io Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package fixio.netty.pipeline.client; import fixio.events.LogonEvent; import fixio.fixprotocol.*; import fixio.fixprotocol.session.FixSession; import fixio.handlers.FixApplication; import fixio.netty.pipeline.AbstractSessionHandler; import io.netty.channel.ChannelHandlerContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; public class ClientSessionHandler extends AbstractSessionHandler { private final static Logger LOGGER = LoggerFactory.getLogger(ClientSessionHandler.class); private final FixSessionSettingsProvider sessionSettingsProvider; private final MessageSequenceProvider messageSequenceProvider; public ClientSessionHandler(FixSessionSettingsProvider settingsProvider, MessageSequenceProvider messageSequenceProvider, FixApplication fixApplication) { super(fixApplication); assert (settingsProvider != null) : "FixSessionSettingsProvider is expected."; this.sessionSettingsProvider = settingsProvider; this.messageSequenceProvider = messageSequenceProvider; } private static FixMessageBuilderImpl createLogonRequest(FixSessionSettingsProvider sessionSettingsProvider) { FixMessageBuilderImpl messageBuilder = new FixMessageBuilderImpl(MessageTypes.LOGON); messageBuilder.add(FieldType.HeartBtInt, sessionSettingsProvider.getHeartbeatInterval()); messageBuilder.add(FieldType.EncryptMethod, 0); return messageBuilder; } @Override protected void decode(ChannelHandlerContext ctx, FixMessage msg, List<Object> out) throws Exception { final FixMessageHeader header = msg.getHeader(); FixSession session = getSession(ctx); if (MessageTypes.LOGON.equals(header.getMessageType())) { if (session != null) { int incomingMsgSeqNum = header.getMsgSeqNum(); if (!session.checkIncomingSeqNum(incomingMsgSeqNum)) { int expectedMsgSeqNum = session.getNextIncomingMessageSeqNum(); if (incomingMsgSeqNum > expectedMsgSeqNum) { FixMessageBuilder resendRequest = new FixMessageBuilderImpl(MessageTypes.RESEND_REQUEST); resendRequest.add(FieldType.BeginSeqNo, expectedMsgSeqNum); resendRequest.add(FieldType.EndSeqNo, incomingMsgSeqNum - 1); prepareMessageToSend(ctx, session, resendRequest); ctx.writeAndFlush(resendRequest); } else { getLogger().warn("Message Sequence Too Low"); ctx.channel().close(); return; } } getLogger().info("Fix Session Established."); LogonEvent logonEvent = new LogonEvent(session); out.add(logonEvent); return; } else { throw new IllegalStateException("Duplicate Logon Request. Session Already Established."); } } super.decode(ctx, msg, out); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { getLogger().info("Connection established, starting Client FIX session."); FixMessageBuilder logonRequest = createLogonRequest(sessionSettingsProvider); FixSession pendingSession = createSession(sessionSettingsProvider); setSession(ctx, pendingSession); prepareMessageToSend(ctx, pendingSession, logonRequest); getLogger().info("Sending Logon: {}", logonRequest); ctx.writeAndFlush(logonRequest); } private FixSession createSession(FixSessionSettingsProvider settingsProvider) { int nextIncomingSeqNum; if (settingsProvider.isResetMsgSeqNum()) { nextIncomingSeqNum = 1; } else { nextIncomingSeqNum = messageSequenceProvider.getMsgInSeqNum(); } FixSession session = FixSession.newBuilder() .beginString(settingsProvider.getBeginString()) .senderCompId(settingsProvider.getSenderCompID()) .senderSubId(settingsProvider.getSenderSubID()) .targetCompId(settingsProvider.getTargetCompID()) .targetSubId(settingsProvider.getTargetSubID()) .build(); session.setNextIncomingMessageSeqNum(nextIncomingSeqNum); if (settingsProvider.isResetMsgSeqNum()) { nextIncomingSeqNum = 1; } else { nextIncomingSeqNum = messageSequenceProvider.getMsgInSeqNum(); } session.setNextOutgoingMessageSeqNum(messageSequenceProvider.getMsgOutSeqNum()); session.setNextIncomingMessageSeqNum(nextIncomingSeqNum); return session; } @Override protected Logger getLogger() { return LOGGER; } }
apache-2.0
ow2-chameleon/fuchsia
core/src/main/java/org/ow2/chameleon/fuchsia/core/declaration/DeclarationBuilder.java
3432
package org.ow2.chameleon.fuchsia.core.declaration; /* * #%L * OW2 Chameleon - Fuchsia Core * %% * Copyright (C) 2009 - 2014 OW2 Chameleon * %% * 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. * #L% */ import java.util.HashMap; import java.util.Map; /** * A Builder for Declaration. There's two way to use it :. * - Build a Declaration with metadata * - Build a Declaration from another Declaration with extra-metadata * <p/> * If you doing it wrong, {@link IllegalStateException} are thrown. */ class DeclarationBuilder<B extends DeclarationBuilder<B, D>, D extends Declaration> { private Map<String, Object> metadata; private Map<String, Object> extraMetadata; private D declaration; DeclarationBuilder() { this.metadata = null; this.declaration = null; this.extraMetadata = new HashMap<String, Object>(); } DeclarationBuilder(Map<String, Object> metadata) { this(); this.metadata = metadata; } DeclarationBuilder(D declaration) { this(); this.declaration = declaration; } public ValueSetter key(String key) { if (declaration != null) { throw new IllegalStateException(); } return new ValueSetter(key); } public ExtraValueSetter extraKey(String key) { if (declaration == null) { throw new IllegalStateException(); } return new ExtraValueSetter(key); } public B withExtraMetadata(Map<String, Object> extraMetadata) { if (declaration == null) { throw new IllegalStateException(); } this.extraMetadata = extraMetadata; return (B) this; } public D build() { if (metadata != null && declaration == null) { return (D) new DeclarationImpl(metadata); } else if (metadata == null && declaration != null) { return (D) new DeclarationDecorator(declaration, extraMetadata); } else { throw new IllegalStateException(); } } private void addMetadata(String key, Object value) { if (metadata == null) { metadata = new HashMap<String, Object>(); } metadata.put(key, value); } private void addExtraMetadata(String key, Object value) { extraMetadata.put(key, value); } public class ValueSetter { private final String key; ValueSetter(String key) { this.key = key; } public B value(Object value) { addMetadata(key, value); return (B) DeclarationBuilder.this; } } public class ExtraValueSetter { private final String key; ExtraValueSetter(String key) { this.key = key; } public B value(Object value) { addExtraMetadata(key, value); return (B) DeclarationBuilder.this; } } }
apache-2.0
treasure-data/digdag
digdag-core/src/main/java/io/digdag/core/database/Transaction.java
208
package io.digdag.core.database; import org.skife.jdbi.v2.Handle; public interface Transaction { Handle getHandle(ConfigMapper configMapper); void commit(); void abort(); void reset(); }
apache-2.0
JamesHe1990/hw3-jiacongh1
hw3-jiacongh/src/main/java/edu/cmu/deiis/types/Sentence.java
1482
/* First created by JCasGen Sat Sep 21 21:09:31 EDT 2013 */ package edu.cmu.deiis.types; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.jcas.cas.TOP_Type; /** * Data structure to save sentence. Each sentence may be analyzed to a question or an answer * @generated */ public class Sentence extends Annotation { /** @generated * @ordered */ @SuppressWarnings ("hiding") public final static int typeIndexID = JCasRegistry.register(Sentence.class); /** @generated * @ordered */ @SuppressWarnings ("hiding") public final static int type = typeIndexID; /** @generated */ @Override public int getTypeIndexID() {return typeIndexID;} /** Never called. Disable default constructor * @generated */ protected Sentence() {/* intentionally empty block */} /** Internal - constructor used by generator * @generated */ public Sentence(int addr, TOP_Type type) { super(addr, type); readObject(); } /** @generated */ public Sentence(JCas jcas) { super(jcas); readObject(); } /** @generated */ public Sentence(JCas jcas, int begin, int end) { super(jcas); setBegin(begin); setEnd(end); readObject(); } /** <!-- begin-user-doc --> * Write your own initialization here * <!-- end-user-doc --> @generated modifiable */ private void readObject() {/*default - does nothing empty block */} }
apache-2.0
OSGP/Platform
osgp-adapter-domain-smartmetering/src/main/java/org/opensmartgridplatform/adapter/domain/smartmetering/application/mapping/customconverters/WeekProfileConverter.java
3945
/** * Copyright 2017 Smart Society Services B.V. * * 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 */ package org.opensmartgridplatform.adapter.domain.smartmetering.application.mapping.customconverters; import java.util.Objects; import org.opensmartgridplatform.adapter.domain.smartmetering.application.mapping.ConfigurationMapper; import org.opensmartgridplatform.domain.core.valueobjects.smartmetering.DayProfile; import org.opensmartgridplatform.domain.core.valueobjects.smartmetering.WeekProfile; import org.opensmartgridplatform.dto.valueobjects.smartmetering.DayProfileDto; import org.opensmartgridplatform.dto.valueobjects.smartmetering.WeekProfileDto; import ma.glasnost.orika.MappingContext; import ma.glasnost.orika.converter.BidirectionalConverter; import ma.glasnost.orika.metadata.Type; public class WeekProfileConverter extends BidirectionalConverter<WeekProfileDto, WeekProfile> { private final ConfigurationMapper mapper; public WeekProfileConverter() { this.mapper = new ConfigurationMapper(); } public WeekProfileConverter(final ConfigurationMapper mapper) { this.mapper = mapper; } @Override public boolean equals(final Object other) { if (!(other instanceof WeekProfileConverter)) { return false; } if (!super.equals(other)) { return false; } final WeekProfileConverter o = (WeekProfileConverter) other; if (this.mapper == null) { return o.mapper == null; } return this.mapper.getClass().equals(o.mapper.getClass()); } @Override public int hashCode() { return super.hashCode() + Objects.hashCode(this.mapper); } @Override public WeekProfile convertTo(final WeekProfileDto source, final Type<WeekProfile> destinationType, final MappingContext context) { if (source == null) { return null; } return WeekProfile.newBuilder().withWeekProfileName(source.getWeekProfileName()) .withMonday(this.convertDayProfileTo(source.getMonday())) .withTuesday(this.convertDayProfileTo(source.getTuesday())) .withWednesday(this.convertDayProfileTo(source.getWednesday())) .withThursday(this.convertDayProfileTo(source.getThursday())) .withFriday(this.convertDayProfileTo(source.getFriday())) .withSaturday(this.convertDayProfileTo(source.getSaturday())) .withSunday(this.convertDayProfileTo(source.getSunday())).build(); } private DayProfile convertDayProfileTo(final DayProfileDto dayProfile) { return this.mapper.map(dayProfile, DayProfile.class); } @Override public WeekProfileDto convertFrom(final WeekProfile source, final Type<WeekProfileDto> destinationType, final MappingContext context) { if (source == null) { return null; } return WeekProfileDto.newBuilder().withWeekProfileName(source.getWeekProfileName()) .withMonday(this.convertDayProfileFrom(source.getMonday())) .withTuesday(this.convertDayProfileFrom(source.getTuesday())) .withWednesday(this.convertDayProfileFrom(source.getWednesday())) .withThursday(this.convertDayProfileFrom(source.getThursday())) .withFriday(this.convertDayProfileFrom(source.getFriday())) .withSaturday(this.convertDayProfileFrom(source.getSaturday())) .withSunday(this.convertDayProfileFrom(source.getSunday())).build(); } private DayProfileDto convertDayProfileFrom(final DayProfile dayProfile) { return this.mapper.map(dayProfile, DayProfileDto.class); } }
apache-2.0
yy13003/Im002
im002/src/com/example/im002/ui/UpdateInfoActivity.java
1755
package com.example.im002.ui; import android.os.Bundle; import android.widget.EditText; import cn.bmob.v3.listener.UpdateListener; import com.example.im002.R; import com.example.im002.bean.User; import com.example.im002.view.HeaderLayout.onRightImageButtonClickListener; /** * 设置昵称和性别 * * @ClassName: SetNickAndSexActivity * @Description: TODO */ public class UpdateInfoActivity extends ActivityBase { EditText edit_nick; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_set_updateinfo); initView(); } private void initView() { initTopBarForBoth("修改昵称", R.drawable.base_action_bar_true_bg_selector, new onRightImageButtonClickListener() { @Override public void onClick() { // TODO Auto-generated method stub String nick = edit_nick.getText().toString(); if (nick.equals("")) { ShowToast("请填写昵称!"); return; } updateInfo(nick); } }); edit_nick = (EditText) findViewById(R.id.edit_nick); } /** 修改资料 * updateInfo * @Title: updateInfo * @return void * @throws */ private void updateInfo(String nick) { final User user = userManager.getCurrentUser(User.class); user.setNick(nick); user.update(this, new UpdateListener() { @Override public void onSuccess() { // TODO Auto-generated method stub ShowToast("修改成功"); finish(); } @Override public void onFailure(int arg0, String arg1) { // TODO Auto-generated method stub ShowToast("onFailure:" + arg1); } }); } }
apache-2.0
akraskovski/product-management-system
server/src/main/java/by/kraskovski/pms/application/security/audit/SecurityAspect.java
1417
package by.kraskovski.pms.application.security.audit; import by.kraskovski.pms.audit.LoggingAuditor; import lombok.AllArgsConstructor; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * Spring AOP {@link Aspect} for security-services auditing, */ @Aspect @Component @AllArgsConstructor(onConstructor = @__(@Autowired)) public class SecurityAspect { private final LoggingAuditor auditor; @Pointcut("execution(* by.kraskovski.pms.application.security.service.*.*(..)))") public void service() { // do nothing } @Before("by.kraskovski.pms.application.security.audit.SecurityAspect.service()") public void logService(final JoinPoint joinPoint) { auditor.logService(joinPoint.getTarget().toString(), joinPoint.getSignature().getName(), joinPoint.getArgs()); } @AfterThrowing(pointcut = "by.kraskovski.pms.application.security.audit.SecurityAspect.service()", throwing = "exception") public void logException(final JoinPoint joinPoint, final Throwable exception) { auditor.logException(joinPoint.getTarget().toString(), exception); } }
apache-2.0
deepaktwr/BitFrames
bitframe/src/main/java/proj/me/bitframe/shading_four/ImageShadingFour.java
64909
package proj.me.bitframe.shading_four; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Color; import androidx.palette.graphics.Palette; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import com.squareup.picasso.Callback; import com.squareup.picasso.MemoryPolicy; import com.squareup.picasso.NetworkPolicy; import com.squareup.picasso.Picasso; import java.util.List; import proj.me.bitframe.BeanBitFrame; import proj.me.bitframe.BeanImage; import proj.me.bitframe.FrameModel; import proj.me.bitframe.ImageShades; import proj.me.bitframe.ImageType; import proj.me.bitframe.R; import proj.me.bitframe.dimentions.BeanShade4; import proj.me.bitframe.exceptions.FrameException; import proj.me.bitframe.helper.Utils; /** * Created by Deepak.Tiwari on 29-09-2015. */ public final class ImageShadingFour extends ImageShades { LayoutInflater inflater; Context context; int totalImages; String imageLink1, imageLink2, imageLink3, imageLink4; BeanBitFrame beanBitFrame1, beanBitFrame2, beanBitFrame3, beanBitFrame4; BindingShadeFour bindingShadeFour; FrameModel frameModel; int[] resultColor = new int[4]; public ImageShadingFour(Context context, int totalImages, FrameModel frameModel) { inflater = LayoutInflater.from(context); this.context = context; this.totalImages = totalImages; beanBitFrame1 = new BeanBitFrame(); beanBitFrame2 = new BeanBitFrame(); beanBitFrame3 = new BeanBitFrame(); beanBitFrame4 = new BeanBitFrame(); beanBitFrame1.setLoaded(true); beanBitFrame2.setLoaded(true); beanBitFrame3.setLoaded(true); beanBitFrame4.setLoaded(true); this.frameModel = frameModel; } @Override protected void updateFrameUi(List<Bitmap> images, List<BeanImage> beanImages, boolean hasImageProperties) throws FrameException{ BeanBitFrame beanBitFrameFirst = null, beanBitFrameSecond = null, beanBitFrameThird = null, beanBitFrameFourth = null; if(hasImageProperties){ beanBitFrameFirst = (BeanBitFrame) beanImages.get(0); beanBitFrameSecond = (BeanBitFrame) beanImages.get(1); beanBitFrameThird = (BeanBitFrame) beanImages.get(2); beanBitFrameFourth = (BeanBitFrame) beanImages.get(3); } int width1 = hasImageProperties ? (int)beanBitFrameFirst.getWidth() : images.get(0).getWidth(); int height1 = hasImageProperties ? (int)beanBitFrameFirst.getHeight() : images.get(0).getHeight(); int width2 = hasImageProperties ? (int)beanBitFrameSecond.getWidth() : images.get(1).getWidth(); int height2 = hasImageProperties ? (int)beanBitFrameSecond.getHeight() : images.get(1).getHeight(); int width3 = hasImageProperties ? (int)beanBitFrameThird.getWidth() : images.get(2).getWidth(); int height3 = hasImageProperties ? (int)beanBitFrameThird.getHeight() : images.get(2).getHeight(); int width4 = hasImageProperties ? (int)beanBitFrameFourth.getWidth() : images.get(3).getWidth(); int height4 = hasImageProperties ? (int)beanBitFrameFourth.getHeight() : images.get(3).getHeight(); Utils.logMessage("MAX_WIDTH" + " " + frameModel.getMaxContainerWidth()); Utils.logMessage("MAX_HEIGHT" + " " + frameModel.getMaxContainerHeight()); Utils.logMessage("MIN_WIDTH" + " " + frameModel.getMinFrameWidth()); Utils.logMessage("MIN_HIGHT" + " " + frameModel.getMinFrameHeight()); Utils.logMessage("getWidth1 : " + " " + width1); Utils.logMessage("getHeight1 : " + " " + height1); Utils.logMessage("getWidth2 : " + " " + width2); Utils.logMessage("getHeight2 : " + " " + height2); Utils.logMessage("getWidth3 : " + " " + width3); Utils.logMessage("getHeight3 : " + " " + height3); Utils.logMessage("getWidth4 : " + " " + width4); Utils.logMessage("getHeight4 : " + " " + height4 + "\n\n"); BeanShade4 beanShade4 = ShadeFour.calculateDimentions(frameModel, width1, height1, width2, height2, width3, height3, width4, height4); Utils.logMessage("Start" + " ++++++++++++++++++++++++++++++++++++Start"); Utils.logMessage("getWidth1 : " + " " + beanShade4.getWidth1()); Utils.logMessage("getHeight1 : " + " " + beanShade4.getHeight1()); Utils.logMessage("getWidth2 : " + " " + beanShade4.getWidth2()); Utils.logMessage("getHeight2 : " + " " + beanShade4.getHeight2()); Utils.logMessage("getWidth3 : " + " " + beanShade4.getWidth3()); Utils.logMessage("getHeight3 : " + " " + beanShade4.getHeight3()); Utils.logMessage("getWidth4 : " + " " + beanShade4.getWidth4()); Utils.logMessage("getHeight4 : " + " " + beanShade4.getHeight4()); for(int i=0;i<4;i++) Utils.logMessage("image order : " + " " + beanShade4.getImageOrderList().get(i)); Utils.logMessage("layoutType : " + " " + beanShade4.getLayoutType()); Utils.logMessage("End" + " ++++++++++++++++++++++++++++++++++++End"); imageLink1 = beanImages.get(0).getImageLink(); imageLink2 = beanImages.get(1).getImageLink(); imageLink3 = beanImages.get(2).getImageLink(); imageLink4 = beanImages.get(3).getImageLink(); int firstPrimaryCount = beanImages.get(0).getPrimaryCount(); int firstSecondaryCount = beanImages.get(0).getSecondaryCount(); int secondPrimaryCount = beanImages.get(1).getPrimaryCount(); int secondSecondaryCount = beanImages.get(1).getSecondaryCount(); int thirdPrimaryCount = beanImages.get(2).getPrimaryCount(); int thirdSecondaryCount = beanImages.get(2).getSecondaryCount(); int fourthPrimaryCount = beanImages.get(3).getPrimaryCount(); int fourthSecondaryCount = beanImages.get(3).getSecondaryCount(); bindingShadeFour = new BindingShadeFour(); View root = null; switch(beanShade4.getLayoutType()){ case VERT: root = bindingShadeFour.bind(inflater.inflate(R.layout.view_multiple_vert, null), this); break; case HORZ: root = bindingShadeFour.bind(inflater.inflate(R.layout.view_multiple_horz, null), this); break; case VERT_DOUBLE: root = bindingShadeFour.bind(inflater.inflate(R.layout.view_multiple_vert_double, null), this); break; case HORZ_DOUBLE: root = bindingShadeFour.bind(inflater.inflate(R.layout.view_multiple_horz_double, null), this); break; case VERT_HORZ: root = bindingShadeFour.bind(inflater.inflate(R.layout.view_multiple_vert_horz, null), this); break; case HORZ_VERT: root = bindingShadeFour.bind(inflater.inflate(R.layout.view_multiple_horz_vert, null), this); break; case IDENTICAL_VARY_WIDTH: root = bindingShadeFour.bind(inflater.inflate(R.layout.view_multiple_vary_width, null), this); break; case IDENTICAL_VARY_HEIGHT: root = bindingShadeFour.bind(inflater.inflate(R.layout.view_multiple_vary_height, null), this); break; default: throw new FrameException("invalid layout type"); } Bitmap bitmap1 = null, bitmap2 = null, bitmap3 = null, bitmap4 = null; int resultColor = 0; boolean hasGreaterVibrantPopulation = false; switch (beanShade4.getImageOrderList().get(0)){ case FIRST: bitmap1 = hasImageProperties ? null : images.get(0); bindingShadeFour.setFirstComment(beanImages.get(0).getImageComment()); imageLink1 = beanImages.get(0).getImageLink(); firstPrimaryCount = beanImages.get(0).getPrimaryCount(); firstSecondaryCount = beanImages.get(0).getSecondaryCount(); if(hasImageProperties) { hasGreaterVibrantPopulation = beanBitFrameFirst.isHasGreaterVibrantPopulation(); resultColor = hasGreaterVibrantPopulation ? beanBitFrameFirst.getVibrantColor() : beanBitFrameFirst.getMutedColor(); switch (frameModel.getColorCombination()) { case VIBRANT_TO_MUTED: if (hasGreaterVibrantPopulation) resultColor = beanBitFrameFirst.getVibrantColor(); else resultColor = beanBitFrameFirst.getMutedColor(); break; case MUTED_TO_VIBRANT: if (hasGreaterVibrantPopulation) resultColor = beanBitFrameFirst.getMutedColor(); else resultColor = beanBitFrameFirst.getVibrantColor(); break; } bindingShadeFour.setFirstImageBgColor(resultColor); bindingShadeFour.setFirstCommentBgColor(Utils.getColorWithTransparency(resultColor, frameModel.getCommentTransparencyPercent())); beanBitFrame1.setMutedColor(beanBitFrameFirst.getMutedColor()); beanBitFrame1.setVibrantColor(beanBitFrameFirst.getVibrantColor()); beanBitFrame1.setHasGreaterVibrantPopulation(hasGreaterVibrantPopulation); beanBitFrame1.setPrimaryCount(beanBitFrameFirst.getPrimaryCount()); beanBitFrame1.setSecondaryCount(beanBitFrameFirst.getSecondaryCount()); beanBitFrame1.setWidth(/*beanShade4.getWidth1()*/beanBitFrameFirst.getWidth()); beanBitFrame1.setHeight(/*beanShade4.getHeight1()*/beanBitFrameFirst.getHeight()); } break; case SECOND: bitmap1 = hasImageProperties ? null : images.get(1); bindingShadeFour.setFirstComment(beanImages.get(1).getImageComment()); imageLink1 = beanImages.get(1).getImageLink(); firstPrimaryCount = beanImages.get(1).getPrimaryCount(); firstSecondaryCount = beanImages.get(1).getSecondaryCount(); if(hasImageProperties) { hasGreaterVibrantPopulation = beanBitFrameSecond.isHasGreaterVibrantPopulation(); resultColor = hasGreaterVibrantPopulation ? beanBitFrameSecond.getVibrantColor() : beanBitFrameSecond.getMutedColor(); switch (frameModel.getColorCombination()) { case VIBRANT_TO_MUTED: if (hasGreaterVibrantPopulation) resultColor = beanBitFrameSecond.getVibrantColor(); else resultColor = beanBitFrameSecond.getMutedColor(); break; case MUTED_TO_VIBRANT: if (hasGreaterVibrantPopulation) resultColor = beanBitFrameSecond.getMutedColor(); else resultColor = beanBitFrameSecond.getVibrantColor(); break; } bindingShadeFour.setFirstImageBgColor(resultColor); bindingShadeFour.setFirstCommentBgColor(Utils.getColorWithTransparency(resultColor, frameModel.getCommentTransparencyPercent())); beanBitFrame1.setMutedColor(beanBitFrameSecond.getMutedColor()); beanBitFrame1.setVibrantColor(beanBitFrameSecond.getVibrantColor()); beanBitFrame1.setHasGreaterVibrantPopulation(hasGreaterVibrantPopulation); beanBitFrame1.setPrimaryCount(beanBitFrameSecond.getPrimaryCount()); beanBitFrame1.setSecondaryCount(beanBitFrameSecond.getSecondaryCount()); beanBitFrame1.setWidth(/*beanShade4.getWidth1()*/beanBitFrameSecond.getWidth()); beanBitFrame1.setHeight(/*beanShade4.getHeight1()*/beanBitFrameSecond.getHeight()); } break; case THIRD: bitmap1 = hasImageProperties ? null : images.get(2); bindingShadeFour.setFirstComment(beanImages.get(2).getImageComment()); imageLink1 = beanImages.get(2).getImageLink(); firstPrimaryCount = beanImages.get(2).getPrimaryCount(); firstSecondaryCount = beanImages.get(2).getSecondaryCount(); if(hasImageProperties) { hasGreaterVibrantPopulation = beanBitFrameThird.isHasGreaterVibrantPopulation(); resultColor = hasGreaterVibrantPopulation ? beanBitFrameThird.getVibrantColor() : beanBitFrameThird.getMutedColor(); switch (frameModel.getColorCombination()) { case VIBRANT_TO_MUTED: if (hasGreaterVibrantPopulation) resultColor = beanBitFrameThird.getVibrantColor(); else resultColor = beanBitFrameThird.getMutedColor(); break; case MUTED_TO_VIBRANT: if (hasGreaterVibrantPopulation) resultColor = beanBitFrameThird.getMutedColor(); else resultColor = beanBitFrameThird.getVibrantColor(); break; } bindingShadeFour.setFirstImageBgColor(resultColor); bindingShadeFour.setFirstCommentBgColor(Utils.getColorWithTransparency(resultColor, frameModel.getCommentTransparencyPercent())); beanBitFrame1.setMutedColor(beanBitFrameThird.getMutedColor()); beanBitFrame1.setVibrantColor(beanBitFrameThird.getVibrantColor()); beanBitFrame1.setHasGreaterVibrantPopulation(hasGreaterVibrantPopulation); beanBitFrame1.setPrimaryCount(beanBitFrameThird.getPrimaryCount()); beanBitFrame1.setSecondaryCount(beanBitFrameThird.getSecondaryCount()); beanBitFrame1.setWidth(/*beanShade4.getWidth1()*/beanBitFrameThird.getWidth()); beanBitFrame1.setHeight(/*beanShade4.getHeight1()*/beanBitFrameThird.getHeight()); } break; case FOURTH: bitmap1 = hasImageProperties ? null : images.get(3); bindingShadeFour.setFirstComment(beanImages.get(3).getImageComment()); imageLink1 = beanImages.get(3).getImageLink(); firstPrimaryCount = beanImages.get(3).getPrimaryCount(); firstSecondaryCount = beanImages.get(3).getSecondaryCount(); if(hasImageProperties) { hasGreaterVibrantPopulation = beanBitFrameFourth.isHasGreaterVibrantPopulation(); resultColor = hasGreaterVibrantPopulation ? beanBitFrameFourth.getVibrantColor() : beanBitFrameFourth.getMutedColor(); switch (frameModel.getColorCombination()) { case VIBRANT_TO_MUTED: if (hasGreaterVibrantPopulation) resultColor = beanBitFrameFourth.getVibrantColor(); else resultColor = beanBitFrameFourth.getMutedColor(); break; case MUTED_TO_VIBRANT: if (hasGreaterVibrantPopulation) resultColor = beanBitFrameFourth.getMutedColor(); else resultColor = beanBitFrameFourth.getVibrantColor(); break; } bindingShadeFour.setFirstImageBgColor(resultColor); bindingShadeFour.setFirstCommentBgColor(Utils.getColorWithTransparency(resultColor, frameModel.getCommentTransparencyPercent())); beanBitFrame1.setMutedColor(beanBitFrameFourth.getMutedColor()); beanBitFrame1.setVibrantColor(beanBitFrameFourth.getVibrantColor()); beanBitFrame1.setHasGreaterVibrantPopulation(hasGreaterVibrantPopulation); beanBitFrame1.setPrimaryCount(beanBitFrameFourth.getPrimaryCount()); beanBitFrame1.setSecondaryCount(beanBitFrameFourth.getSecondaryCount()); beanBitFrame1.setWidth(/*beanShade3.getWidth1()*/beanBitFrameFourth.getWidth()); beanBitFrame1.setHeight(/*beanShade3.getHeight1()*/beanBitFrameFourth.getHeight()); } break; default: throw new FrameException("invalid image order"); }switch (beanShade4.getImageOrderList().get(1)){ case FIRST: bitmap2 = hasImageProperties ? null : images.get(0); bindingShadeFour.setSecondComment(beanImages.get(0).getImageComment()); imageLink2 = beanImages.get(0).getImageLink(); secondPrimaryCount = beanImages.get(0).getPrimaryCount(); secondSecondaryCount = beanImages.get(0).getSecondaryCount(); if(hasImageProperties) { hasGreaterVibrantPopulation = beanBitFrameFirst.isHasGreaterVibrantPopulation(); resultColor = hasGreaterVibrantPopulation ? beanBitFrameFirst.getVibrantColor() : beanBitFrameFirst.getMutedColor(); switch (frameModel.getColorCombination()) { case VIBRANT_TO_MUTED: if (hasGreaterVibrantPopulation) resultColor = beanBitFrameFirst.getVibrantColor(); else resultColor = beanBitFrameFirst.getMutedColor(); break; case MUTED_TO_VIBRANT: if (hasGreaterVibrantPopulation) resultColor = beanBitFrameFirst.getMutedColor(); else resultColor = beanBitFrameFirst.getVibrantColor(); break; } bindingShadeFour.setSecondImageBgColor(resultColor); bindingShadeFour.setSecondCommentBgColor(Utils.getColorWithTransparency(resultColor, frameModel.getCommentTransparencyPercent())); beanBitFrame2.setMutedColor(beanBitFrameFirst.getMutedColor()); beanBitFrame2.setVibrantColor(beanBitFrameFirst.getVibrantColor()); beanBitFrame2.setHasGreaterVibrantPopulation(hasGreaterVibrantPopulation); beanBitFrame2.setPrimaryCount(beanBitFrameFirst.getPrimaryCount()); beanBitFrame2.setSecondaryCount(beanBitFrameFirst.getSecondaryCount()); beanBitFrame2.setWidth(/*beanShade4.getWidth1()*/beanBitFrameFirst.getWidth()); beanBitFrame2.setHeight(/*beanShade4.getHeight1()*/beanBitFrameFirst.getHeight()); } break; case SECOND: bitmap2 = hasImageProperties ? null : images.get(1); bindingShadeFour.setSecondComment(beanImages.get(1).getImageComment()); imageLink2 = beanImages.get(1).getImageLink(); secondPrimaryCount = beanImages.get(1).getPrimaryCount(); secondSecondaryCount = beanImages.get(1).getSecondaryCount(); if(hasImageProperties) { hasGreaterVibrantPopulation = beanBitFrameSecond.isHasGreaterVibrantPopulation(); resultColor = hasGreaterVibrantPopulation ? beanBitFrameSecond.getVibrantColor() : beanBitFrameSecond.getMutedColor(); switch (frameModel.getColorCombination()) { case VIBRANT_TO_MUTED: if (hasGreaterVibrantPopulation) resultColor = beanBitFrameSecond.getVibrantColor(); else resultColor = beanBitFrameSecond.getMutedColor(); break; case MUTED_TO_VIBRANT: if (hasGreaterVibrantPopulation) resultColor = beanBitFrameSecond.getMutedColor(); else resultColor = beanBitFrameSecond.getVibrantColor(); break; } bindingShadeFour.setSecondImageBgColor(resultColor); bindingShadeFour.setSecondCommentBgColor(Utils.getColorWithTransparency(resultColor, frameModel.getCommentTransparencyPercent())); beanBitFrame2.setMutedColor(beanBitFrameSecond.getMutedColor()); beanBitFrame2.setVibrantColor(beanBitFrameSecond.getVibrantColor()); beanBitFrame2.setHasGreaterVibrantPopulation(hasGreaterVibrantPopulation); beanBitFrame2.setPrimaryCount(beanBitFrameSecond.getPrimaryCount()); beanBitFrame2.setSecondaryCount(beanBitFrameSecond.getSecondaryCount()); beanBitFrame2.setWidth(/*beanShade4.getWidth1()*/beanBitFrameSecond.getWidth()); beanBitFrame2.setHeight(/*beanShade4.getHeight1()*/beanBitFrameSecond.getHeight()); } break; case THIRD: bitmap2 = hasImageProperties ? null : images.get(2); bindingShadeFour.setSecondComment(beanImages.get(2).getImageComment()); imageLink2 = beanImages.get(2).getImageLink(); secondPrimaryCount = beanImages.get(2).getPrimaryCount(); secondSecondaryCount = beanImages.get(2).getSecondaryCount(); if(hasImageProperties) { hasGreaterVibrantPopulation = beanBitFrameThird.isHasGreaterVibrantPopulation(); resultColor = hasGreaterVibrantPopulation ? beanBitFrameThird.getVibrantColor() : beanBitFrameThird.getMutedColor(); switch (frameModel.getColorCombination()) { case VIBRANT_TO_MUTED: if (hasGreaterVibrantPopulation) resultColor = beanBitFrameThird.getVibrantColor(); else resultColor = beanBitFrameThird.getMutedColor(); break; case MUTED_TO_VIBRANT: if (hasGreaterVibrantPopulation) resultColor = beanBitFrameThird.getMutedColor(); else resultColor = beanBitFrameThird.getVibrantColor(); break; } bindingShadeFour.setSecondImageBgColor(resultColor); bindingShadeFour.setSecondCommentBgColor(Utils.getColorWithTransparency(resultColor, frameModel.getCommentTransparencyPercent())); beanBitFrame2.setMutedColor(beanBitFrameThird.getMutedColor()); beanBitFrame2.setVibrantColor(beanBitFrameThird.getVibrantColor()); beanBitFrame2.setHasGreaterVibrantPopulation(hasGreaterVibrantPopulation); beanBitFrame2.setPrimaryCount(beanBitFrameThird.getPrimaryCount()); beanBitFrame2.setSecondaryCount(beanBitFrameThird.getSecondaryCount()); beanBitFrame2.setWidth(/*beanShade4.getWidth1()*/beanBitFrameThird.getWidth()); beanBitFrame2.setHeight(/*beanShade4.getHeight1()*/beanBitFrameThird.getHeight()); } break; case FOURTH: bitmap2 = hasImageProperties ? null : images.get(3); bindingShadeFour.setSecondComment(beanImages.get(3).getImageComment()); imageLink2 = beanImages.get(3).getImageLink(); secondPrimaryCount = beanImages.get(3).getPrimaryCount(); secondSecondaryCount = beanImages.get(3).getSecondaryCount(); if(hasImageProperties) { hasGreaterVibrantPopulation = beanBitFrameFourth.isHasGreaterVibrantPopulation(); resultColor = hasGreaterVibrantPopulation ? beanBitFrameFourth.getVibrantColor() : beanBitFrameFourth.getMutedColor(); switch (frameModel.getColorCombination()) { case VIBRANT_TO_MUTED: if (hasGreaterVibrantPopulation) resultColor = beanBitFrameFourth.getVibrantColor(); else resultColor = beanBitFrameFourth.getMutedColor(); break; case MUTED_TO_VIBRANT: if (hasGreaterVibrantPopulation) resultColor = beanBitFrameFourth.getMutedColor(); else resultColor = beanBitFrameFourth.getVibrantColor(); break; } bindingShadeFour.setSecondImageBgColor(resultColor); bindingShadeFour.setSecondCommentBgColor(Utils.getColorWithTransparency(resultColor, frameModel.getCommentTransparencyPercent())); beanBitFrame2.setMutedColor(beanBitFrameFourth.getMutedColor()); beanBitFrame2.setVibrantColor(beanBitFrameFourth.getVibrantColor()); beanBitFrame2.setHasGreaterVibrantPopulation(hasGreaterVibrantPopulation); beanBitFrame2.setPrimaryCount(beanBitFrameFourth.getPrimaryCount()); beanBitFrame2.setSecondaryCount(beanBitFrameFourth.getSecondaryCount()); beanBitFrame2.setWidth(/*beanShade4.getWidth1()*/beanBitFrameFourth.getWidth()); beanBitFrame2.setHeight(/*beanShade4.getHeight1()*/beanBitFrameFourth.getHeight()); } break; default: throw new FrameException("invalid image order"); }switch (beanShade4.getImageOrderList().get(2)){ case FIRST: bitmap3 = hasImageProperties ? null : images.get(0); bindingShadeFour.setThirdComment(beanImages.get(0).getImageComment()); imageLink3 = beanImages.get(0).getImageLink(); thirdPrimaryCount = beanImages.get(0).getPrimaryCount(); thirdSecondaryCount = beanImages.get(0).getSecondaryCount(); if(hasImageProperties) { hasGreaterVibrantPopulation = beanBitFrameFirst.isHasGreaterVibrantPopulation(); resultColor = hasGreaterVibrantPopulation ? beanBitFrameFirst.getVibrantColor() : beanBitFrameFirst.getMutedColor(); switch (frameModel.getColorCombination()) { case VIBRANT_TO_MUTED: if (hasGreaterVibrantPopulation) resultColor = beanBitFrameFirst.getVibrantColor(); else resultColor = beanBitFrameFirst.getMutedColor(); break; case MUTED_TO_VIBRANT: if (hasGreaterVibrantPopulation) resultColor = beanBitFrameFirst.getMutedColor(); else resultColor = beanBitFrameFirst.getVibrantColor(); break; } bindingShadeFour.setThirdImageBgColor(resultColor); bindingShadeFour.setThirdCommentBgColor(Utils.getColorWithTransparency(resultColor, frameModel.getCommentTransparencyPercent())); beanBitFrame3.setMutedColor(beanBitFrameFirst.getMutedColor()); beanBitFrame3.setVibrantColor(beanBitFrameFirst.getVibrantColor()); beanBitFrame3.setHasGreaterVibrantPopulation(hasGreaterVibrantPopulation); beanBitFrame3.setPrimaryCount(beanBitFrameFirst.getPrimaryCount()); beanBitFrame3.setSecondaryCount(beanBitFrameFirst.getSecondaryCount()); beanBitFrame3.setWidth(/*beanShade4.getWidth1()*/beanBitFrameFirst.getWidth()); beanBitFrame3.setHeight(/*beanShade4.getHeight1()*/beanBitFrameFirst.getHeight()); } break; case SECOND: bitmap3 = hasImageProperties ? null : images.get(1); bindingShadeFour.setThirdComment(beanImages.get(1).getImageComment()); imageLink3 = beanImages.get(1).getImageLink(); thirdPrimaryCount = beanImages.get(1).getPrimaryCount(); thirdSecondaryCount = beanImages.get(1).getSecondaryCount(); if(hasImageProperties) { hasGreaterVibrantPopulation = beanBitFrameSecond.isHasGreaterVibrantPopulation(); resultColor = hasGreaterVibrantPopulation ? beanBitFrameSecond.getVibrantColor() : beanBitFrameSecond.getMutedColor(); switch (frameModel.getColorCombination()) { case VIBRANT_TO_MUTED: if (hasGreaterVibrantPopulation) resultColor = beanBitFrameSecond.getVibrantColor(); else resultColor = beanBitFrameSecond.getMutedColor(); break; case MUTED_TO_VIBRANT: if (hasGreaterVibrantPopulation) resultColor = beanBitFrameSecond.getMutedColor(); else resultColor = beanBitFrameSecond.getVibrantColor(); break; } bindingShadeFour.setThirdImageBgColor(resultColor); bindingShadeFour.setThirdCommentBgColor(Utils.getColorWithTransparency(resultColor, frameModel.getCommentTransparencyPercent())); beanBitFrame3.setMutedColor(beanBitFrameSecond.getMutedColor()); beanBitFrame3.setVibrantColor(beanBitFrameSecond.getVibrantColor()); beanBitFrame3.setHasGreaterVibrantPopulation(hasGreaterVibrantPopulation); beanBitFrame3.setPrimaryCount(beanBitFrameSecond.getPrimaryCount()); beanBitFrame3.setSecondaryCount(beanBitFrameSecond.getSecondaryCount()); beanBitFrame3.setWidth(/*beanShade4.getWidth1()*/beanBitFrameSecond.getWidth()); beanBitFrame3.setHeight(/*beanShade4.getHeight1()*/beanBitFrameSecond.getHeight()); } break; case THIRD: bitmap3 = hasImageProperties ? null : images.get(2); bindingShadeFour.setThirdComment(beanImages.get(2).getImageComment()); imageLink3 = beanImages.get(2).getImageLink(); thirdPrimaryCount = beanImages.get(2).getPrimaryCount(); thirdSecondaryCount = beanImages.get(2).getSecondaryCount(); if(hasImageProperties) { hasGreaterVibrantPopulation = beanBitFrameThird.isHasGreaterVibrantPopulation(); resultColor = hasGreaterVibrantPopulation ? beanBitFrameThird.getVibrantColor() : beanBitFrameThird.getMutedColor(); switch (frameModel.getColorCombination()) { case VIBRANT_TO_MUTED: if (hasGreaterVibrantPopulation) resultColor = beanBitFrameThird.getVibrantColor(); else resultColor = beanBitFrameThird.getMutedColor(); break; case MUTED_TO_VIBRANT: if (hasGreaterVibrantPopulation) resultColor = beanBitFrameThird.getMutedColor(); else resultColor = beanBitFrameThird.getVibrantColor(); break; } bindingShadeFour.setThirdImageBgColor(resultColor); bindingShadeFour.setThirdCommentBgColor(Utils.getColorWithTransparency(resultColor, frameModel.getCommentTransparencyPercent())); beanBitFrame3.setMutedColor(beanBitFrameThird.getMutedColor()); beanBitFrame3.setVibrantColor(beanBitFrameThird.getVibrantColor()); beanBitFrame3.setHasGreaterVibrantPopulation(hasGreaterVibrantPopulation); beanBitFrame3.setPrimaryCount(beanBitFrameThird.getPrimaryCount()); beanBitFrame3.setSecondaryCount(beanBitFrameThird.getSecondaryCount()); beanBitFrame3.setWidth(/*beanShade4.getWidth1()*/beanBitFrameThird.getWidth()); beanBitFrame3.setHeight(/*beanShade4.getHeight1()*/beanBitFrameThird.getHeight()); } break; case FOURTH: bitmap3 = hasImageProperties ? null : images.get(3); bindingShadeFour.setThirdComment(beanImages.get(3).getImageComment()); imageLink3 = beanImages.get(3).getImageLink(); thirdPrimaryCount = beanImages.get(3).getPrimaryCount(); thirdSecondaryCount = beanImages.get(3).getSecondaryCount(); if(hasImageProperties) { hasGreaterVibrantPopulation = beanBitFrameFourth.isHasGreaterVibrantPopulation(); resultColor = hasGreaterVibrantPopulation ? beanBitFrameFourth.getVibrantColor() : beanBitFrameFourth.getMutedColor(); switch (frameModel.getColorCombination()) { case VIBRANT_TO_MUTED: if (hasGreaterVibrantPopulation) resultColor = beanBitFrameFourth.getVibrantColor(); else resultColor = beanBitFrameFourth.getMutedColor(); break; case MUTED_TO_VIBRANT: if (hasGreaterVibrantPopulation) resultColor = beanBitFrameFourth.getMutedColor(); else resultColor = beanBitFrameFourth.getVibrantColor(); break; } bindingShadeFour.setThirdImageBgColor(resultColor); bindingShadeFour.setThirdCommentBgColor(Utils.getColorWithTransparency(resultColor, frameModel.getCommentTransparencyPercent())); beanBitFrame3.setMutedColor(beanBitFrameFourth.getMutedColor()); beanBitFrame3.setVibrantColor(beanBitFrameFourth.getVibrantColor()); beanBitFrame3.setHasGreaterVibrantPopulation(hasGreaterVibrantPopulation); beanBitFrame3.setPrimaryCount(beanBitFrameFourth.getPrimaryCount()); beanBitFrame3.setSecondaryCount(beanBitFrameFourth.getSecondaryCount()); beanBitFrame3.setWidth(/*beanShade4.getWidth1()*/beanBitFrameFourth.getWidth()); beanBitFrame3.setHeight(/*beanShade4.getHeight1()*/beanBitFrameFourth.getHeight()); } break; default: throw new FrameException("invalid image order"); }switch (beanShade4.getImageOrderList().get(3)){ case FIRST: bitmap4 = hasImageProperties ? null : images.get(0); bindingShadeFour.setFourthComment(beanImages.get(0).getImageComment()); imageLink4 = beanImages.get(0).getImageLink(); fourthPrimaryCount = beanImages.get(0).getPrimaryCount(); fourthSecondaryCount = beanImages.get(0).getSecondaryCount(); if(hasImageProperties) { hasGreaterVibrantPopulation = beanBitFrameFirst.isHasGreaterVibrantPopulation(); resultColor = hasGreaterVibrantPopulation ? beanBitFrameFirst.getVibrantColor() : beanBitFrameFirst.getMutedColor(); switch (frameModel.getColorCombination()) { case VIBRANT_TO_MUTED: if (hasGreaterVibrantPopulation) resultColor = beanBitFrameFirst.getVibrantColor(); else resultColor = beanBitFrameFirst.getMutedColor(); break; case MUTED_TO_VIBRANT: if (hasGreaterVibrantPopulation) resultColor = beanBitFrameFirst.getMutedColor(); else resultColor = beanBitFrameFirst.getVibrantColor(); break; } bindingShadeFour.setFourthImageBgColor(resultColor); bindingShadeFour.setFourthCommentBgColor(Utils.getColorWithTransparency(resultColor, frameModel.getCommentTransparencyPercent())); beanBitFrame4.setMutedColor(beanBitFrameFirst.getMutedColor()); beanBitFrame4.setVibrantColor(beanBitFrameFirst.getVibrantColor()); beanBitFrame4.setHasGreaterVibrantPopulation(hasGreaterVibrantPopulation); beanBitFrame4.setPrimaryCount(beanBitFrameFirst.getPrimaryCount()); beanBitFrame4.setSecondaryCount(beanBitFrameFirst.getSecondaryCount()); beanBitFrame4.setWidth(/*beanShade4.getWidth1()*/beanBitFrameFirst.getWidth()); beanBitFrame4.setHeight(/*beanShade4.getHeight1()*/beanBitFrameFirst.getHeight()); } break; case SECOND: bitmap4 = hasImageProperties ? null : images.get(1); bindingShadeFour.setFourthComment(beanImages.get(1).getImageComment()); imageLink4 = beanImages.get(1).getImageLink(); fourthPrimaryCount = beanImages.get(1).getPrimaryCount(); fourthSecondaryCount = beanImages.get(1).getSecondaryCount(); if(hasImageProperties) { hasGreaterVibrantPopulation = beanBitFrameSecond.isHasGreaterVibrantPopulation(); resultColor = hasGreaterVibrantPopulation ? beanBitFrameSecond.getVibrantColor() : beanBitFrameSecond.getMutedColor(); switch (frameModel.getColorCombination()) { case VIBRANT_TO_MUTED: if (hasGreaterVibrantPopulation) resultColor = beanBitFrameSecond.getVibrantColor(); else resultColor = beanBitFrameSecond.getMutedColor(); break; case MUTED_TO_VIBRANT: if (hasGreaterVibrantPopulation) resultColor = beanBitFrameSecond.getMutedColor(); else resultColor = beanBitFrameSecond.getVibrantColor(); break; } bindingShadeFour.setFourthImageBgColor(resultColor); bindingShadeFour.setFourthCommentBgColor(Utils.getColorWithTransparency(resultColor, frameModel.getCommentTransparencyPercent())); beanBitFrame4.setMutedColor(beanBitFrameSecond.getMutedColor()); beanBitFrame4.setVibrantColor(beanBitFrameSecond.getVibrantColor()); beanBitFrame4.setHasGreaterVibrantPopulation(hasGreaterVibrantPopulation); beanBitFrame4.setPrimaryCount(beanBitFrameSecond.getPrimaryCount()); beanBitFrame4.setSecondaryCount(beanBitFrameSecond.getSecondaryCount()); beanBitFrame4.setWidth(/*beanShade4.getWidth1()*/beanBitFrameSecond.getWidth()); beanBitFrame4.setHeight(/*beanShade4.getHeight1()*/beanBitFrameSecond.getHeight()); } break; case THIRD: bitmap4 = hasImageProperties ? null : images.get(2); bindingShadeFour.setFourthComment(beanImages.get(2).getImageComment()); imageLink4 = beanImages.get(2).getImageLink(); fourthPrimaryCount = beanImages.get(2).getPrimaryCount(); fourthSecondaryCount = beanImages.get(2).getSecondaryCount(); if(hasImageProperties) { hasGreaterVibrantPopulation = beanBitFrameThird.isHasGreaterVibrantPopulation(); resultColor = hasGreaterVibrantPopulation ? beanBitFrameThird.getVibrantColor() : beanBitFrameThird.getMutedColor(); switch (frameModel.getColorCombination()) { case VIBRANT_TO_MUTED: if (hasGreaterVibrantPopulation) resultColor = beanBitFrameThird.getVibrantColor(); else resultColor = beanBitFrameThird.getMutedColor(); break; case MUTED_TO_VIBRANT: if (hasGreaterVibrantPopulation) resultColor = beanBitFrameThird.getMutedColor(); else resultColor = beanBitFrameThird.getVibrantColor(); break; } bindingShadeFour.setFourthImageBgColor(resultColor); bindingShadeFour.setFourthCommentBgColor(Utils.getColorWithTransparency(resultColor, frameModel.getCommentTransparencyPercent())); beanBitFrame4.setMutedColor(beanBitFrameThird.getMutedColor()); beanBitFrame4.setVibrantColor(beanBitFrameThird.getVibrantColor()); beanBitFrame4.setHasGreaterVibrantPopulation(hasGreaterVibrantPopulation); beanBitFrame4.setPrimaryCount(beanBitFrameThird.getPrimaryCount()); beanBitFrame4.setSecondaryCount(beanBitFrameThird.getSecondaryCount()); beanBitFrame4.setWidth(/*beanShade4.getWidth1()*/beanBitFrameThird.getWidth()); beanBitFrame4.setHeight(/*beanShade4.getHeight1()*/beanBitFrameThird.getHeight()); } break; case FOURTH: bitmap4 = hasImageProperties ? null : images.get(3); bindingShadeFour.setFourthComment(beanImages.get(3).getImageComment()); imageLink4 = beanImages.get(3).getImageLink(); fourthPrimaryCount = beanImages.get(3).getPrimaryCount(); fourthSecondaryCount = beanImages.get(3).getSecondaryCount(); if(hasImageProperties) { hasGreaterVibrantPopulation = beanBitFrameFourth.isHasGreaterVibrantPopulation(); resultColor = hasGreaterVibrantPopulation ? beanBitFrameFourth.getVibrantColor() : beanBitFrameFourth.getMutedColor(); switch (frameModel.getColorCombination()) { case VIBRANT_TO_MUTED: if (hasGreaterVibrantPopulation) resultColor = beanBitFrameFourth.getVibrantColor(); else resultColor = beanBitFrameFourth.getMutedColor(); break; case MUTED_TO_VIBRANT: if (hasGreaterVibrantPopulation) resultColor = beanBitFrameFourth.getMutedColor(); else resultColor = beanBitFrameFourth.getVibrantColor(); break; } bindingShadeFour.setFourthImageBgColor(resultColor); bindingShadeFour.setFourthCommentBgColor(Utils.getColorWithTransparency(resultColor, frameModel.getCommentTransparencyPercent())); beanBitFrame4.setMutedColor(beanBitFrameFourth.getMutedColor()); beanBitFrame4.setVibrantColor(beanBitFrameFourth.getVibrantColor()); beanBitFrame4.setHasGreaterVibrantPopulation(hasGreaterVibrantPopulation); beanBitFrame4.setPrimaryCount(beanBitFrameFourth.getPrimaryCount()); beanBitFrame4.setSecondaryCount(beanBitFrameFourth.getSecondaryCount()); beanBitFrame4.setWidth(/*beanShade4.getWidth1()*/beanBitFrameFourth.getWidth()); beanBitFrame4.setHeight(/*beanShade4.getHeight1()*/beanBitFrameFourth.getHeight()); } break; default: throw new FrameException("invalid image order"); } final ImageView imageView1 = (ImageView)root.findViewById(R.id.view_multiple_image1); final ImageView imageView2 = (ImageView)root.findViewById(R.id.view_multiple_image2); final ImageView imageView3 = (ImageView)root.findViewById(R.id.view_multiple_image3); final ImageView imageView4 = (ImageView)root.findViewById(R.id.view_multiple_image4); if(totalImages > 4) { bindingShadeFour.setCounterVisibility(true); bindingShadeFour.setCounterText((totalImages - 4 > frameModel.getMaxExtraCount() ? (frameModel.getMaxExtraCount() + "+") : ("+" + (totalImages - 4)))); } BindingShadeFour.setLayoutWidth(imageView1, beanShade4.getWidth1()); BindingShadeFour.setLayoutWidth(imageView2, beanShade4.getWidth2()); BindingShadeFour.setLayoutWidth(imageView3, beanShade4.getWidth3()); BindingShadeFour.setLayoutWidth(imageView4, beanShade4.getWidth4()); BindingShadeFour.setLayoutHeight(imageView1, beanShade4.getHeight1()); BindingShadeFour.setLayoutHeight(imageView2, beanShade4.getHeight2()); BindingShadeFour.setLayoutHeight(imageView3, beanShade4.getHeight3()); BindingShadeFour.setLayoutHeight(imageView4, beanShade4.getHeight4()); bindingShadeFour.setFirstImageScaleType(frameModel.getScaleType()); bindingShadeFour.setSecondImageScaleType(frameModel.getScaleType()); bindingShadeFour.setThirdImageScaleType(frameModel.getScaleType()); bindingShadeFour.setFourthImageScaleType(frameModel.getScaleType()); if(!hasImageProperties) { BindingShadeFour.setBitmap(imageView1, bitmap1); Palette.from(bitmap1).generate(new PaletteListener(0, this)); BindingShadeFour.setBitmap(imageView2, bitmap2); Palette.from(bitmap2).generate(new PaletteListener(1, this)); BindingShadeFour.setBitmap(imageView3, bitmap3); Palette.from(bitmap3).generate(new PaletteListener(2, this)); BindingShadeFour.setBitmap(imageView4, bitmap4); Palette.from(bitmap4).generate(new PaletteListener(3, this)); } bindingShadeFour.setFirstCommentVisibility(frameModel.isShouldShowComment()); bindingShadeFour.setSecondCommentVisibility(frameModel.isShouldShowComment()); bindingShadeFour.setThirdCommentVisibility(frameModel.isShouldShowComment()); bindingShadeFour.setFourthCommentVisibility(frameModel.isShouldShowComment()); //a/c to layout type switch (beanShade4.getLayoutType()){ case VERT: addImageView(root, beanShade4.getWidth1(), beanShade4.getHeight1() + beanShade4.getHeight2(), false); break; case HORZ: addImageView(root, beanShade4.getWidth1() + beanShade4.getWidth2(), beanShade4.getHeight1(), false); break; case VERT_DOUBLE: addImageView(root, beanShade4.getWidth1(), beanShade4.getHeight1() + beanShade4.getHeight2() + beanShade4.getHeight3(), false); break; case HORZ_DOUBLE: addImageView(root, beanShade4.getWidth1() + beanShade4.getWidth2() + beanShade4.getWidth3(), beanShade4.getHeight1(), false); break; case VERT_HORZ: addImageView(root, beanShade4.getWidth1(), beanShade4.getHeight1() + beanShade4.getHeight2(), false); break; case HORZ_VERT: addImageView(root, beanShade4.getWidth1() + beanShade4.getWidth2(), beanShade4.getHeight1(), false); break; case IDENTICAL_VARY_WIDTH: addImageView(root, beanShade4.getWidth1() + beanShade4.getWidth2(), beanShade4.getHeight1() + beanShade4.getHeight3(), false); break; case IDENTICAL_VARY_HEIGHT: addImageView(root, beanShade4.getWidth1() + beanShade4.getWidth3(), beanShade4.getHeight1() + beanShade4.getHeight2(), false); break; default: throw new FrameException("invalid layout type"); } if(!hasImageProperties) { //need to give actual dimensions for future calculations in different devices beanBitFrame1.setWidth(/*beanShade4.getWidth1()*/bitmap1.getWidth()); beanBitFrame1.setHeight(/*beanShade4.getHeight1()*/bitmap1.getHeight()); beanBitFrame2.setWidth(/*beanShade4.getWidth2()*/bitmap2.getWidth()); beanBitFrame2.setHeight(/*beanShade4.getHeight2()*/bitmap3.getHeight()); beanBitFrame3.setWidth(/*beanShade4.getWidth3()*/bitmap3.getWidth()); beanBitFrame3.setHeight(/*beanShade4.getHeight3()*/bitmap3.getHeight()); beanBitFrame4.setWidth(/*beanShade4.getWidth4()*/bitmap4.getWidth()); beanBitFrame4.setHeight(/*beanShade4.getHeight4()*/bitmap4.getHeight()); } beanBitFrame1.setImageLink(imageLink1); beanBitFrame1.setImageComment(bindingShadeFour.getFirstComment()); beanBitFrame1.setPrimaryCount(firstPrimaryCount); beanBitFrame1.setSecondaryCount(firstSecondaryCount); beanBitFrame2.setImageLink(imageLink2); beanBitFrame2.setImageComment(bindingShadeFour.getSecondComment()); beanBitFrame2.setPrimaryCount(secondPrimaryCount); beanBitFrame2.setSecondaryCount(secondSecondaryCount); beanBitFrame3.setImageLink(imageLink3); beanBitFrame3.setImageComment(bindingShadeFour.getThirdComment()); beanBitFrame3.setPrimaryCount(thirdPrimaryCount); beanBitFrame3.setSecondaryCount(thirdSecondaryCount); beanBitFrame4.setImageLink(imageLink4); beanBitFrame4.setImageComment(bindingShadeFour.getFourthComment()); beanBitFrame4.setPrimaryCount(fourthPrimaryCount); beanBitFrame4.setSecondaryCount(fourthSecondaryCount); if(hasImageProperties){ int mixedColor = Utils.getMixedArgbColor(bindingShadeFour.getFirstImageBgColor(), bindingShadeFour.getSecondImageBgColor(), bindingShadeFour.getThirdImageBgColor(), bindingShadeFour.getFourthImageBgColor()); int inverseColor = Utils.getInverseColor(mixedColor); setColorsToAddMoreView(bindingShadeFour.getFourthImageBgColor(), mixedColor, inverseColor); frameResult(beanBitFrame1, beanBitFrame2, beanBitFrame3, beanBitFrame4); //bindingShadeThree.setDividerVisible(Utils.showShowDivider()); bindingShadeFour.setDividerColor(inverseColor); final Picasso picasso = getCurrentFramePicasso(); //need to notify ImageShading too, to load image via picasso Utils.logVerbose("IMAGE_LOADING : "+" going to load four image"); if(frameModel.isShouldStoreImages()){ Utils.getPicassoRequestCreator(picasso, imageLink1).fit().centerInside().noPlaceholder().into(imageView1, new Callback() { @Override public void onSuccess() { //do nothing Utils.logVerbose("IMAGE_LOADING success"); } @Override public void onError() { Utils.logVerbose("IMAGE_LOADING error"); Utils.getPicassoRequestCreator(picasso, imageLink1+"?"+System.currentTimeMillis()).fit().centerInside().noPlaceholder().into(imageView1); } }); Utils.getPicassoRequestCreator(picasso, imageLink2).fit().centerInside().noPlaceholder().into(imageView2, new Callback() { @Override public void onSuccess() { //do nothing Utils.logVerbose("IMAGE_LOADING success"); } @Override public void onError() { Utils.logVerbose("IMAGE_LOADING error"); Utils.getPicassoRequestCreator(picasso, imageLink2+"?"+System.currentTimeMillis()).fit().centerInside().noPlaceholder().into(imageView2); } }); Utils.getPicassoRequestCreator(picasso, imageLink3).fit().centerInside().noPlaceholder().into(imageView3, new Callback() { @Override public void onSuccess() { //do nothing Utils.logVerbose("IMAGE_LOADING success"); } @Override public void onError() { Utils.logVerbose("IMAGE_LOADING error"); Utils.getPicassoRequestCreator(picasso, imageLink3+"?"+System.currentTimeMillis()).fit().centerInside().noPlaceholder().into(imageView3); } }); Utils.getPicassoRequestCreator(picasso, imageLink4).fit().centerInside().noPlaceholder().into(imageView4, new Callback() { @Override public void onSuccess() { //do nothing Utils.logVerbose("IMAGE_LOADING success"); } @Override public void onError() { Utils.logVerbose("IMAGE_LOADING error"); Utils.getPicassoRequestCreator(picasso, imageLink4+"?"+System.currentTimeMillis()).fit().centerInside().noPlaceholder().into(imageView4); } }); }else { Utils.getPicassoRequestCreator(picasso, imageLink1).memoryPolicy(MemoryPolicy.NO_STORE) .networkPolicy(NetworkPolicy.NO_STORE).fit().centerInside().noPlaceholder().into(imageView1, new Callback() { @Override public void onSuccess() { //do nothing Utils.logVerbose("IMAGE_LOADING success"); } @Override public void onError() { Utils.logVerbose("IMAGE_LOADING error"); Utils.getPicassoRequestCreator(picasso, imageLink1+"?"+System.currentTimeMillis()).memoryPolicy(MemoryPolicy.NO_STORE) .networkPolicy(NetworkPolicy.NO_STORE).fit().centerInside().noPlaceholder().into(imageView1); } }); Utils.getPicassoRequestCreator(picasso, imageLink2).memoryPolicy(MemoryPolicy.NO_STORE) .networkPolicy(NetworkPolicy.NO_STORE).fit().centerInside().noPlaceholder().into(imageView2, new Callback() { @Override public void onSuccess() { //do nothing Utils.logVerbose("IMAGE_LOADING success"); } @Override public void onError() { Utils.logVerbose("IMAGE_LOADING error"); Utils.getPicassoRequestCreator(picasso, imageLink2+"?"+System.currentTimeMillis()).memoryPolicy(MemoryPolicy.NO_STORE) .networkPolicy(NetworkPolicy.NO_STORE).fit().centerInside().noPlaceholder().into(imageView2); } }); Utils.getPicassoRequestCreator(picasso, imageLink3).memoryPolicy(MemoryPolicy.NO_STORE) .networkPolicy(NetworkPolicy.NO_STORE).fit().centerInside().noPlaceholder().into(imageView3, new Callback() { @Override public void onSuccess() { //do nothing Utils.logVerbose("IMAGE_LOADING success"); } @Override public void onError() { Utils.logVerbose("IMAGE_LOADING error"); Utils.getPicassoRequestCreator(picasso, imageLink3+"?"+System.currentTimeMillis()).memoryPolicy(MemoryPolicy.NO_STORE) .networkPolicy(NetworkPolicy.NO_STORE).fit().centerInside().noPlaceholder().into(imageView3); } }); Utils.getPicassoRequestCreator(picasso, imageLink4).memoryPolicy(MemoryPolicy.NO_STORE) .networkPolicy(NetworkPolicy.NO_STORE).fit().centerInside().noPlaceholder().into(imageView4, new Callback() { @Override public void onSuccess() { //do nothing Utils.logVerbose("IMAGE_LOADING success"); } @Override public void onError() { Utils.logVerbose("IMAGE_LOADING error"); Utils.getPicassoRequestCreator(picasso, imageLink4+"?"+System.currentTimeMillis()).memoryPolicy(MemoryPolicy.NO_STORE) .networkPolicy(NetworkPolicy.NO_STORE).fit().centerInside().noPlaceholder().into(imageView4); } }); } } } @Override protected void onPaletteGenerated(Palette palette, int viewId) throws FrameException { int defaultColor = Color.parseColor("#ffffffff"); int resultColor = 0; Palette.Swatch vibrantSwatch = palette.getVibrantSwatch(); Palette.Swatch mutedSwatch = palette.getMutedSwatch(); int vibrantPopulation = vibrantSwatch == null ? 0 : vibrantSwatch.getPopulation(); int mutedPopulation = mutedSwatch == null ? 0 : mutedSwatch.getPopulation(); int vibrantColor = palette.getVibrantColor(defaultColor); int mutedColor = palette.getMutedColor(defaultColor); boolean hasGreaterVibrantPopulation = vibrantPopulation > mutedPopulation; switch(frameModel.getColorCombination()){ case VIBRANT_TO_MUTED: if(hasGreaterVibrantPopulation && vibrantColor > 0) resultColor = vibrantColor; else resultColor = mutedColor; break; case MUTED_TO_VIBRANT: if(hasGreaterVibrantPopulation && mutedColor > 0) resultColor = mutedColor; else resultColor = vibrantColor; break; default: throw new FrameException("could not found color combination"); } Utils.logMessage("vibrant pop = "+vibrantPopulation+" muted pop"+mutedPopulation); switch(viewId){ case 0: bindingShadeFour.setFirstImageBgColor(resultColor); bindingShadeFour.setFirstCommentBgColor(Utils.getColorWithTransparency(resultColor, frameModel.getCommentTransparencyPercent())); beanBitFrame1.setMutedColor(mutedColor); beanBitFrame1.setVibrantColor(vibrantColor); beanBitFrame1.setHasGreaterVibrantPopulation(hasGreaterVibrantPopulation); break; case 1: bindingShadeFour.setSecondImageBgColor(resultColor); bindingShadeFour.setSecondCommentBgColor(Utils.getColorWithTransparency(resultColor, frameModel.getCommentTransparencyPercent())); beanBitFrame2.setMutedColor(mutedColor); beanBitFrame2.setVibrantColor(vibrantColor); beanBitFrame2.setHasGreaterVibrantPopulation(hasGreaterVibrantPopulation); break; case 2: bindingShadeFour.setThirdImageBgColor(resultColor); bindingShadeFour.setThirdCommentBgColor(Utils.getColorWithTransparency(resultColor, frameModel.getCommentTransparencyPercent())); beanBitFrame3.setMutedColor(mutedColor); beanBitFrame3.setVibrantColor(vibrantColor); beanBitFrame3.setHasGreaterVibrantPopulation(hasGreaterVibrantPopulation); break; case 3: bindingShadeFour.setFourthImageBgColor(resultColor); bindingShadeFour.setFourthCommentBgColor(Utils.getColorWithTransparency(resultColor, frameModel.getCommentTransparencyPercent())); beanBitFrame4.setMutedColor(mutedColor); beanBitFrame4.setVibrantColor(vibrantColor); beanBitFrame4.setHasGreaterVibrantPopulation(hasGreaterVibrantPopulation); break; default: throw new FrameException("invalid view counter"); } ImageShadingFour.this.resultColor[viewId] = resultColor; if(ImageShadingFour.this.resultColor[0] == 0 || ImageShadingFour.this.resultColor[1] == 0 || ImageShadingFour.this.resultColor[2] == 0 || ImageShadingFour.this.resultColor[3] == 0) return; int mixedColor = Utils.getMixedArgbColor(ImageShadingFour.this.resultColor); beanBitFrame1.setMutedColor(beanBitFrame1.getMutedColor() <= 0 ? mixedColor : beanBitFrame1.getMutedColor()); beanBitFrame1.setVibrantColor(beanBitFrame1.getVibrantColor() <= 0 ? mixedColor : beanBitFrame1.getVibrantColor()); beanBitFrame2.setMutedColor(beanBitFrame2.getMutedColor() <= 0 ? mixedColor : beanBitFrame2.getMutedColor()); beanBitFrame2.setVibrantColor(beanBitFrame2.getVibrantColor() <= 0 ? mixedColor : beanBitFrame2.getVibrantColor()); beanBitFrame3.setMutedColor(beanBitFrame3.getMutedColor() <= 0 ? mixedColor : beanBitFrame3.getMutedColor()); beanBitFrame3.setVibrantColor(beanBitFrame3.getVibrantColor() <= 0 ? mixedColor : beanBitFrame3.getVibrantColor()); beanBitFrame4.setMutedColor(beanBitFrame4.getMutedColor() <= 0 ? mixedColor : beanBitFrame4.getMutedColor()); beanBitFrame4.setVibrantColor(beanBitFrame4.getVibrantColor() <= 0 ? mixedColor : beanBitFrame4.getVibrantColor()); int inverseColor = Utils.getInverseColor(mixedColor); setColorsToAddMoreView(resultColor, mixedColor, inverseColor); frameResult(beanBitFrame1, beanBitFrame2, beanBitFrame3, beanBitFrame4); //bindingShadeFour.setDividerVisible(Utils.showShowDivider()); bindingShadeFour.setDividerColor(inverseColor); } @Override public void onImageShadeClick(View view) { switch((String)view.getTag()){ case "img1": imageClicked(ImageType.VIEW_MULTIPLE_1, 1, imageLink1); break; case "img2": imageClicked(ImageType.VIEW_MULTIPLE_1, 2, imageLink2); break; case "img3": imageClicked(ImageType.VIEW_MULTIPLE_1, 3, imageLink3); break; case "img4": imageClicked(ImageType.VIEW_MULTIPLE_1, 4, imageLink4); break; } } }
apache-2.0
wendal/NutzCN-Material-Design
android-image-picker-master/src/main/java/com/wgs/picker/framework/LocalImageLoader.java
6335
package com.wgs.picker.framework; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.LruCache; import android.widget.ImageView; import java.lang.ref.SoftReference; import java.util.LinkedList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Created by w.gs on 2015/7/17. */ public class LocalImageLoader { /** * 任务队列 **/ private final LinkedList<LoadImageTask> mTask = new LinkedList<>(); /** * 内存缓存 **/ private LruCache<String, SoftReference<Bitmap>> mLruCache; /** * 线程池 **/ private ExecutorService mExecutorService; private static LocalImageLoader instance = new LocalImageLoader(); private LocalImageLoader() { mExecutorService = Executors.newFixedThreadPool(1); // 获取应用程序最大可用内存 int maxMemory = (int) Runtime.getRuntime().maxMemory(); int cacheSize = maxMemory / 8; mLruCache = new LruCache<String, SoftReference<Bitmap>>(cacheSize) { protected int sizeOf(String key, Bitmap value) { return value.getRowBytes() * value.getHeight(); } }; mExecutor.start(); } public static LocalImageLoader getInstance() { return instance; } private Thread mExecutor = new Thread() { public void run() { while (true) { while (mTask.size() > 0) { LoadImageTask task = getTask(); ImageView view = task.view; int width = view.getWidth(); int height = view.getHeight(); if (width == 0 || height == 0) { //这里的大小设置仅适配该图片选择器 非通用设置 width = Density.getSceenWidth(view.getContext()) / 3; height = width; } Bitmap bitmap = decodeSampledBitmapFromResource(task.url, width, height); if (bitmap != null) { mLruCache.put(task.url, new SoftReference<Bitmap>(bitmap)); task.onFinished(bitmap); } } synchronized (this) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } }; private LoadImageTask getTask() { //任务队列只保存最近30条任务 之前的任务丢弃 while (mTask.size() > 30) { mTask.removeFirst(); } return mTask.removeFirst(); } public void displayImage(final String url, final ImageView view) { view.setTag(url); SoftReference<Bitmap> softReference = mLruCache.get(url); final Bitmap bitmap = softReference == null ? null : softReference.get(); if (bitmap != null) { view.post(new Runnable() { public void run() { if (view.getTag().equals(url)) view.setImageBitmap(bitmap); } }); } else { LoadImageTask task = new LoadImageTask(url, view); if (!mTask.contains(task)) { mTask.add(task); } synchronized (mExecutor) { mExecutor.notify(); } } } public void displayImage(final String url, final ImageView view, int default_img) { view.setImageResource(default_img); displayImage(url, view); } public void displaySingleImage(final String path, final ImageView view, final int width, final int height) { new Thread() { public void run() { final Bitmap bitmap = decodeSampledBitmapFromResource(path, width, height); view.post(new Runnable() { public void run() { view.setImageBitmap(bitmap); } }); } }.start(); } class LoadImageTask { public LoadImageTask(String url, ImageView view) { this.url = url; this.view = view; } ImageView view; String url; public void onFinished(final Bitmap bitmap) { view.post(new Runnable() { public void run() { if (url.equals(view.getTag())) { view.setImageBitmap(bitmap); } } }); } public boolean equals(Object o) { LoadImageTask task = (LoadImageTask) o; return url.equals(task.url); } } /** * 根据计算的inSampleSize,得到压缩后图片 **/ private Bitmap decodeSampledBitmapFromResource(String pathName, int reqWidth, int reqHeight) { // 第一次解析将inJustDecodeBounds设置为true,来获取图片大小 final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(pathName, options); // 调用上面定义的方法计算inSampleSize值 options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // 使用获取到的inSampleSize值再次解析图片 options.inJustDecodeBounds = false; Bitmap bitmap = BitmapFactory.decodeFile(pathName, options); return bitmap; } /** * 计算inSampleSize,用于压缩图片 **/ private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { // 源图片的宽度 int width = options.outWidth; int height = options.outHeight; int inSampleSize = 1; if (width > reqWidth && height > reqHeight) { // 计算出实际宽度和目标宽度的比率 int widthRatio = Math.round((float) width / (float) reqWidth); int heightRatio = Math.round((float) width / (float) reqWidth); inSampleSize = Math.max(widthRatio, heightRatio); } return inSampleSize; } }
apache-2.0
Myasuka/systemml
system-ml/src/test/java/com/ibm/bi/dml/test/integration/functions/binary/matrix_full_other/FullPPredMatrixTest.java
13435
/** * (C) Copyright IBM Corp. 2010, 2015 * * 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.ibm.bi.dml.test.integration.functions.binary.matrix_full_other; import java.util.HashMap; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.ibm.bi.dml.api.DMLScript; import com.ibm.bi.dml.api.DMLScript.RUNTIME_PLATFORM; import com.ibm.bi.dml.lops.LopProperties.ExecType; import com.ibm.bi.dml.runtime.matrix.data.MatrixValue.CellIndex; import com.ibm.bi.dml.test.integration.AutomatedTestBase; import com.ibm.bi.dml.test.integration.TestConfiguration; import com.ibm.bi.dml.test.utils.TestUtils; /** * The main purpose of this test is to verify various input combinations for * matrix-matrix ppred operations that internally translate to binary operations. * */ public class FullPPredMatrixTest extends AutomatedTestBase { private final static String TEST_NAME1 = "PPredMatrixTest"; private final static String TEST_DIR = "functions/binary/matrix_full_other/"; private final static String TEST_CLASS_DIR = TEST_DIR + FullPPredMatrixTest.class.getSimpleName() + "/"; private final static double eps = 1e-10; private final static int rows1 = 1383; private final static int cols1 = 1432; private final static double sparsity1 = 0.7; private final static double sparsity2 = 0.01; public enum Type{ GREATER, LESS, EQUALS, NOT_EQUALS, GREATER_EQUALS, LESS_EQUALS, } @Override public void setUp() { addTestConfiguration( TEST_NAME1, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME1, new String[] { "C" }) ); TestUtils.clearAssertionInformation(); if (TEST_CACHE_ENABLED) { setOutAndExpectedDeletionDisabled(true); } } @BeforeClass public static void init() { TestUtils.clearDirectory(TEST_DATA_DIR + TEST_CLASS_DIR); } @AfterClass public static void cleanUp() { if (TEST_CACHE_ENABLED) { TestUtils.clearDirectory(TEST_DATA_DIR + TEST_CLASS_DIR); } } @Test public void testPPredGreaterDenseDenseCP() { runPPredTest(Type.GREATER, false, false, ExecType.CP); } @Test public void testPPredGreaterDenseSparseCP() { runPPredTest(Type.GREATER, false, true, ExecType.CP); } @Test public void testPPredGreaterSparseDenseCP() { runPPredTest(Type.GREATER, true, false, ExecType.CP); } @Test public void testPPredGreaterSparseSparseCP() { runPPredTest(Type.GREATER, true, true, ExecType.CP); } @Test public void testPPredGreaterEqualsDenseDenseCP() { runPPredTest(Type.GREATER_EQUALS, false, false, ExecType.CP); } @Test public void testPPredGreaterEqualsDenseSparseCP() { runPPredTest(Type.GREATER_EQUALS, false, true, ExecType.CP); } @Test public void testPPredGreaterEqualsSparseDenseCP() { runPPredTest(Type.GREATER_EQUALS, true, false, ExecType.CP); } @Test public void testPPredGreaterEqualsSparseSparseCP() { runPPredTest(Type.GREATER_EQUALS, true, true, ExecType.CP); } @Test public void testPPredEqualsDenseDenseCP() { runPPredTest(Type.EQUALS, false, false, ExecType.CP); } @Test public void testPPredEqualsDenseSparseCP() { runPPredTest(Type.EQUALS, false, true, ExecType.CP); } @Test public void testPPredEqualsSparseDenseCP() { runPPredTest(Type.EQUALS, true, false, ExecType.CP); } @Test public void testPPredEqualsSparseSparseCP() { runPPredTest(Type.EQUALS, true, true, ExecType.CP); } @Test public void testPPredNotEqualsDenseDenseCP() { runPPredTest(Type.NOT_EQUALS, false, false, ExecType.CP); } @Test public void testPPredNotEqualsDenseSparseCP() { runPPredTest(Type.NOT_EQUALS, false, true, ExecType.CP); } @Test public void testPPredNotEqualsSparseDenseCP() { runPPredTest(Type.NOT_EQUALS, true, false, ExecType.CP); } @Test public void testPPredNotEqualsSparseSparseCP() { runPPredTest(Type.NOT_EQUALS, true, true, ExecType.CP); } @Test public void testPPredLessDenseDenseCP() { runPPredTest(Type.LESS, false, false, ExecType.CP); } @Test public void testPPredLessDenseSparseCP() { runPPredTest(Type.LESS, false, true, ExecType.CP); } @Test public void testPPredLessSparseDenseCP() { runPPredTest(Type.LESS, true, false, ExecType.CP); } @Test public void testPPredLessSparseSparseCP() { runPPredTest(Type.LESS, true, true, ExecType.CP); } @Test public void testPPredLessEqualsDenseDenseCP() { runPPredTest(Type.LESS_EQUALS, false, false, ExecType.CP); } @Test public void testPPredLessEqualsDenseSparseCP() { runPPredTest(Type.LESS_EQUALS, false, true, ExecType.CP); } @Test public void testPPredLessEqualsSparseDenseCP() { runPPredTest(Type.LESS_EQUALS, true, false, ExecType.CP); } @Test public void testPPredLessEqualsSparseSparseCP() { runPPredTest(Type.LESS_EQUALS, true, true, ExecType.CP); } // ------------------------ @Test public void testPPredGreaterDenseDenseSP() { runPPredTest(Type.GREATER, false, false, ExecType.SPARK); } @Test public void testPPredGreaterDenseSparseSP() { runPPredTest(Type.GREATER, false, true, ExecType.SPARK); } @Test public void testPPredGreaterSparseDenseSP() { runPPredTest(Type.GREATER, true, false, ExecType.SPARK); } @Test public void testPPredGreaterSparseSparseSP() { runPPredTest(Type.GREATER, true, true, ExecType.SPARK); } @Test public void testPPredGreaterEqualsDenseDenseSP() { runPPredTest(Type.GREATER_EQUALS, false, false, ExecType.SPARK); } @Test public void testPPredGreaterEqualsDenseSparseSP() { runPPredTest(Type.GREATER_EQUALS, false, true, ExecType.SPARK); } @Test public void testPPredGreaterEqualsSparseDenseSP() { runPPredTest(Type.GREATER_EQUALS, true, false, ExecType.SPARK); } @Test public void testPPredGreaterEqualsSparseSparseSP() { runPPredTest(Type.GREATER_EQUALS, true, true, ExecType.SPARK); } @Test public void testPPredEqualsDenseDenseSP() { runPPredTest(Type.EQUALS, false, false, ExecType.SPARK); } @Test public void testPPredEqualsDenseSparseSP() { runPPredTest(Type.EQUALS, false, true, ExecType.SPARK); } @Test public void testPPredEqualsSparseDenseSP() { runPPredTest(Type.EQUALS, true, false, ExecType.SPARK); } @Test public void testPPredEqualsSparseSparseSP() { runPPredTest(Type.EQUALS, true, true, ExecType.SPARK); } @Test public void testPPredNotEqualsDenseDenseSP() { runPPredTest(Type.NOT_EQUALS, false, false, ExecType.SPARK); } @Test public void testPPredNotEqualsDenseSparseSP() { runPPredTest(Type.NOT_EQUALS, false, true, ExecType.SPARK); } @Test public void testPPredNotEqualsSparseDenseSP() { runPPredTest(Type.NOT_EQUALS, true, false, ExecType.SPARK); } @Test public void testPPredNotEqualsSparseSparseSP() { runPPredTest(Type.NOT_EQUALS, true, true, ExecType.SPARK); } @Test public void testPPredLessDenseDenseSP() { runPPredTest(Type.LESS, false, false, ExecType.SPARK); } @Test public void testPPredLessDenseSparseSP() { runPPredTest(Type.LESS, false, true, ExecType.SPARK); } @Test public void testPPredLessSparseDenseSP() { runPPredTest(Type.LESS, true, false, ExecType.SPARK); } @Test public void testPPredLessSparseSparseSP() { runPPredTest(Type.LESS, true, true, ExecType.SPARK); } @Test public void testPPredLessEqualsDenseDenseSP() { runPPredTest(Type.LESS_EQUALS, false, false, ExecType.SPARK); } @Test public void testPPredLessEqualsDenseSparseSP() { runPPredTest(Type.LESS_EQUALS, false, true, ExecType.SPARK); } @Test public void testPPredLessEqualsSparseDenseSP() { runPPredTest(Type.LESS_EQUALS, true, false, ExecType.SPARK); } @Test public void testPPredLessEqualsSparseSparseSP() { runPPredTest(Type.LESS_EQUALS, true, true, ExecType.SPARK); } // ---------------------- @Test public void testPPredGreaterDenseDenseMR() { runPPredTest(Type.GREATER, false, false, ExecType.MR); } @Test public void testPPredGreaterDenseSparseMR() { runPPredTest(Type.GREATER, false, true, ExecType.MR); } @Test public void testPPredGreaterSparseDenseMR() { runPPredTest(Type.GREATER, true, false, ExecType.MR); } @Test public void testPPredGreaterSparseSparseMR() { runPPredTest(Type.GREATER, true, true, ExecType.MR); } @Test public void testPPredGreaterEqualsDenseDenseMR() { runPPredTest(Type.GREATER_EQUALS, false, false, ExecType.MR); } @Test public void testPPredGreaterEqualsDenseSparseMR() { runPPredTest(Type.GREATER_EQUALS, false, true, ExecType.MR); } @Test public void testPPredGreaterEqualsSparseDenseMR() { runPPredTest(Type.GREATER_EQUALS, true, false, ExecType.MR); } @Test public void testPPredGreaterEqualsSparseSparseMR() { runPPredTest(Type.GREATER_EQUALS, true, true, ExecType.MR); } @Test public void testPPredEqualsDenseDenseMR() { runPPredTest(Type.EQUALS, false, false, ExecType.MR); } @Test public void testPPredEqualsDenseSparseMR() { runPPredTest(Type.EQUALS, false, true, ExecType.MR); } @Test public void testPPredEqualsSparseDenseMR() { runPPredTest(Type.EQUALS, true, false, ExecType.MR); } @Test public void testPPredEqualsSparseSparseMR() { runPPredTest(Type.EQUALS, true, true, ExecType.MR); } @Test public void testPPredNotEqualsDenseDenseMR() { runPPredTest(Type.NOT_EQUALS, false, false, ExecType.MR); } @Test public void testPPredNotEqualsDenseSparseMR() { runPPredTest(Type.NOT_EQUALS, false, true, ExecType.MR); } @Test public void testPPredNotEqualsSparseDenseMR() { runPPredTest(Type.NOT_EQUALS, true, false, ExecType.MR); } @Test public void testPPredNotEqualsSparseSparseMR() { runPPredTest(Type.NOT_EQUALS, true, true, ExecType.MR); } @Test public void testPPredLessDenseDenseMR() { runPPredTest(Type.LESS, false, false, ExecType.MR); } @Test public void testPPredLessDenseSparseMR() { runPPredTest(Type.LESS, false, true, ExecType.MR); } @Test public void testPPredLessSparseDenseMR() { runPPredTest(Type.LESS, true, false, ExecType.MR); } @Test public void testPPredLessSparseSparseMR() { runPPredTest(Type.LESS, true, true, ExecType.MR); } @Test public void testPPredLessEqualsDenseDenseMR() { runPPredTest(Type.LESS_EQUALS, false, false, ExecType.MR); } @Test public void testPPredLessEqualsDenseSparseMR() { runPPredTest(Type.LESS_EQUALS, false, true, ExecType.MR); } @Test public void testPPredLessEqualsSparseDenseMR() { runPPredTest(Type.LESS_EQUALS, true, false, ExecType.MR); } @Test public void testPPredLessEqualsSparseSparseMR() { runPPredTest(Type.LESS_EQUALS, true, true, ExecType.MR); } /** * * @param type * @param instType * @param sparse */ private void runPPredTest( Type type, boolean sp1, boolean sp2, ExecType et ) { String TEST_NAME = TEST_NAME1; int rows = rows1; int cols = cols1; RUNTIME_PLATFORM platformOld = rtplatform; switch( et ){ case MR: rtplatform = RUNTIME_PLATFORM.HADOOP; break; case SPARK: rtplatform = RUNTIME_PLATFORM.SPARK; break; default: rtplatform = RUNTIME_PLATFORM.HYBRID; break; } boolean sparkConfigOld = DMLScript.USE_LOCAL_SPARK_CONFIG; if( rtplatform == RUNTIME_PLATFORM.SPARK ) DMLScript.USE_LOCAL_SPARK_CONFIG = true; double sparsityLeft = sp1 ? sparsity2 : sparsity1; double sparsityRight = sp2 ? sparsity2 : sparsity1; String TEST_CACHE_DIR = ""; if (TEST_CACHE_ENABLED) { TEST_CACHE_DIR = type.ordinal() + "_" + rows + "_" + cols + "_" + sparsityLeft + "_" + sparsityRight + "/"; } try { TestConfiguration config = getTestConfiguration(TEST_NAME); loadTestConfiguration(config, TEST_CACHE_DIR); /* This is for running the junit test the new way, i.e., construct the arguments directly */ String HOME = SCRIPT_DIR + TEST_DIR; fullDMLScriptName = HOME + TEST_NAME + ".dml"; programArgs = new String[]{"-args", input("A"), input("B"), Integer.toString(type.ordinal()), output("C") }; fullRScriptName = HOME + TEST_NAME + ".R"; rCmd = "Rscript" + " " + fullRScriptName + " " + inputDir() + " " + type.ordinal() + " " + expectedDir(); //generate actual dataset double[][] A = getRandomMatrix(rows, cols, -10, 10, sparsityLeft, 7); writeInputMatrixWithMTD("A", A, true); double[][] B = getRandomMatrix(rows, cols, -15, 15, sparsityRight, 3); writeInputMatrixWithMTD("B", B, true); //run tests runTest(true, false, null, -1); runRScript(true); //compare matrices HashMap<CellIndex, Double> dmlfile = readDMLMatrixFromHDFS("C"); HashMap<CellIndex, Double> rfile = readRMatrixFromFS("C"); TestUtils.compareMatrices(dmlfile, rfile, eps, "Stat-DML", "Stat-R"); } finally { rtplatform = platformOld; DMLScript.USE_LOCAL_SPARK_CONFIG = sparkConfigOld; } } }
apache-2.0
googleads/google-ads-java
google-ads-stubs-v10/src/main/java/com/google/ads/googleads/v10/services/CampaignFeedServiceSettings.java
7292
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.ads.googleads.v10.services; import com.google.ads.googleads.v10.services.stub.CampaignFeedServiceStubSettings; import com.google.api.core.ApiFunction; import com.google.api.core.BetaApi; import com.google.api.gax.core.GoogleCredentialsProvider; import com.google.api.gax.core.InstantiatingExecutorProvider; import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider; import com.google.api.gax.rpc.ApiClientHeaderProvider; import com.google.api.gax.rpc.ClientContext; import com.google.api.gax.rpc.ClientSettings; import com.google.api.gax.rpc.StubSettings; import com.google.api.gax.rpc.TransportChannelProvider; import com.google.api.gax.rpc.UnaryCallSettings; import java.io.IOException; import java.util.List; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * Settings class to configure an instance of {@link CampaignFeedServiceClient}. * * <p>The default instance has everything set to sensible defaults: * * <ul> * <li> The default service address (googleads.googleapis.com) and default port (443) are used. * <li> Credentials are acquired automatically through Application Default Credentials. * <li> Retries are configured for idempotent methods but not for non-idempotent methods. * </ul> * * <p>The builder of this class is recursive, so contained classes are themselves builders. When * build() is called, the tree of builders is called to create the complete settings object. * * <p>For example, to set the total timeout of mutateCampaignFeeds to 30 seconds: * * <pre>{@code * CampaignFeedServiceSettings.Builder campaignFeedServiceSettingsBuilder = * CampaignFeedServiceSettings.newBuilder(); * campaignFeedServiceSettingsBuilder * .mutateCampaignFeedsSettings() * .setRetrySettings( * campaignFeedServiceSettingsBuilder * .mutateCampaignFeedsSettings() * .getRetrySettings() * .toBuilder() * .setTotalTimeout(Duration.ofSeconds(30)) * .build()); * CampaignFeedServiceSettings campaignFeedServiceSettings = * campaignFeedServiceSettingsBuilder.build(); * }</pre> */ @Generated("by gapic-generator-java") public class CampaignFeedServiceSettings extends ClientSettings<CampaignFeedServiceSettings> { /** Returns the object with the settings used for calls to mutateCampaignFeeds. */ public UnaryCallSettings<MutateCampaignFeedsRequest, MutateCampaignFeedsResponse> mutateCampaignFeedsSettings() { return ((CampaignFeedServiceStubSettings) getStubSettings()).mutateCampaignFeedsSettings(); } public static final CampaignFeedServiceSettings create(CampaignFeedServiceStubSettings stub) throws IOException { return new CampaignFeedServiceSettings.Builder(stub.toBuilder()).build(); } /** Returns a builder for the default ExecutorProvider for this service. */ public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { return CampaignFeedServiceStubSettings.defaultExecutorProviderBuilder(); } /** Returns the default service endpoint. */ public static String getDefaultEndpoint() { return CampaignFeedServiceStubSettings.getDefaultEndpoint(); } /** Returns the default service scopes. */ public static List<String> getDefaultServiceScopes() { return CampaignFeedServiceStubSettings.getDefaultServiceScopes(); } /** Returns a builder for the default credentials for this service. */ public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { return CampaignFeedServiceStubSettings.defaultCredentialsProviderBuilder(); } /** Returns a builder for the default ChannelProvider for this service. */ public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() { return CampaignFeedServiceStubSettings.defaultGrpcTransportProviderBuilder(); } public static TransportChannelProvider defaultTransportChannelProvider() { return CampaignFeedServiceStubSettings.defaultTransportChannelProvider(); } @BetaApi("The surface for customizing headers is not stable yet and may change in the future.") public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { return CampaignFeedServiceStubSettings.defaultApiClientHeaderProviderBuilder(); } /** Returns a new builder for this class. */ public static Builder newBuilder() { return Builder.createDefault(); } /** Returns a new builder for this class. */ public static Builder newBuilder(ClientContext clientContext) { return new Builder(clientContext); } /** Returns a builder containing all the values of this settings class. */ public Builder toBuilder() { return new Builder(this); } protected CampaignFeedServiceSettings(Builder settingsBuilder) throws IOException { super(settingsBuilder); } /** Builder for CampaignFeedServiceSettings. */ public static class Builder extends ClientSettings.Builder<CampaignFeedServiceSettings, Builder> { protected Builder() throws IOException { this(((ClientContext) null)); } protected Builder(ClientContext clientContext) { super(CampaignFeedServiceStubSettings.newBuilder(clientContext)); } protected Builder(CampaignFeedServiceSettings settings) { super(settings.getStubSettings().toBuilder()); } protected Builder(CampaignFeedServiceStubSettings.Builder stubSettings) { super(stubSettings); } private static Builder createDefault() { return new Builder(CampaignFeedServiceStubSettings.newBuilder()); } public CampaignFeedServiceStubSettings.Builder getStubSettingsBuilder() { return ((CampaignFeedServiceStubSettings.Builder) getStubSettings()); } /** * Applies the given settings updater function to all of the unary API methods in this service. * * <p>Note: This method does not support applying settings to streaming methods. */ public Builder applyToAllUnaryMethods( ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) { super.applyToAllUnaryMethods( getStubSettingsBuilder().unaryMethodSettingsBuilders(), settingsUpdater); return this; } /** Returns the builder for the settings used for calls to mutateCampaignFeeds. */ public UnaryCallSettings.Builder<MutateCampaignFeedsRequest, MutateCampaignFeedsResponse> mutateCampaignFeedsSettings() { return getStubSettingsBuilder().mutateCampaignFeedsSettings(); } @Override public CampaignFeedServiceSettings build() throws IOException { return new CampaignFeedServiceSettings(this); } } }
apache-2.0
dreedyman/Rio
rio-lib/src/test/java/org/rioproject/impl/associations/AssociationCollectionTest.java
6448
/* * Copyright to the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.rioproject.impl.associations; import org.junit.Assert; import net.jini.core.lookup.ServiceItem; import org.junit.Test; import org.rioproject.associations.Association; import org.rioproject.associations.AssociationDescriptor; import org.rioproject.impl.associations.DefaultAssociation; import java.util.*; /** * Tests adding, removing and iterating over collection of associated services */ public class AssociationCollectionTest { @Test public void testAdd() { Association<Dummy> a = new DefaultAssociation<Dummy>(new AssociationDescriptor()); for(int i=0; i<10; i++) a.addServiceItem(AssociationUtils.makeServiceItem(i)); Assert.assertEquals("Should have 10 associated services", 10, a.getServiceCount()); int i=0; for(Dummy d : a.getServices()) { Assert.assertEquals(i, d.getIndex()); i++; } } @Test public void testAddRemove() { Association<Dummy> a = new DefaultAssociation<Dummy>(new AssociationDescriptor()); for(int i=0; i<10; i++) a.addServiceItem(AssociationUtils.makeServiceItem(i)); Assert.assertEquals("Should have 10 associated services", 10, a.getServiceCount()); ServiceItem[] items = a.getServiceItems(); List<ServiceItem> list = new ArrayList<ServiceItem>(); list.addAll(Arrays.asList(items)); Random r = new Random(); while(list.size()>0) { int toRemove = r.nextInt(list.size()); ServiceItem item = list.remove(toRemove); ServiceItem removed = a.removeService((Dummy)item.service); Assert.assertEquals(item.service, removed.service); } Assert.assertEquals("Should have 0 associated services", 0, a.getServiceCount()); } @Test public void testNext() { Association<Dummy> a = new DefaultAssociation<Dummy>(new AssociationDescriptor()); for(int i=0; i<10; i++) a.addServiceItem(AssociationUtils.makeServiceItem(i)); Assert.assertEquals("Should have 10 associated services", 10, a.getServiceCount()); for(int i=0; i<a.getServiceCount(); i++) { ServiceItem item = a.getNextServiceItem(); Assert.assertEquals(i, ((Dummy)item.service).getIndex()); } Assert.assertEquals(0, ((Dummy)a.getNextServiceItem().service).getIndex()); } @Test public void testNextAndAdd() { Association<Dummy> a = new DefaultAssociation<Dummy>(new AssociationDescriptor()); for(int i=0; i<10; i++) a.addServiceItem(AssociationUtils.makeServiceItem(i)); Assert.assertEquals("Should have 10 associated services", 10, a.getServiceCount()); for(int i=0; i<a.getServiceCount(); i++) { ServiceItem item = a.getNextServiceItem(); Assert.assertEquals(i, ((Dummy)item.service).getIndex()); } a.addServiceItem(AssociationUtils.makeServiceItem(a.getServiceCount())); Assert.assertEquals(10, ((Dummy)a.getNextServiceItem().service).getIndex()); } @Test public void testNextAndRemove() { Association<Dummy> a = new DefaultAssociation<Dummy>(new AssociationDescriptor()); for(int i=0; i<10; i++) a.addServiceItem(AssociationUtils.makeServiceItem(i)); Assert.assertEquals("Should have 10 associated services", 10, a.getServiceCount()); for(int i=0; i<a.getServiceCount(); i++) { ServiceItem item = a.getNextServiceItem(); Assert.assertEquals(i, ((Dummy)item.service).getIndex()); } ServiceItem removed = a.removeService(new DummyImpl(0)); Assert.assertNotNull(removed); Assert.assertEquals(9, a.getServiceCount()); Assert.assertEquals(1, ((Dummy)a.getNextServiceItem().service).getIndex()); Assert.assertEquals(2, ((Dummy)a.getNextServiceItem().service).getIndex()); removed = a.removeService(new DummyImpl(3)); Assert.assertNotNull(removed); Assert.assertEquals(8, a.getServiceCount()); Assert.assertEquals(4, ((Dummy)a.getNextServiceItem().service).getIndex()); Assert.assertEquals(5, ((Dummy)a.getNextServiceItem().service).getIndex()); Assert.assertEquals(6, ((Dummy)a.getNextServiceItem().service).getIndex()); removed = a.removeService(new DummyImpl(7)); Assert.assertNotNull(removed); removed = a.removeService(new DummyImpl(8)); Assert.assertNotNull(removed); removed = a.removeService(new DummyImpl(9)); Assert.assertNotNull(removed); Assert.assertEquals(5, a.getServiceCount()); removed = a.removeService(new DummyImpl(1)); Assert.assertNotNull(removed); Assert.assertEquals(2, ((Dummy)a.getNextServiceItem().service).getIndex()); } @Test public void testIterable() { Association<Dummy> a = new DefaultAssociation<Dummy>(new AssociationDescriptor()); for(int i=0; i<10; i++) a.addServiceItem(AssociationUtils.makeServiceItem(i)); Assert.assertEquals("Should have 10 associated services", 10, a.getServiceCount()); int i=0; for(Dummy d : a) { Assert.assertEquals(i, d.getIndex()); i++; } } @Test public void testEmpty() { Association<Dummy> a = new DefaultAssociation<Dummy>(new AssociationDescriptor()); Assert.assertNull(a.getNextServiceItem()); Assert.assertNull(a.getService()); Assert.assertNull(a.getServiceItem()); Assert.assertNull(a.removeService(new DummyImpl(0))); Assert.assertEquals(0, a.getServices().size()); Assert.assertFalse(a.iterator().hasNext()); Assert.assertEquals(0, a.getServiceCount()); } }
apache-2.0
ChinaQuants/Strata
modules/measure/src/main/java/com/opengamma/strata/measure/StandardMeasures.java
3076
/** * Copyright (C) 2016 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.strata.measure; import com.opengamma.strata.calc.ImmutableMeasure; import com.opengamma.strata.calc.Measure; /** * The standard set of measures that can be calculated by Strata. */ final class StandardMeasures { // present value, with currency conversion public static final Measure PRESENT_VALUE = ImmutableMeasure.of("PresentValue"); // explain present value, with no currency conversion public static final Measure EXPLAIN_PRESENT_VALUE = ImmutableMeasure.of("ExplainPresentValue", false); // PV01 calibrated sum public static final Measure PV01_CALIBRATED_SUM = ImmutableMeasure.of("PV01CalibratedSum"); // PV01 calibrated bucketed public static final Measure PV01_CALIBRATED_BUCKETED = ImmutableMeasure.of("PV01CalibratedBucketed"); // PV01 market quote sum public static final Measure PV01_MARKET_QUOTE_SUM = ImmutableMeasure.of("PV01MarketQuoteSum"); // PV01 market quote bucketed public static final Measure PV01_MARKET_QUOTE_BUCKETED = ImmutableMeasure.of("PV01MarketQuoteBucketed"); //------------------------------------------------------------------------- // accrued interest public static final Measure ACCRUED_INTEREST = ImmutableMeasure.of("AccruedInterest"); // cash flows public static final Measure CASH_FLOWS = ImmutableMeasure.of("CashFlows"); // currency exposure, with no currency conversion public static final Measure CURRENCY_EXPOSURE = ImmutableMeasure.of("CurrencyExposure", false); // current cash public static final Measure CURRENT_CASH = ImmutableMeasure.of("CurrentCash"); // forward FX rate public static final Measure FORWARD_FX_RATE = ImmutableMeasure.of("ForwardFxRate", false); // leg present value public static final Measure LEG_PRESENT_VALUE = ImmutableMeasure.of("LegPresentValue"); // leg initial notional public static final Measure LEG_INITIAL_NOTIONAL = ImmutableMeasure.of("LegInitialNotional"); // par rate, which is a decimal rate that does not need currency conversion public static final Measure PAR_RATE = ImmutableMeasure.of("ParRate", false); // par spread, which is a decimal rate that does not need currency conversion public static final Measure PAR_SPREAD = ImmutableMeasure.of("ParSpread", false); // the resolved target public static final Measure RESOLVED_TARGET = ImmutableMeasure.of("ResolvedTarget", false); // unit price, which is treated as a simple decimal number even if it refers to a currency public static final Measure UNIT_PRICE = ImmutableMeasure.of("UnitPrice", false); //------------------------------------------------------------------------- // semi-parallel gamma bucketed PV01 public static final Measure PV01_SEMI_PARALLEL_GAMMA_BUCKETED = ImmutableMeasure.of("PV01SemiParallelGammaBucketed"); // single-node gamma bucketed PV01 public static final Measure PV01_SINGLE_NODE_GAMMA_BUCKETED = ImmutableMeasure.of("PV01SingleNodeGammaBucketed"); }
apache-2.0
vietj/vertx-pg-client
vertx-sql-client-templates/src/test/java/io/vertx/sqlclient/templates/MySQLDataObject.java
636
package io.vertx.sqlclient.templates; import io.vertx.codegen.annotations.DataObject; import io.vertx.core.json.JsonObject; import io.vertx.sqlclient.templates.annotations.ParametersMapped; import io.vertx.sqlclient.templates.annotations.RowMapped; import java.time.Duration; @DataObject @RowMapped @ParametersMapped public class MySQLDataObject { private Duration duration; public MySQLDataObject() { } public MySQLDataObject(JsonObject json) { } public Duration getDuration() { return duration; } public MySQLDataObject setDuration(Duration duration) { this.duration = duration; return this; } }
apache-2.0
stagraqubole/presto
presto-main/src/main/java/com/facebook/presto/serde/PagesSerde.java
4803
/* * 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.facebook.presto.serde; import com.facebook.presto.spi.Page; import com.facebook.presto.spi.block.Block; import com.facebook.presto.spi.block.BlockEncoding; import com.facebook.presto.spi.block.BlockEncodingSerde; import com.google.common.collect.AbstractIterator; import io.airlift.slice.SliceInput; import io.airlift.slice.SliceOutput; import java.util.Iterator; import static com.google.common.base.Preconditions.checkNotNull; import static java.util.Arrays.asList; public final class PagesSerde { private PagesSerde() {} public static void writePages(BlockEncodingSerde blockEncodingSerde, SliceOutput sliceOutput, Page... pages) { writePages(blockEncodingSerde, sliceOutput, asList(pages).iterator()); } public static void writePages(BlockEncodingSerde blockEncodingSerde, SliceOutput sliceOutput, Iterable<Page> pages) { writePages(blockEncodingSerde, sliceOutput, pages.iterator()); } public static void writePages(BlockEncodingSerde blockEncodingSerde, SliceOutput sliceOutput, Iterator<Page> pages) { PagesWriter pagesWriter = new PagesWriter(blockEncodingSerde, sliceOutput); while (pages.hasNext()) { pagesWriter.append(pages.next()); } } public static Iterator<Page> readPages(BlockEncodingSerde blockEncodingSerde, SliceInput sliceInput) { return new PagesReader(blockEncodingSerde, sliceInput); } private static class PagesWriter { private final BlockEncodingSerde blockEncodingSerde; private final SliceOutput sliceOutput; private BlockEncoding[] blockEncodings; private PagesWriter(BlockEncodingSerde blockEncodingSerde, SliceOutput sliceOutput) { this.blockEncodingSerde = checkNotNull(blockEncodingSerde, "blockEncodingSerde is null"); this.sliceOutput = checkNotNull(sliceOutput, "sliceOutput is null"); } public PagesWriter append(Page page) { checkNotNull(page, "page is null"); if (blockEncodings == null) { Block[] blocks = page.getBlocks(); blockEncodings = new BlockEncoding[blocks.length]; sliceOutput.writeInt(blocks.length); for (int i = 0; i < blocks.length; i++) { Block block = blocks[i]; BlockEncoding blockEncoding = block.getEncoding(); blockEncodings[i] = blockEncoding; blockEncodingSerde.writeBlockEncoding(sliceOutput, blockEncoding); } } sliceOutput.writeInt(page.getPositionCount()); Block[] blocks = page.getBlocks(); for (int i = 0; i < blocks.length; i++) { blockEncodings[i].writeBlock(sliceOutput, blocks[i]); } return this; } } private static class PagesReader extends AbstractIterator<Page> { private final BlockEncoding[] blockEncodings; private final SliceInput sliceInput; public PagesReader(BlockEncodingSerde blockEncodingSerde, SliceInput sliceInput) { this.sliceInput = sliceInput; if (!sliceInput.isReadable()) { endOfData(); blockEncodings = new BlockEncoding[0]; return; } int channelCount = sliceInput.readInt(); blockEncodings = new BlockEncoding[channelCount]; for (int i = 0; i < blockEncodings.length; i++) { blockEncodings[i] = blockEncodingSerde.readBlockEncoding(sliceInput); } } @Override protected Page computeNext() { if (!sliceInput.isReadable()) { return endOfData(); } int positions = sliceInput.readInt(); Block[] blocks = new Block[blockEncodings.length]; for (int i = 0; i < blocks.length; i++) { blocks[i] = blockEncodings[i].readBlock(sliceInput); } @SuppressWarnings("UnnecessaryLocalVariable") Page page = new Page(positions, blocks); return page; } } }
apache-2.0
sharpdeep/assistant-android
app/src/main/java/com/sharpdeep/assistant_android/model/resultModel/Discussion.java
2905
package com.sharpdeep.assistant_android.model.resultModel; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.sharpdeep.assistant_android.util.DateUtil; import java.util.Calendar; import java.util.Date; public class Discussion { @SerializedName("content") @Expose private String content; @SerializedName("createTime") @Expose private String createTime; @SerializedName("fromUserName") @Expose private String fromUserName; @SerializedName("toUserName") @Expose private String toUserName; @SerializedName("type") @Expose private int type; @SerializedName("updateTime") @Expose private String updateTime; public Discussion(){} public Discussion(String fromUserName,String toUserName,String content){ super(); this.fromUserName = fromUserName; this.toUserName = toUserName; this.content = content; String now = DateUtil.getDateStr(Calendar.getInstance().getTime(),"yyyy-MM-dd HH:mm:ss"); this.createTime = now; this.updateTime = now; } /** * * @return * The content */ public String getContent() { return content; } /** * * @param content * The content */ public void setContent(String content) { this.content = content; } /** * * @return * The createTime */ public String getCreateTime() { return createTime; } /** * * @param createTime * The createTime */ public void setCreateTime(String createTime) { this.createTime = createTime; } /** * * @return * The fromUserName */ public String getFromUserName() { return fromUserName; } /** * * @param fromUserName * The fromUserName */ public void setFromUserName(String fromUserName) { this.fromUserName = fromUserName; } /** * * @return * The toUserName */ public String getToUserName() { return toUserName; } /** * * @param toUserName * The toUserName */ public void setToUserName(String toUserName) { this.toUserName = toUserName; } /** * * @return * The type */ public int getType() { return type; } /** * * @param type * The type */ public void setType(int type) { this.type = type; } /** * * @return * The updateTime */ public String getUpdateTime() { return updateTime; } /** * * @param updateTime * The updateTime */ public void setUpdateTime(String updateTime) { this.updateTime = updateTime; } }
apache-2.0
TranscendComputing/TopStackLoadBalancer
test/java/com/transcend/loadbalancer/integration/DeregisterInstancesFromLoadBalancerTest.java
2593
/* * TopStack (c) Copyright 2012-2013 Transcend Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the License); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an AS IS BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.transcend.loadbalancer.integration; import static org.junit.Assert.assertNotNull; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; import javax.annotation.Resource; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import com.msi.tough.core.Appctx; import com.transcend.loadbalancer.actions.RegisterInstancesWithLoadBalancerLocalTest; import com.transcend.loadbalancer.helper.LoadBalancerHelper; import com.transcend.loadbalancer.message.RegisterInstancesWithLoadBalancerMessage.RegisterInstancesWithLoadBalancerRequest; import com.transcend.loadbalancer.message.RegisterInstancesWithLoadBalancerMessage.RegisterInstancesWithLoadBalancerResponse; public class DeregisterInstancesFromLoadBalancerTest extends RegisterInstancesWithLoadBalancerLocalTest { private final static Logger logger = Appctx .getLogger(DeregisterInstancesFromLoadBalancerTest.class.getName()); protected final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS-"); private final String baseName = dateFormat.format(new Date())+ UUID.randomUUID().toString().substring(0, 3); String name1 = "elb-ri-1-" + baseName; String name2 = "elb-ri-2-" + baseName; @Resource LoadBalancerHelper loadBalancerHelper = null; @Before @Override public void createInitial() throws Exception { name1 = loadBalancerHelper.getOrCreateLoadBalancer(name1); logger.debug("Using LB for testing: " + name1); } @Test @Override public void testGoodRegisterInstance() throws Exception { RegisterInstancesWithLoadBalancerRequest.Builder request = registerInstanceRequest(name1); RegisterInstancesWithLoadBalancerResponse result = loadBalancerHelper.submitAndWait(request.build()); assertNotNull(result); logger.debug("Got response: " + result); } }
apache-2.0
kilgerm/mockins
src/main/java/net/kilger/mockins/generator/valueprovider/factory/MapValueProviderFactory.java
967
package net.kilger.mockins.generator.valueprovider.factory; import java.util.Map; import net.kilger.mockins.generator.valueprovider.ValueProvider; import net.kilger.mockins.generator.valueprovider.ValueProviderFactory; import net.kilger.mockins.generator.valueprovider.impl.EmptyMapValueProvider; /** * TODO: There's the follwong problem with all collection classes: * We'd like to provide non-empty implementations as value as well, * but how could we tell the element type? * Since that info is not availabe at runtime. */ public class MapValueProviderFactory implements ValueProviderFactory { @SuppressWarnings("unchecked") public <T> ValueProvider<T> valueProvider(Class<T> clazz) { return (ValueProvider<T>) new EmptyMapValueProvider(clazz); } public boolean specificFor(Class<?> clazz) { return clazz.equals(Map.class); } public boolean canHandle(Class<?> clazz) { return specificFor(clazz); } }
apache-2.0
diverproject/Biblioteca
src/localhost/biblioteca/dao/LivroDAO.java
5838
package localhost.biblioteca.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.http.HttpServletRequest; import localhost.biblioteca.core.Biblioteca; import localhost.biblioteca.core.Mysql; import localhost.biblioteca.core.Sql; import localhost.biblioteca.entidades.Livro; public class LivroDAO extends AbstractDao<Livro> { public LivroDAO(HttpServletRequest request) { super(request); } @Override public String validar(Livro livro) { if (!validarPaginas(livro)) return "número de páginas inválida"; if (!validarTradutor(livro)) return "tradutor inválido"; if (!validarIsbn(livro)) return "isbn inválido"; return null; } public boolean validarPaginas(Livro livro) { if (livro.getPaginas() > 10) return true; if (livro.getPaginas() < 3000) return false; return true; } public boolean validarTradutor(Livro livro) { if (livro.getTradutor() == null) return true; if (livro.getTradutor().length() == 0) return false; if (livro.getTradutor().length() < 3) return false; if (livro.getTradutor().length() > 48) return false; return true; } public boolean validarIsbn(Livro livro) { if (livro.getIsbn() == null) return false; if (livro.getIsbn().length() != 13) return false; return true; } @Override public int proximo() { try { Sql sql = new Mysql(); Connection connection = sql.getConnection(); String query = "SELECT auto_increment FROM information_schema.tables WHERE table_schema = 'biblioteca' AND table_name = 'livros'"; PreparedStatement ps = connection.prepareStatement(query); ResultSet result = ps.executeQuery(); if (result.next()) return result.getInt("auto_increment"); else return 1; } catch (SQLException e) { Biblioteca.alert(request, "exception", "SQLException (%s)", e.getMessage()); return 0; } catch (ClassNotFoundException e) { Biblioteca.alert(request, "exception", "ClassNotFoundException (%s)", e.getMessage()); return 0; } } @Override public boolean inserir(Livro livro) { try { Sql sql = new Mysql(); Connection connection = sql.getConnection(); String query = "INSERT INTO livros (paginas, tradutor, isbn) VALUES (?, ?, ?)"; PreparedStatement ps = connection.prepareStatement(query); ps.setInt(1, livro.getPaginas()); ps.setString(2, livro.getTradutor()); ps.setString(3, livro.getIsbn()); return ps.executeUpdate() != PreparedStatement.EXECUTE_FAILED; } catch (SQLException e) { Biblioteca.alert(request, "exception", "SQLException (%s)", e.getMessage()); return false; } catch (ClassNotFoundException e) { Biblioteca.alert(request, "exception", "ClassNotFoundException (%s)", e.getMessage()); return false; } } @Override public boolean atualizar(Livro livro) { try { Sql sql = new Mysql(); Connection connection = sql.getConnection(); String query = "UPDATE livros SET paginas = ?, tradutor = ?, isbn = ? WHERE id = ?"; PreparedStatement ps = connection.prepareStatement(query); ps.setInt(1, livro.getPaginas()); ps.setString(2, livro.getTradutor()); ps.setString(3, livro.getIsbn()); ps.setInt(4, livro.getId()); return ps.executeUpdate() != PreparedStatement.EXECUTE_FAILED; } catch (SQLException e) { Biblioteca.alert(request, "exception", "SQLException (%s)", e.getMessage()); return false; } catch (ClassNotFoundException e) { Biblioteca.alert(request, "exception", "ClassNotFoundException (%s)", e.getMessage()); return false; } } @Override public boolean remover(Livro livro) { try { Sql sql = new Mysql(); Connection connection = sql.getConnection(); String query = "DELETE FROM livros WHERE id = ?"; PreparedStatement ps = connection.prepareStatement(query); ps.setInt(1, livro.getId()); return ps.executeUpdate() != PreparedStatement.EXECUTE_FAILED; } catch (SQLException e) { Biblioteca.alert(request, "exception", "SQLException (%s)", e.getMessage()); return false; } catch (ClassNotFoundException e) { Biblioteca.alert(request, "exception", "ClassNotFoundException (%s)", e.getMessage()); return false; } } @Override public boolean truncar() { try { Sql sql = new Mysql(); Connection connection = sql.getConnection(); String query = "TRUNCATE livros"; PreparedStatement ps = connection.prepareStatement(query); return ps.executeUpdate() != PreparedStatement.EXECUTE_FAILED; } catch (SQLException e) { Biblioteca.alert(request, "exception", "SQLException (%s)", e.getMessage()); return false; } catch (ClassNotFoundException e) { Biblioteca.alert(request, "exception", "ClassNotFoundException (%s)", e.getMessage()); return false; } } public Livro selecionar(int id) { try { Sql sql = new Mysql(); Connection connection = sql.getConnection(); String query = "SELECT * FROM livros WHERE id = ?"; PreparedStatement ps = connection.prepareStatement(query); ps.setInt(1, id); ResultSet result = ps.executeQuery(); if (!result.next()) return null; return new Livro() .setPaginas(result.getInt("paginas")) .setTradutor(result.getString("tradutor")) .setIsbn(result.getString("isbn")); } catch (SQLException e) { Biblioteca.alert(request, "exception", "SQLException (%s)", e.getMessage()); return null; } catch (ClassNotFoundException e) { Biblioteca.alert(request, "exception", "ClassNotFoundException (%s)", e.getMessage()); return null; } } }
apache-2.0
NationalSecurityAgency/ghidra
Ghidra/Features/Base/src/test.slow/java/ghidra/program/database/symbol/SymbolManagerSourceTest.java
15964
/* ### * IP: GHIDRA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ghidra.program.database.symbol; import static org.junit.Assert.*; import org.junit.*; import ghidra.program.database.ProgramBuilder; import ghidra.program.database.ProgramDB; import ghidra.program.database.function.OverlappingFunctionException; import ghidra.program.model.address.*; import ghidra.program.model.listing.*; import ghidra.program.model.mem.Memory; import ghidra.program.model.symbol.*; import ghidra.test.AbstractGhidraHeadedIntegrationTest; import ghidra.util.exception.DuplicateNameException; import ghidra.util.exception.InvalidInputException; import ghidra.util.task.TaskMonitorAdapter; public class SymbolManagerSourceTest extends AbstractGhidraHeadedIntegrationTest { private ProgramDB program; private SymbolTable st; private AddressSpace space; private ReferenceManager refMgr; private int transactionID; private Namespace globalScope; public SymbolManagerSourceTest() { super(); } @Before public void setUp() throws Exception { program = createDefaultProgram(testName.getMethodName(), ProgramBuilder._TOY, this); globalScope = program.getGlobalNamespace(); space = program.getAddressFactory().getDefaultAddressSpace(); Memory memory = program.getMemory(); transactionID = program.startTransaction("Test"); memory.createInitializedBlock("test", addr(0), 5000, (byte) 0, TaskMonitorAdapter.DUMMY_MONITOR, false); st = program.getSymbolTable(); refMgr = program.getReferenceManager(); } @After public void tearDown() throws Exception { if (program != null) { program.endTransaction(transactionID, true); program.release(this); } } private Address addr(long l) { return space.getAddress(l); } private Symbol createSymbol(Address addr, String name, Namespace namespace, SourceType source) throws InvalidInputException { return st.createLabel(addr, name, namespace, source); } private void createDataReference(Address fromAddr, Address toAddr) { refMgr.addMemoryReference(fromAddr, toAddr, RefType.DATA, SourceType.USER_DEFINED, 0); } private void createDefaultFunction(Address entryPoint, AddressSet addrSet) throws DuplicateNameException, InvalidInputException, OverlappingFunctionException { FunctionManager functionMgr = program.getFunctionManager(); Function f = functionMgr.createFunction(SymbolUtilities.getDefaultFunctionName(entryPoint), entryPoint, addrSet, SourceType.DEFAULT); assertNotNull(f); } /* ***** TEST CASES ***** */ @Test public void testCreateUserSymbol() throws Exception { Symbol s = createSymbol(addr(0x0100), "UserSymbol", globalScope, SourceType.USER_DEFINED); assertEquals("UserSymbol", s.getName()); assertEquals(true, s.getSource() == SourceType.USER_DEFINED); } @Test public void testCreateImportedSymbol() throws Exception { Symbol s = createSymbol(addr(0x0100), "ImportedSymbol", globalScope, SourceType.IMPORTED); assertEquals("ImportedSymbol", s.getName()); assertEquals(true, s.getSource() == SourceType.IMPORTED); } @Test public void testCreateAnalysisSymbol() throws Exception { Symbol s = createSymbol(addr(0x0100), "AnalysisSymbol", globalScope, SourceType.ANALYSIS); assertEquals("AnalysisSymbol", s.getName()); assertEquals(true, s.getSource() == SourceType.ANALYSIS); } @Test public void testCreateDefaultSymbol() throws Exception { Address endAddr = addr(0x0200); Address entryPoint = addr(0x0100); AddressSet addrSet = new AddressSet(entryPoint, endAddr); createDefaultFunction(entryPoint, addrSet); Function f = program.getFunctionManager().getFunctionAt(addr(0x0100)); assertNotNull(f); assertEquals("FUN_00000100", f.getName()); Symbol[] symbols = st.getSymbols(addr(0x0100)); assertEquals(1, symbols.length); Symbol s = symbols[0]; assertEquals("FUN_00000100", s.getName()); assertEquals(true, s.getSource() == SourceType.DEFAULT); assertEquals(false, s.isDynamic()); } @Test public void testCreateDynamicSymbol() throws Exception { Address fromAddr = addr(0x0200); Address toAddr = addr(0x0100); createDataReference(fromAddr, toAddr); Symbol[] symbols = st.getSymbols(addr(0x0100)); assertEquals(1, symbols.length); Symbol s = symbols[0]; assertEquals("DAT_00000100", s.getName()); assertEquals(true, s.getSource() == SourceType.DEFAULT); assertEquals(true, s.isDynamic()); } @Test public void testSetSymbolSource() throws Exception { Symbol s = createSymbol(addr(0x0100), "MySymbol", globalScope, SourceType.USER_DEFINED); assertEquals(SourceType.USER_DEFINED, s.getSource()); s.setSource(SourceType.ANALYSIS); assertEquals(SourceType.ANALYSIS, s.getSource()); s.setSource(SourceType.IMPORTED); assertEquals(SourceType.IMPORTED, s.getSource()); try { s.setSource(SourceType.DEFAULT); Assert.fail("Shouldn't be able to set source on a Label symbol."); } catch (IllegalArgumentException e) { } assertEquals(SourceType.IMPORTED, s.getSource()); s.setSource(SourceType.USER_DEFINED); assertEquals(SourceType.USER_DEFINED, s.getSource()); } @Test public void testSetFunctionSource() throws Exception { Listing listing = program.getListing(); AddressSet set = new AddressSet(); set.addRange(addr(100), addr(150)); set.addRange(addr(300), addr(310)); set.addRange(addr(320), addr(330)); listing.createFunction("fredFunc", addr(100), set, SourceType.USER_DEFINED); Symbol s1 = st.getPrimarySymbol(addr(100)); assertNotNull(s1); assertEquals("fredFunc", s1.getName()); assertTrue(s1.isPrimary()); try { s1.setSource(SourceType.DEFAULT); Assert.fail("Shouldn't be able to set function source to DEFAULT."); } catch (IllegalArgumentException e) { } s1.setName("FUN_00000064", SourceType.DEFAULT); Symbol s2 = st.getPrimarySymbol(addr(100)); assertNotNull(s2); assertEquals("FUN_00000064", s2.getName()); } @Test public void testSetSymbolPinned() throws Exception { Symbol s = createSymbol(addr(0x0100), "MySymbol", globalScope, SourceType.USER_DEFINED); assertEquals(false, s.isPinned()); s.setPinned(true); assertEquals(true, s.isPinned()); s.setPinned(false); assertEquals(false, s.isPinned()); } @Test public void testSetDefaultSymbolToNewName() throws Exception { Address fromAddr = addr(0x0200); Address toAddr = addr(0x0100); createDataReference(fromAddr, toAddr); Symbol[] symbols = st.getSymbols(addr(0x0100)); assertEquals(1, symbols.length); Symbol s = symbols[0]; assertEquals("DAT_00000100", s.getName()); assertEquals(true, s.getSource() == SourceType.DEFAULT); s.setName("MySymbol", SourceType.USER_DEFINED); symbols = st.getSymbols(addr(0x0100)); assertEquals(1, symbols.length); s = symbols[0]; assertEquals("MySymbol", s.getName()); assertEquals(true, s.getSource() == SourceType.USER_DEFINED); } @Test public void testSetNonDefaultToDefault() throws Exception { Symbol s = createSymbol(addr(0x0100), "UserSymbol", globalScope, SourceType.USER_DEFINED); assertEquals("UserSymbol", s.getName()); assertEquals(true, s.getSource() == SourceType.USER_DEFINED); try { s.setSource(SourceType.DEFAULT); Assert.fail("Shouldn't be able to set source to default."); } catch (IllegalArgumentException e) { // Success } Symbol[] symbols = st.getSymbols(addr(0x0100)); assertEquals(1, symbols.length); s = symbols[0]; assertEquals("UserSymbol", s.getName()); assertEquals(SourceType.USER_DEFINED, s.getSource()); assertEquals(false, s.getSource() == SourceType.DEFAULT); } @Test public void testSetDefaultToNonDefault() throws Exception { createDataReference(addr(0x0120), addr(0x0100));// Should cause default label at 0x0120 Symbol[] symbols = st.getSymbols(addr(0x0100)); assertEquals(1, symbols.length); Symbol s = symbols[0]; assertEquals("DAT_00000100", s.getName()); assertEquals(true, s.getSource() == SourceType.DEFAULT); assertEquals(true, s.isDynamic()); try { s.setSource(SourceType.USER_DEFINED); Assert.fail("Shouldn't be able to change from default to non-default."); } catch (IllegalArgumentException e) { } try { s.setName("blue", SourceType.USER_DEFINED); } catch (IllegalArgumentException e) { Assert.fail(e.getMessage()); } symbols = st.getSymbols(addr(0x0100)); assertEquals(1, symbols.length); s = symbols[0]; assertEquals("blue", s.getName()); assertEquals(SourceType.USER_DEFINED, s.getSource()); try { s.setSource(SourceType.DEFAULT); Assert.fail("Shouldn't be able to set symbol source to default"); } catch (IllegalArgumentException e) { // expected } } @Test public void testSetSymbolName() throws Exception { Symbol s = createSymbol(addr(0x0100), "UserSymbol", globalScope, SourceType.USER_DEFINED); assertEquals("UserSymbol", s.getName()); assertEquals(true, s.getSource() == SourceType.USER_DEFINED); s.setName("MyAnalysis", SourceType.ANALYSIS); Symbol[] symbols = st.getSymbols(addr(0x0100)); assertEquals(1, symbols.length); s = symbols[0]; assertEquals("MyAnalysis", s.getName()); assertEquals(true, s.getSource() == SourceType.ANALYSIS); s.setName("IMPORTED", SourceType.IMPORTED); symbols = st.getSymbols(addr(0x0100)); assertEquals(1, symbols.length); s = symbols[0]; assertEquals("IMPORTED", s.getName()); assertEquals(true, s.getSource() == SourceType.IMPORTED); s.setName("NewStuff", SourceType.USER_DEFINED); symbols = st.getSymbols(addr(0x0100)); assertEquals(1, symbols.length); s = symbols[0]; assertEquals("NewStuff", s.getName()); assertEquals(true, s.getSource() == SourceType.USER_DEFINED); } @Test public void testCreateMultipleSymbols() throws Exception { createSymbol(addr(0x0100), "UserSymbol", globalScope, SourceType.USER_DEFINED); Symbol[] symbols = st.getSymbols(addr(0x0100)); assertEquals(1, symbols.length); assertEquals("UserSymbol", symbols[0].getName()); assertEquals(true, symbols[0].getSource() == SourceType.USER_DEFINED); assertEquals(true, symbols[0].isPrimary()); createSymbol(addr(0x0100), "AnalysisSymbol", globalScope, SourceType.ANALYSIS); symbols = st.getSymbols(addr(0x0100)); assertEquals(2, symbols.length); assertEquals("UserSymbol", symbols[0].getName()); assertEquals(true, symbols[0].getSource() == SourceType.USER_DEFINED); assertEquals(true, symbols[0].isPrimary()); assertEquals("AnalysisSymbol", symbols[1].getName()); assertEquals(true, symbols[1].getSource() == SourceType.ANALYSIS); createSymbol(addr(0x0100), "ImportedSymbol", globalScope, SourceType.IMPORTED); symbols = st.getSymbols(addr(0x0100)); assertEquals(3, symbols.length); assertEquals("UserSymbol", symbols[0].getName()); assertEquals(true, symbols[0].getSource() == SourceType.USER_DEFINED); assertEquals(true, symbols[0].isPrimary()); assertEquals("AnalysisSymbol", symbols[1].getName()); assertEquals(true, symbols[1].getSource() == SourceType.ANALYSIS); assertEquals("ImportedSymbol", symbols[2].getName()); assertEquals(true, symbols[2].getSource() == SourceType.IMPORTED); createSymbol(addr(0x0100), "espresso", globalScope, SourceType.USER_DEFINED); symbols = st.getSymbols(addr(0x0100)); assertEquals(4, symbols.length); assertEquals("UserSymbol", symbols[0].getName()); assertEquals(true, symbols[0].getSource() == SourceType.USER_DEFINED); assertEquals(true, symbols[0].isPrimary()); assertEquals("AnalysisSymbol", symbols[1].getName()); assertEquals(true, symbols[1].getSource() == SourceType.ANALYSIS); assertEquals("ImportedSymbol", symbols[2].getName()); assertEquals(true, symbols[2].getSource() == SourceType.IMPORTED); assertEquals("espresso", symbols[3].getName()); assertEquals(true, symbols[3].getSource() == SourceType.USER_DEFINED); } @Test public void testCreateClass() throws Exception { GhidraClass c = st.createClass(globalScope, "MyClass", SourceType.USER_DEFINED); Symbol s = c.getSymbol(); assertEquals("MyClass", c.getName()); assertEquals("MyClass", s.getName()); assertEquals(true, s.getSource() == SourceType.USER_DEFINED); assertEquals(globalScope.getSymbol(), s.getParentSymbol()); c = st.createClass(globalScope, "YourImportedSymbol", SourceType.IMPORTED); s = c.getSymbol(); assertEquals("YourImportedSymbol", c.getName()); assertEquals("YourImportedSymbol", s.getName()); assertEquals(true, s.getSource() == SourceType.IMPORTED); assertEquals(globalScope.getSymbol(), s.getParentSymbol()); c = st.createClass(globalScope, "AnalysisClass", SourceType.ANALYSIS); s = c.getSymbol(); assertEquals("AnalysisClass", c.getName()); assertEquals("AnalysisClass", s.getName()); assertEquals(true, s.getSource() == SourceType.ANALYSIS); assertEquals(globalScope.getSymbol(), s.getParentSymbol()); try { c = st.createClass(globalScope, "Class1", SourceType.DEFAULT); Assert.fail("Shouldn't be able to create default Class."); } catch (IllegalArgumentException e) { } } @Test public void testCreateExternalLibrary() throws Exception { Library lib = st.createExternalLibrary("UserLib", SourceType.USER_DEFINED); Symbol s = lib.getSymbol(); assertEquals("UserLib", lib.getName()); assertEquals("UserLib", s.getName()); assertEquals(true, s.getSource() == SourceType.USER_DEFINED); assertEquals(globalScope.getSymbol(), s.getParentSymbol()); lib = st.createExternalLibrary("ImportedLib", SourceType.IMPORTED); s = lib.getSymbol(); assertEquals("ImportedLib", lib.getName()); assertEquals("ImportedLib", s.getName()); assertEquals(true, s.getSource() == SourceType.IMPORTED); assertEquals(globalScope.getSymbol(), s.getParentSymbol()); lib = st.createExternalLibrary("AnalysisLib", SourceType.ANALYSIS); s = lib.getSymbol(); assertEquals("AnalysisLib", lib.getName()); assertEquals("AnalysisLib", s.getName()); assertEquals(true, s.getSource() == SourceType.ANALYSIS); assertEquals(globalScope.getSymbol(), s.getParentSymbol()); try { lib = st.createExternalLibrary("DefaultLib", SourceType.DEFAULT); Assert.fail("Shouldn't be able to create default External Library."); } catch (IllegalArgumentException e) { } } @Test public void testCreateNamespace() throws Exception { Namespace n = st.createNameSpace(globalScope, "MyNamespace", SourceType.USER_DEFINED); Symbol s = n.getSymbol(); assertEquals("MyNamespace", n.getName()); assertEquals("MyNamespace", s.getName()); assertEquals(true, s.getSource() == SourceType.USER_DEFINED); assertEquals(globalScope.getSymbol(), s.getParentSymbol()); n = st.createNameSpace(globalScope, "YourImportedSymbol", SourceType.IMPORTED); s = n.getSymbol(); assertEquals("YourImportedSymbol", n.getName()); assertEquals("YourImportedSymbol", s.getName()); assertEquals(true, s.getSource() == SourceType.IMPORTED); assertEquals(globalScope.getSymbol(), s.getParentSymbol()); n = st.createNameSpace(globalScope, "AnalysisNamespace", SourceType.ANALYSIS); s = n.getSymbol(); assertEquals("AnalysisNamespace", n.getName()); assertEquals("AnalysisNamespace", s.getName()); assertEquals(true, s.getSource() == SourceType.ANALYSIS); assertEquals(globalScope.getSymbol(), s.getParentSymbol()); try { n = st.createNameSpace(globalScope, "Namespace1", SourceType.DEFAULT); Assert.fail("Shouldn't be able to create default Namespace."); } catch (IllegalArgumentException e) { } } }
apache-2.0
luunguyendev/zk1607-training
04.sources/springweb/src/main/java/com/springweb/utils/DBConfig.java
250
package com.springweb.utils; /** * DBConfig * @author ntluu * @version 0.1 * @since 2016-05-09 * @modified: n/a */ public interface DBConfig { String DB_HOST = "127.0.0.1"; String DB_NAME = "firedb"; int DB_PORT = 27017; }
apache-2.0
jayxue/4sharedAndroid
4sharedAndroidSDK/src/main/java/com/wms/forsharedandroid/sdk/api/AccountItem.java
1461
/** * 4shared account item, representing a file or a directory description data. * Implementation includes network serialization functionality. */ package com.wms.forsharedandroid.sdk.api; import org.ksoap2.serialization.SoapPrimitive; public class AccountItem { private long id; private String name; private boolean directory; public AccountItem() { } public long getId() { return id; } public String getName() { return name; } public boolean isDirectory() { return directory; } public String toString() { return directory ? "[" + name + "]" : name; } public void setProperty(String propName, Object value) { if (value == null) { return; } if (value instanceof SoapPrimitive) { value = ((SoapPrimitive) value).toString(); } if (propName.equals("id")) { if (value instanceof Long) { id = ((Long) value).longValue(); } else { id = Long.parseLong(value.toString()); } } if (propName.equals("directory")) { directory = convertBoolean(value); } else if (propName.equals("name")) { name = convertString(value); } } private boolean convertBoolean(Object val) { if (val == null) { return false; } else { return val.toString().toLowerCase().equals("true"); } } private String convertString(Object str) { if (!(str instanceof String)) { return null; } if (((String) str).equals("String{}")) { return ""; } else { return (String) str; } } }
apache-2.0
satoshun/truth-android
truth-android/src/main/java/com/github/satoshun/truth/android/api/gesture/OrientedBoundingBoxSubject.java
2194
package com.github.satoshun.truth.android.api.gesture; import android.gesture.OrientedBoundingBox; import com.github.satoshun.truth.android.api.BaseSubject; import com.google.common.truth.FailureStrategy; import com.google.common.truth.SubjectFactory; public class OrientedBoundingBoxSubject extends BaseSubject<OrientedBoundingBoxSubject, OrientedBoundingBox> { public static final OrientedBoundingBoxSubjectFactory FACTORY = new OrientedBoundingBoxSubjectFactory(); public OrientedBoundingBoxSubject(FailureStrategy failureStrategy, OrientedBoundingBox actual) { super(failureStrategy, actual); } public OrientedBoundingBoxSubject isCenterX(float centerX) { isNotNull(); check().withFailureMessage("is center x") .that(actual().centerX) .isEqualTo(centerX); return this; } public OrientedBoundingBoxSubject isCenterY(float centerY) { isNotNull(); check().withFailureMessage("is center y") .that(actual().centerY) .isEqualTo(centerY); return this; } public OrientedBoundingBoxSubject isHeight(float height) { isNotNull(); check().withFailureMessage("is height") .that(actual().height) .isEqualTo(height); return this; } public OrientedBoundingBoxSubject isOrientation(float orientation) { isNotNull(); check().withFailureMessage("is orientation") .that(actual().orientation) .isEqualTo(orientation); return this; } public OrientedBoundingBoxSubject isSquareness(float squareness) { isNotNull(); check().withFailureMessage("is squareness") .that(actual().squareness) .isEqualTo(squareness); return this; } public OrientedBoundingBoxSubject isWidth(float width) { isNotNull(); check().withFailureMessage("is width") .that(actual().width) .isEqualTo(width); return this; } private static class OrientedBoundingBoxSubjectFactory extends SubjectFactory<OrientedBoundingBoxSubject, OrientedBoundingBox> { @Override public OrientedBoundingBoxSubject getSubject(FailureStrategy fs, OrientedBoundingBox that) { return new OrientedBoundingBoxSubject(fs, that); } } }
apache-2.0
willitscale/oaigatewayrelay
src/uk/co/n3tw0rk/oaigatewayrelay/events/agent/WorkNotReady.java
1219
package uk.co.n3tw0rk.oaigatewayrelay.events.agent; import uk.co.n3tw0rk.oaigatewayrelay.abstraction.events.Agent; /** * <strong>Work Not Ready Class</strong> * * @author James Lockhart <james@n3tw0rk.co.uk> * @version 1.0 * @since 28-12-2014 * * @see SYSTEM OAI SPECIFICATIONS MANUAL – Issue 9.0, April 2005 - Page 27 * * WORK NOT READY – WNR * * USE: * Occurs when an agent at a device is busy serving the previous ACD call and is not yet available * to receive further ACD calls. * * MONITOR TYPE: * Device * * SYNTAX: * WNR,<Resync_Code>,<Mon_Cross_Ref_ID>,<Device_Ext>,<Agent_ID><CR><LF> * * Where: * • Device_Ext: Identifies the extension number where the agent is logged in. * • Agent_ID: Indicates the ID of the agent moving into the Work Not Ready state. * * EXAMPLE: * Agent number 2003 at extension 105 is now “wrapping up” work from the previous call. * 001,WNR,,<MON105>,105,2003 */ public class WorkNotReady extends Agent { public final static String EVENT = "WNR"; public WorkNotReady( String[] eventParts ) { super( eventParts ); } public WorkNotReady( String event ) { super( event ); } @Override public void process() { } }
apache-2.0
Slikey/jBatch
Network/src/main/java/de/slikey/batch/network/common/TPSManager.java
1460
package de.slikey.batch.network.common; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; /** * @author Kevin Carstens * @since 30.04.2015 */ public class TPSManager { public static final long TRACKED_SIZE = 30; private final Map<TickingManager, List<Long>> tracked; public TPSManager() { tracked = new HashMap<>(); } public synchronized void reportTime(TickingManager tickingManager, long currentTime) { List<Long> entries = this.ensureManagerIsTracked(tickingManager); { // Prevent memory leak if (entries.size() >= TRACKED_SIZE) entries.remove(0); } { // Actually track entries.add(currentTime); } } public synchronized float getTPS(TickingManager tickingManager) { List<Long> entries = this.ensureManagerIsTracked(tickingManager); int size = entries.size(); if (size < 2) { return 0f; } long first = entries.get(0); long last = entries.get(size - 1); long timeRange = last - first; return (float) timeRange / size; } private List<Long> ensureManagerIsTracked(TickingManager tickingManager) { List<Long> entries = tracked.get(tickingManager); if (entries == null) { tracked.put(tickingManager, entries = new LinkedList<>()); } return entries; } }
apache-2.0
opencb/opencga
opencga-core/src/main/java/org/opencb/opencga/core/models/sample/Sample.java
14580
/* * Copyright 2015-2020 OpenCB * * 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.opencb.opencga.core.models.sample; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.opencb.biodata.models.clinical.Phenotype; import org.opencb.biodata.models.common.Status; import org.opencb.opencga.core.models.common.Annotable; import org.opencb.opencga.core.models.common.AnnotationSet; import org.opencb.opencga.core.models.common.ExternalSource; import java.util.*; /** * Sample data model hosts information about any biological material, normally extracted from an _Individual_, that is used for a particular * analysis. This is the main data model, it stores the most basic and important information. */ public class Sample extends Annotable { /** * Sample ID in the study, this must be unique in the study but can be repeated in different studies. This is a mandatory parameter * when creating a new sample, this ID cannot be changed at the moment. * * @apiNote Required, Immutable, Unique */ private String id; /** * Generic: Unique 32-character identifier assigned automatically by OpenCGA. * * @apiNote Immutable, Unique */ private String uuid; private ExternalSource source; /** * Describes how the sample was processed in the lab. */ private SampleProcessing processing; /** * Describes how the sample was collected. * * @apiNote * @implNote The sample collection is a list of samples * @since 2.1 */ private SampleCollection collection; /** * Contains different metrics to evaluate the quality of the sample. * * @apiNote * @implNote The sample collection is a list of samples * @see [ZetaGenomics] (https://www.zettagenomics.com) * @since 2.1 */ private SampleQualityControl qualityControl; /** * An integer describing the current data release. * * @apiNote Immutable */ private int release; /** * Generic: Autoincremental version assigned to the registered entry. By default, updates does not create new versions. To enable * versioning, users must set the `incVersion` flag from the /update web service when updating the document. * * @apiNote Immutable */ private int version; /** * Generic: Autogenerated date following the format YYYYMMDDhhmmss containing the date when the entry was first registered. * * @apiNote Immutable */ private String creationDate; /** * Generic: Autogenerated date following the format YYYYMMDDhhmmss containing the date when the entry was last modified. * * @apiNote Immutable */ private String modificationDate; /** * Generic: Users may provide a description for the entry. */ private String description; /** * Indicates if the sample is somatic or germline (default) * * @apiNote */ private boolean somatic; private List<Phenotype> phenotypes; private String individualId; private List<String> fileIds; private List<String> cohortIds; /** * Generic: Object to define the status of the entry. */ private Status status; /** * Generic: Field automatically managed by OpenCGA containing relevant information of the entry. This field is used for internal * purposes and is visible for users. * * @apiNote Immutable */ private SampleInternal internal; /** * Dictionary that can be customised by users to store any additional information users may require. * * @implNote This field is not meant to be queried. It should only contain extra information. To store additional information meant to * be queried, please use annotationSets. */ private Map<String, Object> attributes; public Sample() { } public Sample(String id, String individualId, String description, int release) { this(id, null, null, null, null, release, 1, "", "", description, false, new LinkedList<>(), individualId, new LinkedList<>(), new Status(), null, new LinkedList<>(), new HashMap<>()); } public Sample(String id, String creationDate, String modificationDate, String individualId, ExternalSource source, SampleProcessing processing, SampleCollection collection, int release, int version, String description, boolean somatic, List<Phenotype> phenotypes, List<AnnotationSet> annotationSets, Status status, SampleInternal internal, Map<String, Object> attributes) { this(id, null, source, processing, collection, release, version, creationDate, modificationDate, description, somatic, phenotypes, individualId, new LinkedList<>(), status, internal, annotationSets, attributes); } public Sample(String id, String uuid, ExternalSource source, SampleProcessing processing, SampleCollection collection, int release, int version, String creationDate, String modificationDate, String description, boolean somatic, List<Phenotype> phenotypes, String individualId, List<String> fileIds, Status status, SampleInternal internal, List<AnnotationSet> annotationSets, Map<String, Object> attributes) { this(id, uuid, source, processing, collection, null, release, version, creationDate, modificationDate, description, somatic, phenotypes, individualId, Collections.emptyList(), fileIds, status, internal, annotationSets, attributes); } public Sample(String id, String uuid, ExternalSource source, SampleProcessing processing, SampleCollection collection, SampleQualityControl qualityControl, int release, int version, String creationDate, String modificationDate, String description, boolean somatic, List<Phenotype> phenotypes, String individualId, List<String> cohortIds, List<String> fileIds, Status status, SampleInternal internal, List<AnnotationSet> annotationSets, Map<String, Object> attributes) { this.id = id; this.uuid = uuid; this.source = source; this.processing = processing; this.collection = collection; this.qualityControl = qualityControl; this.release = release; this.version = version; this.creationDate = creationDate; this.modificationDate = modificationDate; this.description = description; this.somatic = somatic; this.phenotypes = phenotypes; this.individualId = individualId; this.fileIds = fileIds; this.cohortIds = cohortIds; this.status = status; this.internal = internal; this.annotationSets = annotationSets; this.attributes = attributes; } @Override public String toString() { final StringBuilder sb = new StringBuilder("Sample{"); sb.append("id='").append(id).append('\''); sb.append(", uuid='").append(uuid).append('\''); sb.append(", source=").append(source); sb.append(", processing=").append(processing); sb.append(", collection=").append(collection); sb.append(", qualityControl=").append(qualityControl); sb.append(", release=").append(release); sb.append(", version=").append(version); sb.append(", creationDate='").append(creationDate).append('\''); sb.append(", modificationDate='").append(modificationDate).append('\''); sb.append(", description='").append(description).append('\''); sb.append(", somatic=").append(somatic); sb.append(", phenotypes=").append(phenotypes); sb.append(", individualId='").append(individualId).append('\''); sb.append(", fileIds=").append(fileIds); sb.append(", cohortIds=").append(cohortIds); sb.append(", status=").append(status); sb.append(", internal=").append(internal); sb.append(", attributes=").append(attributes); sb.append(", annotationSets=").append(annotationSets); sb.append('}'); return sb.toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Sample sample = (Sample) o; return new EqualsBuilder() .append(release, sample.release) .append(version, sample.version) .append(somatic, sample.somatic) .append(id, sample.id) .append(uuid, sample.uuid) .append(processing, sample.processing) .append(collection, sample.collection) .append(individualId, sample.individualId) .append(creationDate, sample.creationDate) .append(modificationDate, sample.modificationDate) .append(description, sample.description) .append(phenotypes, sample.phenotypes) .append(status, sample.status) .append(internal, sample.internal) .append(attributes, sample.attributes) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(17, 37) .append(id) .append(uuid) .append(processing) .append(collection) .append(individualId) .append(release) .append(version) .append(creationDate) .append(modificationDate) .append(description) .append(somatic) .append(phenotypes) .append(status) .append(internal) .append(attributes) .toHashCode(); } @Override public Sample setUid(long uid) { super.setUid(uid); return this; } @Override public Sample setStudyUid(long studyUid) { super.setStudyUid(studyUid); return this; } @Override public String getUuid() { return uuid; } public Sample setUuid(String uuid) { this.uuid = uuid; return this; } @Override public String getId() { return id; } @Override public Sample setId(String id) { this.id = id; return this; } public ExternalSource getSource() { return source; } public Sample setSource(ExternalSource source) { this.source = source; return this; } public SampleProcessing getProcessing() { return processing; } public Sample setProcessing(SampleProcessing processing) { this.processing = processing; return this; } public SampleCollection getCollection() { return collection; } public Sample setCollection(SampleCollection collection) { this.collection = collection; return this; } public SampleQualityControl getQualityControl() { return qualityControl; } public Sample setQualityControl(SampleQualityControl qualityControl) { this.qualityControl = qualityControl; return this; } public String getIndividualId() { return individualId; } public Sample setIndividualId(String individualId) { this.individualId = individualId; return this; } public String getCreationDate() { return creationDate; } public Sample setCreationDate(String creationDate) { this.creationDate = creationDate; return this; } public String getModificationDate() { return modificationDate; } public Sample setModificationDate(String modificationDate) { this.modificationDate = modificationDate; return this; } public String getDescription() { return description; } public Sample setDescription(String description) { this.description = description; return this; } public boolean isSomatic() { return somatic; } public Sample setSomatic(boolean somatic) { this.somatic = somatic; return this; } public int getRelease() { return release; } public Sample setRelease(int release) { this.release = release; return this; } public int getVersion() { return version; } public Sample setVersion(int version) { this.version = version; return this; } public List<Phenotype> getPhenotypes() { return phenotypes; } public Sample setPhenotypes(List<Phenotype> phenotypes) { this.phenotypes = phenotypes; return this; } public List<String> getFileIds() { return fileIds; } public Sample setFileIds(List<String> fileIds) { this.fileIds = fileIds; return this; } public Status getStatus() { return status; } public Sample setStatus(Status status) { this.status = status; return this; } public SampleInternal getInternal() { return internal; } public Sample setInternal(SampleInternal internal) { this.internal = internal; return this; } public Map<String, Object> getAttributes() { return attributes; } public Sample setAttributes(Map<String, Object> attributes) { this.attributes = attributes; return this; } @Override public Sample setAnnotationSets(List<AnnotationSet> annotationSets) { super.setAnnotationSets(annotationSets); return this; } public List<String> getCohortIds() { return cohortIds; } public Sample setCohortIds(List<String> cohortIds) { this.cohortIds = cohortIds; return this; } }
apache-2.0
dagnir/aws-sdk-java
aws-java-sdk-core/src/test/java/com/amazonaws/retry/AmazonHttpClientRetryPolicyTest.java
13339
/* * Copyright 2010-2017 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.retry; import java.io.IOException; import java.util.Random; import java.util.UUID; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.Request; import com.amazonaws.http.AmazonHttpClient; import com.amazonaws.http.ExecutionContext; import com.amazonaws.util.AWSRequestMetrics; /** * Tests that {@link AmazonHttpClient#executeHelper()} method passes the correct * context information into the configured RetryPolicy. */ public class AmazonHttpClientRetryPolicyTest extends RetryPolicyTestBase { private static final int EXPECTED_RETRY_COUNT = 5; private static final Random random = new Random(); private AmazonHttpClient testedClient; /** Reset the RetryPolicy and restart collecting context data */ @Before public void resetContextData() { retryCondition = new ContextDataCollectionRetryCondition(); backoffStrategy = new ContextDataCollectionBackoffStrategy(); // Reset the RetryPolicy clientConfiguration.setRetryPolicy( new RetryPolicy(retryCondition, backoffStrategy, EXPECTED_RETRY_COUNT, // max error retry false)); // ignore the maxErrorRetry in ClientConfiguration level testedClient = new AmazonHttpClient(clientConfiguration); } /** * Tests AmazonHttpClient's behavior upon simulated service exceptions when the * request payload is repeatable. */ @Test public void testServiceExceptionHandling() { int random500StatusCode = 500 + random.nextInt(100); String randomErrorCode = UUID.randomUUID().toString(); // A mock HttpClient that always returns the specified status and error code. injectMockHttpClient(testedClient, new ReturnServiceErrorHttpClient(random500StatusCode, randomErrorCode)); // The ExecutionContext should collect the expected RequestCount ExecutionContext context = new ExecutionContext(true); Request<?> testedRepeatableRequest = getSampleRequestWithRepeatableContent(originalRequest); // It should keep retrying until it reaches the max retry limit and // throws the simulated ASE. AmazonServiceException expectedServiceException = null; try { testedClient.requestExecutionBuilder() .request(testedRepeatableRequest) .errorResponseHandler(errorResponseHandler) .executionContext(context) .execute(); Assert.fail("AmazonServiceException is expected."); } catch (AmazonServiceException ase) { // We should see the original service exception Assert.assertEquals(random500StatusCode, ase.getStatusCode()); Assert.assertEquals(randomErrorCode, ase.getErrorCode()); expectedServiceException = ase; } // Verifies that the correct information was passed into the RetryCondition and BackoffStrategy verifyExpectedContextData(retryCondition, originalRequest, expectedServiceException, EXPECTED_RETRY_COUNT); verifyExpectedContextData(backoffStrategy, originalRequest, expectedServiceException, EXPECTED_RETRY_COUNT); // We also want to check the RequestCount metric is correctly captured. Assert.assertEquals( EXPECTED_RETRY_COUNT + 1, // request count = retries + 1 context.getAwsRequestMetrics() .getTimingInfo().getCounter(AWSRequestMetrics.Field.RequestCount.toString()).intValue()); } /** * Tests AmazonHttpClient's behavior upon simulated IOException during * executing the http request when the request payload is repeatable. */ @Test public void testIOExceptioinHandling() { // A mock HttpClient that always throws the specified IOException object IOException simulatedIOException = new IOException("fake IOException"); injectMockHttpClient(testedClient, new ThrowingExceptionHttpClient(simulatedIOException)); // The ExecutionContext should collect the expected RequestCount ExecutionContext context = new ExecutionContext(true); Request<?> testedRepeatableRequest = getSampleRequestWithRepeatableContent(originalRequest); // It should keep retrying until it reaches the max retry limit and // throws the an ACE containing the simulated IOException. AmazonClientException expectedClientException = null; try { testedClient.requestExecutionBuilder() .request(testedRepeatableRequest) .errorResponseHandler(errorResponseHandler) .executionContext(context) .execute(); Assert.fail("AmazonClientException is expected."); } catch (AmazonClientException ace) { Assert.assertTrue(simulatedIOException == ace.getCause()); expectedClientException = ace; } // Verifies that the correct information was passed into the RetryCondition and BackoffStrategy verifyExpectedContextData(retryCondition, originalRequest, expectedClientException, EXPECTED_RETRY_COUNT); verifyExpectedContextData(backoffStrategy, originalRequest, expectedClientException, EXPECTED_RETRY_COUNT); // We also want to check the RequestCount metric is correctly captured. Assert.assertEquals( EXPECTED_RETRY_COUNT + 1, // request count = retries + 1 context.getAwsRequestMetrics() .getTimingInfo().getCounter(AWSRequestMetrics.Field.RequestCount.toString()).intValue()); } /** * Tests AmazonHttpClient's behavior upon simulated service exceptions when the * request payload is not repeatable. */ @Test public void testServiceExceptionHandlingWithNonRepeatableRequestContent() { int random500StatusCode = 500 + random.nextInt(100); String randomErrorCode = UUID.randomUUID().toString(); // A mock HttpClient that always returns the specified status and error code. injectMockHttpClient(testedClient, new ReturnServiceErrorHttpClient(random500StatusCode, randomErrorCode)); // The ExecutionContext should collect the expected RequestCount ExecutionContext context = new ExecutionContext(true); // A non-repeatable request Request<?> testedNonRepeatableRequest = getSampleRequestWithNonRepeatableContent(originalRequest); // It should fail directly and throw the ASE, without consulting the // custom shouldRetry(..) method. try { testedClient.requestExecutionBuilder() .request(testedNonRepeatableRequest) .errorResponseHandler(errorResponseHandler) .executionContext(context) .execute(); Assert.fail("AmazonServiceException is expected."); } catch (AmazonServiceException ase) { Assert.assertEquals(random500StatusCode, ase.getStatusCode()); Assert.assertEquals(randomErrorCode, ase.getErrorCode()); } // Verifies that shouldRetry and calculateSleepTime were never called verifyExpectedContextData(retryCondition, null, null, EXPECTED_RETRY_COUNT); verifyExpectedContextData(backoffStrategy, null, null, EXPECTED_RETRY_COUNT); Assert.assertEquals( EXPECTED_RETRY_COUNT + 1, // request count = retries + 1 context.getAwsRequestMetrics() .getTimingInfo().getCounter(AWSRequestMetrics.Field.RequestCount.toString()).intValue()); } /** * Tests AmazonHttpClient's behavior upon simulated IOException when the * request payload is not repeatable. */ @Test public void testIOExceptionHandlingWithNonRepeatableRequestContent() { // A mock HttpClient that always throws the specified IOException object IOException simulatedIOException = new IOException("fake IOException"); injectMockHttpClient(testedClient, new ThrowingExceptionHttpClient(simulatedIOException)); // The ExecutionContext should collect the expected RequestCount ExecutionContext context = new ExecutionContext(true); // A non-repeatable request Request<?> testedRepeatableRequest = getSampleRequestWithNonRepeatableContent(originalRequest); // It should fail directly and throw an ACE containing the simulated // IOException, without consulting the // custom shouldRetry(..) method. try { testedClient.requestExecutionBuilder() .request(testedRepeatableRequest) .errorResponseHandler(errorResponseHandler) .executionContext(context) .execute(); Assert.fail("AmazonClientException is expected."); } catch (AmazonClientException ace) { Assert.assertTrue(simulatedIOException == ace.getCause()); } // Verifies that shouldRetry and calculateSleepTime are still called verifyExpectedContextData(retryCondition, null, null, EXPECTED_RETRY_COUNT); verifyExpectedContextData(backoffStrategy, null, null, EXPECTED_RETRY_COUNT); Assert.assertEquals( EXPECTED_RETRY_COUNT + 1, // request count = retries + 1 context.getAwsRequestMetrics() .getTimingInfo().getCounter(AWSRequestMetrics.Field.RequestCount.toString()).intValue()); } /** * Tests AmazonHttpClient's behavior upon simulated RuntimeException (which * should be handled as an unexpected failure and not retried). */ @Test public void testUnexpectedFailureHandling() { // A mock HttpClient that always throws an NPE NullPointerException simulatedNPE = new NullPointerException("fake NullPointerException"); injectMockHttpClient(testedClient, new ThrowingExceptionHttpClient(simulatedNPE)); // The ExecutionContext should collect the expected RequestCount ExecutionContext context = new ExecutionContext(true); Request<?> testedRepeatableRequest = getSampleRequestWithRepeatableContent(originalRequest); // It should fail directly and throw the simulated NPE, without // consulting the custom shouldRetry(..) method. try { testedClient.requestExecutionBuilder() .request(testedRepeatableRequest) .errorResponseHandler(errorResponseHandler) .executionContext(context) .execute(); Assert.fail("AmazonClientException is expected."); } catch (NullPointerException npe) { Assert.assertTrue(simulatedNPE == npe); } // Verifies that shouldRetry and calculateSleepTime were never called verifyExpectedContextData(retryCondition, null, null, 0); verifyExpectedContextData(backoffStrategy, null, null, 0); // The captured RequestCount should be 1 Assert.assertEquals( 1, context.getAwsRequestMetrics() .getTimingInfo().getCounter(AWSRequestMetrics.Field.RequestCount.toString()).intValue()); } }
apache-2.0
lecousin/java-framework-core
net.lecousin.core/src/main/java/net/lecousin/framework/io/data/BytesFromIso8859CharArray.java
2800
package net.lecousin.framework.io.data; import java.nio.ByteBuffer; /** Readable bytes from readable CharArray of ISO-8859 characters. */ public class BytesFromIso8859CharArray implements Bytes.Readable { protected CharArray array; protected boolean freeCharArrayOnFree; /** Constructor. */ public BytesFromIso8859CharArray(CharArray array, boolean freeCharArrayOnFree) { this.array = array; this.freeCharArrayOnFree = freeCharArrayOnFree; } @Override public void setPosition(int position) { array.setPosition(position); } @Override public int length() { return array.length(); } @Override public int remaining() { return array.remaining(); } @Override public boolean hasRemaining() { return array.hasRemaining(); } @Override public int position() { return array.position(); } /** Return the original CharArray from which this object has been created. */ public CharArray getOriginalBuffer() { return array; } @Override public byte getForward(int offset) { return (byte)array.getForward(offset); } @Override public void get(byte[] buffer, int offset, int length) { for (int i = 0; i < length; ++i) buffer[offset + i] = get(); } @Override public byte get() { return (byte)array.get(); } @Override public ByteBuffer toByteBuffer() { byte[] bytes = new byte[remaining()]; get(bytes, 0, bytes.length); return ByteBuffer.wrap(bytes); } @Override public BytesFromIso8859CharArray subBuffer(int startPosition, int length) { return new BytesFromIso8859CharArray(array.subBuffer(startPosition, length), false); } @Override public void free() { if (freeCharArrayOnFree) array.free(); } /** Writable bytes from writable CharArray of ISO-8859 characters. */ public static class Writable extends BytesFromIso8859CharArray implements Bytes.Writable { /** Constructor. */ public Writable(CharArray.Writable array, boolean freeCharArrayOnFree) { super(array, freeCharArrayOnFree); } /** Return the original CharArray.Writable from which this object has been created. */ @Override public CharArray.Writable getOriginalBuffer() { return (CharArray.Writable)array; } @Override public BytesFromIso8859CharArray.Writable subBuffer(int startPosition, int length) { return new BytesFromIso8859CharArray.Writable(((CharArray.Writable)array).subBuffer(startPosition, length), false); } @Override public void put(byte b) { ((CharArray.Writable)array).put((char)(b & 0xFF)); } @Override public void put(byte[] buffer, int offset, int length) { for (int i = 0; i < length; ++i) ((CharArray.Writable)array).put((char)(buffer[offset + i] & 0xFF)); } @Override public ByteBuffer toByteBuffer() { throw new UnsupportedOperationException(); } } }
apache-2.0
edgar615/javase-study
designpattern-study/src/test/java/com/edgar/designpattern/templatemethod/ftoc/Ftocraw.java
798
package com.edgar.designpattern.templatemethod.ftoc; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Ftocraw { /** * @param args * @throws java.io.IOException */ public static void main(String[] args) throws IOException { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); boolean done = false; while (!done) { String fahrString = br.readLine(); if (fahrString == null || fahrString.length() == 0) { done = true; } else { double fahr = Double.parseDouble(fahrString); double celcius = 5.0/9.0*(fahr - 32); System.out.println("F=" + fahr + ", C=" + celcius); } } System.out.println("ftoc exit"); } }
apache-2.0
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/InternalEventTracker.java
974
package com.wonderpush.sdk; import org.json.JSONObject; public class InternalEventTracker { InternalEventTracker() {} public void trackInternalEvent(String type, JSONObject eventData, JSONObject customData) { WonderPush.trackInternalEvent(type, eventData, customData); } public void trackInternalEvent(String type, JSONObject eventData) { WonderPush.trackInternalEvent(type, eventData); } public void countInternalEvent(String type, JSONObject eventData) { WonderPush.countInternalEvent(type, eventData); } public void countInternalEvent(String type, JSONObject eventData, JSONObject customData) { WonderPush.countInternalEvent(type, eventData, customData); } public WonderPush.SubscriptionStatus getSubscriptionStatus() { return WonderPush.getSubscriptionStatus(); } public boolean isSubscriptionStatusOptIn() { return WonderPush.isSubscriptionStatusOptIn(); } }
apache-2.0
onyxbits/raccoon4
src/main/java/de/onyxbits/weave/swing/ImageLoaderListener.java
968
/* * Copyright 2015 Patrick Ahlbrecht * * 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.onyxbits.weave.swing; import java.awt.Image; /** * Callback interface * * @author patrick * */ public interface ImageLoaderListener { /** * Called when a requested image is ready. * * @param source * where the image was loaded from * @param img * the image */ public void onImageReady(String source, Image img); }
apache-2.0
okinawaopenlabs/of-patch-manager
src/main/java/org/okinawaopenlabs/ofpm/json/topology/logical/LogicalLink.java
2255
/* * Copyright 2015 Okinawa Open Laboratory, General Incorporated Association * * 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.okinawaopenlabs.ofpm.json.topology.logical; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.okinawaopenlabs.ofpm.json.device.PortData; public class LogicalLink implements Cloneable { private List<PortData> link; /* Setters and Getters */ public List<PortData> getLink() { return link; } public void setLink(List<PortData> link) { this.link = link; } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(this.getClass() != obj.getClass()) return false; LogicalLink other = (LogicalLink)obj; if (other.link == this.link) return true; if (other.link == null) return false; if (this.link == null) return false; if (!other.link.containsAll(this.link)) return false; if (!this.link.containsAll(other.link)) return false; return true; } @Override public int hashCode() { int hash = 0; if (this.link != null) { for (PortData port : this.link) { hash += port.hashCode(); } } return hash; } @Override public LogicalLink clone() { LogicalLink newObj = new LogicalLink(); if (this.link != null) { newObj.link = new ArrayList<PortData>(); for (PortData port : this.link) { newObj.link.add(port.clone()); } } return newObj; } public String toJson() { Gson gson = new Gson(); Type type = new TypeToken<LogicalLink>(){}.getType(); return gson.toJson(this, type); } @Override public String toString() { return this.toJson(); } }
apache-2.0