text
stringlengths 7
1.01M
|
|---|
package com.lfp.zt.pattern.establish.singleton;
/**
* Project: zt-javabase
* Title: 懒汉式单例
* Description: 利用双重校验锁方式实现。
* Date: 2019-01-02
* Copyright: Copyright (c) 2019
* Company: LFP
*
* @author ZhuTao
* @version 2.0
*/
public class LazySingleton {
private volatile static LazySingleton instance;
private LazySingleton() {
System.out.println(this.getClass().getSimpleName()+" 初始化......");
}
public static LazySingleton getInstance(){
if (instance==null){ // 首次检测,减少后续加锁操作调用次数
synchronized (LazySingleton.class){ // 加锁,保证顺序执行
if (instance==null){ // 再次检测,因为首次检测可能会进来多个线程,在加锁后顺序执行,
// 在次此检测可以保证只有第一个线程执行,后续的就无需执行。
instance = new LazySingleton(); // 该步骤包括:1、分配内存空间,2、初始化对象,3、对象指向内存,
// 因为new对象是多个指令,可能出现重排序,利用volatile关键字防止重排序
}
}
}
return instance;
}
@Override
public String toString() {
return this.getClass().getSimpleName()+" 运行......";
}
}
|
package com.insoul.rental;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import org.apache.commons.io.IOUtils;
public class InitSQLiteDB {
public static void main(String[] args) {
try {
ClassLoader classLoader = InitSQLiteDB.class.getClassLoader();
String sql = IOUtils.toString(classLoader.getResourceAsStream("schema.sql"));
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:db/rental.db");
Statement statement = conn.createStatement();
statement.executeUpdate(sql);
statement.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
public class exChar {
public static void main (String[] args) {
char ch1, ch2, ch3, ch4;
ch1 = 88;
ch2 = 'Y';
ch3 = ch1++;
ch4 = ch2--;
System.out.println ("Символ Y в системе 88, а X 89");
System.out.println("Первая переменная равна " + ch1 + " , а вторая переменная равна " + ch2);
System.out.println("Теперь мы как бы добавили символу Y (88)(его значению 1, то есть чтобы он стал следующим символом (89)) " + ch3);
System.out.println("Теперь мы отняли у символа X (89) (у его значения 1, то есть чтобы он стал предыдущим (88)) " + ch4);
}
}
|
package pers.fcz.rabbitmq.website.topic;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.util.Scanner;
/**
* RabbitMQ官网教程 Topic 模式 (发送消息)
* @author Mr.F
* @since 2019/7/26 10:55
**/
public class EmitLogTopic {
private static final String EXCHANGE_NAME = "topic_logs";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
try (Connection connection = factory.newConnection();
Channel channel = connection.createChannel()) {
channel.exchangeDeclare(EXCHANGE_NAME, "topic");
while (true) {
Scanner scanner = new Scanner(System.in);
// 队列名称
System.out.println("Please print routingKey: ");
String routingKey = scanner.nextLine();;
// 消息
System.out.println("Please send message: ");
String message = scanner.nextLine();
channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes("UTF-8"));
System.out.println(" [x] Sent '" + routingKey + "':'" + message + "'");
}
}
}
}
|
/*
*
*
*
*
*
*
*
*
*
*
*
*
*/
/*
* IncremenalConverter.java
* Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.converters;
/**
* Marker interface for a loader/saver that can retrieve instances incrementally
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision 1.0 $
*/
public interface IncrementalConverter {
}
|
package cz.cvut.fit.miadp.mvcgame.bridge;
import cz.cvut.fit.miadp.mvcgame.config.MvcGameConfig;
import cz.cvut.fit.miadp.mvcgame.model.geometry.Position;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
public class JavaFxGraphics implements IGameGraphicsImplementor{
private GraphicsContext gc;
public JavaFxGraphics(GraphicsContext gc) {
this.gc = gc;
}
private Map<String, Image> imageCache = new HashMap<>();
@Override
public void drawImage(String path, Position pos) {
Image img;
if (imageCache.containsKey(path)){
img = imageCache.get(path);
}else{
img = new Image(path);
imageCache.put(path, img);
}
this.gc.drawImage(img, pos.getX() - img.getWidth()/2, pos.getY() - img.getHeight()/2);
}
@Override
public void drawText(String text, Position pos) {
this.gc.strokeText(text, pos.getX(), pos.getY());
}
@Override
public void drawLine(Position begin, Position end) {
this.gc.strokeLine(begin.getX(), begin.getY(), end.getX(), end.getY());
}
@Override
public void clear() {
this.gc.clearRect(0, 0, MvcGameConfig.MAX_X, MvcGameConfig.MAX_Y);
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.spi.core.remoting;
/**
* A ConnectionLifeCycleListener is called by the remoting implementation to notify of connection events.
* @deprecated use {@link ClientConnectionLifeCycleListener} instead.
*/
@Deprecated
public interface ConnectionLifeCycleListener extends BaseConnectionLifeCycleListener<String> {
}
|
package com.taolibrary.util.time;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* 文件作者:余涛
* 功能描述:日期工具
* 创建时间:2019/9/22 15:43
*/
public class DateUtils {
/**
* 格式化时间
* @param formatType 格式类型 eg:"yyyy-MM-dd HH-mm-ss"
* @param time date.getTime()
* @return
*/
public static String formatTime(String formatType, long time) {
//使用common-lang包下面的DateFormatUtils类
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(formatType);
return simpleDateFormat.format(time);
}
/**
* 通过日期格式获取Date数据
* @param formatType 格式类型 eg:"yyyy-MM-dd HH:mm:ss"
* @param formatData 相应的格式化数据 eg:2018-08-08 15:14:00
* @return Data类型
*/
public static Date getDateByString(String formatType, String formatData) {
Date date = null;
if(formatData == null) {
return date;
}
SimpleDateFormat format = new SimpleDateFormat(formatType);
try {
date = format.parse(formatData);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
/**
* 通过日期格式获取相应的String类型日期
* @param formatType 格式类型 eg:"yyyy-MM-dd HH:mm:ss"
* @param date
* @return 返回相应格式化时间,String类型
*/
public static String getTimeByDate(String formatType, Date date) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(formatType);
String time = simpleDateFormat.format(date);
return time;
}
/**
* 通过相应的格式化类型数据,获取和现在的相隔时间
* @param formatType 格式类型 eg:"yyyy-MM-dd HH:mm:ss"
* @param formatData 相应的格式化数据 eg:2018-08-08 15:14:00
* @return
*/
public static String getShortTime(String formatType, String formatData) {
String shortString = null;
long now = Calendar.getInstance().getTimeInMillis();
Date date = getDateByString(formatType, formatData);
if(date == null) {
return shortString;
}
long delTime = (now - date.getTime()) / 1000;
if (delTime > 365 * 24 * 60 * 60) {
shortString = (int) (delTime / (365 * 24 * 60 * 60)) + "年前";
} else if (delTime > 24 * 60 * 60) {
shortString = (int) (delTime / (24 * 60 * 60)) + "天前";
} else if (delTime > 60 * 60) {
shortString = (int) (delTime / (60 * 60)) + "小时前";
} else if (delTime > 60) {
shortString = (int) (delTime / (60)) + "分前";
} else if (delTime > 1) {
shortString = delTime + "秒前";
} else {
shortString = "1秒前";
}
return shortString;
}
/**
* 获取星期
* @param date
* @return 星期信息
*/
public static String dayForWeek(Date date){
String[] weekDays = { "周日", "周一", "周二", "周三", "周四", "周五", "周六"};
Calendar cal = Calendar.getInstance();
try {
cal.setTime(date);
} catch (Exception e) {
e.printStackTrace();
}
int w = cal.get(Calendar.DAY_OF_WEEK) - 1; // 指示一个星期中的某天。
if (w < 0)
w = 0;
return weekDays[w];
}
/**
* 获取星期
* @param date
* @return 星期信息 数字
*/
public static int dayForWeekDig(Date date){
int[] weekDays = { 7, 1, 2, 3, 4, 5, 6};
Calendar cal = Calendar.getInstance();
try {
cal.setTime(date);
} catch (Exception e) {
e.printStackTrace();
}
int w = cal.get(Calendar.DAY_OF_WEEK) - 1; // 指示一个星期中的某天。
if (w < 0)
w = 0;
return weekDays[w];
}
/**
* 获取网络时间 (默认百度)
* @param format 时间格式 eg:"yyyy-MM-dd HH:mm:ss"
* @return 返回格式化的时间 String类型
*/
public static String getNetworkTime(String format) {
return getNetworkTime("http://www.baidu.com", format);
}
/**
* 获取网络时间
* @param webUrl 链接
* @param format 时间格式 eg:"yyyy-MM-dd HH:mm:ss"
* @return 返回格式化的时间 String类型
*/
public static String getNetworkTime(String webUrl, String format) {
try {
URL url=new URL(webUrl);
URLConnection conn=url.openConnection();
conn.connect();
long dateL=conn.getDate();
Date date=new Date(dateL);
//在这里,如果是想返回sql的Date类型则修改方法的返回类型
//将目前获取到的网络时间util.Date转换成sql.Date的操作如下:
// java.sql.Date date1=new java.sql.Date(date.getTime());//年 月 日
//java.sql.Time date2=new java.sql.Time(date.getTime());//时 分 秒
//java.sql.Timestamp date3=new java.sql.Timestamp(date.getTime());//年 月 日 时 分 秒 毫秒
//System.out.println("输出当前时间年月日"+date1);
// System.out.println("输出当前时间时分秒"+date2);
//System.out.println("输出当前时间年月日时分秒毫秒"+date3);
//以下是将时间转换成String类型并返回
SimpleDateFormat dateFormat=new SimpleDateFormat(format);
return dateFormat.format(date);
}catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
return "";
}
}
|
/*
* 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.cloud.bigtable.hbase1_x;
import static com.google.common.truth.Truth.assertThat;
import com.google.api.gax.core.NoCredentialsProvider;
import com.google.auth.Credentials;
import com.google.bigtable.v2.*;
import com.google.bigtable.v2.ReadRowsResponse.CellChunk;
import com.google.cloud.bigtable.hbase.BigtableConfiguration;
import com.google.cloud.bigtable.hbase.BigtableOptionsFactory;
import com.google.cloud.bigtable.metrics.BigtableClientMetrics;
import com.google.cloud.bigtable.metrics.BigtableClientMetrics.MetricLevel;
import com.google.cloud.bigtable.metrics.Counter;
import com.google.cloud.bigtable.metrics.Meter;
import com.google.cloud.bigtable.metrics.MetricRegistry;
import com.google.cloud.bigtable.metrics.Timer;
import com.google.cloud.bigtable.test.helper.TestServerBuilder;
import com.google.common.base.Stopwatch;
import com.google.common.collect.Range;
import com.google.protobuf.ByteString;
import com.google.protobuf.BytesValue;
import com.google.protobuf.StringValue;
import io.grpc.Server;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import io.grpc.stub.StreamObserver;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.client.Row;
import org.apache.hadoop.hbase.shaded.org.apache.commons.lang.RandomStringUtils;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class TestMetrics {
private final String TEST_PROJECT_ID = "fake-project-id";
private final String TEST_INSTANCE_ID = "fake-instance-id";
private final TableName TABLE_NAME = TableName.valueOf("fake-table");
private Server server;
private FakeMetricRegistry fakeMetricRegistry;
private MetricRegistry originalMetricRegistry;
private BigtableClientMetrics.MetricLevel originalLevelToLog;
private static final FakeDataService fakeDataService = new FakeDataService();
private BigtableConnection connection;
private static final byte[] rowKey = Bytes.toBytes("row");
private static final byte[] columnFamily = Bytes.toBytes("cf");
private static final byte[] qualifier = Bytes.toBytes("q");
private static final byte[] value = Bytes.toBytes("value");
private static final ReadRowsResponse readRowsResponse =
ReadRowsResponse.newBuilder()
.addChunks(
CellChunk.newBuilder()
.setRowKey(ByteString.copyFrom(rowKey))
.setFamilyName(StringValue.of("cf"))
.setQualifier(BytesValue.newBuilder().setValue(ByteString.copyFrom(qualifier)))
.setTimestampMicros(1_000)
.setValue(ByteString.copyFrom(value))
.setCommitRow(true))
.build();
private static final Status fakeErrorStatus = Status.UNAVAILABLE;
private static final int fakeErrorCount = 3;
@Before
public void setUp() throws IOException {
server = TestServerBuilder.newInstance().addService(fakeDataService).buildAndStart();
originalLevelToLog = BigtableClientMetrics.getLevelToLog();
originalMetricRegistry = BigtableClientMetrics.getMetricRegistry(originalLevelToLog);
Configuration configuration = new Configuration(false);
configuration.set(BigtableOptionsFactory.PROJECT_ID_KEY, TEST_PROJECT_ID);
configuration.set(BigtableOptionsFactory.INSTANCE_ID_KEY, TEST_INSTANCE_ID);
configuration.set(BigtableOptionsFactory.BIGTABLE_NULL_CREDENTIAL_ENABLE_KEY, "true");
configuration.set(BigtableOptionsFactory.BIGTABLE_DATA_CHANNEL_COUNT_KEY, "1");
configuration.set(
BigtableOptionsFactory.BIGTABLE_EMULATOR_HOST_KEY, "localhost:" + server.getPort());
configuration.set(BigtableOptionsFactory.BIGTABLE_USE_GCJ_CLIENT, "true");
fakeMetricRegistry = new FakeMetricRegistry();
BigtableClientMetrics.setMetricRegistry(fakeMetricRegistry);
BigtableClientMetrics.setLevelToLog(MetricLevel.Trace);
connection = new BigtableConnection(configuration);
}
@After
public void tearDown() throws IOException, InterruptedException {
if (server != null) {
server.shutdownNow();
server.awaitTermination();
}
connection.close();
BigtableClientMetrics.setMetricRegistry(originalMetricRegistry);
BigtableClientMetrics.setLevelToLog(originalLevelToLog);
fakeDataService.reset();
}
/*
* This tests metric instrumentation by using a fake service to inject failures.
* The fake service will fail the first 3 readrows requests, causing the client to start exponential retries.
*/
@Test
public void readRows() throws IOException, InterruptedException {
Table table = connection.getTable(TABLE_NAME);
Stopwatch stopwatch = Stopwatch.createStarted();
Result result = table.get(new Get(new byte[2]));
long methodInvocationLatency = stopwatch.elapsed(TimeUnit.MILLISECONDS);
fakeDataService.popLastRequest();
long tableGetLatencyMetric =
fakeMetricRegistry.results.get("google-cloud-bigtable.table.get.latency").get();
long retriesPerformedMetric =
fakeMetricRegistry
.results
.get("google-cloud-bigtable.grpc.method.ReadRow.retries.performed")
.get();
long clientOperationLatencyMetric =
fakeMetricRegistry
.results
.get("google-cloud-bigtable.grpc.method.ReadRow.operation.latency")
.get();
long rpcErrorsMetric =
fakeMetricRegistry
.results
.get("google-cloud-bigtable.grpc.errors." + fakeErrorStatus.getCode().name())
.get();
long rpcPerformedMetric =
fakeMetricRegistry.results.get("google-cloud-bigtable.grpc.rpc.performed").get();
assertThat(retriesPerformedMetric).isEqualTo(fakeErrorCount);
assertThat(tableGetLatencyMetric).isAtMost(methodInvocationLatency);
assertThat(clientOperationLatencyMetric).isAtMost(methodInvocationLatency);
assertThat(rpcErrorsMetric).isEqualTo(fakeErrorCount);
assertThat(rpcPerformedMetric).isEqualTo(fakeErrorCount + 1);
// ReadRows sleeps 40 milliseconds before returning the response. Wait for response to return
// and verify again there should have no more active rpc
Thread.sleep(40);
long activeRpcMetric =
fakeMetricRegistry.results.get("google-cloud-bigtable.grpc.rpc.active").get();
assertThat(activeRpcMetric).isEqualTo(0);
}
@Test
public void rowMutations() throws IOException {
Table table = connection.getTable(TABLE_NAME);
RowMutations row = new RowMutations(rowKey);
row.add(new Put(rowKey).addColumn(columnFamily, qualifier, value));
Stopwatch stopwatch = Stopwatch.createStarted();
table.mutateRow(row);
long methodInvocationLatency = stopwatch.elapsed(TimeUnit.MILLISECONDS);
fakeDataService.popLastRequest();
long latency =
fakeMetricRegistry
.results
.get("google-cloud-bigtable.grpc.method.MutateRow.rpc.latency")
.get();
assertThat(latency)
.isIn(
Range.closed(fakeDataService.getMutateRowServerSideLatency(), methodInvocationLatency));
}
@Test
public void appendFailure() throws IOException {
Table table = connection.getTable(TABLE_NAME);
Append append = new Append(rowKey);
append.add(columnFamily, qualifier, value);
Stopwatch stopwatch = Stopwatch.createUnstarted();
try {
stopwatch.start();
table.append(append);
Assert.fail("operation should have failed");
} catch (Exception e) {
long methodInvocationLatency = stopwatch.elapsed(TimeUnit.MILLISECONDS);
fakeDataService.popLastRequest();
long failureCount =
fakeMetricRegistry
.results
.get("google-cloud-bigtable.grpc.method.ReadModifyWriteRow.failure")
.get();
long operationLatency =
fakeMetricRegistry
.results
.get("google-cloud-bigtable.grpc.method.ReadModifyWriteRow.operation.latency")
.get();
assertThat(failureCount).isEqualTo(1);
assertThat(operationLatency)
.isIn(
Range.closed(
fakeDataService.getReadModifyWriteRowServerSideLatency(),
methodInvocationLatency));
}
}
@Test
public void testScanMetrics() throws IOException {
Scan scan = new Scan().withStartRow(rowKey).withStopRow(rowKey, true);
Table table = connection.getTable(TABLE_NAME);
Stopwatch stopwatch = Stopwatch.createStarted();
ResultScanner testScanner = table.getScanner(scan);
testScanner.next();
testScanner.close();
long methodInvocationLatency = stopwatch.elapsed(TimeUnit.MILLISECONDS);
fakeDataService.popLastRequest();
long scannerResultsLatencyMetric =
fakeMetricRegistry.results.get("google-cloud-bigtable.scanner.results.latency").get();
long scannerResultsMetric =
fakeMetricRegistry.results.get("google-cloud-bigtable.scanner.results").get();
assertThat(scannerResultsMetric).isEqualTo(1);
assertThat(scannerResultsLatencyMetric).isAtMost(methodInvocationLatency);
}
@Test
public void testFirstResponseLatency() throws IOException {
Scan scan = new Scan().withStartRow(rowKey).withStopRow(rowKey, true);
Table table = connection.getTable(TABLE_NAME);
Stopwatch stopwatch = Stopwatch.createStarted();
ResultScanner testScanner = table.getScanner(scan);
testScanner.next();
testScanner.close();
long methodInvocationLatency = stopwatch.elapsed(TimeUnit.MILLISECONDS);
fakeDataService.popLastRequest();
long firstResponseLatencyMetric =
fakeMetricRegistry
.results
.get("google-cloud-bigtable.grpc.method.ReadRows.firstResponse.latency")
.get();
// adding buffer time to the upper range to allow for a race between the emulator and the client
// recording the duration
assertThat(firstResponseLatencyMetric).isAtMost(methodInvocationLatency - 20 / 2);
}
@Test
public void testActiveSessionsAndChannels() throws IOException {
// There should already be 1 active session and 1 channel from connection (connecting to
// emulator will set pool size to 1)
long currentActiveSessions =
fakeMetricRegistry.results.get("google-cloud-bigtable.session.active").get();
long currentActiveChannels =
fakeMetricRegistry.results.get("google-cloud-bigtable.grpc.channel.active").get();
assertThat(currentActiveSessions).isEqualTo(1);
assertThat(currentActiveChannels).isEqualTo(1);
// Create a new session
int connectionCount = 10;
Configuration configuration = new Configuration(false);
configuration.set(BigtableOptionsFactory.PROJECT_ID_KEY, TEST_PROJECT_ID);
configuration.set(BigtableOptionsFactory.INSTANCE_ID_KEY, TEST_INSTANCE_ID);
configuration.set(BigtableOptionsFactory.BIGTABLE_NULL_CREDENTIAL_ENABLE_KEY, "true");
configuration.set(
BigtableOptionsFactory.BIGTABLE_DATA_CHANNEL_COUNT_KEY, String.valueOf(connectionCount));
configuration.set(BigtableOptionsFactory.BIGTABLE_USE_GCJ_CLIENT, "true");
BigtableConnection newConnection = new BigtableConnection(configuration);
currentActiveSessions =
fakeMetricRegistry.results.get("google-cloud-bigtable.session.active").get();
currentActiveChannels =
fakeMetricRegistry.results.get("google-cloud-bigtable.grpc.channel.active").get();
assertThat(currentActiveSessions).isEqualTo(2);
assertThat(currentActiveChannels).isEqualTo(connectionCount + 1);
newConnection.close();
currentActiveSessions =
fakeMetricRegistry.results.get("google-cloud-bigtable.session.active").get();
currentActiveChannels =
fakeMetricRegistry.results.get("google-cloud-bigtable.grpc.channel.active").get();
assertThat(currentActiveSessions).isEqualTo(1);
assertThat(currentActiveChannels).isEqualTo(1);
}
@Test
public void testChannelPoolCachingActiveChannel() throws Exception {
// Test channel pool caching
int connectionCount = 10;
Configuration configuration = new Configuration(false);
configuration.set(BigtableOptionsFactory.PROJECT_ID_KEY, TEST_PROJECT_ID);
configuration.set(BigtableOptionsFactory.INSTANCE_ID_KEY, TEST_INSTANCE_ID);
configuration.set(
BigtableOptionsFactory.BIGTABLE_DATA_CHANNEL_COUNT_KEY, String.valueOf(connectionCount));
configuration.set(BigtableOptionsFactory.BIGTABLE_USE_GCJ_CLIENT, "true");
configuration.set(BigtableOptionsFactory.BIGTABLE_USE_CACHED_DATA_CHANNEL_POOL, "true");
Credentials credentials = NoCredentialsProvider.create().getCredentials();
configuration = BigtableConfiguration.withCredentials(configuration, credentials);
BigtableConnection sharedConnection1 = new BigtableConnection(configuration);
BigtableConnection sharedConnection2 = new BigtableConnection(configuration);
long currentActiveChannels =
fakeMetricRegistry.results.get("google-cloud-bigtable.grpc.channel.active").get();
// sharedConnection1 and 2 should share channels, plus the 1 that's created in setup
assertThat(currentActiveChannels).isEqualTo(connectionCount + 1);
// closing one shared bigtable connection shouldn't decrement shared channels count
sharedConnection1.close();
currentActiveChannels =
fakeMetricRegistry.results.get("google-cloud-bigtable.grpc.channel.active").get();
assertThat(currentActiveChannels).isEqualTo(connectionCount + 1);
// Active channels should be 1 after both shared bigtable connections are closed
sharedConnection2.close();
currentActiveChannels =
fakeMetricRegistry.results.get("google-cloud-bigtable.grpc.channel.active").get();
assertThat(currentActiveChannels).isEqualTo(1);
Thread.sleep(100);
}
@Test
public void testBulkMutationMetrics() throws IOException, InterruptedException {
Table table = connection.getTable(TABLE_NAME);
List<Row> rows = new ArrayList<>();
int entries = 20;
for (int i = 0; i < entries; i++) {
rows.add(
new Put(Bytes.toBytes(RandomStringUtils.random(8)))
.addColumn(Bytes.toBytes("cf"), Bytes.toBytes("q"), Bytes.toBytes("SomeValue")));
}
Object[] resultsOrErrors = new Object[rows.size()];
table.batch(rows, resultsOrErrors);
long mutationAdded =
fakeMetricRegistry.results.get("google-cloud-bigtable.bulk-mutator.mutations.added").get();
assertThat(mutationAdded).isEqualTo(entries);
table.close();
}
private static class FakeDataService extends BigtableGrpc.BigtableImplBase {
private final AtomicLong callCount = new AtomicLong(1);
private final Stopwatch readRowsStopwatch = Stopwatch.createUnstarted();
private final Stopwatch readModifyWriteRowStopwatch = Stopwatch.createUnstarted();
private final Stopwatch mutateRowStopwatch = Stopwatch.createUnstarted();
private long readRowServerSideLatency;
private long readModifyWriteRowServerSideLatency;
private long mutateRowServerSideLatency;
private final Object lock = new Object();
final ConcurrentLinkedQueue requests = new ConcurrentLinkedQueue();
@SuppressWarnings("unchecked")
<T> T popLastRequest() {
return (T) requests.poll();
}
public long getReadRowServerSideLatency() {
synchronized (lock) {
return readRowServerSideLatency;
}
}
public long getMutateRowServerSideLatency() {
synchronized (lock) {
return mutateRowServerSideLatency;
}
}
public long getReadModifyWriteRowServerSideLatency() {
synchronized (lock) {
return readModifyWriteRowServerSideLatency;
}
}
public void reset() {
readRowsStopwatch.reset();
readModifyWriteRowStopwatch.reset();
mutateRowStopwatch.reset();
callCount.set(1);
}
@Override
public void readRows(
ReadRowsRequest request, StreamObserver<ReadRowsResponse> responseObserver) {
requests.add(request);
synchronized (lock) {
if (!readRowsStopwatch.isRunning()) {
readRowsStopwatch.start();
}
if (callCount.getAndIncrement() < fakeErrorCount + 1) {
responseObserver.onError(new StatusRuntimeException(fakeErrorStatus));
} else {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
responseObserver.onError(e);
return;
}
responseObserver.onNext(readRowsResponse);
// sleep after the response to test first response latency
try {
Thread.sleep(20);
} catch (InterruptedException e) {
responseObserver.onError(e);
return;
}
readRowServerSideLatency = readRowsStopwatch.elapsed(TimeUnit.MILLISECONDS);
responseObserver.onCompleted();
}
}
}
@Override
public void readModifyWriteRow(
ReadModifyWriteRowRequest request,
StreamObserver<ReadModifyWriteRowResponse> responseObserver) {
if (!readModifyWriteRowStopwatch.isRunning()) {
readModifyWriteRowStopwatch.start();
}
requests.add(request);
readModifyWriteRowServerSideLatency =
readModifyWriteRowStopwatch.elapsed(TimeUnit.MILLISECONDS);
responseObserver.onError(new StatusRuntimeException(Status.FAILED_PRECONDITION));
}
@Override
public void mutateRow(
MutateRowRequest request, StreamObserver<MutateRowResponse> responseObserver) {
if (!mutateRowStopwatch.isRunning()) {
mutateRowStopwatch.start();
}
requests.add(request);
responseObserver.onNext(MutateRowResponse.newBuilder().build());
mutateRowServerSideLatency = mutateRowStopwatch.elapsed(TimeUnit.MILLISECONDS);
responseObserver.onCompleted();
}
@Override
public void mutateRows(
MutateRowsRequest request, StreamObserver<MutateRowsResponse> responseObserver) {
responseObserver.onNext(MutateRowsResponse.newBuilder().build());
responseObserver.onCompleted();
}
}
private static class FakeMetricRegistry implements MetricRegistry {
private final Object lock = new Object();
private final Map<String, AtomicLong> results = new HashMap<>();
@Override
public Counter counter(final String name) {
// counter operations either increment or decrement a key's value
return new Counter() {
@Override
public void inc() {
synchronized (lock) {
AtomicLong atomicLong = results.get(name);
if (atomicLong == null) {
AtomicLong value = new AtomicLong();
results.put(name, value);
}
}
results.get(name).getAndIncrement();
}
@Override
public void dec() {
synchronized (lock) {
AtomicLong atomicLong = results.get(name);
if (atomicLong == null) {
AtomicLong value = new AtomicLong();
results.put(name, value);
}
}
results.get(name).getAndDecrement();
}
};
}
@Override
public Timer timer(final String name) {
// timer operations overwrite a key's value
return new Timer() {
final Stopwatch stopwatch = Stopwatch.createStarted();
@Override
public Context time() {
return new Context() {
@Override
public void close() {
synchronized (lock) {
results.put(name, new AtomicLong(stopwatch.elapsed(TimeUnit.MILLISECONDS)));
}
}
};
}
@Override
public void update(long duration, TimeUnit unit) {
// update operations overwrite a key's value
synchronized (lock) {
results.put(name, new AtomicLong(duration));
}
}
};
}
@Override
public Meter meter(final String name) {
// meter operations increment the current key's value
return new Meter() {
@Override
public void mark() {
synchronized (lock) {
AtomicLong atomicLong = results.get(name);
if (atomicLong == null) {
AtomicLong value = new AtomicLong();
results.put(name, value);
}
}
results.get(name).getAndIncrement();
}
// unless a size is specified, in which case it is overridden
@Override
public void mark(long size) {
synchronized (lock) {
results.put(name, new AtomicLong(size));
}
}
};
}
}
}
|
package org.opensrp.service;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.joda.time.DateTime;
import org.opensrp.domain.Manifest;
import org.opensrp.repository.ManifestRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Service
public class ManifestService {
private static Logger logger = LogManager.getLogger(ManifestService.class.toString());
private ManifestRepository manifestRepository;
@Autowired
public void setManifestRepository(ManifestRepository manifestRepository) {
this.manifestRepository = manifestRepository;
}
public ManifestRepository getManifestRepository() {
return manifestRepository;
}
public List<Manifest> getAllManifest() {
return manifestRepository.getAll();
}
public List<Manifest> getAllManifest(int limit) { return manifestRepository.getAll(limit);}
public void addOrUpdateManifest(Manifest manifest) {
if (StringUtils.isBlank(manifest.getIdentifier()))
throw new IllegalArgumentException("Id not specified");
manifest.setUpdatedAt(new DateTime());
if (manifestRepository.get(manifest.getIdentifier()) != null) {
manifestRepository.update(manifest);
} else {
manifest.setCreatedAt(new DateTime());
manifestRepository.add(manifest);
}
}
public Manifest addManifest(Manifest manifest) {
if (StringUtils.isBlank(manifest.getIdentifier()))
throw new IllegalArgumentException("Id not specified");
manifest.setCreatedAt(new DateTime());
manifest.setUpdatedAt(new DateTime());
manifestRepository.add(manifest);
return manifest;
}
public Manifest updateManifest(Manifest manifest) {
if (StringUtils.isBlank(manifest.getIdentifier()))
throw new IllegalArgumentException("Id not specified");
manifest.setUpdatedAt(new DateTime());
manifestRepository.update(manifest);
return manifest;
}
public Manifest getManifest(String identifier) {
if (StringUtils.isBlank(identifier))
return null;
return getManifestRepository().get(identifier);
}
public Set<String> saveManifests(List<Manifest> manifests) {
Set<String> manifestWithErrors = new HashSet<>();
for (Manifest manifest : manifests) {
try {
addOrUpdateManifest(manifest);
} catch (Exception e) {
logger.error(e.getMessage(), e);
manifestWithErrors.add(manifest.getIdentifier());
}
}
return manifestWithErrors;
}
public void deleteManifest(Manifest manifest) {
if (StringUtils.isBlank(manifest.getIdentifier())) {
throw new IllegalArgumentException("Identifier not specified");
}
manifestRepository.safeRemove(manifest);
}
public Manifest getManifestByAppId(String appId) {
if (StringUtils.isBlank(appId))
return null;
return manifestRepository.getManifestByAppId(appId);
}
public List<Manifest> getManifestsByAppId(String appId) {
if (StringUtils.isBlank(appId))
return null;
return manifestRepository.getManifestsByAppId(appId);
}
public Manifest getManifest(@NonNull String appId, @NonNull String appVersion) {
return manifestRepository.getManifest(appId, appVersion);
}
}
|
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct.itest.supertypegeneration.usage;
import org.mapstruct.itest.supertypegeneration.GenBase;
/**
* @author Gunnar Morling
*/
@GenBase(2)
public class OrderDto extends OrderDtoBase {
private String item;
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
}
|
/*
* Copyright 2018 JDCLOUD.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.
*
* Quota
* 集群配额相关接口
*
* OpenAPI spec version: v1
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
package com.jdcloud.sdk.service.kubernetes.model;
import java.util.List;
import java.util.ArrayList;
import com.jdcloud.sdk.service.common.model.Filter;
import com.jdcloud.sdk.annotation.Required;
import com.jdcloud.sdk.service.JdcloudRequest;
/**
* 查询(k8s 集群)配额
*/
public class DescribeQuotasRequest extends JdcloudRequest implements java.io.Serializable {
private static final long serialVersionUID = 1L;
/**
* resourceTypes - 资源类型,暂时只支持[kubernetes]
*/
private List<Filter> filters;
/**
* Region ID
* Required:true
*/
@Required
private String regionId;
/**
* get resourceTypes - 资源类型,暂时只支持[kubernetes]
*
* @return
*/
public List<Filter> getFilters() {
return filters;
}
/**
* set resourceTypes - 资源类型,暂时只支持[kubernetes]
*
* @param filters
*/
public void setFilters(List<Filter> filters) {
this.filters = filters;
}
/**
* get Region ID
*
* @return
*/
public String getRegionId() {
return regionId;
}
/**
* set Region ID
*
* @param regionId
*/
public void setRegionId(String regionId) {
this.regionId = regionId;
}
/**
* set resourceTypes - 资源类型,暂时只支持[kubernetes]
*
* @param filters
*/
public DescribeQuotasRequest filters(List<Filter> filters) {
this.filters = filters;
return this;
}
/**
* set Region ID
*
* @param regionId
*/
public DescribeQuotasRequest regionId(String regionId) {
this.regionId = regionId;
return this;
}
/**
* add item to resourceTypes - 资源类型,暂时只支持[kubernetes]
*
* @param filter
*/
public void addFilter(Filter filter) {
if (this.filters == null) {
this.filters = new ArrayList<>();
}
this.filters.add(filter);
}
}
|
/*
* Copyright © 2017 <code@io7m.com> http://io7m.com
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package com.io7m.cantoria.api;
import org.immutables.value.Value;
import org.immutables.vavr.encodings.VavrEncodingEnabled;
/**
* A qualified open.
*/
@CImmutableStyleType
@Value.Immutable
@VavrEncodingEnabled
public interface CModuleQualifiedOpensType
{
/**
* @return The name of the opened package.
*/
@Value.Parameter(order = 0)
String packageName();
/**
* @return The module to which this package is opened.
*/
@Value.Parameter(order = 1)
String moduleName();
}
|
/*
* 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 testify.util.function;
import org.opentest4j.AssertionFailedError;
import java.util.Objects;
@FunctionalInterface
public interface RawPredicate<T> extends java.util.function.Predicate<T> {
boolean testRaw(T t) throws Exception;
default boolean test(T t) {
try {
return testRaw(t);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new AssertionFailedError("", e);
}
}
default RawPredicate<T> negate() { return t -> !this.testRaw(t); }
default RawPredicate<T> and(RawPredicate<? super T> that) {
return t -> this.testRaw(t) && that.testRaw(t);
}
default RawPredicate<T> or(RawPredicate<? super T> that) {
return t -> this.testRaw(t) || that.testRaw(t);
}
static <T> RawPredicate<T> isEqual(Object targetRef) {
return t -> Objects.equals(targetRef, t);
}
}
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.hardware_acceleration;
import static org.chromium.base.test.util.Restriction.RESTRICTION_TYPE_LOW_END_DEVICE;
import android.test.suitebuilder.annotation.SmallTest;
import org.chromium.base.ApplicationStatus;
import org.chromium.base.test.util.DisabledTest;
import org.chromium.base.test.util.Restriction;
import org.chromium.chrome.browser.document.DocumentActivity;
import org.chromium.chrome.browser.document.DocumentModeTestBase;
/**
* Tests that DocumentActivity is hardware accelerated only high-end devices.
*/
@DisabledTest
public class DocumentActivityHWATest extends DocumentModeTestBase {
@SmallTest
public void testHardwareAcceleration() throws Exception {
Utils.assertHardwareAcceleration(startAndWaitActivity(false));
}
@SmallTest
public void testHardwareAccelerationIncognito() throws Exception {
Utils.assertHardwareAcceleration(startAndWaitActivity(true));
}
@Restriction(RESTRICTION_TYPE_LOW_END_DEVICE)
@SmallTest
public void testNoRenderThread() throws Exception {
startAndWaitActivity(false);
Utils.assertNoRenderThread();
}
@Restriction(RESTRICTION_TYPE_LOW_END_DEVICE)
@SmallTest
public void testNoRenderThreadIncognito() throws Exception {
startAndWaitActivity(true);
Utils.assertNoRenderThread();
}
private DocumentActivity startAndWaitActivity(boolean incognito) throws Exception {
launchViaViewIntent(incognito, URL_1, "Page 1");
return (DocumentActivity) ApplicationStatus.getLastTrackedFocusedActivity();
}
}
|
package priv.kimking.base.jvm;
import priv.kimking.base.jvm.classpath.Classpath;
/**
* <p>
*
* @author kim
* @date 2021/11/22
*/
public class App {
public static void main(String[] args) {
Cmd cmd = Cmd.parse(args);
if (!cmd.ok || cmd.helpFlag) {
System.out.println("Usage: <main class> [-options] class [args...]");
return;
}
if (cmd.versionFlag) {
System.out.println("java version \"1.8.0\"");
return;
}
startJVM(cmd);
}
private static void startJVM(Cmd cmd) {
// System.out.printf("classpath:%s class:%s args:%s\n", cmd.classpath, cmd.getMainClass(), cmd.getAppArgs());
Classpath cp = new Classpath(cmd.jre, cmd.classpath);
System.out.printf("classpath:%s class:%s args:%s\n", cp, cmd.getMainClass(), cmd.getAppArgs());
//获取className
String className = cmd.getMainClass().replace(".", "/");
try {
byte[] classData = cp.readClass(className);
System.out.println("classData:");
for (byte b : classData) {
//16进制输出
System.out.print(String.format("%02x", b & 0xff) + " ");
}
} catch (Exception e) {
System.out.println("Could not find or load main class " + cmd.getMainClass());
e.printStackTrace();
}
}
}
|
package com.grootan.kwebtonative;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Main Singleton Class to handle webview wrapper
*/
public class KWebToNative {
public static KWebToNative _shared;
private HashMap<String, List<KWebToNativeListenerDelegate>> _listeners;
private WebView _webview;
private Gson _gson;
private KWebToNativeWebViewClient _client;
/**
* Private constructor
*/
private KWebToNative() {
_listeners = new HashMap<>();
_gson = new Gson();
}
/**
* Method to get instance of KWebToNative
* @return
*/
public static KWebToNative shared() {
if (_shared == null) {
_shared = new KWebToNative();
}
return _shared;
}
/**
* Method to initialize webview and webviewclient
* @param webView
* @param webViewClient
*/
public void initialize(WebView webView, WebViewClient webViewClient)
{
if(_client == null)
{
_client = new KWebToNativeWebViewClient(_shared);
}
this._client.setDelegate(webViewClient);
this._webview = webView;
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(_client);
}
/**
* Method to listen on events
* @param eventName
* @param delegate
*/
public void on(String eventName,KWebToNativeListenerDelegate delegate )
{
List<KWebToNativeListenerDelegate> delegates = _listeners.get(eventName);
if(delegates == null)
{
delegates = new ArrayList<>();
}
delegates.add(delegate);
_listeners.put(eventName,delegates);
}
/**
* Method not to listen for events, it will remove the listener which is called with on
* @param eventName
*/
public void off(String eventName)
{
_listeners.remove(eventName);
}
/**
* Method to send payload to webview
* @param eventName
* @param payload
*/
public void send(String eventName, Object payload)
{
send(eventName, payload);
}
/**
* Method to send payload to webview with callback
* @param eventName
* @param payload
* @param delegate
*/
public void send(String eventName, Object payload, KWebToNativeCallbackDelegate delegate)
{
if(_webview == null)
{
throw new NullPointerException("Webview cannot be null, you must call initialize before calling send");
}
String jsonData = _gson.toJson(payload);
_webview.loadUrl(String.format("javascript:KWebToNative.trigger(\"%s\",%s);",eventName,jsonData));
delegate.onComplete();
}
/**
* Method to handled payload from webview
* @param webView
* @param envelope
*/
protected void triggerEventFromWebView(final WebView webView,
WebViewPayload envelope) {
String type = envelope.type;
if (_listeners.containsKey(type)) {
List<KWebToNativeListenerDelegate> handlers = _listeners.get(type);
for (KWebToNativeListenerDelegate handler:
handlers ) {
handler.onMessage(envelope.payload);
}
}
}
}
|
package io.quarkus.deployment.steps;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
import org.jboss.logging.Logger;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import io.quarkus.bootstrap.BootstrapDebug;
import io.quarkus.bootstrap.classloading.ClassPathElement;
import io.quarkus.bootstrap.classloading.QuarkusClassLoader;
import io.quarkus.deployment.QuarkusClassWriter;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.builditem.ApplicationArchivesBuildItem;
import io.quarkus.deployment.builditem.BytecodeTransformerBuildItem;
import io.quarkus.deployment.builditem.LaunchModeBuildItem;
import io.quarkus.deployment.builditem.LiveReloadBuildItem;
import io.quarkus.deployment.builditem.TransformedClassesBuildItem;
import io.quarkus.deployment.index.ConstPoolScanner;
import io.quarkus.runtime.LaunchMode;
public class ClassTransformingBuildStep {
private static final Logger log = Logger.getLogger(ClassTransformingBuildStep.class);
/**
* Cache used for dev mode to save the result for classes that have not changed.
*/
private static final Map<String, TransformedClassesBuildItem.TransformedClass> transformedClassesCache = new ConcurrentHashMap<>();
private static volatile BiFunction<String, byte[], byte[]> lastTransformers;
public static byte[] transform(String className, byte[] classData) {
if (lastTransformers == null) {
return classData;
}
return lastTransformers.apply(className, classData);
}
@BuildStep
TransformedClassesBuildItem handleClassTransformation(List<BytecodeTransformerBuildItem> bytecodeTransformerBuildItems,
ApplicationArchivesBuildItem appArchives, LiveReloadBuildItem liveReloadBuildItem,
LaunchModeBuildItem launchModeBuildItem)
throws ExecutionException, InterruptedException {
if (bytecodeTransformerBuildItems.isEmpty()) {
return new TransformedClassesBuildItem(Collections.emptyMap());
}
final Map<String, List<BytecodeTransformerBuildItem>> bytecodeTransformers = new HashMap<>(
bytecodeTransformerBuildItems.size());
Set<String> noConstScanning = new HashSet<>();
Map<String, Set<String>> constScanning = new HashMap<>();
Set<String> eager = new HashSet<>();
Set<String> nonCacheable = new HashSet<>();
for (BytecodeTransformerBuildItem i : bytecodeTransformerBuildItems) {
bytecodeTransformers.computeIfAbsent(i.getClassToTransform(), (h) -> new ArrayList<>())
.add(i);
if (i.getRequireConstPoolEntry() == null || i.getRequireConstPoolEntry().isEmpty()) {
noConstScanning.add(i.getClassToTransform());
} else {
constScanning.computeIfAbsent(i.getClassToTransform(), (s) -> new HashSet<>())
.addAll(i.getRequireConstPoolEntry());
}
if (i.isEager()) {
eager.add(i.getClassToTransform());
}
if (!i.isCacheable()) {
nonCacheable.add(i.getClassToTransform());
}
}
QuarkusClassLoader cl = (QuarkusClassLoader) Thread.currentThread().getContextClassLoader();
Map<String, Path> transformedToArchive = new ConcurrentHashMap<>();
// now copy all the contents to the runner jar
// we also record if any additional archives needed transformation
// when we copy these archives we will remove the problematic classes
final ExecutorService executorPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
final ConcurrentLinkedDeque<Future<TransformedClassesBuildItem.TransformedClass>> transformed = new ConcurrentLinkedDeque<>();
final Map<Path, Set<TransformedClassesBuildItem.TransformedClass>> transformedClassesByJar = new HashMap<>();
ClassLoader transformCl = Thread.currentThread().getContextClassLoader();
lastTransformers = new BiFunction<String, byte[], byte[]>() {
@Override
public byte[] apply(String className, byte[] originalBytes) {
List<BytecodeTransformerBuildItem> classTransformers = bytecodeTransformers.get(className);
if (classTransformers == null) {
return originalBytes;
}
List<BiFunction<String, ClassVisitor, ClassVisitor>> visitors = classTransformers.stream()
.map(BytecodeTransformerBuildItem::getVisitorFunction).filter(Objects::nonNull)
.collect(Collectors.toList());
List<BiFunction<String, byte[], byte[]>> preVisitFunctions = classTransformers.stream()
.map(BytecodeTransformerBuildItem::getInputTransformer).filter(Objects::nonNull)
.collect(Collectors.toList());
ClassLoader old = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(transformCl);
String classFileName = className.replace('.', '/') + ".class";
List<ClassPathElement> archives = cl.getElementsWithResource(classFileName);
if (!archives.isEmpty()) {
ClassPathElement classPathElement = archives.get(0);
Path jar = classPathElement.getRoot();
byte[] classData = classPathElement.getResource(classFileName).getData();
Set<String> constValues = constScanning.get(className);
if (constValues != null && !noConstScanning.contains(className)) {
if (!ConstPoolScanner.constPoolEntryPresent(classData, constValues)) {
return originalBytes;
}
}
byte[] data = transformClass(className, visitors, classData, preVisitFunctions);
TransformedClassesBuildItem.TransformedClass transformedClass = new TransformedClassesBuildItem.TransformedClass(
className, data,
classFileName, eager.contains(className));
return transformedClass.getData();
} else {
return originalBytes;
}
} finally {
Thread.currentThread().setContextClassLoader(old);
}
}
};
try {
for (Map.Entry<String, List<BytecodeTransformerBuildItem>> entry : bytecodeTransformers
.entrySet()) {
String className = entry.getKey();
boolean cacheable = !nonCacheable.contains(className);
if (cacheable && transformedClassesCache.containsKey(className)) {
if (liveReloadBuildItem.getChangeInformation() != null) {
if (!liveReloadBuildItem.getChangeInformation().getChangedClasses().contains(className)) {
//we can use the cached transformation
handleTransformedClass(transformedToArchive, transformedClassesByJar,
transformedClassesCache.get(className));
continue;
}
}
}
String classFileName = className.replace('.', '/') + ".class";
List<ClassPathElement> archives = cl.getElementsWithResource(classFileName);
if (!archives.isEmpty()) {
ClassPathElement classPathElement = archives.get(0);
Path jar = classPathElement.getRoot();
if (jar == null) {
log.warnf("Cannot transform %s as its containing application archive could not be found.",
entry.getKey());
continue;
}
List<BiFunction<String, ClassVisitor, ClassVisitor>> visitors = entry.getValue().stream()
.map(BytecodeTransformerBuildItem::getVisitorFunction).filter(Objects::nonNull)
.collect(Collectors.toList());
List<BiFunction<String, byte[], byte[]>> preVisitFunctions = entry.getValue().stream()
.map(BytecodeTransformerBuildItem::getInputTransformer).filter(Objects::nonNull)
.collect(Collectors.toList());
transformedToArchive.put(classFileName, jar);
transformed.add(executorPool.submit(new Callable<TransformedClassesBuildItem.TransformedClass>() {
@Override
public TransformedClassesBuildItem.TransformedClass call() throws Exception {
ClassLoader old = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(transformCl);
Set<String> constValues = constScanning.get(className);
byte[] classData = classPathElement.getResource(classFileName).getData();
if (constValues != null && !noConstScanning.contains(className)) {
if (!ConstPoolScanner.constPoolEntryPresent(classData, constValues)) {
return null;
}
}
byte[] data = transformClass(className, visitors, classData, preVisitFunctions);
TransformedClassesBuildItem.TransformedClass transformedClass = new TransformedClassesBuildItem.TransformedClass(
className, data,
classFileName, eager.contains(className));
if (cacheable && launchModeBuildItem.getLaunchMode() == LaunchMode.DEVELOPMENT) {
transformedClassesCache.put(className, transformedClass);
}
return transformedClass;
} finally {
Thread.currentThread().setContextClassLoader(old);
}
}
}));
} else {
log.warnf("Cannot transform %s as its containing application archive could not be found.",
entry.getKey());
}
}
} finally {
executorPool.shutdown();
}
if (!transformed.isEmpty()) {
for (Future<TransformedClassesBuildItem.TransformedClass> i : transformed) {
final TransformedClassesBuildItem.TransformedClass res = i.get();
if (res != null) {
handleTransformedClass(transformedToArchive, transformedClassesByJar, res);
}
}
}
return new TransformedClassesBuildItem(transformedClassesByJar);
}
private byte[] transformClass(String className, List<BiFunction<String, ClassVisitor, ClassVisitor>> visitors,
byte[] classData, List<BiFunction<String, byte[], byte[]>> preVisitFunctions) {
for (BiFunction<String, byte[], byte[]> i : preVisitFunctions) {
classData = i.apply(className, classData);
}
byte[] data;
if (!visitors.isEmpty()) {
ClassReader cr = new ClassReader(classData);
ClassWriter writer = new QuarkusClassWriter(cr,
ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
ClassVisitor visitor = writer;
for (BiFunction<String, ClassVisitor, ClassVisitor> i : visitors) {
visitor = i.apply(className, visitor);
}
cr.accept(visitor, 0);
data = writer.toByteArray();
} else {
data = classData;
}
if (BootstrapDebug.DEBUG_TRANSFORMED_CLASSES_DIR != null) {
File debugPath = new File(BootstrapDebug.DEBUG_TRANSFORMED_CLASSES_DIR);
if (!debugPath.exists()) {
debugPath.mkdir();
}
File classFile = new File(debugPath, className.replace('.', '/') + ".class");
classFile.getParentFile().mkdirs();
try (FileOutputStream classWriter = new FileOutputStream(classFile)) {
classWriter.write(data);
} catch (Exception e) {
log.errorf(e, "Failed to write transformed class %s", className);
}
log.infof("Wrote transformed class to %s", classFile.getAbsolutePath());
}
return data;
}
private void handleTransformedClass(Map<String, Path> transformedToArchive,
Map<Path, Set<TransformedClassesBuildItem.TransformedClass>> transformedClassesByJar,
TransformedClassesBuildItem.TransformedClass res) {
transformedClassesByJar.computeIfAbsent(transformedToArchive.get(res.getFileName()), (a) -> new HashSet<>())
.add(res);
}
}
|
/*
* This file was automatically generated by EvoSuite
* Fri Aug 24 13:01:05 GMT 2018
*/
package org.databene.jdbacl;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.evosuite.runtime.EvoAssertions.*;
import java.io.File;
import java.io.PipedReader;
import java.io.PipedWriter;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import javax.sql.ConnectionPoolDataSource;
import org.apache.derby.iapi.services.io.DynamicByteArrayOutputStream;
import org.apache.derby.iapi.sql.dictionary.ColumnDescriptorList;
import org.apache.derby.iapi.sql.dictionary.GenericDescriptorList;
import org.apache.derby.iapi.store.raw.xact.RawTransaction;
import org.apache.derby.impl.sql.catalog.DataDictionaryImpl;
import org.databene.commons.version.VersionNumber;
import org.databene.jdbacl.NameSpec;
import org.databene.jdbacl.SQLUtil;
import org.databene.jdbacl.model.DBCatalog;
import org.databene.jdbacl.model.DBColumn;
import org.databene.jdbacl.model.DBConstraint;
import org.databene.jdbacl.model.DBDataType;
import org.databene.jdbacl.model.DBForeignKeyConstraint;
import org.databene.jdbacl.model.DBNonUniqueIndex;
import org.databene.jdbacl.model.DBNotNullConstraint;
import org.databene.jdbacl.model.DBObject;
import org.databene.jdbacl.model.DBPrimaryKeyConstraint;
import org.databene.jdbacl.model.DBSchema;
import org.databene.jdbacl.model.DBTable;
import org.databene.jdbacl.model.DBUniqueConstraint;
import org.databene.jdbacl.model.DBUniqueIndex;
import org.databene.jdbacl.model.DefaultDBColumn;
import org.databene.jdbacl.model.DefaultDBTable;
import org.databene.jdbacl.model.DefaultDatabase;
import org.databene.jdbacl.model.TableContainer;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.evosuite.runtime.System;
import org.evosuite.runtime.mock.java.io.MockFile;
import org.evosuite.runtime.mock.java.io.MockPrintWriter;
import org.evosuite.runtime.testdata.EvoSuiteFile;
import org.evosuite.runtime.testdata.EvoSuiteLocalAddress;
import org.evosuite.runtime.testdata.FileSystemHandling;
import org.evosuite.runtime.testdata.NetworkHandling;
import org.h2.jdbcx.JdbcConnectionPool;
import org.h2.jdbcx.JdbcDataSource;
import org.junit.runner.RunWith;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true)
public class SQLUtil_ESTest extends SQLUtil_ESTest_scaffolding {
/**
//Test case number: 0
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test00() throws Throwable {
// Undeclared exception!
try {
SQLUtil.renderColumnTypeWithSize((DBColumn) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.databene.jdbacl.SQLUtil", e);
}
}
/**
//Test case number: 1
/*Coverage entropy=1.7917594692280547
*/
@Test(timeout = 4000)
public void test01() throws Throwable {
SQLUtil.mutatesStructure("owner");
String[] stringArray0 = new String[9];
stringArray0[0] = null;
stringArray0[1] = "owner";
stringArray0[2] = "owner";
stringArray0[3] = null;
stringArray0[4] = null;
stringArray0[5] = "";
stringArray0[6] = null;
stringArray0[7] = "owner";
stringArray0[8] = null;
SQLUtil.leftJoin((String) null, stringArray0, "op_open/create_blob ", "alter session", stringArray0);
DefaultDBTable defaultDBTable0 = new DefaultDBTable("");
defaultDBTable0.getColumns();
// Undeclared exception!
try {
defaultDBTable0.getColumn("");
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// Column '' not found in table ''
//
verifyException("org.databene.jdbacl.model.DefaultDBTable", e);
}
}
/**
//Test case number: 2
/*Coverage entropy=1.7917594692280547
*/
@Test(timeout = 4000)
public void test02() throws Throwable {
String string0 = "INSERT INTO INFORMATION_SCHEMA.LOB_DATA(BLOCK, COMPRESSED, DATA) VALUES(?, ?, ?)";
SQLUtil.isQuery("INSERT INTO INFORMATION_SCHEMA.LOB_DATA(BLOCK, COMPRESSED, DATA) VALUES(?, ?, ?)");
SQLUtil sQLUtil0 = new SQLUtil();
DefaultDBTable defaultDBTable0 = new DefaultDBTable();
defaultDBTable0.getPrimaryKeyConstraint();
NameSpec nameSpec0 = NameSpec.NEVER;
// Undeclared exception!
try {
SQLUtil.ukSpec((DBUniqueConstraint) null, nameSpec0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.databene.jdbacl.SQLUtil", e);
}
}
/**
//Test case number: 3
/*Coverage entropy=2.0794415416798357
*/
@Test(timeout = 4000)
public void test03() throws Throwable {
SQLUtil.mutatesDataOrStructure("");
SQLUtil.mutatesDataOrStructure("");
SQLUtil.isProcedureCall("");
String string0 = "AZNI#]}tlG)o";
DefaultDatabase defaultDatabase0 = new DefaultDatabase("AZNI#]}tlG)o", "AZNI#]}tlG)o", (VersionNumber) null);
defaultDatabase0.getTable("", false);
String[] stringArray0 = new String[6];
stringArray0[0] = "";
stringArray0[1] = "AZNI#]}tlG)o";
stringArray0[2] = "AZNI#]}tlG)o";
stringArray0[3] = "";
stringArray0[4] = "";
stringArray0[5] = "AZNI#]}tlG)o";
// Undeclared exception!
try {
SQLUtil.renderQuery((DBTable) null, stringArray0, stringArray0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.databene.jdbacl.SQLUtil", e);
}
}
/**
//Test case number: 4
/*Coverage entropy=1.0986122886681096
*/
@Test(timeout = 4000)
public void test04() throws Throwable {
String string0 = "uW@a9'RYw`";
SQLUtil.substituteMarkers("uW@a9'RYw`", "uW@a9'RYw`", "uW@a9'RYw`");
SQLUtil sQLUtil0 = new SQLUtil();
DefaultDBTable defaultDBTable0 = new DefaultDBTable();
// Undeclared exception!
try {
defaultDBTable0.getColumn("");
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// Column '' not found in table 'null'
//
verifyException("org.databene.jdbacl.model.DefaultDBTable", e);
}
}
/**
//Test case number: 5
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test05() throws Throwable {
DefaultDBTable defaultDBTable0 = new DefaultDBTable("c013800d-00fb-2641-07ec-000000134f30");
defaultDBTable0.getPrimaryKeyConstraint();
String string0 = SQLUtil.substituteMarkers("$Y~HCmJg<WcQzK", "", (Object) null);
assertEquals("null$nullYnull~nullHnullCnullmnullJnullgnull<nullWnullcnullQnullznullKnull", string0);
}
/**
//Test case number: 6
/*Coverage entropy=2.20478541691352
*/
@Test(timeout = 4000)
public void test06() throws Throwable {
Object[] objectArray0 = SQLUtil.parseColumnTypeAndSize("9q");
SQLUtil.isQuery("9q");
SQLUtil.mutatesDataOrStructure("");
Object object0 = new Object();
SQLUtil.renderValue(object0);
DefaultDBTable defaultDBTable0 = new DefaultDBTable("");
NameSpec nameSpec0 = NameSpec.IF_REPRODUCIBLE;
byte[] byteArray0 = new byte[1];
byteArray0[0] = (byte)81;
DynamicByteArrayOutputStream dynamicByteArrayOutputStream0 = new DynamicByteArrayOutputStream(byteArray0);
MockPrintWriter mockPrintWriter0 = new MockPrintWriter(dynamicByteArrayOutputStream0, true);
PrintWriter printWriter0 = mockPrintWriter0.printf("java.lang.Object@66176201", objectArray0);
SQLUtil.renderCreateTable(defaultDBTable0, true, nameSpec0, printWriter0);
assertEquals(41, dynamicByteArrayOutputStream0.getPosition());
assertEquals(41, dynamicByteArrayOutputStream0.getUsed());
}
/**
//Test case number: 7
/*Coverage entropy=1.0986122886681096
*/
@Test(timeout = 4000)
public void test07() throws Throwable {
SQLUtil.removeComments("[>%r+");
GenericDescriptorList genericDescriptorList0 = new GenericDescriptorList();
VersionNumber versionNumber0 = new VersionNumber(genericDescriptorList0, genericDescriptorList0);
DefaultDatabase defaultDatabase0 = new DefaultDatabase("[>%r+", "", versionNumber0);
defaultDatabase0.getTable("[>%r+", false);
DBDataType dBDataType0 = DBDataType.getInstance(4711, "|XAResource.TMNOFLAGS");
Integer integer0 = RawTransaction.LOCK_ESCALATE;
Integer integer1 = RawTransaction.LOCK_ESCALATE;
DefaultDBColumn defaultDBColumn0 = new DefaultDBColumn("|XAResource.TMNOFLAGS", (DBTable) null, dBDataType0, integer0, integer1);
SQLUtil.renderColumn(defaultDBColumn0);
String[] stringArray0 = new String[8];
stringArray0[0] = "";
stringArray0[1] = "[>%r+";
stringArray0[2] = "";
stringArray0[3] = "[>%r+";
stringArray0[4] = "[>%r+";
stringArray0[5] = "[>%r+";
stringArray0[6] = "[>%r+";
stringArray0[7] = "";
DBUniqueConstraint dBUniqueConstraint0 = null;
try {
dBUniqueConstraint0 = new DBUniqueConstraint((DBTable) null, "", false, stringArray0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.databene.jdbacl.model.DBUniqueConstraint", e);
}
}
/**
//Test case number: 8
/*Coverage entropy=1.6094379124341005
*/
@Test(timeout = 4000)
public void test08() throws Throwable {
String[] stringArray0 = new String[9];
stringArray0[0] = null;
stringArray0[1] = null;
stringArray0[2] = null;
stringArray0[3] = null;
stringArray0[4] = null;
stringArray0[5] = null;
stringArray0[6] = null;
stringArray0[7] = "ALTER TABLE ";
stringArray0[8] = null;
String string0 = SQLUtil.renderColumnListWithTableName((String) null, stringArray0);
assertEquals("null.null, null.null, null.null, null.null, null.null, null.null, null.null, null.ALTER TABLE , null.null", string0);
DefaultDBTable defaultDBTable0 = new DefaultDBTable();
DBUniqueConstraint dBUniqueConstraint0 = new DBUniqueConstraint(defaultDBTable0, ", ", false, stringArray0);
DBUniqueIndex dBUniqueIndex0 = new DBUniqueIndex("m$7SfIZdkG~]JI9", false, dBUniqueConstraint0);
DBTable dBTable0 = dBUniqueIndex0.getTable();
DBForeignKeyConstraint dBForeignKeyConstraint0 = new DBForeignKeyConstraint("null.null, null.null, null.null, null.null, null.null, null.null, null.null, null.ALTER TABLE , null.null", false, dBTable0, stringArray0, dBTable0, stringArray0);
NameSpec nameSpec0 = NameSpec.NEVER;
String string1 = SQLUtil.fkSpec(dBForeignKeyConstraint0, nameSpec0);
assertEquals("FOREIGN KEY (, , , , , , , ALTER TABLE , ) REFERENCES null(, , , , , , , ALTER TABLE , )", string1);
}
/**
//Test case number: 9
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test09() throws Throwable {
String string0 = SQLUtil.normalize("--", false);
assertEquals("--", string0);
}
/**
//Test case number: 10
/*Coverage entropy=2.1972245773362196
*/
@Test(timeout = 4000)
public void test10() throws Throwable {
boolean boolean0 = SQLUtil.isProcedureCall("|K3.apq'W~o@%N_5?f");
assertFalse(boolean0);
Boolean boolean1 = SQLUtil.mutatesDataOrStructure("FOREIGN KEY ");
assertNull(boolean1);
String[] stringArray0 = new String[6];
stringArray0[0] = "`Y^J$5l#Hps]'}7EG7";
stringArray0[1] = "FOREIGN KEY ";
stringArray0[2] = "FOREIGN KEY ";
stringArray0[3] = "|K3.apq'W~o@%N_5?f";
stringArray0[4] = "02L";
stringArray0[5] = "FOREIGN KEY ";
String string0 = SQLUtil.innerJoin("FOREIGN KEY ", stringArray0, "org.postgresql.jdbc3.AbstractJdbc3Clob", "org.postgresql.jdbc3.AbstractJdbc3Clob", stringArray0);
assertEquals("org.postgresql.jdbc3.AbstractJdbc3Clob as org.postgresql.jdbc3.AbstractJdbc3Clob on FOREIGN KEY .`Y^J$5l#Hps]'}7EG7 = org.postgresql.jdbc3.AbstractJdbc3Clob.`Y^J$5l#Hps]'}7EG7 and FOREIGN KEY .FOREIGN KEY = org.postgresql.jdbc3.AbstractJdbc3Clob.FOREIGN KEY and FOREIGN KEY .FOREIGN KEY = org.postgresql.jdbc3.AbstractJdbc3Clob.FOREIGN KEY and FOREIGN KEY .|K3.apq'W~o@%N_5?f = org.postgresql.jdbc3.AbstractJdbc3Clob.|K3.apq'W~o@%N_5?f and FOREIGN KEY .02L = org.postgresql.jdbc3.AbstractJdbc3Clob.02L and FOREIGN KEY .FOREIGN KEY = org.postgresql.jdbc3.AbstractJdbc3Clob.FOREIGN KEY ", string0);
}
/**
//Test case number: 11
/*Coverage entropy=0.7356219397587946
*/
@Test(timeout = 4000)
public void test11() throws Throwable {
SQLUtil.normalize("LOCKS", false);
String[] stringArray0 = new String[8];
stringArray0[0] = "";
stringArray0[1] = "LOCKS";
stringArray0[2] = "LOCKS";
stringArray0[3] = "org.apache.derby.impl.sql.execute.HashJoinResultSet";
stringArray0[4] = "LOCKS";
stringArray0[5] = "LOCKS";
stringArray0[6] = "LOCKS";
stringArray0[7] = "LOCKS";
SQLUtil.renderColumnListWithTableName("LOCKS", stringArray0);
// Undeclared exception!
try {
SQLUtil.renderColumn((DBColumn) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.databene.jdbacl.SQLUtil", e);
}
}
/**
//Test case number: 12
/*Coverage entropy=1.6094379124341005
*/
@Test(timeout = 4000)
public void test12() throws Throwable {
DefaultDBColumn defaultDBColumn0 = new DefaultDBColumn((String) null, (DBTable) null, 0, "MA7h<$Z^1>q_FD,Xab");
SQLUtil.renderColumn(defaultDBColumn0);
String[] stringArray0 = new String[3];
stringArray0[0] = "null MA7H<$Z^1>Q_FD,XAB NULL";
defaultDBColumn0.setTable((DBTable) null);
defaultDBColumn0.setNullable(true);
stringArray0[1] = "MA7h<$Z^1>q_FD,Xab";
stringArray0[2] = "null MA7H<$Z^1>Q_FD,XAB NULL";
SQLUtil.renderColumnListWithTableName("MA7h<$Z^1>q_FD,Xab", stringArray0);
SQLUtil.renderColumnNames(stringArray0);
DefaultDBTable defaultDBTable0 = new DefaultDBTable();
DBNotNullConstraint dBNotNullConstraint0 = null;
try {
dBNotNullConstraint0 = new DBNotNullConstraint(defaultDBTable0, "null MA7H<$Z^1>Q_FD,XAB NULL", true, "E");
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// Column 'E' not found in table 'null'
//
verifyException("org.databene.jdbacl.model.DefaultDBTable", e);
}
}
/**
//Test case number: 13
/*Coverage entropy=2.6390573296152584
*/
@Test(timeout = 4000)
public void test13() throws Throwable {
DefaultDBTable defaultDBTable0 = new DefaultDBTable("");
String[] stringArray0 = new String[9];
stringArray0[0] = "";
SQLUtil.ownerDotComponent(defaultDBTable0);
String[] stringArray1 = new String[0];
DBPrimaryKeyConstraint dBPrimaryKeyConstraint0 = new DBPrimaryKeyConstraint(defaultDBTable0, "call", true, stringArray1);
NameSpec nameSpec0 = NameSpec.NEVER;
SQLUtil.pkSpec(dBPrimaryKeyConstraint0, nameSpec0);
SQLUtil.renderQuery(defaultDBTable0, stringArray0, stringArray0);
DBForeignKeyConstraint dBForeignKeyConstraint0 = new DBForeignKeyConstraint((String) null, false, defaultDBTable0, stringArray0, defaultDBTable0, stringArray0);
dBForeignKeyConstraint0.toString();
Object object0 = new Object();
Integer integer0 = RawTransaction.ABORT;
dBForeignKeyConstraint0.equals(integer0);
dBForeignKeyConstraint0.columnReferencedBy("");
SQLUtil.fkSpec(dBForeignKeyConstraint0, nameSpec0);
StringBuilder stringBuilder0 = new StringBuilder("");
SQLUtil.addRequiredCondition("<X9pZg;x9F]<R", stringBuilder0);
SQLUtil.isQuery("O");
dBForeignKeyConstraint0.setDoc("<X9pZg;x9F]<R");
SQLUtil.removeComments("8J^d('.W");
LinkedList<DBColumn> linkedList0 = new LinkedList<DBColumn>();
// Undeclared exception!
try {
SQLUtil.renderColumnNames((List<DBColumn>) linkedList0);
fail("Expecting exception: IndexOutOfBoundsException");
} catch(IndexOutOfBoundsException e) {
//
// Index: 0, Size: 0
//
verifyException("java.util.LinkedList", e);
}
}
/**
//Test case number: 14
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test14() throws Throwable {
DefaultDBTable defaultDBTable0 = new DefaultDBTable("");
String[] stringArray0 = new String[9];
stringArray0[0] = "";
stringArray0[1] = "";
stringArray0[2] = "";
stringArray0[3] = "~jHmh";
stringArray0[4] = "~jHmh";
stringArray0[5] = "";
stringArray0[6] = "";
stringArray0[7] = "dk%_9f";
stringArray0[8] = "~jHmh";
DBUniqueConstraint dBUniqueConstraint0 = new DBUniqueConstraint(defaultDBTable0, " or ", true, stringArray0);
dBUniqueConstraint0.equals(" or ");
String string0 = SQLUtil.constraintName(dBUniqueConstraint0);
assertEquals("CONSTRAINT \" or \" ", string0);
}
/**
//Test case number: 15
/*Coverage entropy=2.133381930264545
*/
@Test(timeout = 4000)
public void test15() throws Throwable {
Object[] objectArray0 = SQLUtil.parseColumnTypeAndSize("9q");
SQLUtil.isQuery("9q");
SQLUtil.mutatesDataOrStructure("");
Object object0 = new Object();
SQLUtil.renderValue(object0);
DefaultDBTable defaultDBTable0 = new DefaultDBTable("");
NameSpec nameSpec0 = NameSpec.IF_REPRODUCIBLE;
byte[] byteArray0 = new byte[4];
byteArray0[0] = (byte)81;
byteArray0[1] = (byte)81;
byteArray0[2] = (byte)81;
byteArray0[3] = (byte)81;
DynamicByteArrayOutputStream dynamicByteArrayOutputStream0 = new DynamicByteArrayOutputStream(byteArray0);
MockPrintWriter mockPrintWriter0 = new MockPrintWriter(dynamicByteArrayOutputStream0, true);
PrintWriter printWriter0 = mockPrintWriter0.printf("java.lang.Object@7d9a496", objectArray0);
SQLUtil.renderCreateTable(defaultDBTable0, false, nameSpec0, printWriter0);
assertEquals(40, dynamicByteArrayOutputStream0.getPosition());
assertEquals(40, dynamicByteArrayOutputStream0.getUsed());
}
/**
//Test case number: 16
/*Coverage entropy=1.0986122886681096
*/
@Test(timeout = 4000)
public void test16() throws Throwable {
DefaultDBTable defaultDBTable0 = new DefaultDBTable("[>%r+");
String[] stringArray0 = new String[9];
stringArray0[0] = "ohniujc";
stringArray0[1] = "t:V";
stringArray0[2] = "dk%_9f";
stringArray0[3] = "ohniujc";
stringArray0[4] = "ohniujc";
stringArray0[5] = "[>%r+";
stringArray0[6] = "dk%_9f";
stringArray0[7] = "|XARESOURCE.TMNOFLAGS";
stringArray0[8] = "[>%r+";
DBUniqueConstraint dBUniqueConstraint0 = new DBUniqueConstraint(defaultDBTable0, "?q1TVHQ%QGi|7M%I", true, stringArray0);
Object object0 = new Object();
dBUniqueConstraint0.equals("[>%r+");
String string0 = SQLUtil.constraintName(dBUniqueConstraint0);
assertEquals("CONSTRAINT ?q1TVHQ%QGi|7M%I ", string0);
String string1 = SQLUtil.typeAndName(dBUniqueConstraint0);
assertNotNull(string1);
assertEquals("unique constraint ?q1TVHQ%QGi|7M%I", string1);
}
/**
//Test case number: 17
/*Coverage entropy=2.2194910043994125
*/
@Test(timeout = 4000)
public void test17() throws Throwable {
DefaultDBTable defaultDBTable0 = new DefaultDBTable("");
String[] stringArray0 = new String[9];
stringArray0[0] = "";
SQLUtil.ownerDotComponent(defaultDBTable0);
String[] stringArray1 = new String[0];
DBPrimaryKeyConstraint dBPrimaryKeyConstraint0 = new DBPrimaryKeyConstraint(defaultDBTable0, "call", true, stringArray1);
NameSpec nameSpec0 = NameSpec.NEVER;
SQLUtil.pkSpec(dBPrimaryKeyConstraint0, nameSpec0);
SQLUtil.renderQuery(defaultDBTable0, stringArray0, stringArray0);
DBForeignKeyConstraint dBForeignKeyConstraint0 = new DBForeignKeyConstraint((String) null, false, defaultDBTable0, stringArray0, defaultDBTable0, stringArray0);
dBForeignKeyConstraint0.toString();
Object object0 = new Object();
Integer integer0 = RawTransaction.ABORT;
dBForeignKeyConstraint0.equals(integer0);
dBForeignKeyConstraint0.columnReferencedBy("");
SQLUtil.fkSpec(dBForeignKeyConstraint0, nameSpec0);
StringBuilder stringBuilder0 = new StringBuilder("");
SQLUtil.addRequiredCondition("<X9pZg;x9F]<R", stringBuilder0);
assertEquals("<X9pZg;x9F]<R", stringBuilder0.toString());
SQLUtil.normalize("\u0001\u00C3", false);
SQLUtil.constraintName(dBPrimaryKeyConstraint0);
DBDataType dBDataType0 = DBDataType.getInstance((-1847), "CONSTRAINT call ");
DefaultDBColumn defaultDBColumn0 = new DefaultDBColumn("", defaultDBTable0, dBDataType0, integer0, integer0);
SQLUtil.renderColumn(defaultDBColumn0);
String string0 = SQLUtil.constraintSpec(dBForeignKeyConstraint0, nameSpec0);
assertEquals("FOREIGN KEY (, , , , , , , , ) REFERENCES (, , , , , , , , )", string0);
}
/**
//Test case number: 18
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test18() throws Throwable {
String[] stringArray0 = new String[5];
stringArray0[0] = " = ";
stringArray0[1] = " = ";
stringArray0[2] = " = ";
stringArray0[3] = " = ";
String string0 = SQLUtil.normalize("N%FTAbt8R|{m\"Av-1", false);
assertEquals("N % FTAbt8R | { m \"Av-1\"", string0);
}
/**
//Test case number: 19
/*Coverage entropy=2.0866739010750055
*/
@Test(timeout = 4000)
public void test19() throws Throwable {
Boolean boolean0 = SQLUtil.mutatesStructure("owner");
assertFalse(boolean0);
String[] stringArray0 = new String[9];
stringArray0[0] = null;
stringArray0[1] = "owner";
stringArray0[2] = "owner";
stringArray0[3] = null;
stringArray0[4] = null;
stringArray0[5] = "";
stringArray0[6] = null;
stringArray0[8] = null;
DefaultDBTable defaultDBTable0 = new DefaultDBTable("owner");
NameSpec nameSpec0 = NameSpec.IF_REPRODUCIBLE;
byte[] byteArray0 = new byte[1];
byteArray0[0] = (byte)81;
DynamicByteArrayOutputStream dynamicByteArrayOutputStream0 = new DynamicByteArrayOutputStream(byteArray0);
MockPrintWriter mockPrintWriter0 = new MockPrintWriter(dynamicByteArrayOutputStream0, false);
mockPrintWriter0.print(673L);
PrintWriter printWriter0 = mockPrintWriter0.printf("owner", (Object[]) stringArray0);
SQLUtil.renderCreateTable(defaultDBTable0, true, nameSpec0, printWriter0);
String[] stringArray1 = new String[0];
DBUniqueConstraint dBUniqueConstraint0 = new DBUniqueConstraint(defaultDBTable0, stringArray0[0], true, stringArray1);
NameSpec nameSpec1 = NameSpec.ALWAYS;
String string0 = SQLUtil.constraintSpec(dBUniqueConstraint0, nameSpec1);
assertEquals("UNIQUE ()", string0);
}
/**
//Test case number: 20
/*Coverage entropy=1.9061547465398496
*/
@Test(timeout = 4000)
public void test20() throws Throwable {
boolean boolean0 = SQLUtil.isDML("OHNIUjc");
DataDictionaryImpl dataDictionaryImpl0 = new DataDictionaryImpl();
String[] stringArray0 = new String[3];
stringArray0[0] = "}qI<ANWT";
stringArray0[1] = "OHNIUjc";
stringArray0[2] = "}qI<ANWT";
String string0 = SQLUtil.join("}qI<ANWT", "}qI<ANWT", stringArray0, "}qI<ANWT", (String) null, stringArray0);
assertEquals("}qI<ANWT join }qI<ANWT as null on }qI<ANWT.}qI<ANWT = null.}qI<ANWT and }qI<ANWT.OHNIUjc = null.OHNIUjc and }qI<ANWT.}qI<ANWT = null.}qI<ANWT", string0);
Boolean boolean1 = SQLUtil.mutatesStructure("OHNIUjc");
assertTrue(boolean1.equals((Object)boolean0));
Character character0 = Character.valueOf('l');
String string1 = SQLUtil.renderValue(character0);
assertEquals("'l'", string1);
}
/**
//Test case number: 21
/*Coverage entropy=2.2102535776209735
*/
@Test(timeout = 4000)
public void test21() throws Throwable {
DefaultDBTable defaultDBTable0 = new DefaultDBTable("");
String[] stringArray0 = new String[9];
stringArray0[0] = "";
SQLUtil.ownerDotComponent(defaultDBTable0);
String[] stringArray1 = new String[0];
DBPrimaryKeyConstraint dBPrimaryKeyConstraint0 = new DBPrimaryKeyConstraint(defaultDBTable0, "", true, stringArray1);
NameSpec nameSpec0 = NameSpec.NEVER;
SQLUtil.pkSpec(dBPrimaryKeyConstraint0, nameSpec0);
SQLUtil.renderQuery(defaultDBTable0, stringArray0, stringArray0);
DBForeignKeyConstraint dBForeignKeyConstraint0 = new DBForeignKeyConstraint((String) null, false, defaultDBTable0, stringArray0, defaultDBTable0, stringArray0);
dBForeignKeyConstraint0.toString();
Object object0 = new Object();
Integer integer0 = RawTransaction.ABORT;
dBForeignKeyConstraint0.equals(integer0);
DBUniqueConstraint dBUniqueConstraint0 = new DBUniqueConstraint(defaultDBTable0, (String) null, true, stringArray1);
dBUniqueConstraint0.isIdentical(dBPrimaryKeyConstraint0);
Object object1 = new Object();
SQLUtil.constraintName(dBUniqueConstraint0);
TableContainer tableContainer0 = new TableContainer("");
// Undeclared exception!
try {
tableContainer0.getCatalog();
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.databene.jdbacl.model.TableContainer", e);
}
}
/**
//Test case number: 22
/*Coverage entropy=1.9091747482626005
*/
@Test(timeout = 4000)
public void test22() throws Throwable {
boolean boolean0 = SQLUtil.isProcedureCall("|K3.apq'W~o@%N_5?f");
assertFalse(boolean0);
Boolean boolean1 = SQLUtil.mutatesDataOrStructure("|K3.apq'W~o@%N_5?f");
assertNull(boolean1);
SQLUtil.normalize("43Y58.U", true);
SQLUtil.removeComments("|K3.apq'W~o@%N_5?f");
String string0 = SQLUtil.normalize(";t6pPL#{Sdf", true);
assertEquals("; t6pPL # { Sdf", string0);
}
/**
//Test case number: 23
/*Coverage entropy=1.4683033468870397
*/
@Test(timeout = 4000)
public void test23() throws Throwable {
FileSystemHandling.appendStringToFile((EvoSuiteFile) null, "");
SQLUtil.parseColumnTypeAndSize("");
SQLUtil.mutatesDataOrStructure("select intoohniujc");
String string0 = SQLUtil.normalize("<_@b0|OwUg,Eeg", false);
String[] stringArray0 = new String[4];
stringArray0[0] = "<_@b0|OwUg,Eeg";
stringArray0[1] = "WRf[`|:~Ol=p-S)";
stringArray0[2] = null;
stringArray0[3] = null;
String string1 = SQLUtil.join((String) null, "WRf[`|:~Ol=p-S)", stringArray0, "WRf[`|:~Ol=p-S)", "<_@b0|OwUg,Eeg", stringArray0);
assertFalse(string1.equals((Object)string0));
}
/**
//Test case number: 24
/*Coverage entropy=0.25731864054383163
*/
@Test(timeout = 4000)
public void test24() throws Throwable {
String string0 = SQLUtil.normalize(">~{X;[vbj/ns%", true);
assertEquals("> ~ { X ; [ vbj / ns %", string0);
String string1 = SQLUtil.removeComments("> ~ { X ; [ vbj / ns %");
assertTrue(string1.equals((Object)string0));
}
/**
//Test case number: 25
/*Coverage entropy=2.3195749966735852
*/
@Test(timeout = 4000)
public void test25() throws Throwable {
DefaultDBTable defaultDBTable0 = new DefaultDBTable("");
String[] stringArray0 = new String[9];
stringArray0[0] = "";
String string0 = SQLUtil.ownerDotComponent(defaultDBTable0);
assertEquals("", string0);
String[] stringArray1 = new String[1];
DBPrimaryKeyConstraint dBPrimaryKeyConstraint0 = new DBPrimaryKeyConstraint(defaultDBTable0, "7cal", true, stringArray1);
String string1 = dBPrimaryKeyConstraint0.toString();
assertEquals("CONSTRAINT 7cal PRIMARY KEY ()", string1);
NameSpec nameSpec0 = NameSpec.NEVER;
String string2 = SQLUtil.pkSpec(dBPrimaryKeyConstraint0, nameSpec0);
assertEquals("PRIMARY KEY ()", string2);
String string3 = SQLUtil.renderQuery(defaultDBTable0, stringArray0, stringArray0);
assertEquals("SELECT * FROM WHERE = '' AND null = null AND null = null AND null = null AND null = null AND null = null AND null = null AND null = null AND null = null", string3);
DBForeignKeyConstraint dBForeignKeyConstraint0 = new DBForeignKeyConstraint((String) null, false, defaultDBTable0, stringArray0, defaultDBTable0, stringArray0);
String string4 = dBForeignKeyConstraint0.toString();
assertEquals("FOREIGN KEY (, , , , , , , , ) REFERENCES (, , , , , , , , )", string4);
Object object0 = new Object();
Integer integer0 = RawTransaction.ABORT;
dBForeignKeyConstraint0.equals(integer0);
Object object1 = new Object();
DBUniqueConstraint dBUniqueConstraint0 = new DBUniqueConstraint(defaultDBTable0, "7cal", false, stringArray0);
boolean boolean0 = SQLUtil.isQuery("FOREIGN KEY (, , , , , , , , ) REFERENCES (, , , , , , , , )");
assertFalse(boolean0);
}
/**
//Test case number: 26
/*Coverage entropy=2.3195749966735852
*/
@Test(timeout = 4000)
public void test26() throws Throwable {
Boolean boolean0 = SQLUtil.mutatesStructure("owner");
assertFalse(boolean0);
String[] stringArray0 = new String[9];
stringArray0[0] = "owner";
stringArray0[1] = "owner";
stringArray0[2] = "owner";
stringArray0[3] = "owner";
stringArray0[4] = "owner";
stringArray0[5] = "";
stringArray0[6] = "owner";
stringArray0[7] = "owner";
stringArray0[8] = "owner";
DefaultDBTable defaultDBTable0 = new DefaultDBTable("owner");
NameSpec nameSpec0 = NameSpec.IF_REPRODUCIBLE;
byte[] byteArray0 = new byte[1];
byteArray0[0] = (byte)81;
DynamicByteArrayOutputStream dynamicByteArrayOutputStream0 = new DynamicByteArrayOutputStream(byteArray0);
MockPrintWriter mockPrintWriter0 = new MockPrintWriter(dynamicByteArrayOutputStream0, false);
DBDataType dBDataType0 = DBDataType.getInstance((-1061), "owner");
Integer integer0 = RawTransaction.LOCK_ESCALATE;
DefaultDBColumn defaultDBColumn0 = new DefaultDBColumn("owner", defaultDBTable0, dBDataType0, integer0);
String string0 = SQLUtil.renderColumn(defaultDBColumn0);
assertEquals("owner OWNER(3) NULL", string0);
DBForeignKeyConstraint dBForeignKeyConstraint0 = new DBForeignKeyConstraint("owner", true, defaultDBTable0, stringArray0, defaultDBTable0, stringArray0);
String string1 = SQLUtil.constraintSpec(dBForeignKeyConstraint0, nameSpec0);
assertEquals("CONSTRAINT owner FOREIGN KEY (owner, owner, owner, owner, owner, , owner, owner, owner) REFERENCES owner(owner, owner, owner, owner, owner, , owner, owner, owner)", string1);
}
/**
//Test case number: 27
/*Coverage entropy=0.18490739916777568
*/
@Test(timeout = 4000)
public void test27() throws Throwable {
SQLUtil.normalize("|K3.apq'W~o@%N_5?f", true);
String string0 = SQLUtil.removeComments("^Xqc^T'o5(");
assertEquals("^Xqc^T'o5(", string0);
}
/**
//Test case number: 28
/*Coverage entropy=1.3862943611198906
*/
@Test(timeout = 4000)
public void test28() throws Throwable {
DefaultDBTable defaultDBTable0 = new DefaultDBTable("[>%r+");
String[] stringArray0 = new String[9];
stringArray0[0] = "ohniujc";
DefaultDBTable defaultDBTable1 = new DefaultDBTable(")s");
byte[] byteArray0 = new byte[2];
byteArray0[0] = (byte)81;
byteArray0[1] = (byte)81;
DynamicByteArrayOutputStream dynamicByteArrayOutputStream0 = new DynamicByteArrayOutputStream(byteArray0);
DBPrimaryKeyConstraint dBPrimaryKeyConstraint0 = new DBPrimaryKeyConstraint(defaultDBTable0, (String) null, false, stringArray0);
NameSpec nameSpec0 = NameSpec.NEVER;
StringBuilder stringBuilder0 = SQLUtil.createConstraintSpecBuilder(dBPrimaryKeyConstraint0, nameSpec0);
StringBuilder stringBuilder1 = stringBuilder0.append(62.88F);
StringBuilder stringBuilder2 = stringBuilder1.append((long) (byte)81);
char[] charArray0 = new char[1];
charArray0[0] = 'o';
StringBuilder stringBuilder3 = stringBuilder2.append(charArray0);
SQLUtil.addRequiredCondition("ohniujc", stringBuilder3);
// Undeclared exception!
try {
SQLUtil.normalize((String) null, false);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("java.io.StringReader", e);
}
}
/**
//Test case number: 29
/*Coverage entropy=1.6707441709201767
*/
@Test(timeout = 4000)
public void test29() throws Throwable {
Boolean boolean0 = SQLUtil.mutatesDataOrStructure("*{u");
assertNull(boolean0);
String string0 = SQLUtil.normalize("SELECT * FROM ", true);
assertEquals("SELECT * FROM", string0);
}
/**
//Test case number: 30
/*Coverage entropy=1.1595888143086257
*/
@Test(timeout = 4000)
public void test30() throws Throwable {
DefaultDBTable defaultDBTable0 = new DefaultDBTable("[>%r+");
String[] stringArray0 = new String[9];
stringArray0[0] = "ohniujc";
DefaultDBTable defaultDBTable1 = new DefaultDBTable(")s");
NameSpec nameSpec0 = NameSpec.IF_REPRODUCIBLE;
byte[] byteArray0 = new byte[2];
byteArray0[0] = (byte)81;
byteArray0[1] = (byte)81;
DynamicByteArrayOutputStream dynamicByteArrayOutputStream0 = new DynamicByteArrayOutputStream(byteArray0);
MockPrintWriter mockPrintWriter0 = new MockPrintWriter(dynamicByteArrayOutputStream0, true);
DBDataType dBDataType0 = DBDataType.getInstance((int) (byte)81, "ohniujc");
Integer integer0 = RawTransaction.ABORT;
DefaultDBColumn defaultDBColumn0 = new DefaultDBColumn("[>%r+", defaultDBTable0, dBDataType0, integer0);
defaultDBTable0.addColumn(defaultDBColumn0);
mockPrintWriter0.printf("ohniujc", (Object[]) stringArray0);
SQLUtil.renderCreateTable(defaultDBTable0, true, nameSpec0, mockPrintWriter0);
SQLUtil.normalize(" ekNu$3X", true);
defaultDBTable1.getUniqueConstraint(stringArray0);
// Undeclared exception!
try {
SQLUtil.constraintSpec((DBConstraint) null, nameSpec0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.databene.jdbacl.SQLUtil", e);
}
}
/**
//Test case number: 31
/*Coverage entropy=1.0397207708399179
*/
@Test(timeout = 4000)
public void test31() throws Throwable {
DefaultDBTable defaultDBTable0 = new DefaultDBTable("[>%r+");
DefaultDBTable defaultDBTable1 = new DefaultDBTable();
String[] stringArray0 = new String[9];
stringArray0[0] = "[>%r+";
stringArray0[1] = "m$7SfIZdkG~]JI9";
stringArray0[2] = "[>%r+";
stringArray0[3] = "Bcx";
stringArray0[4] = "alter tableowner";
stringArray0[5] = "m$7SfIZdkG~]JI9";
stringArray0[6] = "[>%r+";
stringArray0[7] = "m$7SfIZdkG~]JI9";
stringArray0[8] = "bl";
DBUniqueConstraint dBUniqueConstraint0 = new DBUniqueConstraint(defaultDBTable0, "[>%r+", false, stringArray0);
dBUniqueConstraint0.addColumnName((String) null);
Object object0 = new Object();
Character character0 = new Character('A');
dBUniqueConstraint0.equals("bl");
defaultDBTable1.getUniqueConstraint(stringArray0);
String string0 = SQLUtil.constraintName(dBUniqueConstraint0);
assertEquals("CONSTRAINT [>%r+ ", string0);
String string1 = SQLUtil.typeAndName(defaultDBTable1);
assertEquals("table null", string1);
assertNotNull(string1);
}
/**
//Test case number: 32
/*Coverage entropy=1.15374194270109
*/
@Test(timeout = 4000)
public void test32() throws Throwable {
DefaultDBTable defaultDBTable0 = new DefaultDBTable("[>%r+");
DefaultDBTable defaultDBTable1 = new DefaultDBTable();
String[] stringArray0 = new String[2];
stringArray0[0] = "select";
stringArray0[1] = "m$7SfIZdkG~]JI9";
DBForeignKeyConstraint dBForeignKeyConstraint0 = new DBForeignKeyConstraint("select ", false, defaultDBTable0, stringArray0, defaultDBTable0, stringArray0);
NameSpec nameSpec0 = NameSpec.IF_REPRODUCIBLE;
String string0 = SQLUtil.fkSpec(dBForeignKeyConstraint0, nameSpec0);
assertEquals("FOREIGN KEY (select, m$7SfIZdkG~]JI9) REFERENCES [>%r+(select, m$7SfIZdkG~]JI9)", string0);
}
/**
//Test case number: 33
/*Coverage entropy=1.6726254461503207
*/
@Test(timeout = 4000)
public void test33() throws Throwable {
Boolean boolean0 = SQLUtil.mutatesStructure("owner");
assertFalse(boolean0);
String[] stringArray0 = new String[9];
stringArray0[0] = "owner";
stringArray0[1] = "owner";
stringArray0[2] = "owner";
stringArray0[3] = "owner";
stringArray0[4] = "owner";
DefaultDBTable defaultDBTable0 = new DefaultDBTable("owner");
String[] stringArray1 = new String[4];
stringArray1[0] = "owner";
stringArray1[1] = "owner";
stringArray1[2] = "owner";
stringArray1[3] = " NOT";
DBNonUniqueIndex dBNonUniqueIndex0 = new DBNonUniqueIndex("create unique indexselect intoohniujc", false, defaultDBTable0, stringArray1);
dBNonUniqueIndex0.equals(" NOT");
defaultDBTable0.removeIndex(dBNonUniqueIndex0);
defaultDBTable0.getColumns();
SQLUtil.removeComments("create unique indexselect intoohniujc");
String string0 = SQLUtil.ownerDotComponent(dBNonUniqueIndex0);
assertEquals("owner.create unique indexselect intoohniujc", string0);
}
/**
//Test case number: 34
/*Coverage entropy=1.9273921261392744
*/
@Test(timeout = 4000)
public void test34() throws Throwable {
SQLUtil.mutatesDataOrStructure("callselect intoohniujc");
byte[] byteArray0 = new byte[7];
byteArray0[0] = (byte) (-60);
byteArray0[1] = (byte)24;
byteArray0[2] = (byte)60;
byteArray0[3] = (byte) (-45);
byteArray0[4] = (byte) (-121);
byteArray0[5] = (byte)108;
SQLUtil.mutatesDataOrStructure("rename");
// Undeclared exception!
try {
SQLUtil.removeComments((String) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
}
}
/**
//Test case number: 35
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test35() throws Throwable {
DefaultDBTable defaultDBTable0 = new DefaultDBTable("drop table");
DefaultDBTable defaultDBTable1 = new DefaultDBTable();
String[] stringArray0 = new String[8];
stringArray0[0] = "m$7SfIZdkG~]JI9";
stringArray0[1] = "alter tableowner";
stringArray0[2] = "bl";
stringArray0[3] = "drop table";
stringArray0[4] = "drop table";
stringArray0[5] = "bl";
stringArray0[6] = "m$7SfIZdkG~]JI9";
stringArray0[7] = "drop table";
byte[] byteArray0 = new byte[8];
byteArray0[0] = (byte) (-15);
byteArray0[1] = (byte) (-24);
byteArray0[2] = (byte) (-78);
byteArray0[3] = (byte)37;
byteArray0[4] = (byte)25;
byteArray0[5] = (byte)5;
byteArray0[6] = (byte)36;
byteArray0[7] = (byte) (-111);
NetworkHandling.sendDataOnTcp((EvoSuiteLocalAddress) null, byteArray0);
Object object0 = new Object();
Character character0 = new Character('8');
defaultDBTable1.getUniqueConstraint(stringArray0);
String string0 = SQLUtil.typeAndName((DBObject) null);
assertNull(string0);
}
/**
//Test case number: 36
/*Coverage entropy=1.9730014063936125
*/
@Test(timeout = 4000)
public void test36() throws Throwable {
SQLUtil.mutatesStructure("owner");
String[] stringArray0 = new String[9];
stringArray0[0] = "owner";
stringArray0[1] = "owner";
stringArray0[2] = "owner";
stringArray0[3] = "owner";
stringArray0[4] = "owner";
stringArray0[5] = "";
stringArray0[6] = "owner";
stringArray0[7] = "owner";
stringArray0[8] = "owner";
DefaultDBTable defaultDBTable0 = new DefaultDBTable("owner");
byte byte0 = (byte)81;
byte[] byteArray0 = new byte[1];
byteArray0[0] = (byte)81;
DynamicByteArrayOutputStream dynamicByteArrayOutputStream0 = new DynamicByteArrayOutputStream(byteArray0);
MockPrintWriter mockPrintWriter0 = new MockPrintWriter(dynamicByteArrayOutputStream0, false);
int int0 = (-1061);
DBDataType dBDataType0 = DBDataType.getInstance((-1061), "owner");
dBDataType0.isNumber();
Integer integer0 = RawTransaction.LOCK_ESCALATE;
DefaultDBColumn defaultDBColumn0 = new DefaultDBColumn("owner", defaultDBTable0, dBDataType0, integer0);
SQLUtil.renderColumn(defaultDBColumn0);
SQLUtil.normalize("c", false);
StringBuilder stringBuilder0 = new StringBuilder((CharSequence) "");
StringBuilder stringBuilder1 = SQLUtil.addOptionalCondition("lV", stringBuilder0);
int int1 = (-128);
// Undeclared exception!
try {
stringBuilder1.insert((-128), (CharSequence) stringBuilder0);
fail("Expecting exception: IndexOutOfBoundsException");
} catch(IndexOutOfBoundsException e) {
//
// dstOffset -128
//
verifyException("java.lang.AbstractStringBuilder", e);
}
}
/**
//Test case number: 37
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test37() throws Throwable {
DefaultDBTable defaultDBTable0 = new DefaultDBTable("[>%r+");
DefaultDBTable defaultDBTable1 = new DefaultDBTable();
String string0 = ", ";
SQLUtil.normalize("F", true);
StringBuilder stringBuilder0 = new StringBuilder((CharSequence) "lV");
SQLUtil.addOptionalCondition("lV", stringBuilder0);
stringBuilder0.append(2076.2480613693);
int int0 = 40;
StringBuilder stringBuilder1 = new StringBuilder();
// Undeclared exception!
try {
stringBuilder1.deleteCharAt((-1794052841));
fail("Expecting exception: StringIndexOutOfBoundsException");
} catch(StringIndexOutOfBoundsException e) {
//
// String index out of range: -1794052841
//
verifyException("java.lang.AbstractStringBuilder", e);
}
}
/**
//Test case number: 38
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test38() throws Throwable {
String string0 = SQLUtil.normalize("{Ho),&", true);
assertEquals("{ Ho), &", string0);
TableContainer tableContainer0 = new TableContainer("{ Ho), &");
TableContainer tableContainer1 = new TableContainer("{ Ho), &");
tableContainer1.getSchema();
String string1 = SQLUtil.normalize("{ Ho), &", true);
assertEquals("{ Ho), &", string1);
}
/**
//Test case number: 39
/*Coverage entropy=2.1972245773362196
*/
@Test(timeout = 4000)
public void test39() throws Throwable {
byte[] byteArray0 = new byte[7];
byteArray0[0] = (byte)2;
byteArray0[1] = (byte)116;
byteArray0[2] = (byte) (-47);
byteArray0[3] = (byte)84;
byteArray0[4] = (byte)77;
byteArray0[5] = (byte)101;
byteArray0[6] = (byte)10;
FileSystemHandling.appendDataToFile((EvoSuiteFile) null, byteArray0);
Boolean boolean0 = SQLUtil.mutatesDataOrStructure("42500");
assertNull(boolean0);
PipedWriter pipedWriter0 = new PipedWriter();
PipedReader pipedReader0 = new PipedReader(pipedWriter0, 44);
pipedReader0.close();
StreamTokenizer streamTokenizer0 = new StreamTokenizer(pipedReader0);
String string0 = SQLUtil.renderNumber(streamTokenizer0);
assertEquals("- 0", string0);
}
/**
//Test case number: 40
/*Coverage entropy=2.0679759122939765
*/
@Test(timeout = 4000)
public void test40() throws Throwable {
DefaultDBTable defaultDBTable0 = new DefaultDBTable();
String[] stringArray0 = new String[18];
stringArray0[0] = "[>%r+";
stringArray0[3] = "[>%r+";
stringArray0[4] = ", ";
stringArray0[5] = ", ";
SQLUtil.mutatesDataOrStructure("truncatecallselect intoohniujc");
SQLUtil.typeAndName(defaultDBTable0);
NameSpec nameSpec0 = NameSpec.NEVER;
// Undeclared exception!
try {
SQLUtil.renderCreateTable(defaultDBTable0, true, nameSpec0, (PrintWriter) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.databene.jdbacl.SQLUtil", e);
}
}
/**
//Test case number: 41
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test41() throws Throwable {
DefaultDBTable defaultDBTable0 = new DefaultDBTable();
System.setCurrentTimeMillis((-1L));
// Undeclared exception!
try {
SQLUtil.parseColumnTypeAndSize("_4zW(}+|Cs:");
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// Illegal column type format: _4zW(}+|Cs:
//
verifyException("org.databene.jdbacl.SQLUtil", e);
}
}
/**
//Test case number: 42
/*Coverage entropy=0.8823830530748153
*/
@Test(timeout = 4000)
public void test42() throws Throwable {
String string0 = "";
DefaultDBTable defaultDBTable0 = new DefaultDBTable("--");
byte byte0 = (byte)81;
byte[] byteArray0 = new byte[2];
byteArray0[0] = (byte)81;
byteArray0[1] = (byte)81;
DynamicByteArrayOutputStream dynamicByteArrayOutputStream0 = new DynamicByteArrayOutputStream(byteArray0);
MockPrintWriter mockPrintWriter0 = new MockPrintWriter(dynamicByteArrayOutputStream0, true);
int int0 = (-1061);
DBDataType dBDataType0 = DBDataType.getInstance((-292), "--");
dBDataType0.isNumber();
Integer integer0 = RawTransaction.LOCK_ESCALATE;
Integer integer1 = RawTransaction.SAVEPOINT_ROLLBACK;
DefaultDBColumn defaultDBColumn0 = new DefaultDBColumn("--", defaultDBTable0, dBDataType0, integer1);
SQLUtil.renderColumn(defaultDBColumn0);
SQLUtil.normalize("|B.@{-0+", true);
StringBuilder stringBuilder0 = new StringBuilder((CharSequence) "-- --(2) NULL");
SQLUtil.addOptionalCondition("--", stringBuilder0);
// Undeclared exception!
try {
stringBuilder0.insert((int) (byte)81, (CharSequence) "--");
fail("Expecting exception: StringIndexOutOfBoundsException");
} catch(StringIndexOutOfBoundsException e) {
//
// String index out of range: 81
//
verifyException("java.lang.AbstractStringBuilder", e);
}
}
/**
//Test case number: 43
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test43() throws Throwable {
String string0 = SQLUtil.normalize(">~{X;[vbj/ns%", true);
assertEquals("> ~ { X ; [ vbj / ns %", string0);
String string1 = SQLUtil.normalize("yO(ojRB", false);
assertEquals("yO (ojRB", string1);
}
/**
//Test case number: 44
/*Coverage entropy=1.8891591637540217
*/
@Test(timeout = 4000)
public void test44() throws Throwable {
SQLUtil.parseColumnTypeAndSize("[>%r+");
DefaultDBTable defaultDBTable0 = new DefaultDBTable();
String[] stringArray0 = new String[8];
stringArray0[0] = "[>%r+";
stringArray0[1] = "[>%r+";
stringArray0[2] = "[>%r+";
stringArray0[3] = "[>%r+";
stringArray0[4] = "[>%r+";
stringArray0[5] = "[>%r+";
stringArray0[6] = "[>%r+";
stringArray0[7] = "[>%r+";
DBPrimaryKeyConstraint dBPrimaryKeyConstraint0 = new DBPrimaryKeyConstraint(defaultDBTable0, "[>%r+", false, stringArray0);
NameSpec nameSpec0 = NameSpec.ALWAYS;
String string0 = SQLUtil.constraintSpec(dBPrimaryKeyConstraint0, nameSpec0);
assertEquals("CONSTRAINT [>%r+ PRIMARY KEY ([>%r+, [>%r+, [>%r+, [>%r+, [>%r+, [>%r+, [>%r+, [>%r+)", string0);
}
/**
//Test case number: 45
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test45() throws Throwable {
DefaultDBTable defaultDBTable0 = new DefaultDBTable();
DBColumn[] dBColumnArray0 = new DBColumn[2];
DBDataType dBDataType0 = DBDataType.getInstance(833, "<OIq#)l");
DefaultDBColumn defaultDBColumn0 = new DefaultDBColumn("y;`^ks/", defaultDBTable0, dBDataType0);
dBColumnArray0[0] = (DBColumn) defaultDBColumn0;
DefaultDBColumn defaultDBColumn1 = new DefaultDBColumn("7|;}&", defaultDBTable0, dBDataType0, (Integer) null);
dBColumnArray0[1] = (DBColumn) defaultDBColumn1;
SQLUtil.renderColumnNames(dBColumnArray0);
TableContainer tableContainer0 = new TableContainer("]_N1Pw TrM5990%B");
// Undeclared exception!
try {
tableContainer0.getCatalog();
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.databene.jdbacl.model.TableContainer", e);
}
}
/**
//Test case number: 46
/*Coverage entropy=1.3862943611198906
*/
@Test(timeout = 4000)
public void test46() throws Throwable {
byte[] byteArray0 = new byte[7];
byteArray0[0] = (byte)2;
byteArray0[1] = (byte)122;
byteArray0[2] = (byte) (-32);
byteArray0[3] = (byte)84;
byteArray0[4] = (byte)84;
byteArray0[5] = (byte)101;
byteArray0[6] = (byte)10;
FileSystemHandling.appendDataToFile((EvoSuiteFile) null, byteArray0);
Boolean boolean0 = SQLUtil.mutatesDataOrStructure("alter session={+z");
assertFalse(boolean0);
assertNotNull(boolean0);
PipedWriter pipedWriter0 = new PipedWriter();
PipedReader pipedReader0 = new PipedReader(pipedWriter0, 44);
pipedReader0.close();
StreamTokenizer streamTokenizer0 = new StreamTokenizer(pipedReader0);
String string0 = SQLUtil.renderNumber(streamTokenizer0);
assertEquals("- 0", string0);
}
/**
//Test case number: 47
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test47() throws Throwable {
LinkedList<DBColumn> linkedList0 = new LinkedList<DBColumn>();
ColumnDescriptorList columnDescriptorList0 = new ColumnDescriptorList();
VersionNumber versionNumber0 = new VersionNumber(columnDescriptorList0, columnDescriptorList0);
DefaultDatabase defaultDatabase0 = new DefaultDatabase("drop mater", "drop mater", versionNumber0);
defaultDatabase0.getTable("drop mater", false);
DBDataType dBDataType0 = DBDataType.getInstance(568, "$z>>v");
DefaultDBColumn defaultDBColumn0 = new DefaultDBColumn("drop mater", (DBTable) null, dBDataType0);
linkedList0.add((DBColumn) defaultDBColumn0);
String string0 = SQLUtil.renderColumnNames((List<DBColumn>) linkedList0);
assertEquals("drop mater", string0);
}
/**
//Test case number: 48
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test48() throws Throwable {
DefaultDBTable defaultDBTable0 = new DefaultDBTable();
SQLUtil.normalize("ater index", true);
TableContainer tableContainer0 = new TableContainer("drop materialized view");
SQLUtil.normalize("QQ8v&]hhrX*@>7vQ`&", true);
String[] stringArray0 = new String[2];
stringArray0[0] = "drop materialized view";
stringArray0[1] = "C+Mp+Z!L";
DBForeignKeyConstraint dBForeignKeyConstraint0 = new DBForeignKeyConstraint("ater index", false, defaultDBTable0, stringArray0, defaultDBTable0, stringArray0);
NameSpec nameSpec0 = NameSpec.NEVER;
JdbcDataSource jdbcDataSource0 = new JdbcDataSource();
JdbcConnectionPool jdbcConnectionPool0 = JdbcConnectionPool.create((ConnectionPoolDataSource) jdbcDataSource0);
jdbcConnectionPool0.getLogWriter();
// Undeclared exception!
try {
SQLUtil.renderAddForeignKey(dBForeignKeyConstraint0, nameSpec0, (PrintWriter) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.databene.jdbacl.SQLUtil", e);
}
}
/**
//Test case number: 49
/*Coverage entropy=1.1537419427010902
*/
@Test(timeout = 4000)
public void test49() throws Throwable {
ArrayList<DBColumn> arrayList0 = new ArrayList<DBColumn>();
DynamicByteArrayOutputStream dynamicByteArrayOutputStream0 = new DynamicByteArrayOutputStream();
MockPrintWriter mockPrintWriter0 = new MockPrintWriter(dynamicByteArrayOutputStream0, true);
DBDataType dBDataType0 = DBDataType.getInstance(7, "op_info_sql ");
Integer integer0 = RawTransaction.ABORT;
DefaultDBTable defaultDBTable0 = new DefaultDBTable();
DefaultDBColumn defaultDBColumn0 = new DefaultDBColumn("create materialized viewselect intoohniujc", defaultDBTable0, dBDataType0, integer0);
DefaultDBColumn defaultDBColumn1 = new DefaultDBColumn("a$eJ7Y\"<c3wL5", defaultDBTable0, dBDataType0);
DefaultDBTable defaultDBTable1 = new DefaultDBTable((String) null);
defaultDBTable1.addColumn(defaultDBColumn0);
NameSpec nameSpec0 = NameSpec.IF_REPRODUCIBLE;
SQLUtil.renderCreateTable(defaultDBTable0, false, nameSpec0, mockPrintWriter0);
assertEquals(120, dynamicByteArrayOutputStream0.getPosition());
String string0 = SQLUtil.normalize("K0MP)o-$O>f?RF", true);
assertEquals("K0MP) o - $ O > f ? R F", string0);
}
/**
//Test case number: 50
/*Coverage entropy=1.4205719259467042
*/
@Test(timeout = 4000)
public void test50() throws Throwable {
DefaultDBTable defaultDBTable0 = new DefaultDBTable();
String[] stringArray0 = new String[4];
stringArray0[0] = "BEGIN_EXE_TIME";
stringArray0[1] = ", ";
stringArray0[2] = "select";
stringArray0[3] = ", ";
DBForeignKeyConstraint dBForeignKeyConstraint0 = new DBForeignKeyConstraint("select", true, defaultDBTable0, stringArray0, defaultDBTable0, stringArray0);
NameSpec nameSpec0 = NameSpec.IF_REPRODUCIBLE;
SQLUtil.fkSpec(dBForeignKeyConstraint0, nameSpec0);
MockFile mockFile0 = new MockFile("bZ`};&nt5j-W%2*9o");
MockPrintWriter mockPrintWriter0 = new MockPrintWriter(mockFile0);
SQLUtil.renderCreateTable(defaultDBTable0, true, nameSpec0, mockPrintWriter0);
assertNull(defaultDBTable0.getDoc());
}
/**
//Test case number: 51
/*Coverage entropy=1.0397207708399179
*/
@Test(timeout = 4000)
public void test51() throws Throwable {
TableContainer tableContainer0 = new TableContainer("qk>w:YZH");
tableContainer0.getTable("renameseect intoohnijc");
DBDataType dBDataType0 = DBDataType.getInstance(32, "renameseect intoohnijc");
Integer integer0 = new Integer(90006);
DefaultDBColumn defaultDBColumn0 = new DefaultDBColumn("SEQUENCE_CATALOG", (DBTable) null, dBDataType0, integer0);
SQLUtil.renderColumn(defaultDBColumn0);
DefaultDBColumn defaultDBColumn1 = new DefaultDBColumn("SEQUENCE_CATALOG", (DBTable) null, dBDataType0);
defaultDBColumn1.setTable((DBTable) null);
DefaultDBColumn defaultDBColumn2 = new DefaultDBColumn("renameseect intoohnijc", (DBTable) null, 30, "SEQUENCE_CATALOG RENAMESEECT INTOOHNIJC(90006) NULL");
// Undeclared exception!
try {
defaultDBColumn2.setNullable(false);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.databene.jdbacl.model.DefaultDBColumn", e);
}
}
/**
//Test case number: 52
/*Coverage entropy=1.6326309271543518
*/
@Test(timeout = 4000)
public void test52() throws Throwable {
DefaultDBTable defaultDBTable0 = new DefaultDBTable();
String[] stringArray0 = new String[4];
stringArray0[0] = "BEGIN_EXE_TIME";
stringArray0[1] = ", ";
stringArray0[2] = "select";
stringArray0[3] = ", ";
DBForeignKeyConstraint dBForeignKeyConstraint0 = new DBForeignKeyConstraint("select", true, defaultDBTable0, stringArray0, defaultDBTable0, stringArray0);
NameSpec nameSpec0 = NameSpec.IF_REPRODUCIBLE;
SQLUtil.fkSpec(dBForeignKeyConstraint0, nameSpec0);
// Undeclared exception!
try {
SQLUtil.parseColumnTypeAndSize("CONSTRAINT select FOREIGN KEY (BEGIN_EXE_TIME, , , select, , ) REFERENCES null(BEGIN_EXE_TIME, , , select, , )");
fail("Expecting exception: NumberFormatException");
} catch(NumberFormatException e) {
//
// For input string: \"BEGIN_EXE_TIME\"
//
verifyException("java.lang.NumberFormatException", e);
}
}
/**
//Test case number: 53
/*Coverage entropy=1.0397207708399179
*/
@Test(timeout = 4000)
public void test53() throws Throwable {
DefaultDBTable defaultDBTable0 = new DefaultDBTable("[G%'>M}A@61QGX", (DBSchema) null);
String[] stringArray0 = new String[1];
stringArray0[0] = null;
DBPrimaryKeyConstraint dBPrimaryKeyConstraint0 = new DBPrimaryKeyConstraint(defaultDBTable0, "M0lxJ2#W", false, stringArray0);
DBUniqueIndex dBUniqueIndex0 = new DBUniqueIndex((String) null, false, dBPrimaryKeyConstraint0);
DBTable dBTable0 = dBUniqueIndex0.getTable();
defaultDBTable0.removeIndex(dBUniqueIndex0);
DBUniqueConstraint dBUniqueConstraint0 = new DBUniqueConstraint(dBTable0, "dH?%kqX", false, stringArray0);
StringBuilder stringBuilder0 = new StringBuilder("d;0b*,eT{(hB1;_u");
StringBuilder stringBuilder1 = stringBuilder0.append((-2.147483648E9));
SQLUtil.appendConstraintName((DBConstraint) dBUniqueConstraint0, stringBuilder1);
assertEquals("d;0b*,eT{(hB1;_u-2.147483648E9CONSTRAINT dH?%kqX ", stringBuilder1.toString());
String string0 = SQLUtil.normalize("drop materialized view42y90", false);
assertEquals("drop materialized view42y90", string0);
}
}
|
package com.swee.cloudconsul.pro.core.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ConsulController {
@GetMapping("/ping")
public String ping() {
return " Service ping";
}
@GetMapping("/my-health-check")
public ResponseEntity<String> myCustomCheck() {
String message = "Testing my healh check function";
return new ResponseEntity<String>(message, HttpStatus.FORBIDDEN);
}
}
|
package com.firetower.user_service;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class UserServiceApplicationTests {
@Test
void contextLoads() {
}
}
|
package org.cuieney.videolife.common.utils;
import android.support.design.widget.Snackbar;
import android.view.View;
/**
* Created by codeest on 16/9/3.
*/
public class SnackbarUtil {
public static void show(View view, String msg) {
Snackbar.make(view, msg, Snackbar.LENGTH_LONG).show();
}
public static void showShort(View view, String msg) {
Snackbar.make(view, msg, Snackbar.LENGTH_SHORT).show();
}
}
|
package net.justugh.sb;
import com.google.gson.GsonBuilder;
import lombok.Getter;
import net.dv8tion.jda.api.AccountType;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.entities.Activity;
import net.dv8tion.jda.api.entities.Guild;
import net.justugh.sb.config.Config;
import net.justugh.sb.guild.config.GuildConfig;
import net.justugh.sb.manager.BotManager;
import net.justugh.sb.manager.CommandManager;
import net.justugh.sb.manager.SuggestionManager;
import net.justugh.sb.manager.UserManager;
import org.apache.commons.io.FileUtils;
import javax.security.auth.login.LoginException;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
@Getter
public class Bot {
private static Bot instance;
private JDA jdaInstance;
private Config config;
private HashMap<Long, GuildConfig> guildConfigCache = new HashMap<>();
private CommandManager commandManager;
private SuggestionManager suggestionManager;
private UserManager userManager;
public static void main(String[] args) {
new Bot().launch();
}
private Bot() {
instance = this;
}
/**
* Do all the essentials to
* launch the Discord bot
*/
private void launch() {
loadConfig();
if (config.getToken().isEmpty() || config.getToken() == null) {
System.out.println("[Suggester]: Cannot start the bot, auth token is invalid.");
System.exit(0);
return;
}
try {
JDABuilder builder = new JDABuilder(AccountType.BOT);
builder.setToken(config.getToken());
builder.setAutoReconnect(true);
builder.setStatus(config.getOnlineStatus());
builder.setActivity(Activity.of(config.getActivity(), config.getPlayingMessage()));
jdaInstance = builder.build();
// We need to do this to make sure we can get the bots guilds to load the configs.
jdaInstance.awaitReady();
loadGuildConfigs();
loadManagers();
} catch (LoginException | InterruptedException e) {
e.printStackTrace();
}
}
/**
* Load managers along with registering
* them as listeners.
*/
private void loadManagers() {
commandManager = new CommandManager();
suggestionManager = new SuggestionManager();
userManager = new UserManager();
jdaInstance.addEventListener(new BotManager());
jdaInstance.addEventListener(commandManager);
jdaInstance.addEventListener(suggestionManager);
jdaInstance.addEventListener(userManager);
}
/**
* Load the configuration
*/
private void loadConfig() {
File configFile = new File("config.json");
try {
if (!configFile.exists()) {
config = new Config();
FileUtils.write(configFile, new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create().toJson(config), StandardCharsets.UTF_8);
} else {
config = new GsonBuilder().create().fromJson(new FileReader(configFile), Config.class);
// We do this to make sure the config has any new fields from the GuildConfig class
FileUtils.write(configFile, new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create().toJson(config), StandardCharsets.UTF_8);
}
} catch(IOException e) {
e.printStackTrace();
}
}
/**
* Load Guild configuration files.
*/
private void loadGuildConfigs() {
for (Guild guild : jdaInstance.getSelfUser().getMutualGuilds()) {
File guildFile = new File("guilds" + File.separator + guild.getIdLong() + File.separator + "config.json");
try {
if (!guildFile.exists()) {
GuildConfig guildConfig = new GuildConfig(guild.getIdLong());
if(guild.getDefaultChannel() != null) {
guildConfig.setDefaultSuggestionChannel(guild.getDefaultChannel().getIdLong());
}
guildConfigCache.put(guild.getIdLong(), guildConfig);
FileUtils.write(guildFile, new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create().toJson(guildConfig), StandardCharsets.UTF_8);
} else {
GuildConfig guildConfig = new GsonBuilder().create().fromJson(new FileReader(guildFile), GuildConfig.class);
if(guildConfig.getDefaultSuggestionChannel() == 0) {
if(guild.getDefaultChannel() != null) {
guildConfig.setDefaultSuggestionChannel(guild.getDefaultChannel().getIdLong());
}
}
guildConfigCache.put(guild.getIdLong(), guildConfig);
// We do this to make sure the config has any new fields from the GuildConfig class
FileUtils.write(guildFile, new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create().toJson(guildConfig), StandardCharsets.UTF_8);
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
/**
* Get the Guild configuration.
*
* @param guildID The Guild's ID.
* @return The instance of the Guild Config.
*/
public GuildConfig getGuildConfig(long guildID) {
return guildConfigCache.get(guildID);
}
/**
* Get the Bot instance.
*
* @return The instance of the Bot.
*/
public static Bot getInstance() {
return instance;
}
}
|
package industrialcraft.common.tier;
public enum ItemPipeTier {
WOODEN,
TIN,
COPPER,
IRON,
GOLD,
BRONZE;
private static final ItemPipeTier[] TIERS = values();
}
|
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2020 iText Group NV
Authors: iText Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
ITEXT GROUP. ITEXT GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://itextpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using iText.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the iText software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping iText with a closed
source product.
For more information, please contact iText Software Corp. at this
address: sales@itextpdf.com
*/
package com.itextpdf.html2pdf.css.w3c.css21.normal_flow;
import com.itextpdf.html2pdf.css.w3c.W3CCssTest;
public class Width102Test extends W3CCssTest {
@Override
protected String getHtmlFileName() {
return "width-102.xht";
}
}
|
/**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.v5;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.apache.activemq.openwire.*;
import org.apache.activemq.command.*;
/**
* Marshalling code for Open Wire Format for JournalTraceMarshaller
*
*
* NOTE!: This file is auto generated - do not modify!
* if you need to make a change, please see the modify the groovy scripts in the
* under src/gram/script and then use maven openwire:generate to regenerate
* this file.
*
*
*/
public class JournalTraceMarshaller extends BaseDataStreamMarshaller {
/**
* Return the type of Data Structure we marshal
* @return short representation of the type data structure
*/
public byte getDataStructureType() {
return JournalTrace.DATA_STRUCTURE_TYPE;
}
/**
* @return a new object instance
*/
public DataStructure createObject() {
return new JournalTrace();
}
/**
* Un-marshal an object instance from the data input stream
*
* @param o the object to un-marshal
* @param dataIn the data input stream to build the object from
* @throws IOException
*/
public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException {
super.tightUnmarshal(wireFormat, o, dataIn, bs);
JournalTrace info = (JournalTrace)o;
info.setMessage(tightUnmarshalString(dataIn, bs));
}
/**
* Write the booleans that this object uses to a BooleanStream
*/
public int tightMarshal1(OpenWireFormat wireFormat, Object o, BooleanStream bs) throws IOException {
JournalTrace info = (JournalTrace)o;
int rc = super.tightMarshal1(wireFormat, o, bs);
rc += tightMarshalString1(info.getMessage(), bs);
return rc + 0;
}
/**
* Write a object instance to data output stream
*
* @param o the instance to be marshaled
* @param dataOut the output stream
* @throws IOException thrown if an error occurs
*/
public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException {
super.tightMarshal2(wireFormat, o, dataOut, bs);
JournalTrace info = (JournalTrace)o;
tightMarshalString2(info.getMessage(), dataOut, bs);
}
/**
* Un-marshal an object instance from the data input stream
*
* @param o the object to un-marshal
* @param dataIn the data input stream to build the object from
* @throws IOException
*/
public void looseUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn) throws IOException {
super.looseUnmarshal(wireFormat, o, dataIn);
JournalTrace info = (JournalTrace)o;
info.setMessage(looseUnmarshalString(dataIn));
}
/**
* Write the booleans that this object uses to a BooleanStream
*/
public void looseMarshal(OpenWireFormat wireFormat, Object o, DataOutput dataOut) throws IOException {
JournalTrace info = (JournalTrace)o;
super.looseMarshal(wireFormat, o, dataOut);
looseMarshalString(info.getMessage(), dataOut);
}
}
|
package com.viesis.viescraft.client.gui.airship.customize.balloon.sub;
import org.lwjgl.input.Keyboard;
import com.viesis.viescraft.api.GuiVC;
import com.viesis.viescraft.common.entity.airships.EntityAirshipCore;
import net.minecraft.inventory.IInventory;
public class GuiCustomizeMenuBalloonTier3Pg1 extends GuiCustomizeMenuBalloonTierVC {
public GuiCustomizeMenuBalloonTier3Pg1(IInventory playerInv, EntityAirshipCore airshipIn)
{
super(playerInv, airshipIn);
}
/**
* Adds the buttons (and other controls) to the screen in question.
*/
@Override
public void initGui()
{
super.initGui();
buttonList.clear();
Keyboard.enableRepeatEvents(true);
this.buttonList.add(GuiVC.buttonMM1);
this.buttonList.add(GuiVC.buttonMM2);
this.buttonList.add(GuiVC.buttonMM3);
this.buttonList.add(GuiVC.buttonMM4);
this.buttonList.add(GuiVC.buttonMM5);
this.buttonList.add(GuiVC.button501);
this.buttonList.add(GuiVC.button502);
//this.buttonList.add(GuiVC.button503);
//this.buttonList.add(GuiVC.button504);
this.buttonList.add(GuiVC.button505);
this.buttonList.add(GuiVC.button31);
this.buttonList.add(GuiVC.button32);
this.buttonList.add(GuiVC.button33);
this.buttonList.add(GuiVC.button34);
this.buttonList.add(GuiVC.button35);
this.buttonList.add(GuiVC.button36);
this.buttonList.add(GuiVC.button37);
this.buttonList.add(GuiVC.button38);
this.buttonList.add(GuiVC.button39);
this.buttonList.add(GuiVC.button40);
this.buttonList.add(GuiVC.button41);
this.buttonList.add(GuiVC.button42);
GuiVC.buttonMM3.enabled = false;
//TO REMOVE WHEN TEXTURES ARE MADE
GuiVC.button33.visible = false;
GuiVC.button34.visible = false;
GuiVC.button35.visible = false;
GuiVC.button36.visible = false;
GuiVC.button37.visible = false;
GuiVC.button38.visible = false;
GuiVC.button39.visible = false;
GuiVC.button40.visible = false;
GuiVC.button41.visible = false;
GuiVC.button42.visible = false;
}
@Override
protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY)
{
super.drawGuiContainerBackgroundLayer(partialTicks, mouseX, mouseY);
this.grayOutSelectedButton();
}
private void grayOutSelectedButton()
{
if(this.airship.balloonPatternTexture == 31)
{
GuiVC.button31.enabled = false;
}
else
{
GuiVC.button31.enabled = true;
}
if(this.airship.balloonPatternTexture == 32)
{
GuiVC.button32.enabled = false;
}
else
{
GuiVC.button32.enabled = true;
}
if(this.airship.balloonPatternTexture == 33)
{
GuiVC.button33.enabled = false;
}
else
{
GuiVC.button33.enabled = true;
}
if(this.airship.balloonPatternTexture == 34)
{
GuiVC.button34.enabled = false;
}
else
{
GuiVC.button34.enabled = true;
}
if(this.airship.balloonPatternTexture == 35)
{
GuiVC.button35.enabled = false;
}
else
{
GuiVC.button35.enabled = true;
}
if(this.airship.balloonPatternTexture == 36)
{
GuiVC.button36.enabled = false;
}
else
{
GuiVC.button36.enabled = true;
}
if(this.airship.balloonPatternTexture == 37)
{
GuiVC.button37.enabled = false;
}
else
{
GuiVC.button37.enabled = true;
}
if(this.airship.balloonPatternTexture == 38)
{
GuiVC.button38.enabled = false;
}
else
{
GuiVC.button38.enabled = true;
}
if(this.airship.balloonPatternTexture == 39)
{
GuiVC.button39.enabled = false;
}
else
{
GuiVC.button39.enabled = true;
}
if(this.airship.balloonPatternTexture == 40)
{
GuiVC.button40.enabled = false;
}
else
{
GuiVC.button40.enabled = true;
}
if(this.airship.balloonPatternTexture == 41)
{
GuiVC.button41.enabled = false;
}
else
{
GuiVC.button41.enabled = true;
}
if(this.airship.balloonPatternTexture == 42)
{
GuiVC.button42.enabled = false;
}
else
{
GuiVC.button42.enabled = true;
}
}
}
|
/**
* Copyright 2016 vip.com.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* 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.
* </p>
**/
package com.vip.saturn.job.trigger;
import com.vip.saturn.job.basic.AbstractElasticJob;
import com.vip.saturn.job.exception.JobException;
import com.vip.saturn.job.utils.LogEvents;
import com.vip.saturn.job.utils.LogUtils;
import org.quartz.Trigger;
import org.quartz.spi.OperableTrigger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @author chembo.huang
*/
public class SaturnWorker implements Runnable {
static Logger log = LoggerFactory.getLogger(SaturnWorker.class);
private final Object sigLock = new Object();
private final AbstractElasticJob job;
private final Triggered notTriggered;
private volatile OperableTrigger triggerObj;
private volatile boolean paused = false;
private volatile Triggered triggered;
private AtomicBoolean halted = new AtomicBoolean(false);
public SaturnWorker(AbstractElasticJob job, Triggered notTriggered, Trigger trigger) {
this.job = job;
this.notTriggered = notTriggered;
this.triggered = notTriggered;
initTrigger(trigger);
}
void reInitTrigger(Trigger trigger) {
initTrigger(trigger);
synchronized (sigLock) {
sigLock.notifyAll();
}
}
private void initTrigger(Trigger trigger) {
if (trigger == null) {
return;
}
if (!(trigger instanceof OperableTrigger)) {
throw new JobException("the trigger should be the instance of OperableTrigger");
}
this.triggerObj = (OperableTrigger) trigger;
Date ft = this.triggerObj.computeFirstFireTime(null);
if (ft == null) {
LogUtils.warn(log, LogEvents.ExecutorEvent.COMMON,
"Based on configured schedule, the given trigger {} will never fire.", trigger.getKey(),
job.getJobName());
}
}
boolean isShutDown() {
return halted.get();
}
void togglePause(boolean pause) {
synchronized (sigLock) {
paused = pause;
sigLock.notifyAll();
}
}
void halt() {
synchronized (sigLock) {
halted.set(true);
sigLock.notifyAll();
}
}
void trigger(Triggered triggered) {
synchronized (sigLock) {
this.triggered = triggered == null ? notTriggered : triggered;
sigLock.notifyAll();
}
}
Date getNextFireTimePausePeriodEffected() {
if (triggerObj == null) {
return null;
}
triggerObj.updateAfterMisfire(null);
Date nextFireTime = triggerObj.getNextFireTime();
while (nextFireTime != null && job.getConfigService().isInPausePeriod(nextFireTime)) {
nextFireTime = triggerObj.getFireTimeAfter(nextFireTime);
}
return nextFireTime;
}
@Override
public void run() {
while (!halted.get()) {
try {
synchronized (sigLock) {
while (paused && !halted.get()) {
try {
sigLock.wait(1000L);
} catch (InterruptedException ignore) {
}
}
if (halted.get()) {
break;
}
}
boolean noFireTime = false; // 没有下次执行时间,初始化为false
long timeUntilTrigger = 1000;
if (triggerObj != null) {
triggerObj.updateAfterMisfire(null);
long now = System.currentTimeMillis();
Date nextFireTime = triggerObj.getNextFireTime();
if (nextFireTime != null) {
timeUntilTrigger = nextFireTime.getTime() - now;
} else {
noFireTime = true;
}
}
while (!noFireTime && timeUntilTrigger > 2) {
synchronized (sigLock) {
if (halted.get()) {
break;
}
if (triggered.isYes()) {
break;
}
try {
sigLock.wait(timeUntilTrigger);
} catch (InterruptedException ignore) {
}
if (triggerObj != null) {
long now = System.currentTimeMillis();
Date nextFireTime = triggerObj.getNextFireTime();
if (nextFireTime != null) {
timeUntilTrigger = nextFireTime.getTime() - now;
} else {
noFireTime = true;
}
}
}
}
boolean goAhead;
Triggered currentTriggered = notTriggered;
// 触发执行只有两个条件:1.时间到了 2.点立即执行
synchronized (sigLock) {
goAhead = !halted.get() && !paused;
// 重置立即执行标志,赋值当前立即执行数据
if (triggered.isYes()) {
currentTriggered = triggered;
triggered = notTriggered;
} else if (goAhead) { // 非立即执行。即,执行时间到了,或者没有下次执行时间
goAhead = goAhead && !noFireTime; // 有下次执行时间,即执行时间到了,才执行作业
if (goAhead) { // 执行时间到了,更新执行时间
if (triggerObj != null) {
triggerObj.triggered(null);
}
} else { // 没有下次执行时间,则尝试睡一秒,防止不停的循环导致CPU使用率过高(如果cron不再改为周期性执行)
try {
sigLock.wait(1000L);
} catch (InterruptedException ignore) {
}
}
}
}
if (goAhead) {
job.execute(currentTriggered);
}
} catch (RuntimeException e) {
LogUtils.error(log, job.getJobName(), e.getMessage(), e);
}
}
}
}
|
package org.hisp.dhis.coldchain.equipment.hibernate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Conjunction;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hisp.dhis.attribute.Attribute;
import org.hisp.dhis.coldchain.equipment.EquipmentAttributeValue;
import org.hisp.dhis.coldchain.equipment.Equipment;
import org.hisp.dhis.coldchain.equipment.EquipmentStore;
import org.hisp.dhis.coldchain.equipment.EquipmentType;
import org.hisp.dhis.coldchain.equipment.EquipmentTypeAttribute;
import org.hisp.dhis.hibernate.HibernateGenericStore;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public class HibernateEquipmentStore
extends HibernateGenericStore<Equipment>
implements EquipmentStore
{
// -------------------------------------------------------------------------
// Dependencies
// -------------------------------------------------------------------------
/*
private SessionFactory sessionFactory;
public void setSessionFactory( SessionFactory sessionFactory )
{
this.sessionFactory = sessionFactory;
}
*/
// -------------------------------------------------------------------------
// Equipment
// -------------------------------------------------------------------------
/*
public int addEquipment( Equipment equipment )
{
Session session = sessionFactory.getCurrentSession();
return (Integer) session.save( equipment );
}
public void deleteEquipment( Equipment equipment )
{
Session session = sessionFactory.getCurrentSession();
session.delete( equipment );
}
public Collection<Equipment> getAllEquipment()
{
Session session = sessionFactory.getCurrentSession();
return session.createCriteria( Equipment.class ).list();
}
public void updateEquipment( Equipment equipment )
{
Session session = sessionFactory.getCurrentSession();
session.update( equipment );
}
*/
@SuppressWarnings( "unchecked" )
public Collection<Equipment> getEquipments( OrganisationUnit orgUnit )
{
/*
Session session = sessionFactory.getCurrentSession();
Criteria criteria = session.createCriteria( EquipmentTypeAttribute.class );
criteria.add( Restrictions.eq( "organisationUnit", orgUnit ) );
return criteria.list();
*/
return getCriteria( Restrictions.eq( "organisationUnit", orgUnit ) ).list();
}
@SuppressWarnings( "unchecked" )
public Collection<Equipment> getEquipments( OrganisationUnit orgUnit, EquipmentType equipmentType )
{
/*
Session session = sessionFactory.getCurrentSession();
Criteria criteria = session.createCriteria( EquipmentTypeAttribute.class );
criteria.add( Restrictions.eq( "organisationUnit", orgUnit ) );
criteria.add( Restrictions.eq( "equipmentType", equipmentType ) );
return criteria.list();
*/
Criteria crit = getCriteria();
Conjunction con = Restrictions.conjunction();
con.add( Restrictions.eq( "organisationUnit", orgUnit ) );
con.add( Restrictions.eq( "equipmentType", equipmentType ) );
crit.add( con );
// Restrictions.in( "organisationUnit", values );
return crit.list();
}
// public int getCountEquipment( OrganisationUnit orgUnit, EquipmentType equipmentType )
public int getCountEquipment( List<OrganisationUnit> orgUnitList, EquipmentType equipmentType )
{
Number rs = 0;
//System.out.println(" Size of orgUnitList is : " + orgUnitList.size() + " -- " + equipmentType.getId() + equipmentType.getName() );
if ( orgUnitList != null && orgUnitList.size() != 0 )
{
rs = (Number) getCriteria( Restrictions.in( "organisationUnit", orgUnitList ) ).add( Restrictions.eq( "equipmentType", equipmentType ) ).setProjection(
Projections.rowCount() ).uniqueResult();
}
/*
Number rs = (Number) getCriteria( Restrictions.in( "organisationUnit", orgUnitList ) ).add( Restrictions.eq( "equipmentType", equipmentType ) ).setProjection(
Projections.rowCount() ).uniqueResult();
*/
//System.out.println(" RS is : " + rs );
return rs != null ? rs.intValue() : 0;
}
@SuppressWarnings( "unchecked" )
//public Collection<Equipment> getEquipments( OrganisationUnit orgUnit, EquipmentType equipmentType, int min, int max )
public Collection<Equipment> getEquipments( List<OrganisationUnit> orgUnitList, EquipmentType equipmentType, int min, int max )
{
List<Equipment> equipmentList = new ArrayList<Equipment>();
if ( orgUnitList != null && orgUnitList.size() != 0 )
{
return getCriteria( Restrictions.in( "organisationUnit", orgUnitList ) ).add( Restrictions.eq( "equipmentType", equipmentType ) ).setFirstResult( min ).setMaxResults( max ).list();
}
else
{
return equipmentList;
}
//return getCriteria( Restrictions.in( "organisationUnit", orgUnitList ) ).add( Restrictions.eq( "equipmentType", equipmentType ) ).setFirstResult( min ).setMaxResults( max ).list();
}
//public int getCountEquipment( OrganisationUnit orgUnit, EquipmentType equipmentType, EquipmentTypeAttribute equipmentTypeAttribute, String searchText )
public int getCountEquipment( String orgUnitIdsByComma, EquipmentType equipmentType, EquipmentTypeAttribute equipmentTypeAttribute, String searchText, String searchBy )
{
/*
String hql = "SELECT COUNT( DISTINCT ei ) FROM Equipment AS ei " +
" WHERE ei IN ( SELECT ed.equipment FROM EquipmentAttributeValue AS ed WHERE ed.equipmentTypeAttribute.id = "+ equipmentTypeAttribute.getId()+" AND ed.value LIKE '%" + searchText + "%' ) " +
" AND ei.organisationUnit.id IN (" + orgUnitIdsByComma + " ) " +
" AND ei.equipmentType.id = " + equipmentType.getId();
*/
String hql = "";
if( searchBy.equalsIgnoreCase( EquipmentAttributeValue.PREFIX_MODEL_NAME ) )
{
hql = "SELECT COUNT( DISTINCT ei ) FROM Equipment AS ei, Model AS cat" +
" WHERE ei.organisationUnit.id IN (" + orgUnitIdsByComma + " ) " +
" AND ei.equipmentType.id = " + equipmentType.getId() +
"AND cat.name like '%" + searchText + "%' AND cat.id = ei.model.id " ;
}
else if ( searchBy.equalsIgnoreCase( EquipmentAttributeValue.PREFIX_ORGANISATIONUNIT_NAME ))
{
hql = "SELECT COUNT( DISTINCT ei ) FROM Equipment AS ei, OrganisationUnit AS orgUnit" +
" WHERE ei.organisationUnit.id IN (" + orgUnitIdsByComma + " ) " +
" AND ei.equipmentType.id = " + equipmentType.getId() +
"AND orgUnit.name like '%" + searchText + "%' AND orgUnit.id = ei.organisationUnit.id " ;
}
else
{
hql = "SELECT COUNT( DISTINCT ei ) FROM Equipment AS ei " +
" WHERE ei IN ( SELECT ed.equipment FROM EquipmentAttributeValue AS ed WHERE ed.equipmentTypeAttribute.id = "+ equipmentTypeAttribute.getId()+" AND ed.value LIKE '%" + searchText + "%' ) " +
" AND ei.organisationUnit.id IN (" + orgUnitIdsByComma + " ) " +
" AND ei.equipmentType.id = " + equipmentType.getId();
}
Query query = getQuery( hql );
Number rs = (Number) query.uniqueResult();
return (rs != null) ? rs.intValue() : 0;
}
@SuppressWarnings( "unchecked" )
// public Collection<Equipment> getEquipments( OrganisationUnit orgUnit, EquipmentType equipmentType, EquipmentTypeAttribute equipmentTypeAttribute, String searchText, int min, int max )
public Collection<Equipment> getEquipments( String orgUnitIdsByComma, EquipmentType equipmentType, EquipmentTypeAttribute equipmentTypeAttribute, String searchText, String searchBy, int min, int max )
{
/*
String hql = "SELECT DISTINCT ei FROM Equipment AS ei " +
" WHERE ei IN ( SELECT ed.equipment FROM EquipmentAttributeValue AS ed WHERE ed.equipmentTypeAttribute.id = "+ equipmentTypeAttribute.getId()+" AND ed.value like '%" + searchText + "%' ) " +
" AND ei.organisationUnit.id IN (" + orgUnitIdsByComma + " ) " +
" AND ei.equipmentType.id = " + equipmentType.getId();
*/
String hql = "";
//if( EquipmentAttributeValue.PREFIX_MODEL_NAME.equalsIgnoreCase( "modelname" ))
if( searchBy.equalsIgnoreCase( EquipmentAttributeValue.PREFIX_MODEL_NAME ))
{
hql = "SELECT DISTINCT ei FROM Equipment AS ei, Model AS cat" +
" WHERE ei.organisationUnit.id IN (" + orgUnitIdsByComma + " ) " +
" AND ei.equipmentType.id = " + equipmentType.getId() +
"AND cat.name like '%" + searchText + "%' AND cat.id = ei.model.id " ;
}
else if ( searchBy.equalsIgnoreCase( EquipmentAttributeValue.PREFIX_ORGANISATIONUNIT_NAME))
{
hql = "SELECT DISTINCT ei FROM Equipment AS ei, OrganisationUnit AS orgUnit" +
" WHERE ei.organisationUnit.id IN (" + orgUnitIdsByComma + " ) " +
" AND ei.equipmentType.id = " + equipmentType.getId() +
"AND orgUnit.name like '%" + searchText + "%' AND orgUnit.id = ei.organisationUnit.id " ;
}
else
{
hql = "SELECT DISTINCT ei FROM Equipment AS ei " +
" WHERE ei IN ( SELECT ed.equipment FROM EquipmentAttributeValue AS ed WHERE ed.equipmentTypeAttribute.id = "+ equipmentTypeAttribute.getId()+" AND ed.value like '%" + searchText + "%' ) " +
" AND ei.organisationUnit.id IN (" + orgUnitIdsByComma + " ) " +
" AND ei.equipmentType.id = " + equipmentType.getId();
}
/*
String hql1 = "SELECT DISTINCT ei FROM Equipment AS ei, Model AS cat" +
" WHERE ei.organisationUnit.id IN (" + orgUnitIdsByComma + " ) " +
" AND ei.equipmentType.id = " + equipmentType.getId() +
"AND cat.name like '%" + searchText + "%' AND cat.id = ei.model.id " ;
*/
/*
String hql1 = "SELECT DISTINCT ei FROM Equipment AS ei, organisationunit AS orgUnit" +
" WHERE ei.organisationUnit.id IN (" + orgUnitIdsByComma + " ) " +
" AND ei.equipmentType.id = " + equipmentType.getId() +
"AND orgUnit.name like '%" + searchText + "%' AND orgUnit.id = ei.organisationUnit.id " ;
*/
//select EI.*, org.name from equipment as EI ,organisationunit as org where org.name like '%district%' and EI.organisationunitid = org.organisationunitid;
//select EI.*, CAT.name from equipment as EI ,model as CAT where CAT.name like '%VC%' and EI.modelid = CAT.modelid;
Query query = getQuery( hql ).setFirstResult( min ).setMaxResults( max );
return query.list();
}
@SuppressWarnings( "unchecked" )
public Collection<OrganisationUnit> searchOrgUnitListByName( String searchText )
{
String hql = "SELECT orgUnit FROM OrganisationUnit AS orgUnit WHERE orgUnit.name like '%" + searchText + "%'";
Query query = getQuery( hql );
return query.list();
/*
Criteria criteria = getCriteria();
criteria.add(Restrictions.like( "OrganisationUnit.name", "%" + searchText + "%"));
return criteria.list();
*/
}
@SuppressWarnings( "unchecked" )
public Collection<OrganisationUnit> searchOrgUnitListByCode( String searchText )
{
String hql = "SELECT orgUnit FROM OrganisationUnit AS orgUnit WHERE orgUnit.code like '%" + searchText + "%'";
Query query = getQuery( hql );
return query.list();
/*
Criteria criteria = getCriteria();
criteria.add(Restrictions.like( "OrganisationUnit.name", "%" + searchText + "%"));
return criteria.list();
*/
}
// for orgUnit list according to orGUnit Attribute values for paging purpose
public int countOrgUnitByAttributeValue( Collection<Integer> orgunitIds, Attribute attribute, String searchText )
{
Criteria criteria = getCriteria( Restrictions.eq( "organisationUnitAttribute", true ));
criteria.createAlias( "attributeValues", "attributeValue");
criteria.add(Restrictions.eq( "attributeValue.attribute", attribute));
criteria.add(Restrictions.like( "attributeValue.value", "%" + searchText + "%"));
/*
criteria.add(Restrictions.eq( "attributeValues.attribute", attribute));
criteria.add(Restrictions.eq( "attributeValues.attribute", attribute));
*/
criteria.add(Restrictions.in( "id",orgunitIds));
Number rs = (Number) criteria.uniqueResult();
return (rs != null) ? rs.intValue() : 0;
}
// for orgUnit list according to orGUnit Attribute values for paging purpose
@SuppressWarnings( "unchecked" )
public Collection<OrganisationUnit> searchOrgUnitByAttributeValue( Collection<Integer> orgunitIds, Attribute attribute, String searchText, Integer min, Integer max )
{
Criteria criteria = getCriteria( Restrictions.eq( "organisationUnitAttribute", true ));
criteria.createAlias( "attributeValues", "attributeValue");
criteria.add(Restrictions.eq( "attributeValue.attribute", attribute));
criteria.add(Restrictions.like( "attributeValue.value", "%" + searchText + "%"));
criteria.add(Restrictions.in( "id",orgunitIds));
criteria.setFirstResult( min ).setMaxResults( max );
return criteria.list();
}
}
|
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.debugger.streams.psi;
import com.intellij.psi.*;
import com.intellij.psi.util.InheritanceUtil;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* @author Vitaliy.Bibaev
*/
public class StreamApiUtil {
private StreamApiUtil() {
}
public static boolean isStreamCall(@NotNull PsiMethodCallExpression expression) {
return isIntermediateStreamCall(expression) || isProducerStreamCall(expression) || isTerminationStreamCall(expression);
}
public static boolean isProducerStreamCall(@NotNull PsiMethodCallExpression expression) {
final PsiMethod method = expression.resolveMethod();
return (method != null && method.hasModifierProperty(PsiModifier.STATIC)) ||
checkStreamCall(expression, false, true);
}
private static boolean isIntermediateStreamCall(@NotNull PsiMethodCallExpression expression) {
return checkStreamCall(expression, true, true);
}
public static boolean isTerminationStreamCall(@NotNull PsiMethodCallExpression expression) {
return checkStreamCall(expression, true, false);
}
private static boolean checkStreamCall(@NotNull PsiMethodCallExpression expression,
boolean mustParentBeStream,
boolean mustResultBeStream) {
final PsiMethod method = expression.resolveMethod();
if (method != null && mustResultBeStream == isStreamType(expression.getType())) {
final PsiElement methodClass = method.getParent();
if (methodClass instanceof PsiClass) {
return mustParentBeStream == isStreamType((PsiClass)methodClass);
}
}
return false;
}
@Contract("null -> false")
private static boolean isStreamType(@Nullable PsiType psiType) {
return InheritanceUtil.isInheritor(psiType, CommonClassNames.JAVA_UTIL_STREAM_BASE_STREAM);
}
@Contract("null -> false")
private static boolean isStreamType(@Nullable PsiClass psiClass) {
return InheritanceUtil.isInheritor(psiClass, CommonClassNames.JAVA_UTIL_STREAM_BASE_STREAM);
}
}
|
/*
* Copyright (C) 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ymdev.ymzxinglib;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.util.Log;
import java.io.Closeable;
import java.io.IOException;
/**
* Manages beeps and vibrations for {@link CaptureActivity}.
*/
final class BeepManager implements MediaPlayer.OnErrorListener, Closeable {
private static final String TAG = BeepManager.class.getSimpleName();
private static final float BEEP_VOLUME = 0.10f;
private static final long VIBRATE_DURATION = 200L;
private final Activity activity;
private MediaPlayer mediaPlayer;
private boolean playBeep;
private boolean vibrate;
BeepManager(Activity activity) {
this.activity = activity;
this.mediaPlayer = null;
updatePrefs();
}
synchronized void updatePrefs() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
playBeep = shouldBeep(prefs, activity);
vibrate = prefs.getBoolean(PreferencesActivity.KEY_VIBRATE, false);
if (playBeep && mediaPlayer == null) {
// The volume on STREAM_SYSTEM is not adjustable, and users found it too loud,
// so we now play on the music stream.
activity.setVolumeControlStream(AudioManager.STREAM_MUSIC);
mediaPlayer = buildMediaPlayer(activity);
}
}
synchronized void playBeepSoundAndVibrate() {
if (playBeep && mediaPlayer != null) {
mediaPlayer.start();
}
if (vibrate) {
Vibrator vibrator = (Vibrator) activity.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(VIBRATE_DURATION);
}
}
private static boolean shouldBeep(SharedPreferences prefs, Context activity) {
boolean shouldPlayBeep = prefs.getBoolean(PreferencesActivity.KEY_PLAY_BEEP, true);
if (shouldPlayBeep) {
// See if sound settings overrides this
AudioManager audioService = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE);
if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
shouldPlayBeep = false;
}
}
return shouldPlayBeep;
}
private MediaPlayer buildMediaPlayer(Context activity) {
MediaPlayer mediaPlayer = new MediaPlayer();
try (AssetFileDescriptor file = activity.getResources().openRawResourceFd(R.raw.beep)) {
mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setLooping(false);
mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
mediaPlayer.prepare();
return mediaPlayer;
} catch (IOException ioe) {
Log.w(TAG, ioe);
mediaPlayer.release();
return null;
}
}
@Override
public synchronized boolean onError(MediaPlayer mp, int what, int extra) {
if (what == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {
// we are finished, so put up an appropriate error toast if required and finish
activity.finish();
} else {
// possibly media player error, so release and recreate
close();
updatePrefs();
}
return true;
}
@Override
public synchronized void close() {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}
}
|
package maynoothuniversity.summercamp.blocks;
import net.minecraft.block.Block;
import net.minecraft.block.material.MapColor;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.world.World;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
/**
* A class to create a new block in Minecraft.
* This class 'extends' the `Block` class, meaning it inherits all of the
* methods and variables of the `Block` class.
*
* Take a look at net.minecraft.block.Block.java, it can be found in:
* build/tmp/recompileMc/sources/net/minecraft/block/Block.java
*/
public class BlockExample extends Block {
/**
* Constructor for BlockExample.
* This calls the Minecraft Block constructor using `super` below.
* The properties of the block are set here, see the Block class for what
* can be set.
*/
public BlockExample() {
super(Material.ROCK, MapColor.STONE);
setCreativeTab(CreativeTabs.BUILDING_BLOCKS);
setHardness(2.0f);
setHarvestLevel("pickaxe", 1);
/*
* The Unlocalised and Registry names are used by forge to give your
* block a way to be referenced by Minecraft and other mods.
*
* In this case
* Unlocalised name: tile.exampleblock.name
* Registry name: summercamp:exampleblock
*/
setUnlocalizedName("exampleblock");
setRegistryName("exampleblock");
GameRegistry.register(this);
GameRegistry.register(new ItemBlock(this), getRegistryName());
}
/**
* Set the resource location (where the texture is loaded)
*/
@SideOnly(Side.CLIENT)
public void initModel() {
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(this), 0, new ModelResourceLocation(getRegistryName(), "inventory"));
}
/**
* What happens when the block is right clicked.
* @param World world: The world the block is in
* @param BlockPos pos: the x,y,z position of the block
* @param IBlockState state: Current state of the block
* @param EntityPlayer player: Who clicked the block.
* @param EnumHand hand: Either the primary or secondary hand (new in 1.9)
* @param ItemStack heldItem: The item the player is holding, `null` means no item held
* @param EnumFacing side: The side the block was clicked, (north, east, south, west, top, botom)
* @param float hitX, hitY, hitZ: Where the block was clicked
*/
@Override
public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ) {
if (!world.isRemote) {
player.addChatMessage(new TextComponentString("Hello " + player.getName()));
player.addChatMessage(new TextComponentString("Block coordinates: " + "X: " + pos.getX() + " Y: " + pos.getY() + " Z: " + pos.getZ()));
player.addChatMessage(new TextComponentString("Block Right click: " + "hitX: " + hitX + " hitY: " + hitY + " hitZ: " + hitZ));
player.addChatMessage(new TextComponentString("Block Side: " + side));
player.addChatMessage(new TextComponentString("Block Unlocalised name: " + getUnlocalizedName()));
player.addChatMessage(new TextComponentString("Block Registry name: " + getRegistryName()));
}
return true;
}
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <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.storm.trident.windowing;
import org.apache.storm.trident.tuple.TridentTuple;
import java.util.List;
import java.util.Queue;
/**
* Window manager to handle trident tuple events.
*/
public interface ITridentWindowManager {
/**
* This is invoked from {@code org.apache.storm.trident.planner.TridentProcessor}'s prepare method. So any
* initialization tasks can be done before the topology starts accepting tuples. For ex:
* initialize window manager with any earlier stored tuples/triggers and start WindowManager
*/
void prepare();
/**
* This is invoked when from {@code org.apache.storm.trident.planner.TridentProcessor}'s cleanup method. So, any
* cleanup operations like clearing cache or close store connection etc can be done.
*/
void shutdown();
/**
* Add received batch of tuples to cache/store and add them to {@code WindowManager}
*
* @param batchId
* @param tuples
*/
void addTuplesBatch(Object batchId, List<TridentTuple> tuples);
/**
* Returns pending triggers to be emitted.
*
* @return
*/
Queue<StoreBasedTridentWindowManager.TriggerResult> getPendingTriggers();
}
|
package com.redhat.mercury.service.contactdialog.model;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.openapitools.jackson.nullable.JsonNullable;
import javax.validation.Valid;
import javax.validation.constraints.*;
/**
* InlineResponse20024IssuedDeviceInstanceReport
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen", date = "2020-05-08T15:54:49.785-04:00[America/New_York]")
public class InlineResponse20024IssuedDeviceInstanceReport {
@JsonProperty("issuedDeviceInstanceReportRecord")
private Object issuedDeviceInstanceReportRecord;
@JsonProperty("issuedDeviceInstanceReportType")
private String issuedDeviceInstanceReportType;
@JsonProperty("issuedDeviceInstanceReportParameters")
private String issuedDeviceInstanceReportParameters;
@JsonProperty("issuedDeviceInstanceReport")
private Object issuedDeviceInstanceReport;
public InlineResponse20024IssuedDeviceInstanceReport issuedDeviceInstanceReportRecord(Object issuedDeviceInstanceReportRecord) {
this.issuedDeviceInstanceReportRecord = issuedDeviceInstanceReportRecord;
return this;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The input information used to assemble the report that can be on-going, periodic and actual and projected
* @return issuedDeviceInstanceReportRecord
*/
@ApiModelProperty(value = "`status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The input information used to assemble the report that can be on-going, periodic and actual and projected ")
@Valid
public Object getIssuedDeviceInstanceReportRecord() {
return issuedDeviceInstanceReportRecord;
}
public void setIssuedDeviceInstanceReportRecord(Object issuedDeviceInstanceReportRecord) {
this.issuedDeviceInstanceReportRecord = issuedDeviceInstanceReportRecord;
}
public InlineResponse20024IssuedDeviceInstanceReport issuedDeviceInstanceReportType(String issuedDeviceInstanceReportType) {
this.issuedDeviceInstanceReportType = issuedDeviceInstanceReportType;
return this;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Code general-info: The type of external report available
* @return issuedDeviceInstanceReportType
*/
@ApiModelProperty(value = "`status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Code general-info: The type of external report available ")
public String getIssuedDeviceInstanceReportType() {
return issuedDeviceInstanceReportType;
}
public void setIssuedDeviceInstanceReportType(String issuedDeviceInstanceReportType) {
this.issuedDeviceInstanceReportType = issuedDeviceInstanceReportType;
}
public InlineResponse20024IssuedDeviceInstanceReport issuedDeviceInstanceReportParameters(String issuedDeviceInstanceReportParameters) {
this.issuedDeviceInstanceReportParameters = issuedDeviceInstanceReportParameters;
return this;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: The selection parameters for the report (e.g. period, content type)
* @return issuedDeviceInstanceReportParameters
*/
@ApiModelProperty(value = "`status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: The selection parameters for the report (e.g. period, content type) ")
public String getIssuedDeviceInstanceReportParameters() {
return issuedDeviceInstanceReportParameters;
}
public void setIssuedDeviceInstanceReportParameters(String issuedDeviceInstanceReportParameters) {
this.issuedDeviceInstanceReportParameters = issuedDeviceInstanceReportParameters;
}
public InlineResponse20024IssuedDeviceInstanceReport issuedDeviceInstanceReport(Object issuedDeviceInstanceReport) {
this.issuedDeviceInstanceReport = issuedDeviceInstanceReport;
return this;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The external report in any suitable form including selection filters where appropriate
* @return issuedDeviceInstanceReport
*/
@ApiModelProperty(value = "`status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The external report in any suitable form including selection filters where appropriate ")
@Valid
public Object getIssuedDeviceInstanceReport() {
return issuedDeviceInstanceReport;
}
public void setIssuedDeviceInstanceReport(Object issuedDeviceInstanceReport) {
this.issuedDeviceInstanceReport = issuedDeviceInstanceReport;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
InlineResponse20024IssuedDeviceInstanceReport inlineResponse20024IssuedDeviceInstanceReport = (InlineResponse20024IssuedDeviceInstanceReport) o;
return Objects.equals(this.issuedDeviceInstanceReportRecord, inlineResponse20024IssuedDeviceInstanceReport.issuedDeviceInstanceReportRecord) &&
Objects.equals(this.issuedDeviceInstanceReportType, inlineResponse20024IssuedDeviceInstanceReport.issuedDeviceInstanceReportType) &&
Objects.equals(this.issuedDeviceInstanceReportParameters, inlineResponse20024IssuedDeviceInstanceReport.issuedDeviceInstanceReportParameters) &&
Objects.equals(this.issuedDeviceInstanceReport, inlineResponse20024IssuedDeviceInstanceReport.issuedDeviceInstanceReport);
}
@Override
public int hashCode() {
return Objects.hash(issuedDeviceInstanceReportRecord, issuedDeviceInstanceReportType, issuedDeviceInstanceReportParameters, issuedDeviceInstanceReport);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class InlineResponse20024IssuedDeviceInstanceReport {\n");
sb.append(" issuedDeviceInstanceReportRecord: ").append(toIndentedString(issuedDeviceInstanceReportRecord)).append("\n");
sb.append(" issuedDeviceInstanceReportType: ").append(toIndentedString(issuedDeviceInstanceReportType)).append("\n");
sb.append(" issuedDeviceInstanceReportParameters: ").append(toIndentedString(issuedDeviceInstanceReportParameters)).append("\n");
sb.append(" issuedDeviceInstanceReport: ").append(toIndentedString(issuedDeviceInstanceReport)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
package org.prebid.server.vertx;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Promise;
import io.vertx.core.Vertx;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(VertxUnitRunner.class)
public class CircuitBreakerTest {
@Rule
public final MockitoRule mockitoRule = MockitoJUnit.rule();
private Vertx vertx;
private Clock clock;
private CircuitBreaker circuitBreaker;
@Before
public void setUp() {
vertx = Vertx.vertx();
clock = Clock.fixed(Instant.now(), ZoneId.systemDefault());
circuitBreaker = new CircuitBreaker("name", vertx, 1, 100L, 200L, clock);
}
@After
public void tearDown(TestContext context) {
vertx.close(context.asyncAssertSuccess());
}
@Test
public void executeShouldSucceedsIfOperationSucceeds(TestContext context) {
// when
final Future<?> future = executeWithSuccess(context, "value");
// then
assertThat(future.succeeded()).isTrue();
assertThat(future.result()).isEqualTo("value");
}
@Test
public void executeShouldFailsIfCircuitIsClosedAndOperationFails(TestContext context) {
// when
final Future<?> future = executeWithFail(context, "exception");
// then
assertThat(future.failed()).isTrue();
assertThat(future.cause()).isInstanceOf(RuntimeException.class).hasMessage("exception");
}
@Test
public void executeShouldFailsIfCircuitIsHalfOpenedAndOperationFailsAndClosingTimeIsNotPassedBy(
TestContext context) {
// when
final Future<?> future1 = executeWithFail(context, "exception1");
final Future<?> future2 = executeWithFail(context, null);
// then
assertThat(future1.failed()).isTrue();
assertThat(future1.cause()).isInstanceOf(RuntimeException.class).hasMessage("exception1");
assertThat(future2.failed()).isTrue();
assertThat(future2.cause()).isInstanceOf(RuntimeException.class).hasMessage("open circuit");
}
@Test
public void executeShouldFailsIfCircuitIsHalfOpenedAndOperationFails(TestContext context) {
// when
final Future<?> future1 = executeWithFail(context, "exception1");
final Future<?> future2 = executeWithFail(context, null);
waitForClosingInterval(context);
final Future<?> future3 = executeWithFail(context, "exception3");
// then
assertThat(future1.failed()).isTrue();
assertThat(future1.cause()).isInstanceOf(RuntimeException.class).hasMessage("exception1");
assertThat(future2.failed()).isTrue();
assertThat(future2.cause()).isInstanceOf(RuntimeException.class).hasMessage("open circuit");
assertThat(future3.failed()).isTrue();
assertThat(future3.cause()).isInstanceOf(RuntimeException.class).hasMessage("exception3");
}
@Test
public void executeShouldSucceedsIfCircuitIsHalfOpenedAndOperationSucceeds(TestContext context) {
// when
final Future<?> future1 = executeWithFail(context, "exception1");
final Future<?> future2 = executeWithFail(context, "exception2");
waitForClosingInterval(context);
final Future<?> future3 = executeWithSuccess(context, "value after half-open");
// then
assertThat(future1.failed()).isTrue();
assertThat(future1.cause()).isInstanceOf(RuntimeException.class).hasMessage("exception1");
assertThat(future2.failed()).isTrue();
assertThat(future2.cause()).isInstanceOf(RuntimeException.class).hasMessage("open circuit");
assertThat(future3.succeeded()).isTrue();
assertThat(future3.result()).isEqualTo("value after half-open");
}
@Test
public void executeShouldFailsWithOriginalExceptionIfOpeningIntervalExceeds(TestContext context) {
// given
circuitBreaker = new CircuitBreaker("name", vertx, 2, 100L, 200L, clock);
// when
final Future<?> future1 = executeWithFail(context, "exception1");
waitForOpeningInterval(context);
final Future<?> future2 = executeWithFail(context, "exception2");
// then
assertThat(future1.failed()).isTrue();
assertThat(future1.cause()).isInstanceOf(RuntimeException.class).hasMessage("exception1");
assertThat(future2.failed()).isTrue();
assertThat(future2.cause()).isInstanceOf(RuntimeException.class).hasMessage("exception2");
}
private Future<String> executeWithSuccess(TestContext context, String result) {
return execute(context, operationPromise -> operationPromise.complete(result));
}
private Future<String> executeWithFail(TestContext context, String errorMessage) {
return execute(context, operationPromise -> operationPromise.fail(new RuntimeException(errorMessage)));
}
private Future<String> execute(TestContext context, Handler<Promise<String>> handler) {
final Future<String> future = circuitBreaker.execute(handler);
final Async async = context.async();
future.onComplete(ar -> async.complete());
async.await();
return future;
}
private void waitForOpeningInterval(TestContext context) {
waitForInterval(context, 150L);
}
private void waitForClosingInterval(TestContext context) {
waitForInterval(context, 250L);
}
private void waitForInterval(TestContext context, long timeout) {
final Async async = context.async();
vertx.setTimer(timeout, id -> async.complete());
async.await();
}
}
|
package com.foodee.spring.controllers;
import java.util.List;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import com.foodee.models.Food;
import com.foodee.models.FoodLog;
import com.foodee.models.Login;
import com.foodee.models.Users;
import com.foodee.services.FoodServiceInterface;
import com.foodee.services.UserServiceInterface;
@Controller
@RequestMapping("/users")
@SessionAttributes("user")
public class UsersController {
//inject user service
@Autowired
private UserServiceInterface userService;
@Autowired(required = false)
private FoodServiceInterface foodService;
//declare user bean
@ModelAttribute("user")
public Users user() {
return new Users();
}
//trims white space from fields
@InitBinder
public void initBinder(WebDataBinder dataBinder) {
StringTrimmerEditor stringTrimmer = new StringTrimmerEditor(true);
dataBinder.registerCustomEditor(String.class, stringTrimmer);
}
/**
* Shows login in form
* @param request
* @param response
*/
@GetMapping("/login")
public ModelAndView userLogin(@ModelAttribute("login") Login login) {
ModelAndView mav = new ModelAndView("login");
return mav;
}
/**
* Validates user login info and returns home page
* @param login
* @param model
*/
@PostMapping("/authenticateUser")
public String userHome(@ModelAttribute("login") Login login, Model model, HttpSession session) {
//get users from userService
List<Users> authUsers = userService.login(login);
System.out.println("\n\nAuthenticated Users: " + authUsers); //debugging
//if logged in send home, else send to log in
if(authUsers.size() != 0) {
//sets user to user model attribute in session
model.addAttribute("user", authUsers.get(0)) ;
session.setAttribute("userSession", authUsers.get(0));
System.out.println("\n\nLog in user info: " + authUsers.get(0)); //debugging
return "userPortal";
}else {
return "/login";
}
}
/**
* New user registration form
* @param newUser
* @return newUserForm.jsp
*/
@GetMapping("/registrationForm")
public String showFormForAdd(@ModelAttribute("user") Users newUser) {
return "newUserForm";
}
/**
* Registers new user
* @param newUser
* @param bindingResults
*/
@PostMapping("/addNewUser")
public String saveCustomer(@Valid @ModelAttribute("user") Users newUser, BindingResult bindingResults) {
System.out.println("Binding result: " + bindingResults); //for debugging
if(bindingResults.hasErrors()) {
return "newUserForm";
} else {
//save user
userService.addUser(newUser);
return "userPortal";
}
}
@GetMapping("/profile")
public String getProfile(@ModelAttribute("user") Users user) {
if(user.getUserId() != 0){
return "userProfile";
} else {
return "redirect:login";
}
}
/**
* Returns update user page
* @param user
* @return
*/
@GetMapping("/update")
public String updateProfile(@ModelAttribute("user") Users user) {
if(user.getUserId() != 0){
return "updateProfile";
} else {
return "redirect:login";
}
}
@PostMapping("/updateUser")
public String updateUser(@ModelAttribute("user") Users user) {
userService.updateUser(user);
return "redirect:profile";
}
/**
* If logged in returns Users home page
* If not logged in returns login screen
* @param user
*/
@GetMapping("/home")
public String getHome(@ModelAttribute("user") Users user) {
System.out.println("\n\nUser info: " + (user)); //debugging
if(user.getUserId() != 0){
return "userPortal";
} else {
return "redirect:/users/login";
}
}
//--------------------------------------------------------------------------
/**
* New user registration form
* @param newUser
* @return newUserForm.jsp
*/
@GetMapping("/foodlog")
public String getFoodLog(@ModelAttribute("user") Users user, Model model) {
//check if logged in
if(user.getUserId() !=0) {
//get breakfast
List<FoodLog> allFoodLogs = foodService.getAllFoodLogs(user.getUserId());
System.out.println("Outside display method"); //debugging
foodService.displayFoodLogs(allFoodLogs, model);
//get all foods
List<Food> foodList = foodService.getFoods();
model.addAttribute("foods", foodList);
return "foodlog";
}else {
return "redirect:login";
}
}
/**
* Brings up form to add to breakfast
* @param newUser
* @return newUserForm.jsp
*/
@GetMapping("/addToBreakfast")
public String addToBreakfast(Model model) {
return "addToBreakfast";
}
/**
* Brings search results
* @param newUser
* @return newUserForm.jsp
*/
@RequestMapping(value = "/searchFood", method = RequestMethod.GET)
public String addBFoods(@RequestParam("foodName") String foodName, Model model) {
//!!!!!!!!!! FIX TO USER ID IS REQUIRED, TIMEOUT IS CAUSING ISSUES
//get search results
List<Food> searchResults = foodService.searchFood(foodName);
System.out.println("\n\nSearch results: " + searchResults);
model.addAttribute("searchResults", searchResults);
//create food log
model.addAttribute("foodLog", new FoodLog());
return "foodSearchResults";
}
/**
* Adds food to foodlog
* @param newUser
* @param bindingResults
*/
@RequestMapping("/insertLog")
public String insertLog(@ModelAttribute("foodLog") FoodLog foodlog) {
//save log
foodService.addFoodLog(foodlog);
return "redirect:foodlog";
}
/**
* New user registration form
* @param newUser
* @return newUserForm.jsp
*/
@GetMapping("/addFoodForm")
public String newFoodForm(@ModelAttribute("food") Food newFood) {
return "newFoodForm";
}
/**
* Registers new user
* @param newUser
* @param bindingResults
*/
@PostMapping("/addFood")
public String addFood(@Valid @ModelAttribute("food") Food newFood, BindingResult bindingResults) {
System.out.println("Binding result: " + bindingResults); //for debugging
if(bindingResults.hasErrors()) {
return "newFoodForm";
} else {
//save food
foodService.addFood(newFood);
return "redirect:foodlog";
}
}
/**
* Returns update user page
* @param user
* @return
*/
@GetMapping("/updateFoodForm")
public String updateFoodForm(@RequestParam("foodId") int foodId, Model model) {
Food food = foodService.getFood(foodId);
model.addAttribute("food", food);
return "updateFoodForm";
}
@PostMapping("/updateFood")
public String updateFood(@ModelAttribute("food") Food food) {
foodService.updateFood(food);
return "redirect:foodlog";
}
/**
* Edit food log form
* @param user
* @return
*/
@GetMapping("/updateFoodLogForm")
public String updateFoodLogForm(@RequestParam("logId") int logId, Model model) {
FoodLog foodLog = foodService.getFoodLog(logId);
model.addAttribute("foodLog", foodLog);
return "updateFoodLog";
}
/**
* Process the update to food log
* @param foodlog
* @return
*/
@PostMapping("/updateFoodLog")
public String updateFoodLog(@ModelAttribute("foodLog") FoodLog foodlog) {
System.out.println("\n\n\nFood log we are updating: " + foodlog);
foodService.updateFoodLog(foodlog);
return "redirect:foodlog";
}
@GetMapping("/deleteFoodLog")
public String deleteLog(@RequestParam("logId") int logId) {
foodService.deleteLog(logId);
return "redirect:foodlog";
}
@GetMapping("/deleteFood")
public String deleteFood(@RequestParam("foodId") int foodId) {
foodService.deleteFood(foodId);
return "redirect:${pageContext.request.contextPath}/admin/foodlist";
}
//bootstrap debugging page
@GetMapping("/bootstrap")
public String getBootstrap() {
return "bootstrap";
}
}
|
package io.microconfig.core.properties;
import org.junit.jupiter.api.Test;
import static io.microconfig.core.properties.ConfigFormat.PROPERTIES;
import static io.microconfig.core.properties.PropertyImpl.property;
import static org.junit.jupiter.api.Assertions.assertEquals;
class ResolveExceptionTest {
DeclaringComponent current = new DeclaringComponentImpl("ct2", "current", "e1");
DeclaringComponent root = new DeclaringComponentImpl("ct", "root", "e");
Property p = property("key", "value", PROPERTIES, current);
@Test
void withoutCause() {
ResolveException exception = new ResolveException(current, root, "Can't resolve placeholder");
assertEquals("Can't build configs for root component 'root[e]'.\n" +
"Exception in\n" +
"\tcurrent[e1]'\n" +
"Can't resolve placeholder", exception.getMessage().trim());
exception.setProperty(p);
assertEquals("Can't build configs for root component 'root[e]'.\n" +
"Exception in\n" +
"\tcurrent[e1]'\n" +
"\tkey=value\n" +
"Can't resolve placeholder", exception.getMessage().trim());
}
@Test
void withCauseMessage() {
ResolveException exception = new ResolveException(current, root, "Can't resolve placeholder", new NullPointerException("NPE"));
assertEquals("Can't build configs for root component 'root[e]'.\n" +
"Exception in\n" +
"\tcurrent[e1]'\n" +
"Can't resolve placeholder\n" +
"Cause: NPE", exception.getMessage());
exception.setProperty(p);
assertEquals("Can't build configs for root component 'root[e]'.\n" +
"Exception in\n" +
"\tcurrent[e1]'\n" +
"\tkey=value\n" +
"Can't resolve placeholder\n" +
"Cause: NPE", exception.getMessage());
}
}
|
package com.github.it89.cfutils.marketdatastore.entities;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.Currency;
@Getter
@Setter
@Entity
@Table(name = "bond_nominal_values",
uniqueConstraints = {@UniqueConstraint(name = "bond_nominal_values_ui", columnNames = {"time", "figi"})})
public class BondNominalValueEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Long id;
private String figi;
private BigDecimal nominalValue;
private Currency currency;
private Instant time;
}
|
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2004, 2021 Oracle and/or its affiliates. All rights reserved.
*
* Oracle 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.jvnet.fastinfoset;
/**
* The indexes of built-in encoding algorithms.
*
* <p>The indexes of the built-in encoding algorithms are specified
* in ITU-T Rec. X.891 | ISO/IEC 24824-1 (Fast Infoset), clause
* 10. The indexes start from 0 instead of 1 as specified.<p>
*
* @see org.jvnet.fastinfoset.sax.EncodingAlgorithmContentHandler
* @see org.jvnet.fastinfoset.sax.EncodingAlgorithmAttributes
*/
public final class EncodingAlgorithmIndexes {
public static final int HEXADECIMAL = 0;
public static final int BASE64 = 1;
public static final int SHORT = 2;
public static final int INT = 3;
public static final int LONG = 4;
public static final int BOOLEAN = 5;
public static final int FLOAT = 6;
public static final int DOUBLE = 7;
public static final int UUID = 8;
public static final int CDATA = 9;
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.rocketmq.client.impl;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.rocketmq.client.ClientConfig;
import org.apache.rocketmq.client.consumer.PullCallback;
import org.apache.rocketmq.client.consumer.PullResult;
import org.apache.rocketmq.client.consumer.PullStatus;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.hook.SendMessageContext;
import org.apache.rocketmq.client.impl.consumer.PullResultExt;
import org.apache.rocketmq.client.impl.factory.MQClientInstance;
import org.apache.rocketmq.client.impl.producer.DefaultMQProducerImpl;
import org.apache.rocketmq.client.impl.producer.TopicPublishInfo;
import org.apache.rocketmq.client.log.ClientLogger;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.MQVersion;
import org.apache.rocketmq.common.MixAll;
import org.apache.rocketmq.common.TopicConfig;
import org.apache.rocketmq.common.UtilAll;
import org.apache.rocketmq.common.admin.ConsumeStats;
import org.apache.rocketmq.common.admin.TopicStatsTable;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageBatch;
import org.apache.rocketmq.common.message.MessageClientIDSetter;
import org.apache.rocketmq.common.message.MessageConst;
import org.apache.rocketmq.common.message.MessageDecoder;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.common.namesrv.TopAddressing;
import org.apache.rocketmq.common.protocol.RequestCode;
import org.apache.rocketmq.common.protocol.ResponseCode;
import org.apache.rocketmq.common.protocol.body.BrokerStatsData;
import org.apache.rocketmq.common.protocol.body.CheckClientRequestBody;
import org.apache.rocketmq.common.protocol.body.ClusterInfo;
import org.apache.rocketmq.common.protocol.body.ConsumeMessageDirectlyResult;
import org.apache.rocketmq.common.protocol.body.ConsumeStatsList;
import org.apache.rocketmq.common.protocol.body.ConsumerConnection;
import org.apache.rocketmq.common.protocol.body.ConsumerRunningInfo;
import org.apache.rocketmq.common.protocol.body.GetConsumerStatusBody;
import org.apache.rocketmq.common.protocol.body.GroupList;
import org.apache.rocketmq.common.protocol.body.KVTable;
import org.apache.rocketmq.common.protocol.body.LockBatchRequestBody;
import org.apache.rocketmq.common.protocol.body.LockBatchResponseBody;
import org.apache.rocketmq.common.protocol.body.ProducerConnection;
import org.apache.rocketmq.common.protocol.body.QueryConsumeQueueResponseBody;
import org.apache.rocketmq.common.protocol.body.QueryConsumeTimeSpanBody;
import org.apache.rocketmq.common.protocol.body.QueryCorrectionOffsetBody;
import org.apache.rocketmq.common.protocol.body.QueueTimeSpan;
import org.apache.rocketmq.common.protocol.body.ResetOffsetBody;
import org.apache.rocketmq.common.protocol.body.SubscriptionGroupWrapper;
import org.apache.rocketmq.common.protocol.body.TopicConfigSerializeWrapper;
import org.apache.rocketmq.common.protocol.body.TopicList;
import org.apache.rocketmq.common.protocol.body.UnlockBatchRequestBody;
import org.apache.rocketmq.common.protocol.header.CloneGroupOffsetRequestHeader;
import org.apache.rocketmq.common.protocol.header.ConsumeMessageDirectlyResultRequestHeader;
import org.apache.rocketmq.common.protocol.header.ConsumerSendMsgBackRequestHeader;
import org.apache.rocketmq.common.protocol.header.CreateTopicRequestHeader;
import org.apache.rocketmq.common.protocol.header.DeleteSubscriptionGroupRequestHeader;
import org.apache.rocketmq.common.protocol.header.DeleteTopicRequestHeader;
import org.apache.rocketmq.common.protocol.header.EndTransactionRequestHeader;
import org.apache.rocketmq.common.protocol.header.GetConsumeStatsInBrokerHeader;
import org.apache.rocketmq.common.protocol.header.GetConsumeStatsRequestHeader;
import org.apache.rocketmq.common.protocol.header.GetConsumerConnectionListRequestHeader;
import org.apache.rocketmq.common.protocol.header.GetConsumerListByGroupRequestHeader;
import org.apache.rocketmq.common.protocol.header.GetConsumerListByGroupResponseBody;
import org.apache.rocketmq.common.protocol.header.GetConsumerRunningInfoRequestHeader;
import org.apache.rocketmq.common.protocol.header.GetConsumerStatusRequestHeader;
import org.apache.rocketmq.common.protocol.header.GetEarliestMsgStoretimeRequestHeader;
import org.apache.rocketmq.common.protocol.header.GetEarliestMsgStoretimeResponseHeader;
import org.apache.rocketmq.common.protocol.header.GetMaxOffsetRequestHeader;
import org.apache.rocketmq.common.protocol.header.GetMaxOffsetResponseHeader;
import org.apache.rocketmq.common.protocol.header.GetMinOffsetRequestHeader;
import org.apache.rocketmq.common.protocol.header.GetMinOffsetResponseHeader;
import org.apache.rocketmq.common.protocol.header.GetProducerConnectionListRequestHeader;
import org.apache.rocketmq.common.protocol.header.GetTopicStatsInfoRequestHeader;
import org.apache.rocketmq.common.protocol.header.GetTopicsByClusterRequestHeader;
import org.apache.rocketmq.common.protocol.header.PullMessageRequestHeader;
import org.apache.rocketmq.common.protocol.header.PullMessageResponseHeader;
import org.apache.rocketmq.common.protocol.header.QueryConsumeQueueRequestHeader;
import org.apache.rocketmq.common.protocol.header.QueryConsumeTimeSpanRequestHeader;
import org.apache.rocketmq.common.protocol.header.QueryConsumerOffsetRequestHeader;
import org.apache.rocketmq.common.protocol.header.QueryConsumerOffsetResponseHeader;
import org.apache.rocketmq.common.protocol.header.QueryCorrectionOffsetHeader;
import org.apache.rocketmq.common.protocol.header.QueryMessageRequestHeader;
import org.apache.rocketmq.common.protocol.header.QueryTopicConsumeByWhoRequestHeader;
import org.apache.rocketmq.common.protocol.header.ResetOffsetRequestHeader;
import org.apache.rocketmq.common.protocol.header.SearchOffsetRequestHeader;
import org.apache.rocketmq.common.protocol.header.SearchOffsetResponseHeader;
import org.apache.rocketmq.common.protocol.header.SendMessageRequestHeader;
import org.apache.rocketmq.common.protocol.header.SendMessageRequestHeaderV2;
import org.apache.rocketmq.common.protocol.header.SendMessageResponseHeader;
import org.apache.rocketmq.common.protocol.header.UnregisterClientRequestHeader;
import org.apache.rocketmq.common.protocol.header.UpdateConsumerOffsetRequestHeader;
import org.apache.rocketmq.common.protocol.header.ViewBrokerStatsDataRequestHeader;
import org.apache.rocketmq.common.protocol.header.ViewMessageRequestHeader;
import org.apache.rocketmq.common.protocol.header.filtersrv.RegisterMessageFilterClassRequestHeader;
import org.apache.rocketmq.common.protocol.header.namesrv.DeleteKVConfigRequestHeader;
import org.apache.rocketmq.common.protocol.header.namesrv.GetKVConfigRequestHeader;
import org.apache.rocketmq.common.protocol.header.namesrv.GetKVConfigResponseHeader;
import org.apache.rocketmq.common.protocol.header.namesrv.GetKVListByNamespaceRequestHeader;
import org.apache.rocketmq.common.protocol.header.namesrv.GetRouteInfoRequestHeader;
import org.apache.rocketmq.common.protocol.header.namesrv.PutKVConfigRequestHeader;
import org.apache.rocketmq.common.protocol.header.namesrv.WipeWritePermOfBrokerRequestHeader;
import org.apache.rocketmq.common.protocol.header.namesrv.WipeWritePermOfBrokerResponseHeader;
import org.apache.rocketmq.common.protocol.heartbeat.HeartbeatData;
import org.apache.rocketmq.common.protocol.heartbeat.SubscriptionData;
import org.apache.rocketmq.common.protocol.route.TopicRouteData;
import org.apache.rocketmq.common.subscription.SubscriptionGroupConfig;
import org.apache.rocketmq.logging.InternalLogger;
import org.apache.rocketmq.remoting.InvokeCallback;
import org.apache.rocketmq.remoting.RPCHook;
import org.apache.rocketmq.remoting.RemotingClient;
import org.apache.rocketmq.remoting.exception.RemotingCommandException;
import org.apache.rocketmq.remoting.exception.RemotingConnectException;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.apache.rocketmq.remoting.exception.RemotingSendRequestException;
import org.apache.rocketmq.remoting.exception.RemotingTimeoutException;
import org.apache.rocketmq.remoting.exception.RemotingTooMuchRequestException;
import org.apache.rocketmq.remoting.netty.NettyClientConfig;
import org.apache.rocketmq.remoting.netty.NettyRemotingClient;
import org.apache.rocketmq.remoting.netty.ResponseFuture;
import org.apache.rocketmq.remoting.protocol.LanguageCode;
import org.apache.rocketmq.remoting.protocol.RemotingCommand;
import org.apache.rocketmq.remoting.protocol.RemotingSerializable;
/**
* MQ客户端API实现类接口
* */
public class MQClientAPIImpl {
private final static InternalLogger log = ClientLogger.getLog();
private static boolean sendSmartMsg =
Boolean.parseBoolean(System.getProperty("org.apache.rocketmq.client.sendSmartMsg", "true"));
static {
System.setProperty(RemotingCommand.REMOTING_VERSION_KEY, Integer.toString(MQVersion.CURRENT_VERSION));
}
private final RemotingClient remotingClient;
private final TopAddressing topAddressing;
private final ClientRemotingProcessor clientRemotingProcessor;
private String nameSrvAddr = null;
private ClientConfig clientConfig;
public MQClientAPIImpl(final NettyClientConfig nettyClientConfig,
final ClientRemotingProcessor clientRemotingProcessor,
RPCHook rpcHook, final ClientConfig clientConfig) {
this.clientConfig = clientConfig;
topAddressing = new TopAddressing(MixAll.getWSAddr(), clientConfig.getUnitName());
this.remotingClient = new NettyRemotingClient(nettyClientConfig, null);
this.clientRemotingProcessor = clientRemotingProcessor;
this.remotingClient.registerRPCHook(rpcHook);
this.remotingClient.registerProcessor(RequestCode.CHECK_TRANSACTION_STATE, this.clientRemotingProcessor, null);
this.remotingClient.registerProcessor(RequestCode.NOTIFY_CONSUMER_IDS_CHANGED, this.clientRemotingProcessor, null);
this.remotingClient.registerProcessor(RequestCode.RESET_CONSUMER_CLIENT_OFFSET, this.clientRemotingProcessor, null);
this.remotingClient.registerProcessor(RequestCode.GET_CONSUMER_STATUS_FROM_CLIENT, this.clientRemotingProcessor, null);
this.remotingClient.registerProcessor(RequestCode.GET_CONSUMER_RUNNING_INFO, this.clientRemotingProcessor, null);
this.remotingClient.registerProcessor(RequestCode.CONSUME_MESSAGE_DIRECTLY, this.clientRemotingProcessor, null);
}
public List<String> getNameServerAddressList() {
return this.remotingClient.getNameServerAddressList();
}
public RemotingClient getRemotingClient() {
return remotingClient;
}
/**
* 获取名称服务
* @return
*/
public String fetchNameServerAddr() {
try {
String addrs = this.topAddressing.fetchNSAddr();
if (addrs != null) {
if (!addrs.equals(this.nameSrvAddr)) {
log.info("name server address changed, old=" + this.nameSrvAddr + ", new=" + addrs);
this.updateNameServerAddressList(addrs);
this.nameSrvAddr = addrs;
return nameSrvAddr;
}
}
} catch (Exception e) {
log.error("fetchNameServerAddr Exception", e);
}
return nameSrvAddr;
}
public void updateNameServerAddressList(final String addrs) {
String[] addrArray = addrs.split(";");
List<String> list = Arrays.asList(addrArray);
this.remotingClient.updateNameServerAddressList(list);
}
public void start() {
this.remotingClient.start();
}
public void shutdown() {
this.remotingClient.shutdown();
}
public void createSubscriptionGroup(final String addr, final SubscriptionGroupConfig config,
final long timeoutMillis)
throws RemotingException, MQBrokerException, InterruptedException, MQClientException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.UPDATE_AND_CREATE_SUBSCRIPTIONGROUP, null);
byte[] body = RemotingSerializable.encode(config);
request.setBody(body);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public void createTopic(final String addr, final String defaultTopic, final TopicConfig topicConfig,
final long timeoutMillis)
throws RemotingException, MQBrokerException, InterruptedException, MQClientException {
CreateTopicRequestHeader requestHeader = new CreateTopicRequestHeader();
requestHeader.setTopic(topicConfig.getTopicName());
requestHeader.setDefaultTopic(defaultTopic);
requestHeader.setReadQueueNums(topicConfig.getReadQueueNums());
requestHeader.setWriteQueueNums(topicConfig.getWriteQueueNums());
requestHeader.setPerm(topicConfig.getPerm());
requestHeader.setTopicFilterType(topicConfig.getTopicFilterType().name());
requestHeader.setTopicSysFlag(topicConfig.getTopicSysFlag());
requestHeader.setOrder(topicConfig.isOrder());
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.UPDATE_AND_CREATE_TOPIC, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public SendResult sendMessage(
final String addr,
final String brokerName,
final Message msg,
final SendMessageRequestHeader requestHeader,
final long timeoutMillis,
final CommunicationMode communicationMode,
final SendMessageContext context,
final DefaultMQProducerImpl producer
) throws RemotingException, MQBrokerException, InterruptedException {
return sendMessage(addr, brokerName, msg, requestHeader, timeoutMillis, communicationMode, null, null, null, 0, context, producer);
}
public SendResult sendMessage(
final String addr,
final String brokerName,
final Message msg,
final SendMessageRequestHeader requestHeader,
final long timeoutMillis,
final CommunicationMode communicationMode,
final SendCallback sendCallback,
final TopicPublishInfo topicPublishInfo,
final MQClientInstance instance,
final int retryTimesWhenSendFailed,
final SendMessageContext context,
final DefaultMQProducerImpl producer
) throws RemotingException, MQBrokerException, InterruptedException {
long beginStartTime = System.currentTimeMillis();
RemotingCommand request = null;
if (sendSmartMsg || msg instanceof MessageBatch) {
SendMessageRequestHeaderV2 requestHeaderV2 = SendMessageRequestHeaderV2.createSendMessageRequestHeaderV2(requestHeader);
request = RemotingCommand.createRequestCommand(msg instanceof MessageBatch ? RequestCode.SEND_BATCH_MESSAGE : RequestCode.SEND_MESSAGE_V2, requestHeaderV2);
} else {
request = RemotingCommand.createRequestCommand(RequestCode.SEND_MESSAGE, requestHeader);
}
request.setBody(msg.getBody());
switch (communicationMode) {
case ONEWAY:
this.remotingClient.invokeOneway(addr, request, timeoutMillis);
return null;
case ASYNC:
final AtomicInteger times = new AtomicInteger();
long costTimeAsync = System.currentTimeMillis() - beginStartTime;
if (timeoutMillis < costTimeAsync) {
throw new RemotingTooMuchRequestException("sendMessage call timeout");
}
this.sendMessageAsync(addr, brokerName, msg, timeoutMillis - costTimeAsync, request, sendCallback, topicPublishInfo, instance,
retryTimesWhenSendFailed, times, context, producer);
return null;
case SYNC:
long costTimeSync = System.currentTimeMillis() - beginStartTime;
if (timeoutMillis < costTimeSync) {
throw new RemotingTooMuchRequestException("sendMessage call timeout");
}
return this.sendMessageSync(addr, brokerName, msg, timeoutMillis - costTimeSync, request);
default:
assert false;
break;
}
return null;
}
private SendResult sendMessageSync(
final String addr,
final String brokerName,
final Message msg,
final long timeoutMillis,
final RemotingCommand request
) throws RemotingException, MQBrokerException, InterruptedException {
RemotingCommand response = this.remotingClient.invokeSync(addr, request, timeoutMillis);
assert response != null;
return this.processSendResponse(brokerName, msg, response);
}
private void sendMessageAsync(
final String addr,
final String brokerName,
final Message msg,
final long timeoutMillis,
final RemotingCommand request,
final SendCallback sendCallback,
final TopicPublishInfo topicPublishInfo,
final MQClientInstance instance,
final int retryTimesWhenSendFailed,
final AtomicInteger times,
final SendMessageContext context,
final DefaultMQProducerImpl producer
) throws InterruptedException, RemotingException {
this.remotingClient.invokeAsync(addr, request, timeoutMillis, new InvokeCallback() {
@Override
public void operationComplete(ResponseFuture responseFuture) {
RemotingCommand response = responseFuture.getResponseCommand();
if (null == sendCallback && response != null) {
try {
SendResult sendResult = MQClientAPIImpl.this.processSendResponse(brokerName, msg, response);
if (context != null && sendResult != null) {
context.setSendResult(sendResult);
context.getProducer().executeSendMessageHookAfter(context);
}
} catch (Throwable e) {
}
producer.updateFaultItem(brokerName, System.currentTimeMillis() - responseFuture.getBeginTimestamp(), false);
return;
}
if (response != null) {
try {
SendResult sendResult = MQClientAPIImpl.this.processSendResponse(brokerName, msg, response);
assert sendResult != null;
if (context != null) {
context.setSendResult(sendResult);
context.getProducer().executeSendMessageHookAfter(context);
}
try {
sendCallback.onSuccess(sendResult);
} catch (Throwable e) {
}
producer.updateFaultItem(brokerName, System.currentTimeMillis() - responseFuture.getBeginTimestamp(), false);
} catch (Exception e) {
producer.updateFaultItem(brokerName, System.currentTimeMillis() - responseFuture.getBeginTimestamp(), true);
onExceptionImpl(brokerName, msg, 0L, request, sendCallback, topicPublishInfo, instance,
retryTimesWhenSendFailed, times, e, context, false, producer);
}
} else {
producer.updateFaultItem(brokerName, System.currentTimeMillis() - responseFuture.getBeginTimestamp(), true);
if (!responseFuture.isSendRequestOK()) {
MQClientException ex = new MQClientException("send request failed", responseFuture.getCause());
onExceptionImpl(brokerName, msg, 0L, request, sendCallback, topicPublishInfo, instance,
retryTimesWhenSendFailed, times, ex, context, true, producer);
} else if (responseFuture.isTimeout()) {
MQClientException ex = new MQClientException("wait response timeout " + responseFuture.getTimeoutMillis() + "ms",
responseFuture.getCause());
onExceptionImpl(brokerName, msg, 0L, request, sendCallback, topicPublishInfo, instance,
retryTimesWhenSendFailed, times, ex, context, true, producer);
} else {
MQClientException ex = new MQClientException("unknow reseaon", responseFuture.getCause());
onExceptionImpl(brokerName, msg, 0L, request, sendCallback, topicPublishInfo, instance,
retryTimesWhenSendFailed, times, ex, context, true, producer);
}
}
}
});
}
private void onExceptionImpl(final String brokerName,
final Message msg,
final long timeoutMillis,
final RemotingCommand request,
final SendCallback sendCallback,
final TopicPublishInfo topicPublishInfo,
final MQClientInstance instance,
final int timesTotal,
final AtomicInteger curTimes,
final Exception e,
final SendMessageContext context,
final boolean needRetry,
final DefaultMQProducerImpl producer
) {
int tmp = curTimes.incrementAndGet();
if (needRetry && tmp <= timesTotal) {
String retryBrokerName = brokerName;//by default, it will send to the same broker
if (topicPublishInfo != null) { //select one message queue accordingly, in order to determine which broker to send
MessageQueue mqChosen = producer.selectOneMessageQueue(topicPublishInfo, brokerName);
retryBrokerName = mqChosen.getBrokerName();
}
String addr = instance.findBrokerAddressInPublish(retryBrokerName);
log.info("async send msg by retry {} times. topic={}, brokerAddr={}, brokerName={}", tmp, msg.getTopic(), addr,
retryBrokerName);
try {
request.setOpaque(RemotingCommand.createNewRequestId());
sendMessageAsync(addr, retryBrokerName, msg, timeoutMillis, request, sendCallback, topicPublishInfo, instance,
timesTotal, curTimes, context, producer);
} catch (InterruptedException e1) {
onExceptionImpl(retryBrokerName, msg, timeoutMillis, request, sendCallback, topicPublishInfo, instance, timesTotal, curTimes, e1,
context, false, producer);
} catch (RemotingConnectException e1) {
producer.updateFaultItem(brokerName, 3000, true);
onExceptionImpl(retryBrokerName, msg, timeoutMillis, request, sendCallback, topicPublishInfo, instance, timesTotal, curTimes, e1,
context, true, producer);
} catch (RemotingTooMuchRequestException e1) {
onExceptionImpl(retryBrokerName, msg, timeoutMillis, request, sendCallback, topicPublishInfo, instance, timesTotal, curTimes, e1,
context, false, producer);
} catch (RemotingException e1) {
producer.updateFaultItem(brokerName, 3000, true);
onExceptionImpl(retryBrokerName, msg, timeoutMillis, request, sendCallback, topicPublishInfo, instance, timesTotal, curTimes, e1,
context, true, producer);
}
} else {
if (context != null) {
context.setException(e);
context.getProducer().executeSendMessageHookAfter(context);
}
try {
sendCallback.onException(e);
} catch (Exception ignored) {
}
}
}
private SendResult processSendResponse(
final String brokerName,
final Message msg,
final RemotingCommand response
) throws MQBrokerException, RemotingCommandException {
switch (response.getCode()) {
case ResponseCode.FLUSH_DISK_TIMEOUT:
case ResponseCode.FLUSH_SLAVE_TIMEOUT:
case ResponseCode.SLAVE_NOT_AVAILABLE: {
}
case ResponseCode.SUCCESS: {
SendStatus sendStatus = SendStatus.SEND_OK;
switch (response.getCode()) {
case ResponseCode.FLUSH_DISK_TIMEOUT:
sendStatus = SendStatus.FLUSH_DISK_TIMEOUT;
break;
case ResponseCode.FLUSH_SLAVE_TIMEOUT:
sendStatus = SendStatus.FLUSH_SLAVE_TIMEOUT;
break;
case ResponseCode.SLAVE_NOT_AVAILABLE:
sendStatus = SendStatus.SLAVE_NOT_AVAILABLE;
break;
case ResponseCode.SUCCESS:
sendStatus = SendStatus.SEND_OK;
break;
default:
assert false;
break;
}
SendMessageResponseHeader responseHeader =
(SendMessageResponseHeader) response.decodeCommandCustomHeader(SendMessageResponseHeader.class);
MessageQueue messageQueue = new MessageQueue(msg.getTopic(), brokerName, responseHeader.getQueueId());
String uniqMsgId = MessageClientIDSetter.getUniqID(msg);
if (msg instanceof MessageBatch) {
StringBuilder sb = new StringBuilder();
for (Message message : (MessageBatch) msg) {
sb.append(sb.length() == 0 ? "" : ",").append(MessageClientIDSetter.getUniqID(message));
}
uniqMsgId = sb.toString();
}
SendResult sendResult = new SendResult(sendStatus,
uniqMsgId,
responseHeader.getMsgId(), messageQueue, responseHeader.getQueueOffset());
sendResult.setTransactionId(responseHeader.getTransactionId());
String regionId = response.getExtFields().get(MessageConst.PROPERTY_MSG_REGION);
String traceOn = response.getExtFields().get(MessageConst.PROPERTY_TRACE_SWITCH);
if (regionId == null || regionId.isEmpty()) {
regionId = MixAll.DEFAULT_TRACE_REGION_ID;
}
if (traceOn != null && traceOn.equals("false")) {
sendResult.setTraceOn(false);
} else {
sendResult.setTraceOn(true);
}
sendResult.setRegionId(regionId);
return sendResult;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public PullResult pullMessage(
final String addr,
final PullMessageRequestHeader requestHeader,
final long timeoutMillis,
final CommunicationMode communicationMode,
final PullCallback pullCallback
) throws RemotingException, MQBrokerException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.PULL_MESSAGE, requestHeader);
switch (communicationMode) {
case ONEWAY:
assert false;
return null;
case ASYNC:
this.pullMessageAsync(addr, request, timeoutMillis, pullCallback);
return null;
case SYNC:
return this.pullMessageSync(addr, request, timeoutMillis);
default:
assert false;
break;
}
return null;
}
private void pullMessageAsync(
final String addr,
final RemotingCommand request,
final long timeoutMillis,
final PullCallback pullCallback
) throws RemotingException, InterruptedException {
this.remotingClient.invokeAsync(addr, request, timeoutMillis, new InvokeCallback() {
@Override
public void operationComplete(ResponseFuture responseFuture) {
RemotingCommand response = responseFuture.getResponseCommand();
if (response != null) {
try {
PullResult pullResult = MQClientAPIImpl.this.processPullResponse(response);
assert pullResult != null;
pullCallback.onSuccess(pullResult);
} catch (Exception e) {
pullCallback.onException(e);
}
} else {
if (!responseFuture.isSendRequestOK()) {
pullCallback.onException(new MQClientException("send request failed to " + addr + ". Request: " + request, responseFuture.getCause()));
} else if (responseFuture.isTimeout()) {
pullCallback.onException(new MQClientException("wait response from " + addr + " timeout :" + responseFuture.getTimeoutMillis() + "ms" + ". Request: " + request,
responseFuture.getCause()));
} else {
pullCallback.onException(new MQClientException("unknown reason. addr: " + addr + ", timeoutMillis: " + timeoutMillis + ". Request: " + request, responseFuture.getCause()));
}
}
}
});
}
private PullResult pullMessageSync(
final String addr,
final RemotingCommand request,
final long timeoutMillis
) throws RemotingException, InterruptedException, MQBrokerException {
RemotingCommand response = this.remotingClient.invokeSync(addr, request, timeoutMillis);
assert response != null;
return this.processPullResponse(response);
}
private PullResult processPullResponse(
final RemotingCommand response) throws MQBrokerException, RemotingCommandException {
PullStatus pullStatus = PullStatus.NO_NEW_MSG;
switch (response.getCode()) {
case ResponseCode.SUCCESS:
pullStatus = PullStatus.FOUND;
break;
case ResponseCode.PULL_NOT_FOUND:
pullStatus = PullStatus.NO_NEW_MSG;
break;
case ResponseCode.PULL_RETRY_IMMEDIATELY:
pullStatus = PullStatus.NO_MATCHED_MSG;
break;
case ResponseCode.PULL_OFFSET_MOVED:
pullStatus = PullStatus.OFFSET_ILLEGAL;
break;
default:
throw new MQBrokerException(response.getCode(), response.getRemark());
}
PullMessageResponseHeader responseHeader =
(PullMessageResponseHeader) response.decodeCommandCustomHeader(PullMessageResponseHeader.class);
return new PullResultExt(pullStatus, responseHeader.getNextBeginOffset(), responseHeader.getMinOffset(),
responseHeader.getMaxOffset(), null, responseHeader.getSuggestWhichBrokerId(), response.getBody());
}
public MessageExt viewMessage(final String addr, final long phyoffset, final long timeoutMillis)
throws RemotingException, MQBrokerException, InterruptedException {
ViewMessageRequestHeader requestHeader = new ViewMessageRequestHeader();
requestHeader.setOffset(phyoffset);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.VIEW_MESSAGE_BY_ID, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
ByteBuffer byteBuffer = ByteBuffer.wrap(response.getBody());
MessageExt messageExt = MessageDecoder.clientDecode(byteBuffer, true);
return messageExt;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public long searchOffset(final String addr, final String topic, final int queueId, final long timestamp,
final long timeoutMillis)
throws RemotingException, MQBrokerException, InterruptedException {
SearchOffsetRequestHeader requestHeader = new SearchOffsetRequestHeader();
requestHeader.setTopic(topic);
requestHeader.setQueueId(queueId);
requestHeader.setTimestamp(timestamp);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.SEARCH_OFFSET_BY_TIMESTAMP, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
SearchOffsetResponseHeader responseHeader =
(SearchOffsetResponseHeader) response.decodeCommandCustomHeader(SearchOffsetResponseHeader.class);
return responseHeader.getOffset();
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public long getMaxOffset(final String addr, final String topic, final int queueId, final long timeoutMillis)
throws RemotingException, MQBrokerException, InterruptedException {
GetMaxOffsetRequestHeader requestHeader = new GetMaxOffsetRequestHeader();
requestHeader.setTopic(topic);
requestHeader.setQueueId(queueId);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_MAX_OFFSET, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
GetMaxOffsetResponseHeader responseHeader =
(GetMaxOffsetResponseHeader) response.decodeCommandCustomHeader(GetMaxOffsetResponseHeader.class);
return responseHeader.getOffset();
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public List<String> getConsumerIdListByGroup(
final String addr,
final String consumerGroup,
final long timeoutMillis) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException,
MQBrokerException, InterruptedException {
GetConsumerListByGroupRequestHeader requestHeader = new GetConsumerListByGroupRequestHeader();
requestHeader.setConsumerGroup(consumerGroup);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_CONSUMER_LIST_BY_GROUP, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
if (response.getBody() != null) {
GetConsumerListByGroupResponseBody body =
GetConsumerListByGroupResponseBody.decode(response.getBody(), GetConsumerListByGroupResponseBody.class);
return body.getConsumerIdList();
}
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public long getMinOffset(final String addr, final String topic, final int queueId, final long timeoutMillis)
throws RemotingException, MQBrokerException, InterruptedException {
GetMinOffsetRequestHeader requestHeader = new GetMinOffsetRequestHeader();
requestHeader.setTopic(topic);
requestHeader.setQueueId(queueId);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_MIN_OFFSET, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
GetMinOffsetResponseHeader responseHeader =
(GetMinOffsetResponseHeader) response.decodeCommandCustomHeader(GetMinOffsetResponseHeader.class);
return responseHeader.getOffset();
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public long getEarliestMsgStoretime(final String addr, final String topic, final int queueId,
final long timeoutMillis)
throws RemotingException, MQBrokerException, InterruptedException {
GetEarliestMsgStoretimeRequestHeader requestHeader = new GetEarliestMsgStoretimeRequestHeader();
requestHeader.setTopic(topic);
requestHeader.setQueueId(queueId);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_EARLIEST_MSG_STORETIME, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
GetEarliestMsgStoretimeResponseHeader responseHeader =
(GetEarliestMsgStoretimeResponseHeader) response.decodeCommandCustomHeader(GetEarliestMsgStoretimeResponseHeader.class);
return responseHeader.getTimestamp();
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public long queryConsumerOffset(
final String addr,
final QueryConsumerOffsetRequestHeader requestHeader,
final long timeoutMillis
) throws RemotingException, MQBrokerException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.QUERY_CONSUMER_OFFSET, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
QueryConsumerOffsetResponseHeader responseHeader =
(QueryConsumerOffsetResponseHeader) response.decodeCommandCustomHeader(QueryConsumerOffsetResponseHeader.class);
return responseHeader.getOffset();
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public void updateConsumerOffset(
final String addr,
final UpdateConsumerOffsetRequestHeader requestHeader,
final long timeoutMillis
) throws RemotingException, MQBrokerException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.UPDATE_CONSUMER_OFFSET, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public void updateConsumerOffsetOneway(
final String addr,
final UpdateConsumerOffsetRequestHeader requestHeader,
final long timeoutMillis
) throws RemotingConnectException, RemotingTooMuchRequestException, RemotingTimeoutException, RemotingSendRequestException,
InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.UPDATE_CONSUMER_OFFSET, requestHeader);
this.remotingClient.invokeOneway(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr), request, timeoutMillis);
}
public int sendHearbeat(
final String addr,
final HeartbeatData heartbeatData,
final long timeoutMillis
) throws RemotingException, MQBrokerException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.HEART_BEAT, null);
request.setLanguage(clientConfig.getLanguage());
request.setBody(heartbeatData.encode());
RemotingCommand response = this.remotingClient.invokeSync(addr, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return response.getVersion();
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public void unregisterClient(
final String addr,
final String clientID,
final String producerGroup,
final String consumerGroup,
final long timeoutMillis
) throws RemotingException, MQBrokerException, InterruptedException {
final UnregisterClientRequestHeader requestHeader = new UnregisterClientRequestHeader();
requestHeader.setClientID(clientID);
requestHeader.setProducerGroup(producerGroup);
requestHeader.setConsumerGroup(consumerGroup);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.UNREGISTER_CLIENT, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(addr, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public void endTransactionOneway(
final String addr,
final EndTransactionRequestHeader requestHeader,
final String remark,
final long timeoutMillis
) throws RemotingException, MQBrokerException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.END_TRANSACTION, requestHeader);
request.setRemark(remark);
this.remotingClient.invokeOneway(addr, request, timeoutMillis);
}
public void queryMessage(
final String addr,
final QueryMessageRequestHeader requestHeader,
final long timeoutMillis,
final InvokeCallback invokeCallback,
final Boolean isUnqiueKey
) throws RemotingException, MQBrokerException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.QUERY_MESSAGE, requestHeader);
request.addExtField(MixAll.UNIQUE_MSG_QUERY_FLAG, isUnqiueKey.toString());
this.remotingClient.invokeAsync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr), request, timeoutMillis,
invokeCallback);
}
public boolean registerClient(final String addr, final HeartbeatData heartbeat, final long timeoutMillis)
throws RemotingException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.HEART_BEAT, null);
request.setBody(heartbeat.encode());
RemotingCommand response = this.remotingClient.invokeSync(addr, request, timeoutMillis);
return response.getCode() == ResponseCode.SUCCESS;
}
public void consumerSendMessageBack(
final String addr,
final MessageExt msg,
final String consumerGroup,
final int delayLevel,
final long timeoutMillis,
final int maxConsumeRetryTimes
) throws RemotingException, MQBrokerException, InterruptedException {
ConsumerSendMsgBackRequestHeader requestHeader = new ConsumerSendMsgBackRequestHeader();
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.CONSUMER_SEND_MSG_BACK, requestHeader);
requestHeader.setGroup(consumerGroup);
requestHeader.setOriginTopic(msg.getTopic());
requestHeader.setOffset(msg.getCommitLogOffset());
requestHeader.setDelayLevel(delayLevel);
requestHeader.setOriginMsgId(msg.getMsgId());
requestHeader.setMaxReconsumeTimes(maxConsumeRetryTimes);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public Set<MessageQueue> lockBatchMQ(
final String addr,
final LockBatchRequestBody requestBody,
final long timeoutMillis) throws RemotingException, MQBrokerException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.LOCK_BATCH_MQ, null);
request.setBody(requestBody.encode());
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
LockBatchResponseBody responseBody = LockBatchResponseBody.decode(response.getBody(), LockBatchResponseBody.class);
Set<MessageQueue> messageQueues = responseBody.getLockOKMQSet();
return messageQueues;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public void unlockBatchMQ(
final String addr,
final UnlockBatchRequestBody requestBody,
final long timeoutMillis,
final boolean oneway
) throws RemotingException, MQBrokerException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.UNLOCK_BATCH_MQ, null);
request.setBody(requestBody.encode());
if (oneway) {
this.remotingClient.invokeOneway(addr, request, timeoutMillis);
} else {
RemotingCommand response = this.remotingClient
.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr), request, timeoutMillis);
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
}
public TopicStatsTable getTopicStatsInfo(final String addr, final String topic,
final long timeoutMillis) throws InterruptedException,
RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException, MQBrokerException {
GetTopicStatsInfoRequestHeader requestHeader = new GetTopicStatsInfoRequestHeader();
requestHeader.setTopic(topic);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_TOPIC_STATS_INFO, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
TopicStatsTable topicStatsTable = TopicStatsTable.decode(response.getBody(), TopicStatsTable.class);
return topicStatsTable;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public ConsumeStats getConsumeStats(final String addr, final String consumerGroup, final long timeoutMillis)
throws InterruptedException, RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException,
MQBrokerException {
return getConsumeStats(addr, consumerGroup, null, timeoutMillis);
}
public ConsumeStats getConsumeStats(final String addr, final String consumerGroup, final String topic,
final long timeoutMillis)
throws InterruptedException, RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException,
MQBrokerException {
GetConsumeStatsRequestHeader requestHeader = new GetConsumeStatsRequestHeader();
requestHeader.setConsumerGroup(consumerGroup);
requestHeader.setTopic(topic);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_CONSUME_STATS, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
ConsumeStats consumeStats = ConsumeStats.decode(response.getBody(), ConsumeStats.class);
return consumeStats;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public ProducerConnection getProducerConnectionList(final String addr, final String producerGroup,
final long timeoutMillis)
throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException,
MQBrokerException {
GetProducerConnectionListRequestHeader requestHeader = new GetProducerConnectionListRequestHeader();
requestHeader.setProducerGroup(producerGroup);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_PRODUCER_CONNECTION_LIST, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return ProducerConnection.decode(response.getBody(), ProducerConnection.class);
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public ConsumerConnection getConsumerConnectionList(final String addr, final String consumerGroup,
final long timeoutMillis)
throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException,
MQBrokerException {
GetConsumerConnectionListRequestHeader requestHeader = new GetConsumerConnectionListRequestHeader();
requestHeader.setConsumerGroup(consumerGroup);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_CONSUMER_CONNECTION_LIST, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return ConsumerConnection.decode(response.getBody(), ConsumerConnection.class);
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public KVTable getBrokerRuntimeInfo(final String addr, final long timeoutMillis) throws RemotingConnectException,
RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_BROKER_RUNTIME_INFO, null);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return KVTable.decode(response.getBody(), KVTable.class);
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public void updateBrokerConfig(final String addr, final Properties properties, final long timeoutMillis)
throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException,
MQBrokerException, UnsupportedEncodingException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.UPDATE_BROKER_CONFIG, null);
String str = MixAll.properties2String(properties);
if (str != null && str.length() > 0) {
request.setBody(str.getBytes(MixAll.DEFAULT_CHARSET));
RemotingCommand response = this.remotingClient
.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr), request, timeoutMillis);
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
}
public Properties getBrokerConfig(final String addr, final long timeoutMillis)
throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException,
MQBrokerException, UnsupportedEncodingException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_BROKER_CONFIG, null);
RemotingCommand response = this.remotingClient.invokeSync(addr, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return MixAll.string2Properties(new String(response.getBody(), MixAll.DEFAULT_CHARSET));
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public ClusterInfo getBrokerClusterInfo(
final long timeoutMillis) throws InterruptedException, RemotingTimeoutException,
RemotingSendRequestException, RemotingConnectException, MQBrokerException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_BROKER_CLUSTER_INFO, null);
RemotingCommand response = this.remotingClient.invokeSync(null, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return ClusterInfo.decode(response.getBody(), ClusterInfo.class);
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public TopicRouteData getDefaultTopicRouteInfoFromNameServer(final String topic, final long timeoutMillis)
throws RemotingException, MQClientException, InterruptedException {
return getTopicRouteInfoFromNameServer(topic, timeoutMillis, false);
}
public TopicRouteData getTopicRouteInfoFromNameServer(final String topic, final long timeoutMillis)
throws RemotingException, MQClientException, InterruptedException {
return getTopicRouteInfoFromNameServer(topic, timeoutMillis, true);
}
public TopicRouteData getTopicRouteInfoFromNameServer(final String topic, final long timeoutMillis,
boolean allowTopicNotExist) throws MQClientException, InterruptedException, RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException {
GetRouteInfoRequestHeader requestHeader = new GetRouteInfoRequestHeader();
requestHeader.setTopic(topic);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_ROUTEINTO_BY_TOPIC, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(null, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.TOPIC_NOT_EXIST: {
if (allowTopicNotExist && !topic.equals(MixAll.AUTO_CREATE_TOPIC_KEY_TOPIC)) {
log.warn("get Topic [{}] RouteInfoFromNameServer is not exist value", topic);
}
break;
}
case ResponseCode.SUCCESS: {
byte[] body = response.getBody();
if (body != null) {
return TopicRouteData.decode(body, TopicRouteData.class);
}
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public TopicList getTopicListFromNameServer(final long timeoutMillis)
throws RemotingException, MQClientException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_ALL_TOPIC_LIST_FROM_NAMESERVER, null);
RemotingCommand response = this.remotingClient.invokeSync(null, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
byte[] body = response.getBody();
if (body != null) {
return TopicList.decode(body, TopicList.class);
}
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public int wipeWritePermOfBroker(final String namesrvAddr, String brokerName,
final long timeoutMillis) throws RemotingCommandException,
RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQClientException {
WipeWritePermOfBrokerRequestHeader requestHeader = new WipeWritePermOfBrokerRequestHeader();
requestHeader.setBrokerName(brokerName);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.WIPE_WRITE_PERM_OF_BROKER, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(namesrvAddr, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
WipeWritePermOfBrokerResponseHeader responseHeader =
(WipeWritePermOfBrokerResponseHeader) response.decodeCommandCustomHeader(WipeWritePermOfBrokerResponseHeader.class);
return responseHeader.getWipeTopicCount();
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public void deleteTopicInBroker(final String addr, final String topic, final long timeoutMillis)
throws RemotingException, MQBrokerException, InterruptedException, MQClientException {
DeleteTopicRequestHeader requestHeader = new DeleteTopicRequestHeader();
requestHeader.setTopic(topic);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.DELETE_TOPIC_IN_BROKER, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public void deleteTopicInNameServer(final String addr, final String topic, final long timeoutMillis)
throws RemotingException, MQBrokerException, InterruptedException, MQClientException {
DeleteTopicRequestHeader requestHeader = new DeleteTopicRequestHeader();
requestHeader.setTopic(topic);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.DELETE_TOPIC_IN_NAMESRV, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(addr, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public void deleteSubscriptionGroup(final String addr, final String groupName, final long timeoutMillis)
throws RemotingException, MQBrokerException, InterruptedException, MQClientException {
DeleteSubscriptionGroupRequestHeader requestHeader = new DeleteSubscriptionGroupRequestHeader();
requestHeader.setGroupName(groupName);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.DELETE_SUBSCRIPTIONGROUP, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public String getKVConfigValue(final String namespace, final String key, final long timeoutMillis)
throws RemotingException, MQClientException, InterruptedException {
GetKVConfigRequestHeader requestHeader = new GetKVConfigRequestHeader();
requestHeader.setNamespace(namespace);
requestHeader.setKey(key);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_KV_CONFIG, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(null, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
GetKVConfigResponseHeader responseHeader =
(GetKVConfigResponseHeader) response.decodeCommandCustomHeader(GetKVConfigResponseHeader.class);
return responseHeader.getValue();
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public void putKVConfigValue(final String namespace, final String key, final String value, final long timeoutMillis)
throws RemotingException, MQClientException, InterruptedException {
PutKVConfigRequestHeader requestHeader = new PutKVConfigRequestHeader();
requestHeader.setNamespace(namespace);
requestHeader.setKey(key);
requestHeader.setValue(value);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.PUT_KV_CONFIG, requestHeader);
List<String> nameServerAddressList = this.remotingClient.getNameServerAddressList();
if (nameServerAddressList != null) {
RemotingCommand errResponse = null;
for (String namesrvAddr : nameServerAddressList) {
RemotingCommand response = this.remotingClient.invokeSync(namesrvAddr, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
break;
}
default:
errResponse = response;
}
}
if (errResponse != null) {
throw new MQClientException(errResponse.getCode(), errResponse.getRemark());
}
}
}
public void deleteKVConfigValue(final String namespace, final String key, final long timeoutMillis)
throws RemotingException, MQClientException, InterruptedException {
DeleteKVConfigRequestHeader requestHeader = new DeleteKVConfigRequestHeader();
requestHeader.setNamespace(namespace);
requestHeader.setKey(key);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.DELETE_KV_CONFIG, requestHeader);
List<String> nameServerAddressList = this.remotingClient.getNameServerAddressList();
if (nameServerAddressList != null) {
RemotingCommand errResponse = null;
for (String namesrvAddr : nameServerAddressList) {
RemotingCommand response = this.remotingClient.invokeSync(namesrvAddr, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
break;
}
default:
errResponse = response;
}
}
if (errResponse != null) {
throw new MQClientException(errResponse.getCode(), errResponse.getRemark());
}
}
}
public KVTable getKVListByNamespace(final String namespace, final long timeoutMillis)
throws RemotingException, MQClientException, InterruptedException {
GetKVListByNamespaceRequestHeader requestHeader = new GetKVListByNamespaceRequestHeader();
requestHeader.setNamespace(namespace);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_KVLIST_BY_NAMESPACE, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(null, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return KVTable.decode(response.getBody(), KVTable.class);
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public Map<MessageQueue, Long> invokeBrokerToResetOffset(final String addr, final String topic, final String group,
final long timestamp, final boolean isForce, final long timeoutMillis)
throws RemotingException, MQClientException, InterruptedException {
return invokeBrokerToResetOffset(addr, topic, group, timestamp, isForce, timeoutMillis, false);
}
public Map<MessageQueue, Long> invokeBrokerToResetOffset(final String addr, final String topic, final String group,
final long timestamp, final boolean isForce, final long timeoutMillis, boolean isC)
throws RemotingException, MQClientException, InterruptedException {
ResetOffsetRequestHeader requestHeader = new ResetOffsetRequestHeader();
requestHeader.setTopic(topic);
requestHeader.setGroup(group);
requestHeader.setTimestamp(timestamp);
requestHeader.setForce(isForce);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.INVOKE_BROKER_TO_RESET_OFFSET, requestHeader);
if (isC) {
request.setLanguage(LanguageCode.CPP);
}
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
if (response.getBody() != null) {
ResetOffsetBody body = ResetOffsetBody.decode(response.getBody(), ResetOffsetBody.class);
return body.getOffsetTable();
}
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public Map<String, Map<MessageQueue, Long>> invokeBrokerToGetConsumerStatus(final String addr, final String topic,
final String group,
final String clientAddr,
final long timeoutMillis) throws RemotingException, MQClientException, InterruptedException {
GetConsumerStatusRequestHeader requestHeader = new GetConsumerStatusRequestHeader();
requestHeader.setTopic(topic);
requestHeader.setGroup(group);
requestHeader.setClientAddr(clientAddr);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.INVOKE_BROKER_TO_GET_CONSUMER_STATUS, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
if (response.getBody() != null) {
GetConsumerStatusBody body = GetConsumerStatusBody.decode(response.getBody(), GetConsumerStatusBody.class);
return body.getConsumerTable();
}
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public GroupList queryTopicConsumeByWho(final String addr, final String topic, final long timeoutMillis)
throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException,
MQBrokerException {
QueryTopicConsumeByWhoRequestHeader requestHeader = new QueryTopicConsumeByWhoRequestHeader();
requestHeader.setTopic(topic);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.QUERY_TOPIC_CONSUME_BY_WHO, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
GroupList groupList = GroupList.decode(response.getBody(), GroupList.class);
return groupList;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public List<QueueTimeSpan> queryConsumeTimeSpan(final String addr, final String topic, final String group,
final long timeoutMillis)
throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException,
MQBrokerException {
QueryConsumeTimeSpanRequestHeader requestHeader = new QueryConsumeTimeSpanRequestHeader();
requestHeader.setTopic(topic);
requestHeader.setGroup(group);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.QUERY_CONSUME_TIME_SPAN, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
QueryConsumeTimeSpanBody consumeTimeSpanBody = GroupList.decode(response.getBody(), QueryConsumeTimeSpanBody.class);
return consumeTimeSpanBody.getConsumeTimeSpanSet();
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public TopicList getTopicsByCluster(final String cluster, final long timeoutMillis)
throws RemotingException, MQClientException, InterruptedException {
GetTopicsByClusterRequestHeader requestHeader = new GetTopicsByClusterRequestHeader();
requestHeader.setCluster(cluster);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_TOPICS_BY_CLUSTER, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(null, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
byte[] body = response.getBody();
if (body != null) {
TopicList topicList = TopicList.decode(body, TopicList.class);
return topicList;
}
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public void registerMessageFilterClass(final String addr,
final String consumerGroup,
final String topic,
final String className,
final int classCRC,
final byte[] classBody,
final long timeoutMillis) throws RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException,
InterruptedException, MQBrokerException {
RegisterMessageFilterClassRequestHeader requestHeader = new RegisterMessageFilterClassRequestHeader();
requestHeader.setConsumerGroup(consumerGroup);
requestHeader.setClassName(className);
requestHeader.setTopic(topic);
requestHeader.setClassCRC(classCRC);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.REGISTER_MESSAGE_FILTER_CLASS, requestHeader);
request.setBody(classBody);
RemotingCommand response = this.remotingClient.invokeSync(addr, request, timeoutMillis);
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public TopicList getSystemTopicList(
final long timeoutMillis) throws RemotingException, MQClientException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_SYSTEM_TOPIC_LIST_FROM_NS, null);
RemotingCommand response = this.remotingClient.invokeSync(null, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
byte[] body = response.getBody();
if (body != null) {
TopicList topicList = TopicList.decode(response.getBody(), TopicList.class);
if (topicList.getTopicList() != null && !topicList.getTopicList().isEmpty()
&& !UtilAll.isBlank(topicList.getBrokerAddr())) {
TopicList tmp = getSystemTopicListFromBroker(topicList.getBrokerAddr(), timeoutMillis);
if (tmp.getTopicList() != null && !tmp.getTopicList().isEmpty()) {
topicList.getTopicList().addAll(tmp.getTopicList());
}
}
return topicList;
}
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public TopicList getSystemTopicListFromBroker(final String addr, final long timeoutMillis)
throws RemotingException, MQClientException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_SYSTEM_TOPIC_LIST_FROM_BROKER, null);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
byte[] body = response.getBody();
if (body != null) {
TopicList topicList = TopicList.decode(body, TopicList.class);
return topicList;
}
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public boolean cleanExpiredConsumeQueue(final String addr,
long timeoutMillis) throws MQClientException, RemotingConnectException,
RemotingSendRequestException, RemotingTimeoutException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.CLEAN_EXPIRED_CONSUMEQUEUE, null);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return true;
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public boolean cleanUnusedTopicByAddr(final String addr,
long timeoutMillis) throws MQClientException, RemotingConnectException,
RemotingSendRequestException, RemotingTimeoutException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.CLEAN_UNUSED_TOPIC, null);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return true;
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public ConsumerRunningInfo getConsumerRunningInfo(final String addr, String consumerGroup, String clientId,
boolean jstack,
final long timeoutMillis) throws RemotingException, MQClientException, InterruptedException {
GetConsumerRunningInfoRequestHeader requestHeader = new GetConsumerRunningInfoRequestHeader();
requestHeader.setConsumerGroup(consumerGroup);
requestHeader.setClientId(clientId);
requestHeader.setJstackEnable(jstack);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_CONSUMER_RUNNING_INFO, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
byte[] body = response.getBody();
if (body != null) {
ConsumerRunningInfo info = ConsumerRunningInfo.decode(body, ConsumerRunningInfo.class);
return info;
}
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public ConsumeMessageDirectlyResult consumeMessageDirectly(final String addr,
String consumerGroup,
String clientId,
String msgId,
final long timeoutMillis) throws RemotingException, MQClientException, InterruptedException {
ConsumeMessageDirectlyResultRequestHeader requestHeader = new ConsumeMessageDirectlyResultRequestHeader();
requestHeader.setConsumerGroup(consumerGroup);
requestHeader.setClientId(clientId);
requestHeader.setMsgId(msgId);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.CONSUME_MESSAGE_DIRECTLY, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
byte[] body = response.getBody();
if (body != null) {
ConsumeMessageDirectlyResult info = ConsumeMessageDirectlyResult.decode(body, ConsumeMessageDirectlyResult.class);
return info;
}
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public Map<Integer, Long> queryCorrectionOffset(final String addr, final String topic, final String group,
Set<String> filterGroup,
long timeoutMillis) throws MQClientException, RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException,
InterruptedException {
QueryCorrectionOffsetHeader requestHeader = new QueryCorrectionOffsetHeader();
requestHeader.setCompareGroup(group);
requestHeader.setTopic(topic);
if (filterGroup != null) {
StringBuilder sb = new StringBuilder();
String splitor = "";
for (String s : filterGroup) {
sb.append(splitor).append(s);
splitor = ",";
}
requestHeader.setFilterGroups(sb.toString());
}
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.QUERY_CORRECTION_OFFSET, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
if (response.getBody() != null) {
QueryCorrectionOffsetBody body = QueryCorrectionOffsetBody.decode(response.getBody(), QueryCorrectionOffsetBody.class);
return body.getCorrectionOffsets();
}
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public TopicList getUnitTopicList(final boolean containRetry, final long timeoutMillis)
throws RemotingException, MQClientException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_UNIT_TOPIC_LIST, null);
RemotingCommand response = this.remotingClient.invokeSync(null, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
byte[] body = response.getBody();
if (body != null) {
TopicList topicList = TopicList.decode(response.getBody(), TopicList.class);
if (!containRetry) {
Iterator<String> it = topicList.getTopicList().iterator();
while (it.hasNext()) {
String topic = it.next();
if (topic.startsWith(MixAll.RETRY_GROUP_TOPIC_PREFIX))
it.remove();
}
}
return topicList;
}
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public TopicList getHasUnitSubTopicList(final boolean containRetry, final long timeoutMillis)
throws RemotingException, MQClientException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_HAS_UNIT_SUB_TOPIC_LIST, null);
RemotingCommand response = this.remotingClient.invokeSync(null, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
byte[] body = response.getBody();
if (body != null) {
TopicList topicList = TopicList.decode(response.getBody(), TopicList.class);
if (!containRetry) {
Iterator<String> it = topicList.getTopicList().iterator();
while (it.hasNext()) {
String topic = it.next();
if (topic.startsWith(MixAll.RETRY_GROUP_TOPIC_PREFIX))
it.remove();
}
}
return topicList;
}
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public TopicList getHasUnitSubUnUnitTopicList(final boolean containRetry, final long timeoutMillis)
throws RemotingException, MQClientException, InterruptedException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_HAS_UNIT_SUB_UNUNIT_TOPIC_LIST, null);
RemotingCommand response = this.remotingClient.invokeSync(null, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
byte[] body = response.getBody();
if (body != null) {
TopicList topicList = TopicList.decode(response.getBody(), TopicList.class);
if (!containRetry) {
Iterator<String> it = topicList.getTopicList().iterator();
while (it.hasNext()) {
String topic = it.next();
if (topic.startsWith(MixAll.RETRY_GROUP_TOPIC_PREFIX))
it.remove();
}
}
return topicList;
}
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public void cloneGroupOffset(final String addr, final String srcGroup, final String destGroup, final String topic,
final boolean isOffline,
final long timeoutMillis) throws RemotingException, MQClientException, InterruptedException {
CloneGroupOffsetRequestHeader requestHeader = new CloneGroupOffsetRequestHeader();
requestHeader.setSrcGroup(srcGroup);
requestHeader.setDestGroup(destGroup);
requestHeader.setTopic(topic);
requestHeader.setOffline(isOffline);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.CLONE_GROUP_OFFSET, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return;
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public BrokerStatsData viewBrokerStatsData(String brokerAddr, String statsName, String statsKey, long timeoutMillis)
throws MQClientException, RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException,
InterruptedException {
ViewBrokerStatsDataRequestHeader requestHeader = new ViewBrokerStatsDataRequestHeader();
requestHeader.setStatsName(statsName);
requestHeader.setStatsKey(statsKey);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.VIEW_BROKER_STATS_DATA, requestHeader);
RemotingCommand response = this.remotingClient
.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), brokerAddr), request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
byte[] body = response.getBody();
if (body != null) {
return BrokerStatsData.decode(body, BrokerStatsData.class);
}
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public Set<String> getClusterList(String topic,
long timeoutMillis) throws MQClientException, RemotingConnectException,
RemotingSendRequestException, RemotingTimeoutException, InterruptedException {
return Collections.EMPTY_SET;
}
public ConsumeStatsList fetchConsumeStatsInBroker(String brokerAddr, boolean isOrder,
long timeoutMillis) throws MQClientException,
RemotingConnectException, RemotingSendRequestException, RemotingTimeoutException, InterruptedException {
GetConsumeStatsInBrokerHeader requestHeader = new GetConsumeStatsInBrokerHeader();
requestHeader.setIsOrder(isOrder);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_BROKER_CONSUME_STATS, requestHeader);
RemotingCommand response = this.remotingClient
.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), brokerAddr), request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
byte[] body = response.getBody();
if (body != null) {
return ConsumeStatsList.decode(body, ConsumeStatsList.class);
}
}
default:
break;
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public SubscriptionGroupWrapper getAllSubscriptionGroup(final String brokerAddr,
long timeoutMillis) throws InterruptedException,
RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException, MQBrokerException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_ALL_SUBSCRIPTIONGROUP_CONFIG, null);
RemotingCommand response = this.remotingClient
.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), brokerAddr), request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return SubscriptionGroupWrapper.decode(response.getBody(), SubscriptionGroupWrapper.class);
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public TopicConfigSerializeWrapper getAllTopicConfig(final String addr,
long timeoutMillis) throws RemotingConnectException,
RemotingSendRequestException, RemotingTimeoutException, InterruptedException, MQBrokerException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_ALL_TOPIC_CONFIG, null);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), addr),
request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
return TopicConfigSerializeWrapper.decode(response.getBody(), TopicConfigSerializeWrapper.class);
}
default:
break;
}
throw new MQBrokerException(response.getCode(), response.getRemark());
}
public void updateNameServerConfig(final Properties properties, final List<String> nameServers, long timeoutMillis)
throws UnsupportedEncodingException,
MQBrokerException, InterruptedException, RemotingTimeoutException, RemotingSendRequestException,
RemotingConnectException, MQClientException {
String str = MixAll.properties2String(properties);
if (str == null || str.length() < 1) {
return;
}
List<String> invokeNameServers = (nameServers == null || nameServers.isEmpty()) ?
this.remotingClient.getNameServerAddressList() : nameServers;
if (invokeNameServers == null || invokeNameServers.isEmpty()) {
return;
}
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.UPDATE_NAMESRV_CONFIG, null);
request.setBody(str.getBytes(MixAll.DEFAULT_CHARSET));
RemotingCommand errResponse = null;
for (String nameServer : invokeNameServers) {
RemotingCommand response = this.remotingClient.invokeSync(nameServer, request, timeoutMillis);
assert response != null;
switch (response.getCode()) {
case ResponseCode.SUCCESS: {
break;
}
default:
errResponse = response;
}
}
if (errResponse != null) {
throw new MQClientException(errResponse.getCode(), errResponse.getRemark());
}
}
public Map<String, Properties> getNameServerConfig(final List<String> nameServers, long timeoutMillis)
throws InterruptedException,
RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException,
MQClientException, UnsupportedEncodingException {
List<String> invokeNameServers = (nameServers == null || nameServers.isEmpty()) ?
this.remotingClient.getNameServerAddressList() : nameServers;
if (invokeNameServers == null || invokeNameServers.isEmpty()) {
return null;
}
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.GET_NAMESRV_CONFIG, null);
Map<String, Properties> configMap = new HashMap<String, Properties>(4);
for (String nameServer : invokeNameServers) {
RemotingCommand response = this.remotingClient.invokeSync(nameServer, request, timeoutMillis);
assert response != null;
if (ResponseCode.SUCCESS == response.getCode()) {
configMap.put(nameServer, MixAll.string2Properties(new String(response.getBody(), MixAll.DEFAULT_CHARSET)));
} else {
throw new MQClientException(response.getCode(), response.getRemark());
}
}
return configMap;
}
public QueryConsumeQueueResponseBody queryConsumeQueue(final String brokerAddr, final String topic,
final int queueId,
final long index, final int count, final String consumerGroup,
final long timeoutMillis) throws InterruptedException,
RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException, MQClientException {
QueryConsumeQueueRequestHeader requestHeader = new QueryConsumeQueueRequestHeader();
requestHeader.setTopic(topic);
requestHeader.setQueueId(queueId);
requestHeader.setIndex(index);
requestHeader.setCount(count);
requestHeader.setConsumerGroup(consumerGroup);
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.QUERY_CONSUME_QUEUE, requestHeader);
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), brokerAddr), request, timeoutMillis);
assert response != null;
if (ResponseCode.SUCCESS == response.getCode()) {
return QueryConsumeQueueResponseBody.decode(response.getBody(), QueryConsumeQueueResponseBody.class);
}
throw new MQClientException(response.getCode(), response.getRemark());
}
public void checkClientInBroker(final String brokerAddr, final String consumerGroup,
final String clientId, final SubscriptionData subscriptionData,
final long timeoutMillis)
throws InterruptedException, RemotingTimeoutException, RemotingSendRequestException,
RemotingConnectException, MQClientException {
RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.CHECK_CLIENT_CONFIG, null);
CheckClientRequestBody requestBody = new CheckClientRequestBody();
requestBody.setClientId(clientId);
requestBody.setGroup(consumerGroup);
requestBody.setSubscriptionData(subscriptionData);
request.setBody(requestBody.encode());
RemotingCommand response = this.remotingClient.invokeSync(MixAll.brokerVIPChannel(this.clientConfig.isVipChannelEnabled(), brokerAddr), request, timeoutMillis);
assert response != null;
if (ResponseCode.SUCCESS != response.getCode()) {
throw new MQClientException(response.getCode(), response.getRemark());
}
}
}
|
// ============================================================================
//
// Copyright (C) 2006-2019 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.designer.rowgenerator.ui.editor;
import org.talend.core.model.metadata.IMetadataColumn;
import org.talend.core.model.metadata.IMetadataTable;
import org.talend.core.model.metadata.MetadataColumn;
import org.talend.core.ui.metadata.editor.MetadataTableEditor;
import org.talend.designer.rowgenerator.data.FunctionManagerExt;
import org.talend.designer.rowgenerator.ui.RowGeneratorUI;
/**
* qzhang class global comment. Detailled comment <br/>
*
* $Id: MetadataTableEditorExt.java,v 1.3 2007/01/31 05:20:52 pub Exp $
*
*/
public class MetadataTableEditorExt extends MetadataTableEditor {
private RowGeneratorUI ui;
private FunctionManagerExt functionManagerExt;
/**
* qzhang MetadataTableEditorExt constructor comment.
*/
public MetadataTableEditorExt(IMetadataTable metadataTable, String titleName, FunctionManagerExt functionManagerExt) {
super(metadataTable, titleName);
this.functionManagerExt = functionManagerExt;
}
public IMetadataColumn createNewMetadataColumn() {
final MetadataColumnExt metadataColumnExt = new MetadataColumnExt((MetadataColumn) super.createNewMetadataColumn());
metadataColumnExt.setFunction(functionManagerExt.getDefaultFunction(metadataColumnExt, metadataColumnExt
.getTalendType()));
return metadataColumnExt;
}
public void setRowGenUI(RowGeneratorUI ui) {
this.ui = ui;
}
public RowGeneratorUI getRowGenUI() {
return this.ui;
}
}
|
/**
* 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.kerby.asn1;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
public class DataTest {
public static PersonnelRecord createSamplePersonnel() {
PersonnelRecord pr = new PersonnelRecord();
pr.setName(new PersonnelRecord.Name("John", "P", "Smith"));
pr.setTitle("Director");
pr.setEmployeeNumber(new PersonnelRecord.EmployeeNumber(51));
pr.setDateOfHire(new PersonnelRecord.Date("19710917"));
pr.setNameOfSpouse(new PersonnelRecord.Name("Mary", "T", "Smith"));
PersonnelRecord.ChildInformation child1 = new PersonnelRecord.ChildInformation();
child1.setName(new PersonnelRecord.Name("Ralph", "T", "Smith"));
child1.setDateOfBirth(new PersonnelRecord.Date("19571111"));
PersonnelRecord.ChildInformation child2 = new PersonnelRecord.ChildInformation();
child2.setName(new PersonnelRecord.Name("Susan", "B", "Jones"));
child2.setDateOfBirth(new PersonnelRecord.Date("19590717"));
pr.setChildren(new PersonnelRecord.Children(child1, child2));
return pr;
}
public static byte[] createSammplePersonnelEncodingData() {
class BufferOutput {
ByteBuffer buffer;
void put(byte... bytes) {
buffer.put(bytes);
}
void put(String s) {
byte[] bytes = s.getBytes(StandardCharsets.US_ASCII);
buffer.put(bytes);
}
public byte[] output() {
int len = (int) 0x85 + 3;
buffer = ByteBuffer.allocate(len);
// personnel record
put((byte) 0x60, (byte) 0x81, (byte) 0x85);
// -name
put((byte) 0x61, (byte) 0x10);
put((byte) 0x1A, (byte) 0x04); put("John");
put((byte) 0x1A, (byte) 0x01); put("P");
put((byte) 0x1A, (byte) 0x05); put("Smith");
//-title
put((byte) 0xA0, (byte) 0x0A);
put((byte) 0x1A, (byte) 0x08); put("Director");
//-employee number
put((byte) 0x42, (byte) 0x01, (byte) 0x33);
//-date of hire
put((byte) 0xA1, (byte) 0x0A);
put((byte) 0x43, (byte) 0x08); put("19710917");
//-spouse
put((byte) 0xA2, (byte) 0x12);
put((byte) 0x61, (byte) 0x10);
put((byte) 0x1A, (byte) 0x04); put("Mary");
put((byte) 0x1A, (byte) 0x01); put("T");
put((byte) 0x1A, (byte) 0x05); put("Smith");
//-children
put((byte) 0xA3, (byte) 0x42);
//--child 1
put((byte) 0x31, (byte) 0x1F);
//---name
put((byte) 0x61, (byte) 0x11);
put((byte) 0x1A, (byte) 0x05); put("Ralph");
put((byte) 0x1A, (byte) 0x01); put("T");
put((byte) 0x1A, (byte) 0x05); put("Smith");
//-date of birth
put((byte) 0xA0, (byte) 0x0A);
put((byte) 0x43, (byte) 0x08); put("19571111");
//--child 2
put((byte) 0x31, (byte) 0x1F);
//---name
put((byte) 0x61, (byte) 0x11);
put((byte) 0x1A, (byte) 0x05); put("Susan");
put((byte) 0x1A, (byte) 0x01); put("B");
put((byte) 0x1A, (byte) 0x05); put("Jones");
//-date of birth
put((byte) 0xA0, (byte) 0x0A);
put((byte) 0x43, (byte) 0x08); put("19590717");
return buffer.array();
}
}
BufferOutput buffer = new BufferOutput();
return buffer.output();
}
}
|
/*
* Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License. See accompanying
* LICENSE file.
*/
package com.gemstone.gemfire.internal.cache;
import hydra.GsRandom;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import com.gemstone.gemfire.DataSerializable;
import com.gemstone.gemfire.cache.AttributesFactory;
import com.gemstone.gemfire.cache.Cache;
import com.gemstone.gemfire.cache.CacheException;
import com.gemstone.gemfire.cache.PartitionAttributesFactory;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache30.CacheSerializableRunnable;
import com.gemstone.gemfire.distributed.DistributedMember;
import dunit.Host;
import dunit.VM;
/**
* Confirm that the utils used for testing work as advertised
* @since 5.0
* @author mthomas
*
*/
public class PartitionedRegionTestUtilsDUnitTest extends
PartitionedRegionDUnitTestCase
{
final int totalNumBuckets = 5;
public PartitionedRegionTestUtilsDUnitTest(String name) {
super(name);
}
/**
* Test the {@link PartitionedRegion#getSomeKeys(Random)} method, making sure it
* returns keys when there are keys and {@link Collections#EMPTY_SET} when there are none.
* @throws Exception
*/
public void testGetKeys() throws Exception {
final String r = getUniqueName();
Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
VM vm2 = host.getVM(2);
CacheSerializableRunnable create = new CacheSerializableRunnable("CreatePartitionedRegion") {
public void run2() throws CacheException
{
Cache cache = getCache();
AttributesFactory attr = new AttributesFactory();
attr.setPartitionAttributes(new PartitionAttributesFactory()
.setTotalNumBuckets(totalNumBuckets)
.create());
Region p = cache.createRegion(r, attr.create());
assertNotNull(p);
assertTrue(!p.isDestroyed());
assertNull(p.get("Key"));
}
};
vm0.invoke(create);
vm1.invoke(create);
vm2.invoke(create);
vm0.invoke(new CacheSerializableRunnable("GetSomeKeys") {
public void run2() throws CacheException {
PartitionedRegion pr = (PartitionedRegion) getCache().getRegion(r);
GsRandom rand = new GsRandom(123);
// Assert that its empty
for(int i=0; i<5; i++) {
getLogWriter().info("Invocation " + i + " of getSomeKeys");
try {
Set s = null;
s = pr.getSomeKeys(rand);
assertNotNull(s);
assertTrue(s.isEmpty());
} catch (ClassNotFoundException cnfe) {
fail("GetSomeKeys failed with ClassNotFoundException", cnfe);
} catch (IOException ioe) {
fail("GetSomeKeys failed with IOException", ioe);
}
}
final int MAXKEYS=50;
for(int i=0; i<MAXKEYS; i++) {
pr.put("testKey" + i, new Integer(i));
}
// Assert not empty and has value in an accepable range
for(int i=0; i<5; i++) {
getLogWriter().info("Invocation " + i + " of getSomeKeys");
try {
Set s = null;
s = pr.getSomeKeys(rand);
assertNotNull(s);
assertFalse(s.isEmpty());
Integer val;
getLogWriter().info("Invocation " + i + " got " + s.size() + " keys");
for (Iterator it = s.iterator(); it.hasNext(); ) {
Object key = it.next();
getLogWriter().info("Key: " + key);
val = (Integer) pr.get(key);
assertNotNull(val);
assertTrue(val.intValue() >= 0);
assertTrue(val.intValue() < MAXKEYS);
}
} catch (ClassNotFoundException cnfe) {
fail("GetSomeKeys failed with ClassNotFoundException", cnfe);
} catch (IOException ioe) {
fail("GetSomeKeys failed with IOException", ioe);
}
}
}
});
}
/**
* Test the test method PartitionedRegion.getAllNodes
* Verify that it returns nodes after a value has been placed into the PartitionedRegion.
* @see PartitionedRegion#getAllNodes()
*
* @throws Exception
*/
public static class TestGetNodesKey implements DataSerializable {
int hc;
public TestGetNodesKey(int hc) { this.hc = hc; }
public TestGetNodesKey() {};
public int hashCode() {return this.hc; }
public void toData(DataOutput out) throws IOException {out.writeInt(this.hc); }
public void fromData(DataInput in) throws IOException, ClassNotFoundException { this.hc = in.readInt(); }
}
public void testGetNodes() throws Exception {
final String r = getUniqueName();
Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
VM validator = host.getVM(2);
CacheSerializableRunnable createAndTest = new CacheSerializableRunnable("CreatePRAndTestGetAllNodes") {
public void run2() throws CacheException
{
Cache cache = getCache();
AttributesFactory attr = new AttributesFactory();
attr.setPartitionAttributes(new PartitionAttributesFactory()
.setTotalNumBuckets(totalNumBuckets)
.create());
PartitionedRegion p = (PartitionedRegion) cache.createRegion(r, attr.create());
assertNotNull(p);
assertTrue(!p.isDestroyed());
// For each invocation, create a key that has a sequential hashCode.
// Putting this key into the PR should force a new bucket allocation on
// each new VM (assuming a mod on the hashCode), forcing the number of VMs to increase
// when we call getAllNodes each time this method is called.
Integer i = (Integer) p.get("Counter");
final Integer keyHash;
if (i == null) {
i = new Integer(0);
} else {
i = new Integer(i.intValue() + 1);
}
keyHash = i;
p.put("Counter", i);
p.put(new TestGetNodesKey(keyHash.intValue()), i);
Set allN = p.getAllNodes();
assertNotNull(allN);
assertTrue(! allN.isEmpty());
}
};
validator.invoke(createAndTest);
validator.invoke(new CacheSerializableRunnable("AssertGetNodesCreation1") {
public void run2() throws CacheException
{
PartitionedRegion p = (PartitionedRegion) getCache().getRegion(r);
assertNotNull(p);
assertTrue(!p.isDestroyed());
Set allN = p.getAllNodes();
assertNotNull(allN);
assertEquals(1, allN.size());
}}
);
vm0.invoke(createAndTest);
validator.invoke(new CacheSerializableRunnable("AssertGetNodesCreation2") {
public void run2() throws CacheException
{
PartitionedRegion p = (PartitionedRegion) getCache().getRegion(r);
assertNotNull(p);
assertTrue(!p.isDestroyed());
Set allN = p.getAllNodes();
assertNotNull(allN);
assertEquals(2, allN.size());
}}
);
vm1.invoke(createAndTest);
validator.invoke(new CacheSerializableRunnable("AssertGetNodesCreation3") {
public void run2() throws CacheException
{
PartitionedRegion p = (PartitionedRegion) getCache().getRegion(r);
assertNotNull(p);
assertTrue(!p.isDestroyed());
Set allN = p.getAllNodes();
assertNotNull(allN);
assertEquals(3, allN.size());
}}
);
}
/**
* Test the test utiltities that allow investigation of a PartitionedRegion's local cache.
* @throws Exception
*/
public void testLocalCacheOps() throws Exception {
final String r = getUniqueName();
Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
// VM vm1 = host.getVM(1);
VM vm2 = host.getVM(2);
vm0.invoke(new CacheSerializableRunnable("CreatePR") {
public void run2() throws CacheException
{
Cache cache = getCache();
AttributesFactory attr = new AttributesFactory();
attr.setPartitionAttributes(new PartitionAttributesFactory()
.setTotalNumBuckets(totalNumBuckets)
.setLocalMaxMemory(8)
.create());
PartitionedRegion p = (PartitionedRegion) cache.createRegion(r, attr.create());
assertNotNull(p);
}
});
// TODO enable this test when we have the LocalCache properly implemented -- mthomas 2/23/2006
// vm1.invoke(new CacheSerializableRunnable("CreatePRWithLocalCacheAndTestOps") {
// public void run2() throws CacheException
// {
// Cache cache = getCache();
// AttributesFactory attr = new AttributesFactory();
// attr.setScope(Scope.DISTRIBUTED_ACK);
// Properties lp = new Properties();
// lp.setProperty(PartitionAttributesFactory.LOCAL_MAX_MEMORY_PROPERTY, "0");
// attr.setPartitionAttributes(new PartitionAttributesFactory()
// .setLocalProperties(lp)
// .createPartitionAttributes());
//
// PartitionedRegion p = (PartitionedRegion) cache.createRegion(r, attr.create());
// assertNotNull(p);
//
// final String key1 = "lcKey1"; final String val1 = "lcVal1";
// final String key2 = "lcKey2"; final String val2 = "lcVal2";
// // Test localCacheContainsKey
// assertFalse(p.localCacheContainsKey(key1));
// assertFalse(p.localCacheContainsKey(key2));
// p.put(key1, val1);
// assertFalse(p.localCacheContainsKey(key1));
// assertFalse(p.localCacheContainsKey(key2));
// assertEquals(val1, p.get(key1));
// assertTrue(p.localCacheContainsKey(key1));
// assertFalse(p.localCacheContainsKey(key2));
//
// // test localCacheKeySet
// Set lset = p.localCacheKeySet();
// assertTrue(lset.contains(key1));
// assertFalse(lset.contains(key2));
//
// // test localCacheGet
// assertEquals(val1, p.localCacheGet(key1));
// assertNull(p.localCacheGet(key2));
// p.put(key2, val2);
// assertNull(p.localCacheGet(key2));
// assertEquals(val2, p.get(key2));
// assertEquals(val2, p.localCacheGet(key2));
// }
// });
vm2.invoke(new CacheSerializableRunnable("CreatePRWithNoLocalCacheAndTestOps") {
public void run2() throws CacheException
{
Cache cache = getCache();
AttributesFactory attr = new AttributesFactory();
attr.setPartitionAttributes(new PartitionAttributesFactory()
.setTotalNumBuckets(totalNumBuckets)
.setLocalMaxMemory(0)
.create());
PartitionedRegion p = (PartitionedRegion) cache.createRegion(r, attr.create());
assertNotNull(p);
final String key3 = "lcKey3"; final String val3 = "lcVal3";
final String key4 = "lcKey4"; final String val4 = "lcVal4";
// Test localCacheContainsKey
assertFalse(p.localCacheContainsKey(key3));
assertFalse(p.localCacheContainsKey(key4));
p.put(key3, val3);
assertFalse(p.localCacheContainsKey(key3));
assertFalse(p.localCacheContainsKey(key4));
assertEquals(val3, p.get(key3));
assertFalse(p.localCacheContainsKey(key3));
assertFalse(p.localCacheContainsKey(key4));
// test localCacheKeySet
Set lset = p.localCacheKeySet();
assertFalse(lset.contains(key3));
assertFalse(lset.contains(key4));
// test localCacheGet
assertNull(val3, p.localCacheGet(key3));
assertNull(p.localCacheGet(key4));
p.put(key4, val4);
assertNull(p.localCacheGet(key4));
assertEquals(val4, p.get(key4));
assertNull(p.localCacheGet(key4));
}
});
}
/**
* Test the test method PartitionedRegion.getAllNodes
* Verify that it returns nodes after a value has been placed into the PartitionedRegion.
* @see PartitionedRegion#getAllNodes()
*
* @throws Exception
*/
public void testGetBucketKeys() throws Exception {
final String r = getUniqueName();
Host host = Host.getHost(0);
VM vm2 = host.getVM(2);
VM vm3 = host.getVM(3);
CacheSerializableRunnable create = new CacheSerializableRunnable("CreatePR") {
public void run2() throws CacheException
{
Cache cache = getCache();
AttributesFactory attr = new AttributesFactory();
attr.setPartitionAttributes(new PartitionAttributesFactory()
.setTotalNumBuckets(totalNumBuckets)
.create());
PartitionedRegion p = (PartitionedRegion) cache.createRegion(r, attr.create());
assertNotNull(p);
}
};
vm2.invoke(create);
vm3.invoke(create);
// Create an accessor
Cache cache = getCache();
AttributesFactory attr = new AttributesFactory();
attr.setPartitionAttributes(new PartitionAttributesFactory()
.setTotalNumBuckets(totalNumBuckets)
.setLocalMaxMemory(0)
.create());
PartitionedRegion p = (PartitionedRegion) cache.createRegion(r, attr.create());
assertNotNull(p);
final int totalBucks = p.getTotalNumberOfBuckets();
for (int i=totalBucks-1; i>=0; i--) {
Set s = p.getBucketKeys(i);
assertTrue(s.isEmpty());
}
class TestPRKey implements Serializable {
int hashCode;
int differentiator;
TestPRKey(int hash, int differentiator) {
this.hashCode = hash;
this.differentiator = differentiator;
}
public int hashCode() {return hashCode; }
public boolean equals(Object obj) {
if (! (obj instanceof TestPRKey)) {
return false;
}
return ((TestPRKey) obj).differentiator == this.differentiator;
}
public String toString() { return "TestPRKey " + hashCode + " diff " + differentiator; }
}
TestPRKey key;
Integer val;
// Create bucket number of keys, assuming a modulous per key hashCode
// There should be one key per bucket
p.put(new TestPRKey(0, 1), new Integer(0));
p.put(new TestPRKey(0, 2), new Integer(1));
p.put(new TestPRKey(0, 3), new Integer(2));
Set s = p.getBucketKeys(0);
assertEquals(3, s.size());
assertEquals(0, ((TestPRKey) s.iterator().next()).hashCode());
assertEquals(0, ((TestPRKey) s.iterator().next()).hashCode());
assertEquals(0, ((TestPRKey) s.iterator().next()).hashCode());
// Skip bucket zero since we have three keys there, but fill out all the rest with keys
for (int i=totalBucks-1; i>0; i--) {
key = new TestPRKey(i, 0);
val = new Integer(i);
p.put(key, val);
// Integer gottenVal = (Integer) p.get(key);
// assertEquals("Value for key: " + key + " val " + gottenVal + " wasn't expected " + val, val, gottenVal);
}
// Assert that the proper number of keys are placed in each bucket
for (int i=1; i<totalBucks; i++) {
s = p.getBucketKeys(i);
assertEquals(s.size(), 1);
key = (TestPRKey) s.iterator().next();
assertEquals(i, key.hashCode());
// assertEquals(new Integer(i), p.get(key));
}
}
/**
* Test the test method {@link PartitionedRegion#getBucketOwnersForValidation(int)}
* Verify that the information it discovers is the same as the local advisor.
* @throws Exception
*/
public void testGetBucketOwners() throws Exception {
final String rName0 = getUniqueName() + "-r0";
final String rName1 = getUniqueName() + "-r1";
final String rName2 = getUniqueName() + "-r2";
final String[] regions = {rName0, rName1, rName2};
final int numBuckets = 3;
final Host host = Host.getHost(0);
final VM datastore1 = host.getVM(2);
final VM datastore2 = host.getVM(3);
final VM datastore3 = host.getVM(0);
final VM accessor = host.getVM(1);
final CacheSerializableRunnable create = new CacheSerializableRunnable("CreatePR") {
public void run2() throws CacheException
{
Cache cache = getCache();
AttributesFactory attr = new AttributesFactory();
PartitionAttributesFactory paf = new PartitionAttributesFactory()
.setTotalNumBuckets(numBuckets);
for (int redundancy = 0; redundancy < regions.length; redundancy++) {
paf.setRedundantCopies(redundancy);
attr.setPartitionAttributes(paf.create());
PartitionedRegion p =
(PartitionedRegion) cache.createRegion(regions[redundancy], attr.create());
assertNotNull(p);
assertEquals(0, p.size());
}
}
};
datastore1.invoke(create);
datastore2.invoke(create);
datastore3.invoke(create);
accessor.invoke(new CacheSerializableRunnable("CreateAccessorPR") {
public void run2() throws CacheException
{
Cache cache = getCache();
AttributesFactory attr = new AttributesFactory();
PartitionAttributesFactory paf = new PartitionAttributesFactory()
.setTotalNumBuckets(numBuckets)
.setLocalMaxMemory(0);
for (int redundancy = 0; redundancy < regions.length; redundancy++) {
paf.setRedundantCopies(redundancy);
attr.setPartitionAttributes(paf.create());
PartitionedRegion p =
(PartitionedRegion) cache.createRegion(regions[redundancy], attr.create());
assertNotNull(p);
assertEquals(0, p.size());
}
}
});
final CacheSerializableRunnable noBucketOwners = new CacheSerializableRunnable("AssertNoBucketOwners") {
public void run2() throws CacheException
{
String[] regions = {rName0, rName1, rName2};
for (int rs = 0; rs < regions.length; rs++) {
PartitionedRegion p = (PartitionedRegion) getCache().getRegion(regions[rs]);
assertNotNull(p);
assertTrue(!p.isDestroyed());
assertEquals(numBuckets, p.getTotalNumberOfBuckets());
try {
for(int i = 0; i < p.getTotalNumberOfBuckets(); i++) {
assertEquals(0, p.getRegionAdvisor().getBucketOwners(i).size());
assertEquals(0, p.getBucketOwnersForValidation(i).size());
}
} catch (ForceReattemptException noGood) {
fail("Unexpected force retry", noGood);
}
}
}
};
datastore1.invoke(noBucketOwners);
datastore2.invoke(noBucketOwners);
datastore3.invoke(noBucketOwners);
accessor.invoke(noBucketOwners);
accessor.invoke(new CacheSerializableRunnable("CreateOneBucket") {
public void run2() throws CacheException
{
for (int rs = 0; rs < regions.length; rs++) {
PartitionedRegion p = (PartitionedRegion) getCache().getRegion(regions[rs]);
assertNotNull(p);
assertEquals(3, p.getTotalNumberOfBuckets());
// Create one bucket
p.put(new Integer(0), "zero");
assertEquals(1, p.getRegionAdvisor().getCreatedBucketsCount());
}
}
});
final CacheSerializableRunnable oneBucketOwner = new CacheSerializableRunnable("AssertSingleBucketPrimary") {
public void run2() throws CacheException
{
for (int rs = 0; rs < regions.length; rs++) {
PartitionedRegion p = (PartitionedRegion) getCache().getRegion(regions[rs]);
try {
for(Iterator it = p.getRegionAdvisor().getBucketSet().iterator(); it.hasNext(); ) {
Integer bid = (Integer) it.next();
assertEquals(p.getRedundantCopies() + 1, p.getRegionAdvisor().getBucketOwners(bid.intValue()).size());
List prims = p.getBucketOwnersForValidation(bid.intValue());
assertEquals(p.getRedundantCopies() + 1, prims.size());
int primCount = 0;
for (Iterator lit = prims.iterator(); lit.hasNext(); ) {
Object[] memAndBoolean = (Object[]) lit.next();
assertEquals(3, memAndBoolean.length); // memberId, isPrimary and hostToken(new)
assertTrue(memAndBoolean[0] instanceof DistributedMember);
assertEquals(Boolean.class, memAndBoolean[1].getClass());
Boolean isPrimary = (Boolean) memAndBoolean[1];
if (isPrimary.booleanValue()) {
primCount++;
}
}
assertEquals(1, primCount);
}
} catch (ForceReattemptException noGood) {
fail("Unexpected force retry", noGood);
}
}
}
};
accessor.invoke(oneBucketOwner);
datastore1.invoke(oneBucketOwner);
datastore2.invoke(oneBucketOwner);
datastore3.invoke(oneBucketOwner);
}
}
|
package com.raytheon.uf.edex.plugin.scan.process;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;
import com.raytheon.uf.common.dataplugin.persist.PersistablePluginDataObject;
import com.raytheon.uf.common.dataplugin.radar.RadarRecord;
import com.raytheon.uf.common.dataplugin.radar.util.RadarConstants;
import com.raytheon.uf.common.dataplugin.radar.util.RadarConstants.MapValues;
import com.raytheon.uf.common.dataplugin.radar.util.TiltAngleBin;
import com.raytheon.uf.common.dataplugin.scan.data.CellTableData;
import com.raytheon.uf.common.dataplugin.scan.data.CellTableDataRow;
import com.raytheon.uf.common.dataplugin.scan.data.DMDTableData;
import com.raytheon.uf.common.dataplugin.scan.data.DMDTableDataRow;
import com.raytheon.uf.common.dataplugin.scan.data.ScanTableData;
import com.raytheon.uf.common.dataplugin.scan.data.ScanTableDataRow;
import com.raytheon.uf.common.dataplugin.scan.data.TVSTableDataRow;
import com.raytheon.uf.common.monitor.scan.config.SCANConfigEnums.ScanTables;
import com.raytheon.uf.common.monitor.scan.xml.ScanAlarmXML;
import com.raytheon.uf.common.status.UFStatus.Priority;
import com.raytheon.uf.edex.core.EDEXUtil;
import com.raytheon.uf.edex.plugin.scan.ScanURIFilter;
/**
*
* Process incoming TVS Tabular data
*
* <pre>
* SOFTWARE HISTORY
* Date Ticket# Engineer Description
* ------------ -------- ---------- --------------------------
* 05/07/2009 2037 dhladky Initial Creation.
* 11/13/2012 14368 Xiaochuan Required to set alarm time in a quiet time period
* from the last event to new event (new storm come in).
* Aug 31, 2017 6408 njensen Keep product's specific valid time
*
* </pre>
*
* @author dhladky
*/
public class TVSTabularProduct extends RadarProduct {
private static final long serialVersionUID = 1L;
/** TVS Tabular prod ID */
public static final String TVS = "61";
// radar server sends messages from edex to cave, handle that here
private static final String SCAN = "SCAN";
private static Date previousTime = null;
/**
*
* @param uri
* @param tableType
* @param filter
*/
public TVSTabularProduct(String uri, ScanTables tableType,
ScanURIFilter filter) {
super(uri, tableType, filter);
}
@Override
public void process() throws Exception {
RadarRecord rec = getRecord();
ScanTableData<ScanTableDataRow> table = getTableData();
// DR 6408: Keep the times for each product separate
filter.setTvsValidTime(rec.getDataTime().getRefTime());
table.setVolScanTime(rec.getDataTime().getRefTime());
table.setVcp(rec.getVolumeCoveragePattern());
/**
* Sets elevation angle
*/
if (rec.getTrueElevationAngle() != null) {
filter.setTvsTilt(TiltAngleBin.getPrimaryElevationAngle(rec
.getTrueElevationAngle()));
table.setTrueAngle(rec.getTrueElevationAngle().doubleValue());
}
if (getTableType().equals(ScanTables.TVS)) {
List<String> tvsKeys = rec.getIds(MapValues.TVS_TYPE);
// first check for alarms
if (tvsKeys != null) {
ScanAlarmXML alarms = filter.getAlarmData();
StringBuilder alarmString = null;
if (previousTime == null) {
previousTime = rec.getDataTime().getRefTime();
}
if (!tvsKeys.isEmpty() && alarms != null) {
if ((alarms.getTvsAlarmTime() * 60 * 1000) <= (rec
.getDataTime().getRefTime().getTime() - previousTime
.getTime())) {
alarmString = new StringBuilder();
alarmString.append("NEW TVS for " + filter.getIcao()
+ " over the last " + alarms.getTvsAlarmTime()
+ " minutes.");
// TVS always gets displayed regardless, no checks
// necessary
EDEXUtil.sendMessageAlertViz(Priority.CRITICAL,
RadarConstants.PLUGIN_ID, SCAN, "RADAR",
alarmString.toString(), null, null);
}
previousTime = rec.getDataTime().getRefTime();
}
}
// remove all rows regardless of age, we need it to blank
for (String fid : table.getTableData().keySet()) {
// System.out.println("Removing TVS FID: " + fid);
table.removeRow(fid);
}
// add all rows in TVS product
if (tvsKeys != null) {
table.setFeatureIds(tvsKeys);
for (String fid : tvsKeys) {
// System.out.println("Adding TVS FID: " + fid);
table.addRow(
fid,
write(new TVSTableDataRow(rec.getDataTime()), rec,
fid));
}
}
}
filter.getRadarData().setRadarRecord(TVS, rec);
}
@Override
public ScanTableDataRow write(ScanTableDataRow row,
PersistablePluginDataObject rec, String key) {
row = setSpatial(row, key, rec);
row.setIdent(key);
if (((RadarRecord) rec).getProductVals(
RadarConstants.MapValues.TVS_TYPE, key,
RadarConstants.MapValues.STORM_ID) != null) {
((TVSTableDataRow) row).setStrmID(((RadarRecord) rec)
.getProductVals(RadarConstants.MapValues.TVS_TYPE, key,
RadarConstants.MapValues.STORM_ID));
}
if (((RadarRecord) rec).getProductVals(
RadarConstants.MapValues.TVS_TYPE, key,
RadarConstants.MapValues.TVS_FEATURE_TYPE) != null) {
((TVSTableDataRow) row).setType(((RadarRecord) rec).getProductVals(
RadarConstants.MapValues.TVS_TYPE, key,
RadarConstants.MapValues.TVS_FEATURE_TYPE));
updateTables(((RadarRecord) rec).getProductVals(
RadarConstants.MapValues.TVS_TYPE, key,
RadarConstants.MapValues.STORM_ID),
((RadarRecord) rec).getProductVals(
RadarConstants.MapValues.TVS_TYPE, key,
RadarConstants.MapValues.TVS_FEATURE_TYPE));
}
if (((RadarRecord) rec).getProductVals(
RadarConstants.MapValues.TVS_TYPE, key,
RadarConstants.MapValues.TVS_BASE) != null) {
String base = ((RadarRecord) rec).getProductVals(
RadarConstants.MapValues.TVS_TYPE, key,
RadarConstants.MapValues.TVS_BASE);
if (base.startsWith("<") || base.startsWith(">")) {
base = base.substring(1, base.length());
}
((TVSTableDataRow) row).setBase(new Double(base));
}
if (((RadarRecord) rec).getProductVals(
RadarConstants.MapValues.TVS_TYPE, key,
RadarConstants.MapValues.TVS_TOP) != null) {
String top = ((RadarRecord) rec).getProductVals(
RadarConstants.MapValues.TVS_TYPE, key,
RadarConstants.MapValues.TVS_TOP);
if (top.startsWith("<") || top.startsWith(">")) {
top = top.substring(1, top.length());
}
((TVSTableDataRow) row).setTop(new Double(top));
}
if (((RadarRecord) rec).getProductVals(
RadarConstants.MapValues.TVS_TYPE, key,
RadarConstants.MapValues.TVS_DEPTH) != null) {
String depth = ((RadarRecord) rec).getProductVals(
RadarConstants.MapValues.TVS_TYPE, key,
RadarConstants.MapValues.TVS_DEPTH);
if (depth.startsWith("<") || depth.startsWith(">")) {
depth = depth.substring(1, depth.length());
}
((TVSTableDataRow) row).setDepth(new Double(depth));
}
if (((RadarRecord) rec).getProductVals(
RadarConstants.MapValues.TVS_TYPE, key,
RadarConstants.MapValues.TVS_LLDV) != null) {
((TVSTableDataRow) row).setLlDV((new Double(((RadarRecord) rec)
.getProductVals(RadarConstants.MapValues.TVS_TYPE, key,
RadarConstants.MapValues.TVS_LLDV))));
}
if (((RadarRecord) rec).getProductVals(
RadarConstants.MapValues.TVS_TYPE, key,
RadarConstants.MapValues.TVS_AVGDV) != null) {
((TVSTableDataRow) row).setAvgDv((new Double(((RadarRecord) rec)
.getProductVals(RadarConstants.MapValues.TVS_TYPE, key,
RadarConstants.MapValues.TVS_AVGDV))));
}
if (((RadarRecord) rec).getProductVals(
RadarConstants.MapValues.TVS_TYPE, key,
RadarConstants.MapValues.TVS_MXDV) != null) {
((TVSTableDataRow) row).setMaxDV((new Double(((RadarRecord) rec)
.getProductVals(RadarConstants.MapValues.TVS_TYPE, key,
RadarConstants.MapValues.TVS_MXDV))));
}
if (((RadarRecord) rec).getProductVals(
RadarConstants.MapValues.TVS_TYPE, key,
RadarConstants.MapValues.TVS_DVHGT) != null) {
((TVSTableDataRow) row).setMaxDvHt(new Double(((RadarRecord) rec)
.getProductVals(RadarConstants.MapValues.TVS_TYPE, key,
RadarConstants.MapValues.TVS_DVHGT)));
}
if (((RadarRecord) rec).getProductVals(
RadarConstants.MapValues.TVS_TYPE, key,
RadarConstants.MapValues.TVS_MXSHR) != null) {
((TVSTableDataRow) row).setShear(new Double(((RadarRecord) rec)
.getProductVals(RadarConstants.MapValues.TVS_TYPE, key,
RadarConstants.MapValues.TVS_MXSHR)));
}
if (((RadarRecord) rec).getProductVals(
RadarConstants.MapValues.TVS_TYPE, key,
RadarConstants.MapValues.TVS_SHRHGT) != null) {
((TVSTableDataRow) row).setShrHt(new Double(((RadarRecord) rec)
.getProductVals(RadarConstants.MapValues.TVS_TYPE, key,
RadarConstants.MapValues.TVS_SHRHGT)));
}
return row;
}
@Override
public boolean getAllowNew() {
return true;
}
/**
* TVS URI Pattern, Tornadoes
*
* @return
*/
public static Pattern getPattern(String icao, double tiltAngle) {
return Pattern.compile("^" + uriSeparator + RADAR + uriSeparator
+ wildCard + uriSeparator + icao + uriSeparator + TVS
+ uriSeparator + tiltAngle + uriSeparator + layer);
}
/**
* Gets the SQL for lookup
*
* @param icao
* @return
*/
public static String getSQL(String icao, double tiltAngle, int interval) {
return "select datauri from radar where icao = \'" + icao
+ "\' and productcode = " + TVS
+ " and primaryelevationangle = " + tiltAngle
+ " and reftime > (now()- interval \'" + interval
+ " minutes\')";
}
/**
* Updates the Cell & DMD Tables with the TVS value
*
* @param ident
* @param TVS
*/
private void updateTables(String ident, String tvs) {
if ((ident != null) && (tvs != null)) {
CellTableData<?> ctable = (CellTableData<?>) filter
.getData(ScanTables.CELL);
if (ctable != null) {
if (ctable.getTableData().contains(ident)) {
((CellTableDataRow) ctable.getRow(ident)).setTvs(tvs);
}
}
DMDTableData<?> dtable = (DMDTableData<?>) filter
.getData(ScanTables.DMD);
if (dtable != null) {
for (Object id : dtable.getTableData().keySet()) {
if (((DMDTableDataRow) dtable.getRow((String) id))
.getStrmID().equals(ident)) {
((DMDTableDataRow) dtable.getRow((String) id))
.setTvs(tvs);
}
}
}
}
}
}
|
/*
* Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.huawei.wallet.hms.eventticket;
import com.huawei.wallet.hms.ServerApiService;
import com.huawei.wallet.hms.ServerApiServiceImpl;
import com.huawei.wallet.util.ConfigUtil;
import com.huawei.wallet.util.HwWalletObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.junit.Test;
/**
* Event ticket model tests.
*
* @since 2019-12-12
*/
public class EventTicketModelTest {
private final ServerApiService serverApiService = new ServerApiServiceImpl();
/**
* Create a new event ticket model.
* Each event ticket model indicates a style of event ticket passes.
* POST http://XXX/hmspass/v1/eventticket/model
*/
@Test
public void createEventTicketModel() {
System.out.println("createEventTicketModel begin.");
// Read an event ticket model from a JSON file.
JSONObject model = JSONObject.parseObject(ConfigUtil.readFile("EventTicketModel.json"));
// Validate parameters.
HwWalletObjectUtil.validateModel(model);
// Post the new event ticket model to HMS wallet server.
String urlSegment = "eventticket/model";
JSONObject responseModel = serverApiService.postToWalletServer(urlSegment, JSONObject.toJSONString(model));
System.out.println("Posted event ticket model: " + JSONObject.toJSONString(responseModel));
}
/**
* Get an event ticket model by its model ID.
* Run the "createEventTicketModel" test before running this test.
* GET http://xxx/hmspass/v1/eventticket/model/{modelId}
*/
@Test
public void getEventTicketModel() {
System.out.println("getEventTicketModel begin.");
// ID of the event ticket model you want to get.
String modelId = "EventTicketModelTest";
// Get the event ticket model.
String urlSegment = "eventticket/model/";
JSONObject responseModel = serverApiService.getHwWalletObjectById(urlSegment, modelId);
System.out.println("Corresponding event ticket model: " + JSONObject.toJSONString(responseModel));
}
/**
* Get event ticket models belonging to a specific appId.
* Run the "createEventTicketModel" test before running this test.
* GET http://xxx/hmspass/v1/eventticket/model?session=XXX&pageSize=XXX
*/
@Test
public void getEventTicketModelList() {
System.out.println("getEventTicketModelList begin.");
// Get a list of event ticket models.
String urlSegment = "eventticket/model";
JSONArray models = serverApiService.getModels(urlSegment, 5);
System.out.println("Total models count: " + models.size());
System.out.println("Models list: " + models.toJSONString());
}
/**
* Overwrite an event ticket model.
* Run the "createEventTicketModel" test before running this test.
* PUT http://xxx/hmspass/v1/eventticket/model/{modelId}
*/
@Test
public void fullUpdateEventTicketModel() {
System.out.println("fullUpdateEventTicketModel begin.");
// Read a HwWalletObject from a JSON file. This HwWalletObject will overwrite the corresponding model.
JSONObject model = JSONObject.parseObject(ConfigUtil.readFile("FullUpdateEventTicketModel.json"));
// Validate parameters.
HwWalletObjectUtil.validateModel(model);
// Update the event ticket model.
String urlSegment = "eventticket/model/";
JSONObject responseModel = serverApiService.fullUpdateHwWalletObject(urlSegment,
model.getString("passStyleIdentifier"), JSONObject.toJSONString(model));
System.out.println("Updated event ticket model: " + JSONObject.toJSONString(responseModel));
}
/**
* Update an event ticket model.
* Run the "createEventTicketModel" test before running this test.
* PATCH http://xxx/hmspass/v1/eventticket/model/{modelId}
*/
@Test
public void partialUpdateEventTicketModel() {
System.out.println("partialUpdateEventTicketModel begin.");
// ID of the event ticket model you want to update.
String modelId = "eventTicketModelTest";
// Read a HwWalletObject from a JSON file. This HwWalletObject will merge with the corresponding model.
String modelStr = ConfigUtil.readFile("PartialUpdateEventTicketModel.json");
// Update the event ticket model.
String urlSegment = "eventticket/model/";
JSONObject responseModel = serverApiService.partialUpdateHwWalletObject(urlSegment, modelId, modelStr);
System.out.println("Updated event ticket model: " + JSONObject.toJSONString(responseModel));
}
/**
* Add messages to an event ticket model.
* Run the "createEventTicketModel" test before running this test.
* POST http://xxx/hmspass/v1/eventticket/model/{modelId}/addMessage
*/
@Test
public void addMessageToEventTicketModel() {
System.out.println("addMessageToEventTicketModel begin.");
// ID of the event ticket model you want to update.
String modelId = "eventTicketModelTest";
// Create a list of messages you want to add to a model. Each message contains key, value, and label.
// The list should not contain multiple messages with the same key. You can update an existing message by adding
// a new message with the same key. One model contains at most 10 messages. If a model already have 10 messages
// and you keep adding new messages, the oldest messages will be removed. You should not add more than 10
// messages at a time.
// Read messages from a JSON file.
String messagesStr = ConfigUtil.readFile("Messages.json");
// Add messages to the event ticket model.
String urlSegment = "eventticket/model/";
JSONObject responseModel = serverApiService.addMessageToHwWalletObject(urlSegment, modelId, messagesStr);
System.out.println("Updated event ticket model: " + JSONObject.toJSONString(responseModel));
}
}
|
/**
Classes and object identifiers related to the German BSI standard BSI-TR-03111.
*/
package org.bouncycastle.asn1.bsi;
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.shardingsphere.infra.metadata.schema.fixture.rule;
import org.apache.shardingsphere.infra.datanode.DataNode;
import org.apache.shardingsphere.infra.rule.identifier.type.DataNodeContainedRule;
import org.apache.shardingsphere.infra.rule.identifier.type.TableContainedRule;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
public final class DataNodeContainedFixtureRule implements DataNodeContainedRule, TableContainedRule {
private final Map<String, String> actualTableNameMaps = new HashMap<>(4, 1);
public DataNodeContainedFixtureRule() {
actualTableNameMaps.putIfAbsent("data_node_routed_table1_0", "data_node_routed_table1");
actualTableNameMaps.putIfAbsent("data_node_routed_table1_1", "data_node_routed_table1");
actualTableNameMaps.putIfAbsent("data_node_routed_table2_0", "data_node_routed_table2");
actualTableNameMaps.putIfAbsent("data_node_routed_table2_1", "data_node_routed_table2");
}
@Override
public Map<String, Collection<DataNode>> getAllDataNodes() {
return Collections.emptyMap();
}
@Override
public Collection<DataNode> getDataNodesByTableName(final String tableName) {
return Collections.emptyList();
}
@Override
public Optional<String> findFirstActualTable(final String logicTable) {
return Optional.empty();
}
@Override
public boolean isNeedAccumulate(final Collection<String> tables) {
return false;
}
@Override
public Optional<String> findLogicTableByActualTable(final String actualTable) {
return Optional.ofNullable(actualTableNameMaps.get(actualTable));
}
@Override
public Collection<String> getTables() {
return new HashSet<>(actualTableNameMaps.values());
}
@Override
public Optional<String> findActualTableByCatalog(final String catalog, final String logicTable) {
return Optional.empty();
}
@Override
public Collection<String> getAllTables() {
return Collections.emptyList();
}
@Override
public String getType() {
return DataNodeContainedFixtureRule.class.getSimpleName();
}
}
|
package de.illonis.eduras.settings;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import de.illonis.edulog.EduLog;
import de.illonis.eduras.EdurasServer;
import de.illonis.eduras.actions.CreateUnitAction;
import de.illonis.eduras.actions.HealSpellAction;
import de.illonis.eduras.actions.RespawnPlayerAction;
import de.illonis.eduras.actions.ScoutSpellAction;
import de.illonis.eduras.actions.SpawnItemAction;
import de.illonis.eduras.gameobjects.BigBlock;
import de.illonis.eduras.gameobjects.BiggerBlock;
import de.illonis.eduras.gameobjects.Bird;
import de.illonis.eduras.items.weapons.AssaultMissile;
import de.illonis.eduras.items.weapons.AssaultRifle;
import de.illonis.eduras.items.weapons.MineMissile;
import de.illonis.eduras.items.weapons.MineWeapon;
import de.illonis.eduras.items.weapons.Missile;
import de.illonis.eduras.items.weapons.RocketLauncher;
import de.illonis.eduras.items.weapons.RocketMissile;
import de.illonis.eduras.items.weapons.SimpleMissile;
import de.illonis.eduras.items.weapons.SimpleWeapon;
import de.illonis.eduras.items.weapons.SniperMissile;
import de.illonis.eduras.items.weapons.SniperWeapon;
import de.illonis.eduras.items.weapons.SplashMissile;
import de.illonis.eduras.items.weapons.SplashWeapon;
import de.illonis.eduras.items.weapons.SplashedMissile;
import de.illonis.eduras.items.weapons.SwordMissile;
import de.illonis.eduras.items.weapons.SwordWeapon;
import de.illonis.eduras.units.Observer;
import de.illonis.eduras.units.PlayerMainFigure;
/**
* This class holds all flexible settings.
*
* @author Florian Mai <florian.ren.mai@googlemail.com>
*
*/
public final class S {
private final static Logger L = EduLog.getLoggerFor(EdurasServer.class
.getName());
/**
* custom resource folder (empty = default)
*/
public static String resource_folder = "";
/**
* Indicates that application was started from eclipse. Usually set using
* "debug" command line flag.
*/
public static boolean fromEclipse = false;
/**
* Holds the settings that are relevant to the server and must be kept
* synchronized on server and client.
*
* @author Florian Mai <florian.ren.mai@googlemail.com>
*
*/
public static class Server {
// real values
/**
* Max distance of an AI object to its destination at which the target
* is assumed to be reached.
*/
public static double ai_target_reached_distance = 5;
/**
* Denotes the interval in which an AI object's motion behavior is
* updated by the AI.
*/
public static long ai_motion_update_interval = 20;
/**
* Denotes the width of a {@link BigBlock} object.
*/
public static int go_big_block_width = 20;
/**
* Denotes the height of a {@link BigBlock} object.
*/
public static int go_big_block_height = 20;
/**
* Denotes the width of a {@link BiggerBlock} object.
*/
public static int go_bigger_block_width = 40;
/**
* Denotes the height of a {@link BiggerBlock} object.
*/
public static int go_bigger_block_height = 40;
/**
* The speed of a {@link Bird} object.
*/
public static float go_bird_speed = 40;
/**
* Tells whether a {@link Bird} is collidable or not.
*/
public static boolean go_bird_collidable = false;
/**
* Max number of items a {@link PlayerMainFigure} can carry.
*/
public static int player_max_item_capacity = 10;
/**
* Denotes the size of a {@link Missile} object.
*/
public static float go_missile_radius = 5;
/**
* Damage caused by one {@link SimpleMissile} object.
*/
public static int go_simplemissile_damage = 5;
/**
* Area Of Effect of a {@link SimpleMissile} object.
*/
public static float go_simplemissile_damage_radius = 5;
/**
* Speed of a {@link SimpleMissile} object.
*/
public static float go_simplemissile_speed = 100;
/**
* Denotes how far a {@link SimpleMissile} object can go before it
* disappears.
*/
public static float go_simplemissile_maxrange = 200;
/**
* Denotes the size of a {@link SimpleWeapon} object.
*/
public static float go_simpleweapon_shape_radius = 10;
/**
* Cooldown of a {@link SimpleWeapon}.
*/
public static long go_simpleweapon_cooldown = 300;
/**
* Damage caused by a {@link SniperMissile}.
*/
public static int go_snipermissile_damage = 16;
/**
* Area of Effect of a {@link SniperMissile}.
*/
public static float go_snipermissile_damageradius = 1;
/**
* Radius of the shape of a {@link SniperMissile} object.
*/
public static float go_snipermissile_shape_radius = 1.5f;
/**
* Speed of a {@link SniperMissile}.
*/
public static float go_snipermissile_speed = 500;
/**
* Size (radius) of a {@link SniperWeapon} object.
*/
public static float go_sniperweapon_shape_radius = 5;
/**
* Cooldown of {@link SniperWeapon} item.
*/
public static long go_sniperweapon_cooldown = 1050;
/**
* Damage caused by one {@link SplashedMissile} object.
*/
public static int go_splashedmissile_damage = 30;
/**
* Area of Effect of {@link SplashedMissile}.
*/
public static float go_splashedmissile_damageradius = 100;
/**
* Size (radius) of {@link SplashedMissile}.
*/
public static float go_splashedmissile_shape_radius = 3;
/**
* Speed of a {link SplashedMissile}.
*/
public static float go_splashedmissile_speed = 250;
/**
* Damage caused by a {@link SplashMissile}.
*/
public static int go_splashmissile_damage = 7;
/**
* Area of Effect of {@link SplashMissile}.
*/
public static float go_splashmissile_damageradius = 1;
/**
* Size (radius) of {@link SplashMissile}.
*/
public static float go_splashmissile_shape_radius = 5;
/**
* Speed of a {link SplashMissile}.
*/
public static float go_splashmissile_speed = 250;
/**
* Size (radius) of a {link SplashWeapon}.
*/
public static float go_splashweapon_shape_radius = 7;
/**
* Denotes the cooldown when you use a {@link SplashWeapon}.
*/
public static long go_splashweapon_cooldown = 900;
/**
* Damage caused by a {@link SwordMissile}.
*/
public static int go_swordmissile_damage = 2;
/**
* Area of Effect of {@link SwordMissile}.
*/
public static float go_swordmissile_damageradius = 1;
/**
* Speed of {@link SwordMissile}.
*/
public static float go_swordmissile_speed = 100;
/**
* Denotes how far a {@link SwordMissile} can go before it disappears.
*/
public static float go_swordmissile_maxrange = 10;
/**
* Size (radius) of {@link SwordMissile}.
*/
public static float go_swordweapon_shape_radius = 7;
/**
* Denotes the cooldown of the {@link SwordWeapon} before you can use it
* again.
*/
public static long go_swordweapon_cooldown = 100;
/**
* Denotes the default respawn time of all weapons.
*/
public static long go_weapon_respawntime_default = 5000;
/**
* Says how much health a {@link PlayerMainFigure} can have at maximum.
*/
public static int player_maxhealth_default = 30;
/**
* Base speed of a {@link PlayerMainFigure}.
*/
public static float player_speed_default = 50;
/**
* Tells in how many {@link SplashedMissile}s a {@link SplashMissile}
* breaks after hitting something.
*/
public static int go_splashmissile_splinters = 10;
/**
* Rotation gets updated only when it has changed by an angle at least
* this big.
*/
public static double sv_performance_rotationdelta_minimum = 5;
/**
* Denotes the cooldown of a {@link RocketLauncher}.
*/
public static long go_rocketlauncher_cooldown = 3000;
/**
* Area Of Effect of a {@link RocketMissile}.
*/
public static float go_rocketmissile_damageradius = 100;
/**
* Damage caused by a {@link RocketMissile}.
*/
public static int go_rocketmissile_damage = 12;
/**
* Speed of a {@link RocketMissile}.
*/
public static float go_rocketmissile_speed = 150;
/**
* Denotes how far a {@link RocketMissile} can go before it disappears.
*/
public static float go_rocketmissile_maxrange = 400;
/**
* Size (radius) of a {@link MineWeapon}.
*/
public static float go_mineweapon_size = 5;
/**
* Cooldown of {@link MineWeapon}.
*/
public static long go_mineweapon_cooldown = 500;
/**
* Damage caused by a single {@link MineMissile}.
*/
public static int go_minemissile_damage = 6;
/**
* Area Of Effect of a {@link MineMissile}.
*/
public static float go_minemissile_damageradius = 50;
/**
* Speed of a {@link MineMissile}.
*/
public static float go_minemissile_speed = 0;
/**
* Denotes how far a {@link MineMissile} can go before it disappears.
*/
public static float go_minemissile_maxrange = 1;
/**
* Size (radius) of a {@link MineMissile}.
*/
public static float go_minemissile_shape_size = 2;
/**
* Denotes by how much the {@link SplashWeapon}'s ammunition is filled
* up when collecting it.
*/
public static int go_splashweapon_fillamount = 5;
/**
* Denotes the upper limit of how many bullets of a {@link SplashWeapon}
* can be carried.
*/
public static int go_splashweapon_maxammo = 50;
/**
* Denotes by how much the {@link SniperWeapon}'s ammunition is filled
* up when collecting it.
*/
public static int go_sniperweapon_fillamount = 5;
/**
* Denotes the upper limit of how many bullets of a {@link SniperWeapon}
* can be carried.
*/
public static int go_sniperweapon_maxammo = 20;
/**
* Denotes by how much the {@link RocketLauncher}'s ammunition is filled
* up when collecting it.
*/
public static int go_rocketlauncher_fillamount = 6;
/**
* Denotes the upper limit of how many bullets of a
* {@link RocketLauncher} can be carried.
*/
public static int go_rocketlauncher_maxammo = 60;
/**
* Denotes by how much the {@link MineWeapon}'s ammunition is filled up
* when collecting it.
*/
public static int go_mineweapon_fillamount = 3;
/**
* Denotes the upper limit of how many bullets of a {@link MineWeapon}
* can be carried.
*/
public static int go_mineweapon_maxammo = 30;
/**
* Denotes by how much the {@link SimpleWeapon}'s ammunition is filled
* up when collecting it.
*/
public static int go_simpleweapon_fillamount = 25;
/**
* Denotes the upper limit of how many bullets of a {@link SimpleWeapon}
* can be carried.
*/
public static int go_simpleweapon_maxammo = 200;
/**
* Size (radius) of an {@link AssaultRifle}.
*/
public static float go_assaultrifle_shape_size = 5;
/**
* Cooldown of the {@link AssaultRifle}.
*/
public static long go_assaultrifle_cooldown = 200;
/**
* Denotes by how much the {@link AssaultRifle}'s ammunition is filled
* up when collecting it.
*/
public static int go_assaultrifle_fillamount = 50;
/**
* Denotes the upper limit of how many bullets of an
* {@link AssaultRifle} can be carried.
*/
public static int go_assaultrifle_maxammo = 250;
/**
* Damage caused by an {@link AssaultMissile}.
*/
public static int go_assaultmissile_damage = 2;
/**
* Speed of an {@link AssaultMissile}.
*/
public static float go_assaultmissile_speed = 2000;
/**
* Denotes how far an {@link AssaultMissile} can go before it
* disappears.
*/
public static float go_assaultmissile_maxrange = 4000;
/**
* Size (radius) of an {@link AssaultMissile}.
*/
public static float go_assaultmissile_shape_size = 1;
/**
* Area Of Effect of an {@link AssaultMissile}.
*/
public static float go_assaultmissile_damageradius = 3;
/**
* Tells whether neutral objects are always shown when vision is
* enabled.
*/
public static boolean vision_neutral_always = true;
/**
* Tells whether vision is disabled or not.
*/
public static boolean vision_disabled = true;
/**
* Tells whether the application shall shut down if a sysout occurs (use
* it for debugging!).
*/
public static boolean exit_on_sysout = false;
/**
* Determines the interval by which a base generates resources (in ms).
*/
public static long neutralbase_resource_interval = 1000;
/**
* Determines the amount of resources to generate in each interval.
*/
public static int neutralbase_resource_baseamount = 1;
/**
* Determines the default time it takes to conquer a neutral base.
*/
public static long neutralbase_overtaketime_default = 2000;
/**
* Determines how many points a player gains per interval when he had
* conquered a neutral base.
*/
public static int gm_koth_points_per_interval = 1;
/**
* Determines the interval by which a player gains points from a neutral
* base.
*/
public static long gm_koth_gain_points_interval = 10000;
/**
* Determines how much resource it takes to perform a
* {@link RespawnPlayerAction}.
*/
public static int gm_edura_action_respawnplayer_cost = 15;
/**
* Determines how much resource it takes to perform a
* {@link SpawnItemAction} when the item's type is rocketlauncher.
*/
public static int go_rocketlauncher_costs = 100;
/**
* Determines how much resource it takes to perform a
* {@link SpawnItemAction} when the item's type is minelauncher.
*/
public static int go_mineweapon_costs = 100;
/**
* Determines how much resource it takes to perform a
* {@link SpawnItemAction} when the item's type is assaultRifle.
*/
public static int go_assaultrifle_costs = 100;
/**
* Determines how much resource it takes to perform a
* {@link SpawnItemAction} when the item's type is sword.
*/
public static int go_swordweapon_costs = 100;
/**
* Determines how much resource it takes to perform a
* {@link SpawnItemAction} when the item's type is splash weapon.
*/
public static int go_splashweapon_costs = 100;
/**
* Determines how much resource it takes to perform a
* {@link SpawnItemAction} when the item's type is sniper weapon.
*/
public static int go_sniperweapon_costs = 100;
/**
* Determines how much resource it takes to perform a
* {@link SpawnItemAction} when the item's type is simple weapon.
*/
public static int go_simpleweapon_costs = 100;
/**
* Determines how much resource it takes to perform a
* {@link HealSpellAction}.
*/
public static int spell_heal_costs = 100;
/**
* Determines by how many health points a unit is healed when a
* {@link HealSpellAction} is performed on it.
*/
public static int spell_heal_amount = 100;
/**
* Determines how much health an observer can have at max.
*/
public static int unit_observer_maxhealth = 10;
/**
* Determines the angle by which an observer gives vision.
*/
public static float unit_observer_visionangle = 360f;
/**
* Determines the range by which an observer gives vision.
*/
public static float unit_observer_visionrange = 300f;
/**
* Determines how much resource it takes to perform a
* {@link CreateUnitAction} with unit type {@link Observer}.
*/
public static int unit_observer_costs = 100;
/**
* Determines the speed of an {@link Observer}.
*/
public static float unit_observer_speed = 100;
/**
* Determines the range by which a {@link ScoutSpellAction} gives
* vision.
*/
public static float spell_scout_visionrange = 300f;
/**
* Determines the range by which a {@link ScoutSpellAction} gives
* vision.
*/
public static float spell_scout_visionangle = 360f;
/**
* Determines the costs it takes to perform a scout spell.
*/
public static int spell_scout_costs = 50;
/**
* Determines for how long the scout spell lasts, that is, for how long
* vision is given.
*/
public static long spell_scout_duration = 3000;
/**
* Determines the default range for missiles.
*/
public static float go_missile_defaultrange = 5000;
/**
* Determines if damage can be caused to units of the same team.
*/
public static boolean mp_teamattack = false;
/**
* Determines the round time of a match in milliseconds.
*/
public static long sv_roundtime = 300000;
/**
* Determines the amount of resources that each team is given at the
* beginning of an Edura! round.
*/
public static int gm_edura_startmoney = 100;
/**
* Determines what items each player is given when spawning.
*/
public static String[] sv_startweapons = { "ITEM_WEAPON_SWORD" };
/**
* Determines whether a player automatically respawns after some time.
*/
public static boolean gm_edura_automatic_respawn = true;
/**
* The time that elapses before a player is respawned if automatic
* respawing is turned on.
*/
public static long gm_edura_respawn_time = 30000;
/**
* Determines the radius of a healingpotion.
*/
public static float go_healingpotion_radius_size = 10f;
/**
* Determines by how much a healingpotion heals.
*/
public static int go_healingpotion_healamount = 25;
/**
* Determines how long it takes for a healingpotion to respawn.
*/
public static long go_healingpotion_respawntime = 15000;
/**
* The defaul respawn time for powerups.
*/
public static long go_powerup_respawntime_default = 15000;
public static float go_speedpowerup_amount = 50;
public static long go_speedpowerup_duration = 20000;
public static float go_speedpowerup_radius = 10f;
public static long go_speedpowerup_respawntime = 90000;
public static float go_invisibility_powerup_radius = 10f;
public static long go_invisibility_powerup_respawntime = 90000;
public static long go_invisibility_powerup_duration = 15000;
public static int spell_speed_costs = 50;
public static float spell_speed_amount = 50;
public static long spell_speed_duration = 15000;
public static int spell_invisibility_costs = 50;
public static long spell_invisibility_duration = 15000;
public static float go_portal_width = 25;
public static float go_portal_height = 25;
/**
* Determines the accuracy during collision detection. The lower the
* number, the higher the accuracy. In fact, this denotes the distance
* from one collision-detection-point to another.
*/
public static float sv_performance_collision_accuracy = 5;
/**
* Tells how many times per second the game shall be updated.
*/
public static long sv_performance_tickrate = 33;
public static int gm_edura_money_per_kill = 150;
public static int gm_edura_money_per_selfkill = -150;
public static long sv_modeswitch_rts_cooldown = 0;
public static long sv_modeswitch_ego_cooldown = 0;
public static long sv_modeswitch_dead_cooldown = 0;
public static boolean sv_minimap_egomode = true;
/**
* Determines whether the winning condition in edura mode is to conquer
* all bases or to conquer only the opponent's main base.
*/
public static boolean gm_edura_conquer_all_bases = true;
/**
* Determines the maximum blink distance.
*/
public static float sv_blink_distance = 100;
public static long sv_blink_cooldown = 3000;
/**
* Determines if blink is available in deathmatch mode.
*/
public static boolean gm_deathmatch_blink_available = true;
public static long gm_deathmatch_blink_timer = 15000;
public static int spell_blink_costs = 10;
/**
* Determines a player's maximum speed.
*/
public static float player_speed_max = 200;
/**
* Determines if players are allowed to switch teams at any time.
*/
public static boolean sv_switchteams = true;
/**
* Determines how often a simplemissile bounces back from a wall.
*/
public static int go_simplemissile_bounces = 3;
/**
* Determines if objects slide at walls when they collide.
*/
public static boolean sv_collision_smooth = true;
/**
* Determines how close an invis object has to be to an observer in
* order to be seen.
*/
public static float unit_observer_detectionrange = 100;
/**
* Determines how close an invis object has to be to the spell scout in
* order to be seen.
*/
public static float spell_scout_detectionrange = 200;
/**
* Determines how large an observer object is.
*/
public static float unit_observer_shaperadius = 9;
/**
* Determines whether an observer is in stealth mode or not. If so, he's
* not visible and cannot collide with units.
*/
public static boolean unit_observer_stealth = true;
/**
* Determines whether income per base increases when the time is up. The
* more income per base the greater is the advantage for the team that
* is ahead in bases which is intended to speed up the round.
*/
public static boolean gm_edura_timeup_increase_income = true;
/**
* The factor by which each base's income is multiplied when time is up.
*/
public static float gm_edura_timeup_increase_factor = 2;
/**
* Determines whether the income aggregated from all bases shall be
* constant over time.
*/
public static boolean gm_edura_constant_income = true;
/**
* Total income per minute.
*/
public static int gm_edura_income_per_minute = 1000;
/**
* Determines how many rounds are played per round (maximum).
*/
public static int gm_edura_maxrounds = 1;
/**
* Determines the delay before a game starts in milliseconds.
*/
public static long sv_game_restart_delay = 5000;
/**
* Determines if all rounds are played although the winner is already
* fix.
*/
public static boolean gm_edura_play_all_rounds = false;
}
/**
* Holds the settings that are relevant only to the client.
*
* @author Florian Mai <florian.ren.mai@googlemail.com>
*
*/
public static class Client {
/**
* Tells whether the application shall shut down if a sysout occurs (use
* it for debugging!).
*/
public static boolean exit_on_sysout = false;
/**
* Determines if bounding boxes of objects are rendered or not (for
* debugging).
*/
public static boolean debug_render_boundingboxes = false;
/**
* Starts the game in windowed mode (1066x600) when true, otherwise
* fullscreen at current resolution.
*/
public static boolean windowed = false;
public static boolean debug_render_shapes = false;
}
/**
* Denotes if client settings or server settings are affected in some
* context.
*
* @author Florian Mai <florian.ren.mai@googlemail.com>
*
*/
public enum SettingType {
/**
* Client
*/
CLIENT,
/**
* Server
*/
SERVER;
}
/**
* Reads values from the file and writes them to the S classes attributes.
*
* @param file
* The file to read settings from.
*
* The file is expected to look like this:
*
* {@code
* <setting_name1>=<setting_value1>/r
* ...
* <setting_nameN>=<setting_valueN>
* } So each line is assumed to be a key-value pair. The values which could
* be read successfully are
* @param type
* if client is given, the settings in the file are assumed to be
* client settings, otherwise they are considered to be server
* settings.
*/
public static void loadSettings(File file, SettingType type) {
if (file == null) {
L.warning("File must not be NULL!");
return;
}
LinkedList<String[]> readSettings = parseFileToSettings(file);
int numberOfReadSettings = readSettings.size();
int i;
for (i = 0; i < numberOfReadSettings; i++) {
String settingName = readSettings.get(i)[0];
String settingValue = readSettings.get(i)[1];
try {
setSetting(type, settingName, settingValue);
} catch (NoSuchFieldException | SecurityException e) {
L.severe("Couldn't find a value for setting '" + settingName
+ "'.");
continue;
} catch (IllegalAccessException e) {
L.log(Level.SEVERE, "Error while trying to set setting "
+ settingName + " to value " + settingValue, e);
continue;
} catch (IllegalArgumentException e) {
L.log(Level.WARNING,
"Format exception while trying to read the value "
+ settingValue + " of setting " + settingName,
e);
continue;
}
}
}
private static void setSetting(SettingType type, String settingName,
String settingValue) throws NoSuchFieldException,
SecurityException, IllegalArgumentException, IllegalAccessException {
Field setting;
if (type == SettingType.CLIENT) {
setting = S.Client.class.getField(settingName);
} else {
setting = S.Server.class.getField(settingName);
}
L.info("Setting " + setting.getName() + "="
+ setting.get(null).toString());
if (setting.getType().equals(boolean.class)) {
setting.setBoolean(null, Boolean.parseBoolean(settingValue));
}
if (setting.getType().equals(String.class)) {
setting.set(null, settingValue);
}
if (setting.getType().equals(int.class)) {
setting.setInt(null, Integer.parseInt(settingValue));
}
if (setting.getType().equals(long.class)) {
setting.setLong(null, Long.parseLong(settingValue));
}
if (setting.getType().equals(double.class)) {
setting.setDouble(null, Double.parseDouble(settingValue));
}
if (setting.getType().equals(float.class)) {
setting.setFloat(null, Float.parseFloat(settingValue));
}
}
/**
* Sets a single client setting value.
*
* @param settingName
* the setting property's name
* @param settingValue
* the value to set it to
* @throws NoSuchFieldException
* thrown if there is no such property
* @throws SecurityException
* @throws IllegalArgumentException
* thrown if given value's type doesn't apply the specified
* field.
* @throws IllegalAccessException
*/
public static void setClientSetting(String settingName, String settingValue)
throws NoSuchFieldException, SecurityException,
IllegalArgumentException, IllegalAccessException {
setSetting(SettingType.CLIENT, settingName, settingValue);
}
/**
* Sets a single server setting value.
*
* @param settingName
* the setting property's name
* @param settingValue
* the value to set it to
* @throws NoSuchFieldException
* thrown if there is no such property
* @throws SecurityException
* @throws IllegalArgumentException
* thrown if given value's type doesn't apply the specified
* field.
* @throws IllegalAccessException
*/
public static void setServerSetting(String settingName, String settingValue)
throws NoSuchFieldException, SecurityException,
IllegalArgumentException, IllegalAccessException {
setSetting(SettingType.SERVER, settingName, settingValue);
}
private static LinkedList<String[]> parseFileToSettings(File file) {
LinkedList<String[]> readSettings = new LinkedList<String[]>();
BufferedReader fileReader;
try {
fileReader = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e1) {
L.log(Level.SEVERE, "Cannot find file", e1);
return readSettings;
}
String readLine = "";
try {
while ((readLine = fileReader.readLine()) != null) {
String[] settingNameAndValue = readLine.split("=");
if (settingNameAndValue.length == 2) {
readSettings.add(settingNameAndValue);
} else {
L.warning("Were not able to parse line " + readLine);
continue;
}
}
} catch (IOException e) {
L.log(Level.SEVERE,
"An IO error appeared trying to read settings file.", e);
}
try {
fileReader.close();
} catch (IOException e) {
L.log(Level.SEVERE, "Error trying to close the file.");
}
return readSettings;
}
/**
* Writes all settings into a temporary file. The file is deleted when the
* program exits.
*
* @param type
* the type of setting to put in a file. See {@link SettingType}.
* @return the file with settings
* @throws IOException
* thrown if the file can't be created.
*/
public static File putSettingsInFile(SettingType type) throws IOException {
File settingsFile = File.createTempFile(
"edurassettings_" + type.toString(), ".tmp");
PrintWriter fileWriter = new PrintWriter(settingsFile);
Field[] fields = type == SettingType.CLIENT ? S.Client.class
.getFields() : S.Server.class.getFields();
for (Field field : fields) {
try {
fileWriter.write(field.getName() + "="
+ field.get(null).toString() + "\r");
} catch (IllegalArgumentException | IllegalAccessException e) {
L.log(Level.WARNING,
"Exception occured when accessing an S-field. Skipping this one...",
e);
continue;
}
}
fileWriter.close();
return settingsFile;
}
}
|
package com.adapter;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;
public class NoScrollListView extends ListView {
public NoScrollListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
try {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
} catch (Exception e) {
}
}
}
|
class decode
{
public static void main(String s)
{
int n,i=0,j,k;
long p;
String t="",m="";
while(i<s.length())
{
for(j=i;j<(i+3);j++)
{
t=t+s.charAt(i);
}
p=Long.valueOf(t);
if(p>122)
{
p=p/10;
i=i+2;
}
else
i=i+3;
m=m+(char)p;
}
System.out.print(m);
}
}
|
package com.yangdb.fuse.asg.strategy.propertyGrouping;
/*-
* #%L
* fuse-asg
* %%
* Copyright (C) 2016 - 2019 The YangDb Graph Database Project
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import com.yangdb.fuse.asg.strategy.AsgStrategy;
import com.yangdb.fuse.model.asgQuery.AsgEBase;
import com.yangdb.fuse.model.asgQuery.AsgQuery;
import com.yangdb.fuse.model.asgQuery.AsgQueryUtil;
import com.yangdb.fuse.model.asgQuery.AsgStrategyContext;
import com.yangdb.fuse.model.query.EBase;
import com.yangdb.fuse.model.query.quant.Quant1;
import com.yangdb.fuse.model.query.quant.QuantType;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
public class Quant1AllQuantGroupingAsgStrategy implements AsgStrategy {
//region AsgStrategy Implementation
@Override
public void apply(AsgQuery query, AsgStrategyContext context) {
AtomicBoolean hasWorkToDo = new AtomicBoolean(true);
while(hasWorkToDo.get()) {
hasWorkToDo.set(false);
AsgQueryUtil.elements(query, Quant1.class).forEach(quant -> {
if (quant.geteBase().getqType().equals(QuantType.all)) {
AsgQueryUtil.<Quant1, Quant1>nextAdjacentDescendants(quant, Quant1.class).forEach(childQuant -> {
if (childQuant.geteBase().getqType().equals(QuantType.all)) {
hasWorkToDo.set(true);
AsgQueryUtil.replaceParents(quant,childQuant);
AsgQueryUtil.remove(query,childQuant);
}
});
}
});
}
}
//endregion
}
|
/*
* Copyright (C) 2016-2019 Lightbend Inc. <https://www.lightbend.com>
*/
package com.lightbend.lagom.javadsl.api.transport;
import com.lightbend.lagom.javadsl.api.deser.ExceptionMessage;
/** Exception thrown when a message can't be deserialized because its media type is not known. */
public class UnsupportedMediaType extends TransportException {
private static final long serialVersionUID = 1L;
public static final TransportErrorCode ERROR_CODE = TransportErrorCode.UnsupportedMediaType;
public UnsupportedMediaType(MessageProtocol received, MessageProtocol supported) {
super(
ERROR_CODE,
"Could not negotiate a deserializer for type "
+ received
+ ", the default media type supported is "
+ supported);
}
public UnsupportedMediaType(TransportErrorCode errorCode, ExceptionMessage exceptionMessage) {
super(errorCode, exceptionMessage);
}
}
|
/*
* Copyright (c) 2019-2021 GeyserMC. http://geysermc.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.network.translators.bedrock.entity.player;
import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerPositionPacket;
import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerPositionRotationPacket;
import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerRotationPacket;
import com.github.steveice10.packetlib.packet.Packet;
import com.nukkitx.math.vector.Vector3d;
import com.nukkitx.math.vector.Vector3f;
import com.nukkitx.protocol.bedrock.packet.MoveEntityAbsolutePacket;
import com.nukkitx.protocol.bedrock.packet.MovePlayerPacket;
import org.geysermc.connector.GeyserConnector;
import org.geysermc.connector.common.ChatColor;
import org.geysermc.connector.entity.player.SessionPlayerEntity;
import org.geysermc.connector.entity.type.EntityType;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
@Translator(packet = MovePlayerPacket.class)
public class BedrockMovePlayerTranslator extends PacketTranslator<MovePlayerPacket> {
/* The upper and lower bounds to check for the void floor that only exists in Bedrock */
private static final int BEDROCK_OVERWORLD_VOID_FLOOR_UPPER_Y;
private static final int BEDROCK_OVERWORLD_VOID_FLOOR_LOWER_Y;
static {
BEDROCK_OVERWORLD_VOID_FLOOR_UPPER_Y = GeyserConnector.getInstance().getConfig().isExtendedWorldHeight() ? -104 : -40;
BEDROCK_OVERWORLD_VOID_FLOOR_LOWER_Y = BEDROCK_OVERWORLD_VOID_FLOOR_UPPER_Y + 2;
}
@Override
public void translate(GeyserSession session, MovePlayerPacket packet) {
SessionPlayerEntity entity = session.getPlayerEntity();
if (!session.isSpawned()) return;
if (!session.getUpstream().isInitialized()) {
MoveEntityAbsolutePacket moveEntityBack = new MoveEntityAbsolutePacket();
moveEntityBack.setRuntimeEntityId(entity.getGeyserId());
moveEntityBack.setPosition(entity.getPosition());
moveEntityBack.setRotation(entity.getBedrockRotation());
moveEntityBack.setTeleported(true);
moveEntityBack.setOnGround(true);
session.sendUpstreamPacketImmediately(moveEntityBack);
return;
}
session.setLastMovementTimestamp(System.currentTimeMillis());
// Send book update before the player moves
session.getBookEditCache().checkForSend();
if (!session.getTeleportMap().isEmpty()) {
session.confirmTeleport(packet.getPosition().toDouble().sub(0, EntityType.PLAYER.getOffset(), 0));
return;
}
// head yaw, pitch, head yaw
Vector3f rotation = Vector3f.from(packet.getRotation().getY(), packet.getRotation().getX(), packet.getRotation().getY());
boolean positionChanged = !entity.getPosition().equals(packet.getPosition());
boolean rotationChanged = !entity.getRotation().equals(rotation);
// If only the pitch and yaw changed
// This isn't needed, but it makes the packets closer to vanilla
// It also means you can't "lag back" while only looking, in theory
if (!positionChanged && rotationChanged) {
ClientPlayerRotationPacket playerRotationPacket = new ClientPlayerRotationPacket(
packet.isOnGround(), packet.getRotation().getY(), packet.getRotation().getX());
entity.setRotation(rotation);
entity.setOnGround(packet.isOnGround());
session.sendDownstreamPacket(playerRotationPacket);
} else {
if (session.getWorldBorder().isPassingIntoBorderBoundaries(packet.getPosition(), true)) {
return;
}
if (isValidMove(session, entity.getPosition(), packet.getPosition())) {
Vector3d position = session.getCollisionManager().adjustBedrockPosition(packet.getPosition(), packet.isOnGround(), packet.getMode() == MovePlayerPacket.Mode.TELEPORT);
if (position != null) { // A null return value cancels the packet
Packet movePacket;
if (rotationChanged) {
// Send rotation updates as well
movePacket = new ClientPlayerPositionRotationPacket(packet.isOnGround(), position.getX(), position.getY(), position.getZ(),
packet.getRotation().getY(), packet.getRotation().getX());
entity.setRotation(rotation);
} else {
// Rotation did not change; don't send an update with rotation
movePacket = new ClientPlayerPositionPacket(packet.isOnGround(), position.getX(), position.getY(), position.getZ());
}
// Compare positions here for void floor fix below before the player's position variable is set to the packet position
boolean notMovingUp = entity.getPosition().getY() >= packet.getPosition().getY();
entity.setPositionManual(packet.getPosition());
entity.setOnGround(packet.isOnGround());
// Send final movement changes
session.sendDownstreamPacket(movePacket);
if (notMovingUp) {
int floorY = position.getFloorY();
// If the client believes the world has extended height, then it also believes the void floor
// still exists, just at a lower spot
boolean extendedWorld = session.getChunkCache().isExtendedHeight();
if (floorY <= (extendedWorld ? BEDROCK_OVERWORLD_VOID_FLOOR_LOWER_Y : -38)
&& floorY >= (extendedWorld ? BEDROCK_OVERWORLD_VOID_FLOOR_UPPER_Y : -40)) {
// Work around there being a floor at the bottom of the world and teleport the player below it
// Moving from below to above the void floor works fine
entity.setPosition(entity.getPosition().sub(0, 4f, 0));
MovePlayerPacket movePlayerPacket = new MovePlayerPacket();
movePlayerPacket.setRuntimeEntityId(entity.getGeyserId());
movePlayerPacket.setPosition(entity.getPosition());
movePlayerPacket.setRotation(entity.getBedrockRotation());
movePlayerPacket.setMode(MovePlayerPacket.Mode.TELEPORT);
movePlayerPacket.setTeleportationCause(MovePlayerPacket.TeleportationCause.BEHAVIOR);
session.sendUpstreamPacket(movePlayerPacket);
}
}
}
} else {
// Not a valid move
session.getConnector().getLogger().debug("Recalculating position...");
session.getCollisionManager().recalculatePosition();
}
}
// Move parrots to match if applicable
if (entity.getLeftParrot() != null) {
entity.getLeftParrot().moveAbsolute(session, entity.getPosition(), entity.getRotation(), true, false);
}
if (entity.getRightParrot() != null) {
entity.getRightParrot().moveAbsolute(session, entity.getPosition(), entity.getRotation(), true, false);
}
}
private boolean isInvalidNumber(float val) {
return Float.isNaN(val) || Float.isInfinite(val);
}
private boolean isValidMove(GeyserSession session, Vector3f currentPosition, Vector3f newPosition) {
if (isInvalidNumber(newPosition.getX()) || isInvalidNumber(newPosition.getY()) || isInvalidNumber(newPosition.getZ())) {
return false;
}
if (currentPosition.distanceSquared(newPosition) > 300) {
session.getConnector().getLogger().debug(ChatColor.RED + session.getName() + " moved too quickly." +
" current position: " + currentPosition + ", new position: " + newPosition);
return false;
}
return true;
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package hivemall.classifier.multiclass;
import hivemall.model.FeatureValue;
import hivemall.model.IWeightValue;
import hivemall.model.Margin;
import hivemall.model.PredictionModel;
import hivemall.model.WeightValue.WeightValueWithCovar;
import hivemall.utils.math.StatsUtils;
import javax.annotation.Nonnull;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
/**
* Soft Confidence-Weighted binary classifier.
*
* <pre>
* [1] Steven C. H. Hoi, Jialei Wang, Peilin Zhao: Exact Soft Confidence-Weighted Learning. ICML 2012
* </pre>
*
* @link http://icml.cc/2012/papers/86.pdf
*/
public abstract class MulticlassSoftConfidenceWeightedUDTF extends MulticlassOnlineClassifierUDTF {
/** Confidence parameter phi */
protected float phi;
/** Aggressiveness parameter */
protected float c;
@Override
public StructObjectInspector initialize(ObjectInspector[] argOIs) throws UDFArgumentException {
final int numArgs = argOIs.length;
if (numArgs != 2 && numArgs != 3) {
throw new UDFArgumentException(
"MulticlassSoftConfidenceWeightedUDTF takes 2 or 3 arguments: List<String|Int|BitInt> features, {Int|String} label [, constant String options]");
}
return super.initialize(argOIs);
}
@Override
protected boolean useCovariance() {
return true;
}
@Override
protected Options getOptions() {
Options opts = super.getOptions();
opts.addOption("phi", "confidence", true, "Confidence parameter [default 1.0]");
opts.addOption("eta", "hyper_c", true,
"Confidence hyperparameter eta in range (0.5, 1] [default 0.85]");
opts.addOption("c", "aggressiveness", true, "Aggressiveness parameter C [default 1.0]");
return opts;
}
@Override
protected CommandLine processOptions(ObjectInspector[] argOIs) throws UDFArgumentException {
final CommandLine cl = super.processOptions(argOIs);
float phi = 1.f;
float c = 1.f;
if (cl != null) {
String phi_str = cl.getOptionValue("phi");
if (phi_str == null) {
String eta_str = cl.getOptionValue("eta");
if (eta_str != null) {
double eta = Double.parseDouble(eta_str);
if (eta <= 0.5 || eta > 1) {
throw new UDFArgumentException(
"Confidence hyperparameter eta must be in range (0.5, 1]: " + eta_str);
}
phi = (float) StatsUtils.probit(eta, 5d);
}
} else {
phi = Float.parseFloat(phi_str);
}
String c_str = cl.getOptionValue("c");
if (c_str != null) {
c = Float.parseFloat(c_str);
if (!(c > 0.f)) {
throw new UDFArgumentException(
"Aggressiveness parameter C must be C > 0: " + c);
}
}
}
this.phi = phi;
this.c = c;
return cl;
}
@Override
protected void train(@Nonnull final FeatureValue[] features, @Nonnull Object actual_label) {
Margin margin = getMarginAndVariance(features, actual_label, true);
float loss = loss(margin);
if (loss > 0.f) {
float alpha = getAlpha(margin);
if (alpha == 0.f) {
return;
}
float beta = getBeta(margin, alpha);
if (beta == 0.f) {
return;
}
Object missed_label = margin.getMaxIncorrectLabel();
update(features, actual_label, missed_label, alpha, beta);
}
}
protected float loss(Margin margin) {
float var = margin.getVariance();
float m = margin.get();
assert (var != 0);
float loss = phi * (float) Math.sqrt(var) - m;
return Math.max(loss, 0.f);
}
protected abstract float getAlpha(Margin margin);
protected abstract float getBeta(Margin margin, float alpha);
@Description(name = "train_multiclass_scw",
value = "_FUNC_(list<string|int|bigint> features, {int|string} label [, const string options])"
+ " - Returns a relation consists of <{int|string} label, {string|int|bigint} feature, float weight, float covar>",
extended = "Build a prediction model by Soft Confidence-Weighted (SCW-1) multiclass classifier")
public static class SCW1 extends MulticlassSoftConfidenceWeightedUDTF {
private float squared_phi, psi, zeta;
@Override
public StructObjectInspector initialize(ObjectInspector[] argOIs)
throws UDFArgumentException {
StructObjectInspector oi = super.initialize(argOIs);
float phiphi = phi * phi;
this.squared_phi = phiphi;
this.psi = 1.f + phiphi / 2.f;
this.zeta = 1.f + phiphi;
return oi;
}
@Override
protected float getAlpha(Margin margin) {
float m = margin.get();
float var = margin.getVariance();
float alpha_numer = -m * psi + (float) Math.sqrt(
(m * m * squared_phi * squared_phi / 4.f) + (var * squared_phi * zeta));
float alpha_denom = var * zeta;
if (alpha_denom == 0.f) {
return 0.f;
}
float alpha = alpha_numer / alpha_denom;
if (alpha <= 0.f) {
return 0.f;
}
return Math.max(c, alpha);
}
@Override
protected float getBeta(Margin margin, float alpha) {
if (alpha == 0.f) {
return 0.f;
}
float var = margin.getVariance();
float beta_numer = alpha * phi;
float var_alpha_phi = var * beta_numer;
float u = -var_alpha_phi + (float) Math.sqrt(var_alpha_phi * var_alpha_phi + 4.f * var);
float beta_den = u / 2.f + var_alpha_phi;
if (beta_den == 0.f) {
return 0.f;
}
float beta = beta_numer / beta_den;
return beta;
}
}
@Description(name = "train_multiclass_scw2",
value = "_FUNC_(list<string|int|bigint> features, {int|string} label [, const string options])"
+ " - Returns a relation consists of <{int|string} label, {string|int|bigint} feature, float weight, float covar>",
extended = "Build a prediction model by Soft Confidence-Weighted 2 (SCW-2) multiclass classifier")
public static final class SCW2 extends SCW1 {
@Override
protected float getAlpha(Margin margin) {
float m = margin.get();
float var = margin.getVariance();
float squared_phi = phi * phi;
float n = var + c / 2.f;
float v_phi_phi = var * squared_phi;
float v_phi_phi_m = v_phi_phi * m;
float term = v_phi_phi_m * m * var + 4.f * n * var * (n + v_phi_phi);
float gamma = phi * (float) Math.sqrt(term);
float alpha_numer = -(2.f * m * n + v_phi_phi_m) + gamma;
if (alpha_numer <= 0.f) {
return 0.f;
}
float alpha_denom = 2.f * (n * n + n * v_phi_phi);
if (alpha_denom == 0.f) {
return 0.f;
}
float alpha = alpha_numer / alpha_denom;
return Math.max(0.f, alpha);
}
}
protected void update(@Nonnull final FeatureValue[] features, final Object actual_label,
final Object missed_label, final float alpha, final float beta) {
assert (actual_label != null);
if (actual_label.equals(missed_label)) {
throw new IllegalArgumentException(
"Actual label equals to missed label: " + actual_label);
}
PredictionModel model2add = label2model.get(actual_label);
if (model2add == null) {
model2add = createModel();
label2model.put(actual_label, model2add);
}
PredictionModel model2sub = null;
if (missed_label != null) {
model2sub = label2model.get(missed_label);
if (model2sub == null) {
model2sub = createModel();
label2model.put(missed_label, model2sub);
}
}
for (FeatureValue f : features) {// w[f] += y * x[f]
if (f == null) {
continue;
}
final Object k = f.getFeature();
final float v = f.getValueAsFloat();
IWeightValue old_correctclass_w = model2add.get(k);
IWeightValue new_correctclass_w =
getNewWeight(old_correctclass_w, v, alpha, beta, true);
model2add.set(k, new_correctclass_w);
if (model2sub != null) {
IWeightValue old_wrongclass_w = model2sub.get(k);
IWeightValue new_wrongclass_w =
getNewWeight(old_wrongclass_w, v, alpha, beta, false);
model2sub.set(k, new_wrongclass_w);
}
}
}
private static IWeightValue getNewWeight(final IWeightValue old, final float v,
final float alpha, final float beta, final boolean positive) {
final float old_v;
final float old_cov;
if (old == null) {
old_v = 0.f;
old_cov = 1.f;
} else {
old_v = old.get();
old_cov = old.getCovariance();
}
float cv = old_cov * v;
float new_w = positive ? old_v + (alpha * cv) : old_v - (alpha * cv);
float new_cov = old_cov - (beta * cv * cv);
return new WeightValueWithCovar(new_w, new_cov);
}
}
|
/*
* 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.shindig.gadgets.config;
import org.apache.shindig.gadgets.Gadget;
import java.util.Map;
/**
* Interface used by java classes that can inject javascript configuration information
* @since 2.0.0
*/
public interface ConfigContributor {
/**
* Contribute configuration values for a specific gadget in an iframe.
* @param config The config mapping of feature to value.
* @param gadget The gadget to contribute for.
*/
public void contribute(Map<String,Object> config, Gadget gadget);
/**
* Contribute configuration for the container specific javascript. This interface
* should only support params used by JsServlet
*
* @param config The config to add to.
* @param container The container.
* @param host The hostname
*/
public void contribute(Map<String,Object> config, String container, String host);
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.internal.cache.tier.sockets;
import static org.apache.geode.cache.CacheFactory.getAnyInstance;
import static org.apache.geode.cache.Region.SEPARATOR;
import static org.apache.geode.distributed.ConfigurationProperties.LOCATORS;
import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
import static org.apache.geode.internal.AvailablePortHelper.getRandomAvailableTCPPort;
import static org.apache.geode.test.awaitility.GeodeAwaitility.await;
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 static org.junit.Assert.fail;
import java.util.Collection;
import java.util.Iterator;
import java.util.Properties;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.apache.geode.cache.AttributesFactory;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.CacheFactory;
import org.apache.geode.cache.DataPolicy;
import org.apache.geode.cache.NoSubscriptionServersAvailableException;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionAttributes;
import org.apache.geode.cache.Scope;
import org.apache.geode.cache.client.PoolManager;
import org.apache.geode.cache.client.internal.Connection;
import org.apache.geode.cache.client.internal.PoolImpl;
import org.apache.geode.cache.server.CacheServer;
import org.apache.geode.distributed.DistributedSystem;
import org.apache.geode.distributed.internal.ServerLocation;
import org.apache.geode.internal.cache.CacheServerImpl;
import org.apache.geode.internal.cache.ClientServerObserverAdapter;
import org.apache.geode.internal.cache.ClientServerObserverHolder;
import org.apache.geode.test.awaitility.GeodeAwaitility;
import org.apache.geode.test.dunit.Assert;
import org.apache.geode.test.dunit.Host;
import org.apache.geode.test.dunit.IgnoredException;
import org.apache.geode.test.dunit.NetworkUtils;
import org.apache.geode.test.dunit.VM;
import org.apache.geode.test.dunit.WaitCriterion;
import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
import org.apache.geode.test.junit.categories.ClientSubscriptionTest;
/**
* Test to verify Startup. and failover during startup.
*/
@Category({ClientSubscriptionTest.class})
public class HAStartupAndFailoverDUnitTest extends JUnit4DistributedTestCase {
private static final String REGION_NAME =
HAStartupAndFailoverDUnitTest.class.getSimpleName() + "_region";
protected static Cache cache = null;
VM server1 = null;
VM server2 = null;
VM server3 = null;
protected static PoolImpl pool = null;
private static Connection conn = null;
private static Integer PORT1;
private static Integer PORT2;
private static Integer PORT3;
// To verify the primary identification on client side toggeled after notification on client side
protected static boolean identifiedPrimary = false;
@Override
public final void postSetUp() throws Exception {
final Host host = Host.getHost(0);
server1 = host.getVM(0);
server2 = host.getVM(1);
server3 = host.getVM(2);
IgnoredException.addIgnoredException("java.io.IOException");
IgnoredException.addIgnoredException("SocketException");
// start servers first
PORT1 = ((Integer) server1.invoke(() -> HAStartupAndFailoverDUnitTest.createServerCache()));
PORT2 = ((Integer) server2.invoke(() -> HAStartupAndFailoverDUnitTest.createServerCache()));
PORT3 = ((Integer) server3.invoke(() -> HAStartupAndFailoverDUnitTest.createServerCache()));
CacheServerTestUtil.disableShufflingOfEndpoints();
}
/**
* Stops primary server one by one to ensure new primary is selected
*/
@Test
public void testPrimaryFailover() throws Exception {
createClientCache(this.getName(), NetworkUtils.getServerHostName(server1.getHost()));
// primary
server1.invoke(() -> HAStartupAndFailoverDUnitTest.verifyDispatcherIsAlive());
// secondaries
server2.invoke(() -> HAStartupAndFailoverDUnitTest.verifyDispatcherIsNotAlive());
server3.invoke(() -> HAStartupAndFailoverDUnitTest.verifyDispatcherIsNotAlive());
setClientServerObserver();
server1.invoke(() -> HAStartupAndFailoverDUnitTest.stopServer());
waitForPrimaryIdentification();
// primary
server2.invoke(() -> HAStartupAndFailoverDUnitTest.verifyDispatcherIsAlive());
unSetClientServerObserver();
// secondary
server3.invoke(() -> HAStartupAndFailoverDUnitTest.verifyDispatcherIsNotAlive());
setClientServerObserver();
server2.invoke(() -> HAStartupAndFailoverDUnitTest.stopServer());
// primary
waitForPrimaryIdentification();
server3.invoke(() -> HAStartupAndFailoverDUnitTest.verifyDispatcherIsAlive());
unSetClientServerObserver();
server3.invoke(() -> HAStartupAndFailoverDUnitTest.stopServer());
// All servers are dead at this point , no primary in the system.
verifyDeadAndLiveServers(3, 0);
// now start one of the servers
server3.invoke(() -> HAStartupAndFailoverDUnitTest.startServer());
// make sure that the server3 which was started recenty was marked live.
verifyDeadAndLiveServers(2, 1);
// verify that is it primary , and dispatche is running
server3.invoke(() -> HAStartupAndFailoverDUnitTest.verifyDispatcherIsAlive());
}
/**
* verify that when an exeption occurs during making primary , new primary will be selected
*
*/
@Test
public void testExceptionWhileMakingPrimary() throws Exception {
createClientCacheWithIncorrectPrimary(this.getName(),
NetworkUtils.getServerHostName(server1.getHost()));
// failed primary due to incorect host name of the server
// new primary
server2.invoke(() -> HAStartupAndFailoverDUnitTest.verifyDispatcherIsAlive());
// secondary
server3.invoke(() -> HAStartupAndFailoverDUnitTest.verifyDispatcherIsNotAlive());
setClientServerObserver();
// stop new primary
server2.invoke(() -> HAStartupAndFailoverDUnitTest.stopServer());
waitForPrimaryIdentification();
// newly selectd primary
server3.invoke(() -> HAStartupAndFailoverDUnitTest.verifyDispatcherIsAlive());
unSetClientServerObserver();
}
/**
* verify that when an exeption occurs during making primary to two EPs , new primary will be
* selected
*
*/
@Test
public void testTwoPrimaryFailedOneAfterTheAnother() throws Exception {
createClientCacheWithLargeRetryInterval(this.getName(),
NetworkUtils.getServerHostName(server1.getHost()));
// primary
server1.invoke(() -> HAStartupAndFailoverDUnitTest.verifyDispatcherIsAlive());
// secondaries
server2.invoke(() -> HAStartupAndFailoverDUnitTest.verifyDispatcherIsNotAlive());
server3.invoke(() -> HAStartupAndFailoverDUnitTest.verifyDispatcherIsNotAlive());
setClientServerObserver();
server1.invoke(() -> HAStartupAndFailoverDUnitTest.stopServer());
// stop ProbablePrimary
server2.invoke(() -> HAStartupAndFailoverDUnitTest.stopServer());
// processException();
waitForPrimaryIdentification();
// new primary
server3.invoke(() -> HAStartupAndFailoverDUnitTest.verifyDispatcherIsAlive());
unSetClientServerObserver();
}
/**
* verify that Primary Should Be Null And EPList Should Be Empty When All Servers Are Dead
*/
@Test
public void testPrimaryShouldBeNullAndEPListShouldBeEmptyWhenAllServersAreDead()
throws Exception {
createClientCache(this.getName(), NetworkUtils.getServerHostName(server1.getHost()));
verifyPrimaryShouldNotBeNullAndEPListShouldNotBeEmpty();
server1.invoke(() -> HAStartupAndFailoverDUnitTest.stopServer());
server2.invoke(() -> HAStartupAndFailoverDUnitTest.stopServer());
server3.invoke(() -> HAStartupAndFailoverDUnitTest.stopServer());
verifyDeadAndLiveServers(3, 0);
verifyPrimaryShouldBeNullAndEPListShouldBeEmpty();
}
/**
* Tests failover initialization by cacheClientUpdater Thread on failure in Primary Server
*/
@Test
public void testCacheClientUpdatersInitiatesFailoverOnPrimaryFailure() throws Exception {
createClientCacheWithLargeRetryInterval(this.getName(),
NetworkUtils.getServerHostName(server1.getHost()));
server1.invoke(() -> HAStartupAndFailoverDUnitTest.verifyDispatcherIsAlive());
server2.invoke(() -> HAStartupAndFailoverDUnitTest.verifyDispatcherIsNotAlive());
server3.invoke(() -> HAStartupAndFailoverDUnitTest.verifyDispatcherIsNotAlive());
setClientServerObserver();
server1.invoke(() -> HAStartupAndFailoverDUnitTest.stopServer());
waitForPrimaryIdentification();
unSetClientServerObserver();
verifyDeadAndLiveServers(1, 2);
server2.invoke(() -> HAStartupAndFailoverDUnitTest.verifyDispatcherIsAlive());
}
/**
* Tests failover initialization by cacheClientUpdater Thread on failure on Secondary server
*/
@Test
public void testCacheClientUpdaterInitiatesFailoverOnSecondaryFailure() throws Exception {
createClientCacheWithLargeRetryInterval(this.getName(),
NetworkUtils.getServerHostName(server1.getHost()));
server1.invoke(() -> HAStartupAndFailoverDUnitTest.verifyDispatcherIsAlive());
server2.invoke(() -> HAStartupAndFailoverDUnitTest.verifyDispatcherIsNotAlive());
server3.invoke(() -> HAStartupAndFailoverDUnitTest.verifyDispatcherIsNotAlive());
server2.invoke(() -> HAStartupAndFailoverDUnitTest.stopServer());
verifyDeadAndLiveServers(1, 2);
server1.invoke(() -> HAStartupAndFailoverDUnitTest.verifyDispatcherIsAlive());
server3.invoke(() -> HAStartupAndFailoverDUnitTest.verifyDispatcherIsNotAlive());
}
/**
* Tests failover initialization by cacheClientUpdater Thread failure on both Primary and
* Secondary server
*/
@Test
public void testCacheClientUpdaterInitiatesFailoverOnBothPrimaryAndSecondaryFailure()
throws Exception {
createClientCacheWithLargeRetryInterval(this.getName(),
NetworkUtils.getServerHostName(server1.getHost()));
server1.invoke(() -> HAStartupAndFailoverDUnitTest.verifyDispatcherIsAlive());
server2.invoke(() -> HAStartupAndFailoverDUnitTest.verifyDispatcherIsNotAlive());
server3.invoke(() -> HAStartupAndFailoverDUnitTest.verifyDispatcherIsNotAlive());
server1.invoke(() -> HAStartupAndFailoverDUnitTest.stopServer());
server2.invoke(() -> HAStartupAndFailoverDUnitTest.stopServer());
verifyDeadAndLiveServers(2, 1);
server3.invoke(() -> HAStartupAndFailoverDUnitTest.verifyDispatcherIsAlive());
}
/**
* Tests failover initialization by cacheClientUpdater Thread
*/
@Test
public void testCacheClientUpdaterInitiatesFailoverOnBothPrimaryAndSecondaryFailureWithServerMonitors()
throws Exception {
createClientCache(this.getName(), NetworkUtils.getServerHostName(server1.getHost()));
server1.invoke(() -> HAStartupAndFailoverDUnitTest.verifyDispatcherIsAlive());
server2.invoke(() -> HAStartupAndFailoverDUnitTest.verifyDispatcherIsNotAlive());
server3.invoke(() -> HAStartupAndFailoverDUnitTest.verifyDispatcherIsNotAlive());
server1.invoke(() -> HAStartupAndFailoverDUnitTest.stopServer());
server2.invoke(() -> HAStartupAndFailoverDUnitTest.stopServer());
verifyDeadAndLiveServers(2, 1);
server3.invoke(() -> HAStartupAndFailoverDUnitTest.verifyDispatcherIsAlive());
}
/**
* Tests failover initialization by cache operation Threads on secondary
*/
@Test
public void testInitiateFailoverByCacheOperationThreads_Secondary() throws Exception {
// Stop the 3rd server to guarantee the client put will go to the first server
server3.invoke(() -> HAStartupAndFailoverDUnitTest.stopServer());
// create a client with no client updater thread
// so that only cache operation can detect a server failure and should initiate failover
createClientCacheWithLargeRetryIntervalAndWithoutCallbackConnection(this.getName(),
NetworkUtils.getServerHostName(server1.getHost()));
server2.invoke(() -> HAStartupAndFailoverDUnitTest.stopServer());
put();
verifyDeadAndLiveServers(1, 1);
}
public static void put() {
try {
Region r1 = cache.getRegion(SEPARATOR + REGION_NAME);
r1.put("key-1", "server-value-1");
r1.put("key-2", "server-value-2");
r1.put("key-3", "server-value-3");
} catch (Exception ex) {
Assert.fail("failed while r.put()", ex);
}
}
public static void verifyDeadAndLiveServers(final int expectedDeadServers,
final int expectedLiveServers) {
await()
.untilAsserted(() -> assertEquals(expectedLiveServers, pool.getConnectedServerCount()));
}
public static void setClientServerObserver() {
PoolImpl.AFTER_PRIMARY_IDENTIFICATION_FROM_BACKUP_CALLBACK_FLAG = true;
ClientServerObserverHolder.setInstance(new ClientServerObserverAdapter() {
@Override
public void afterPrimaryIdentificationFromBackup(ServerLocation primaryEndpoint) {
synchronized (HAStartupAndFailoverDUnitTest.class) {
HAStartupAndFailoverDUnitTest.identifiedPrimary = true;
HAStartupAndFailoverDUnitTest.class.notifyAll();
}
}
});
}
public static void unSetClientServerObserver() {
synchronized (HAStartupAndFailoverDUnitTest.class) {
PoolImpl.AFTER_PRIMARY_IDENTIFICATION_FROM_BACKUP_CALLBACK_FLAG = false;
HAStartupAndFailoverDUnitTest.identifiedPrimary = false;
ClientServerObserverHolder.setInstance(new ClientServerObserverAdapter());
}
}
public static void stopServer() {
try {
assertEquals("Expected exactly one BridgeServer", 1, cache.getCacheServers().size());
CacheServerImpl bs = (CacheServerImpl) cache.getCacheServers().iterator().next();
assertNotNull(bs);
bs.stop();
} catch (Exception ex) {
Assert.fail("while setting stopServer", ex);
}
}
public static void verifyPrimaryShouldNotBeNullAndEPListShouldNotBeEmpty() {
try {
assertNotNull(" Primary endpoint should not be null", pool.getPrimaryName());
assertTrue("Endpoint List should not be Empty as all server are live",
pool.getConnectedServerCount() > 0);
} catch (Exception e) {
Assert.fail("failed while verifyPrimaryShouldNotBeNullAndEPListShouldNotBeEmpty()", e);
}
}
public static void verifyPrimaryShouldBeNullAndEPListShouldBeEmpty() {
try {
assertNull("Primary endpoint should be null as all server are dead", pool.getPrimaryName());
assertEquals("Endpoint List should be Empty as all server are dead", 0,
pool.getConnectedServerCount());
fail("NoSubscriptionServersAvailableException is expected");
} catch (NoSubscriptionServersAvailableException e) {
// pass
} catch (Exception e) {
Assert.fail("failed while verifyPrimaryShouldBeNullAndEPListShouldBeEmpty()", e);
}
}
public static void startServer() {
try {
Cache c = CacheFactory.getAnyInstance();
assertEquals("Expected exactly one BridgeServer", 1, c.getCacheServers().size());
CacheServerImpl bs = (CacheServerImpl) c.getCacheServers().iterator().next();
assertNotNull(bs);
bs.start();
} catch (Exception ex) {
fail("while startServer() " + ex);
}
}
public static void waitForPrimaryIdentification() {
assertNotNull(cache);
if (!identifiedPrimary) {
synchronized (HAStartupAndFailoverDUnitTest.class) {
if (!identifiedPrimary) {
final int MAX_WAIT = 60 * 1000;
try {
HAStartupAndFailoverDUnitTest.class.wait(MAX_WAIT);
} catch (InterruptedException e) {
fail("Test failed due to InterruptedException in waitForPrimaryIdentification()");
}
if (!identifiedPrimary) {
fail("timed out after waiting " + MAX_WAIT + " millisecs"
+ " for primary to be identified");
}
}
}
}
}
public static void verifyDispatcherIsAlive() {
try {
WaitCriterion wc = new WaitCriterion() {
String excuse;
@Override
public boolean done() {
return cache.getCacheServers().size() == 1;
}
@Override
public String description() {
return excuse;
}
};
GeodeAwaitility.await().untilAsserted(wc);
CacheServerImpl bs = (CacheServerImpl) cache.getCacheServers().iterator().next();
assertNotNull(bs);
assertNotNull(bs.getAcceptor());
assertNotNull(bs.getAcceptor().getCacheClientNotifier());
final CacheClientNotifier ccn = bs.getAcceptor().getCacheClientNotifier();
wc = new WaitCriterion() {
String excuse;
@Override
public boolean done() {
return ccn.getClientProxies().size() > 0;
}
@Override
public String description() {
return excuse;
}
};
GeodeAwaitility.await().untilAsserted(wc);
Collection<CacheClientProxy> proxies = ccn.getClientProxies();
Iterator<CacheClientProxy> iter_prox = proxies.iterator();
if (iter_prox.hasNext()) {
final CacheClientProxy proxy = iter_prox.next();
wc = new WaitCriterion() {
String excuse;
@Override
public boolean done() {
return proxy._messageDispatcher.isAlive();
}
@Override
public String description() {
return excuse;
}
};
GeodeAwaitility.await().untilAsserted(wc);
}
} catch (Exception ex) {
fail("while setting verifyDispatcherIsAlive " + ex);
}
}
public static void verifyDispatcherIsNotAlive() {
try {
Cache c = getAnyInstance();
// assertIndexDetailsEquals("More than one BridgeServer", 1,
// c.getCacheServers().size());
WaitCriterion wc = new WaitCriterion() {
String excuse;
@Override
public boolean done() {
return cache.getCacheServers().size() == 1;
}
@Override
public String description() {
return excuse;
}
};
GeodeAwaitility.await().untilAsserted(wc);
CacheServerImpl bs = (CacheServerImpl) c.getCacheServers().iterator().next();
assertNotNull(bs);
assertNotNull(bs.getAcceptor());
assertNotNull(bs.getAcceptor().getCacheClientNotifier());
final CacheClientNotifier ccn = bs.getAcceptor().getCacheClientNotifier();
wc = new WaitCriterion() {
String excuse;
@Override
public boolean done() {
return ccn.getClientProxies().size() > 0;
}
@Override
public String description() {
return excuse;
}
};
GeodeAwaitility.await().untilAsserted(wc);
Iterator iter_prox = ccn.getClientProxies().iterator();
if (iter_prox.hasNext()) {
CacheClientProxy proxy = (CacheClientProxy) iter_prox.next();
assertFalse("Dispatcher on secondary should not be alive",
proxy._messageDispatcher.isAlive());
}
} catch (Exception ex) {
fail("while setting verifyDispatcherIsNotAlive " + ex);
}
}
private void createCache(Properties props) throws Exception {
DistributedSystem ds = getSystem(props);
assertNotNull(ds);
ds.disconnect();
ds = getSystem(props);
cache = CacheFactory.create(ds);
assertNotNull(cache);
}
public static void createClientCache(String testName, String host) throws Exception {
Properties props = new Properties();
props.setProperty(MCAST_PORT, "0");
props.setProperty(LOCATORS, "");
new HAStartupAndFailoverDUnitTest().createCache(props);
PoolImpl p = (PoolImpl) PoolManager.createFactory().addServer(host, PORT1.intValue())
.addServer(host, PORT2.intValue()).addServer(host, PORT3.intValue())
.setSubscriptionEnabled(true).setSubscriptionRedundancy(-1).setReadTimeout(10000)
// .setRetryInterval(2000)
.create("HAStartupAndFailoverDUnitTestPool");
AttributesFactory factory = new AttributesFactory();
factory.setScope(Scope.LOCAL);
factory.setPoolName(p.getName());
RegionAttributes attrs = factory.create();
cache.createRegion(REGION_NAME, attrs);
pool = p;
conn = pool.acquireConnection();
assertNotNull(conn);
}
public static void createClientCacheWithLargeRetryInterval(String testName, String host)
throws Exception {
Properties props = new Properties();
props.setProperty(MCAST_PORT, "0");
props.setProperty(LOCATORS, "");
new HAStartupAndFailoverDUnitTest().createCache(props);
PoolImpl p = (PoolImpl) PoolManager.createFactory().addServer(host, PORT1.intValue())
.addServer(host, PORT2.intValue()).addServer(host, PORT3.intValue())
.setSubscriptionEnabled(true).setSubscriptionRedundancy(-1).setReadTimeout(10000)
// .setRetryInterval(2000000)
.create("HAStartupAndFailoverDUnitTestPool");
AttributesFactory factory = new AttributesFactory();
factory.setScope(Scope.LOCAL);
factory.setPoolName(p.getName());
RegionAttributes attrs = factory.create();
cache.createRegion(REGION_NAME, attrs);
pool = p;
conn = pool.acquireConnection();
assertNotNull(conn);
}
public static void createClientCacheWithLargeRetryIntervalAndWithoutCallbackConnection(
String testName, String host) throws Exception {
Properties props = new Properties();
props.setProperty(MCAST_PORT, "0");
props.setProperty(LOCATORS, "");
new HAStartupAndFailoverDUnitTest().createCache(props);
CacheServerTestUtil.disableShufflingOfEndpoints();
PoolImpl p;
try {
p = (PoolImpl) PoolManager.createFactory().addServer(host, PORT1.intValue())
.addServer(host, PORT2.intValue()).addServer(host, PORT3.intValue()).setPingInterval(500)
// .setRetryInterval(200000)
.create("HAStartupAndFailoverDUnitTestPool");
} finally {
CacheServerTestUtil.enableShufflingOfEndpoints();
}
AttributesFactory factory = new AttributesFactory();
factory.setScope(Scope.LOCAL);
factory.setPoolName(p.getName());
RegionAttributes attrs = factory.create();
cache.createRegion(REGION_NAME, attrs);
pool = p;
// since the default minConnections is 1 we currently have a connection to
// server1 (vm_0). Now we create a connection to server2 (vm_1)
conn = pool.acquireConnection(new ServerLocation(Host.getHost(0).getHostName(), PORT2));
// assert that the conn is to server2 since the tests assume that this is so
assertNotNull(conn);
assertTrue(conn.getEndpoint().getLocation().getPort() == PORT2);
}
public static void createClientCacheWithIncorrectPrimary(String testName, String host)
throws Exception {
Properties props = new Properties();
props.setProperty(MCAST_PORT, "0");
props.setProperty(LOCATORS, "");
new HAStartupAndFailoverDUnitTest().createCache(props);
final int INCORRECT_PORT = 1;
PoolImpl p = (PoolImpl) PoolManager.createFactory().addServer(host, INCORRECT_PORT)
.addServer(host, PORT2.intValue()).addServer(host, PORT3.intValue())
.setSubscriptionEnabled(true).setSubscriptionRedundancy(-1).setReadTimeout(10000)
// .setRetryInterval(10000)
.create("HAStartupAndFailoverDUnitTestPool");
AttributesFactory factory = new AttributesFactory();
factory.setScope(Scope.LOCAL);
factory.setPoolName(p.getName());
RegionAttributes attrs = factory.create();
cache.createRegion(REGION_NAME, attrs);
pool = p;
conn = pool.acquireConnection();
assertNotNull(conn);
}
public static Integer createServerCache() throws Exception {
new HAStartupAndFailoverDUnitTest().createCache(new Properties());
AttributesFactory factory = new AttributesFactory();
factory.setScope(Scope.DISTRIBUTED_ACK);
factory.setEnableBridgeConflation(true);
factory.setDataPolicy(DataPolicy.REPLICATE);
RegionAttributes attrs = factory.create();
cache.createRegion(REGION_NAME, attrs);
CacheServer server1 = cache.addCacheServer();
int port = getRandomAvailableTCPPort();
server1.setPort(port);
// ensures updates to be sent instead of invalidations
server1.setNotifyBySubscription(true);
server1.setMaximumTimeBetweenPings(180000);
server1.start();
return new Integer(server1.getPort());
}
@Override
public final void preTearDown() throws Exception {
// close the clients first
closeCache();
// then close the servers
server1.invoke(() -> HAStartupAndFailoverDUnitTest.closeCache());
server2.invoke(() -> HAStartupAndFailoverDUnitTest.closeCache());
server3.invoke(() -> HAStartupAndFailoverDUnitTest.closeCache());
CacheServerTestUtil.resetDisableShufflingOfEndpointsFlag();
}
public static void closeCache() {
if (cache != null && !cache.isClosed()) {
PoolImpl.AFTER_PRIMARY_IDENTIFICATION_FROM_BACKUP_CALLBACK_FLAG = false;
HAStartupAndFailoverDUnitTest.identifiedPrimary = false;
cache.close();
cache.getDistributedSystem().disconnect();
}
}
}
|
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.api.ads.adwords.jaxws.v201806.cm;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
*
* Applies the list of mutate operations.
*
* @param operations The operations to apply. The same {@link Label} cannot be specified in
* more than one operation.
* @return The applied {@link Label}s.
* @throws ApiException when there is at least one error with the request
*
*
* <p>Java class for mutate element declaration.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <element name="mutate">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="operations" type="{https://adwords.google.com/api/adwords/cm/v201806}LabelOperation" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"operations"
})
@XmlRootElement(name = "mutate")
public class LabelServiceInterfacemutate {
protected List<LabelOperation> operations;
/**
* Gets the value of the operations property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the operations property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getOperations().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link LabelOperation }
*
*
*/
public List<LabelOperation> getOperations() {
if (operations == null) {
operations = new ArrayList<LabelOperation>();
}
return this.operations;
}
}
|
package com.zhangguojian.json.exception;
public class CastException extends JSONException{
public CastException(String msg) {
super(msg);
}
}
|
package com.wuwenxu.codecamp.base.bean;
import com.wuwenxu.codecamp.base.bean.BeanStruct;
import com.wuwenxu.codecamp.base.utils.CheckUtil;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Hashtable;
import java.util.Map;
/**
* 提供一些BeanUti需要的方法
*/
public class BeanFactory {
/**
* 存放BeanUtil解析过的JavaBean数据
* 只获取简单的属性字段
*/
public static Map<String, Map<String, BeanStruct>> BEAN_SIMPLE_PROPERTIES = new Hashtable<>();
/**
* 存放BeanUtil解析过的JavaBean数据
* 只获取简单的属性字段(忽略字段名字的大小写)
*/
public static Map<String, Map<String, BeanStruct>> BEAN_SIMPLE_PROPERTIESIGNORE = new Hashtable<>();
static {
//可以实现实现明确的JavaBean的配置
}
public static boolean isDeclaredField(String className, String pro) throws ClassNotFoundException {
Class classz = Class.forName(className);
Field[] fields = classz.getFields();
if (CheckUtil.valid(fields)) {
for (Field f : fields) {
if (f.getName().equals(pro)) {
return false;
}
}
}
return true;
}
/**
* 将JavaBean进行解析并存在在static变量中
*
* @param obj
*/
public static void add(Object obj) throws IntrospectionException, ClassNotFoundException {
add(obj.getClass());
}
public static void add(Class clazz) throws IntrospectionException, ClassNotFoundException {
String className = clazz.getName();
if (!CheckUtil.valid(BEAN_SIMPLE_PROPERTIES.get(className))) {
BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
PropertyDescriptor[] proDescrtptors = beanInfo.getPropertyDescriptors();
if (proDescrtptors != null && proDescrtptors.length > 0) {
Map<String, BeanStruct> simpleProperties = new Hashtable<>();
Map<String, BeanStruct> simplePropertiesIgnore = new Hashtable<>();
for (PropertyDescriptor propDesc : proDescrtptors) {
String fieldName = propDesc.getName();
if (!"class".equals(fieldName)) {
Object type = propDesc.getPropertyType();
Method readMethod = propDesc.getReadMethod();
Method writeMethod = propDesc.getWriteMethod();
boolean isDeclared = isDeclaredField(className, fieldName);
simpleProperties.put(fieldName, new BeanStruct(fieldName, type, readMethod, writeMethod, isDeclared));
simplePropertiesIgnore.put(fieldName.toLowerCase(), new BeanStruct(fieldName, type, readMethod, writeMethod, isDeclared));
}
}
BEAN_SIMPLE_PROPERTIES.put(className, simpleProperties);
BEAN_SIMPLE_PROPERTIESIGNORE.put(className, simplePropertiesIgnore);
}
}
}
}
|
/*
* Copyright © 2019 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.plugin.db.batch.action;
import io.cdap.cdap.api.annotation.Description;
import io.cdap.cdap.api.annotation.Macro;
import io.cdap.plugin.db.ConnectionConfig;
/**
* Config for Actions running database commands
*/
public abstract class QueryConfig extends ConnectionConfig {
public static final String QUERY = "query";
@Description("The database command to run.")
@Macro
public String query;
public QueryConfig() {
super();
}
}
|
package com.bumptech.glide.manager;
import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.util.Synthetic;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* A view-less {@link androidx.fragment.app.Fragment} used to safely store an {@link
* com.bumptech.glide.RequestManager} that can be used to start, stop and manage Glide requests
* started for targets within the fragment or activity this fragment is a child of.
*
* @see com.bumptech.glide.manager.RequestManagerFragment
* @see com.bumptech.glide.manager.RequestManagerRetriever
* @see com.bumptech.glide.RequestManager
*/
public class SupportRequestManagerFragment extends Fragment {
private static final String TAG = "SupportRMFragment";
private final ActivityFragmentLifecycle lifecycle;
private final RequestManagerTreeNode requestManagerTreeNode =
new SupportFragmentRequestManagerTreeNode();
private final Set<SupportRequestManagerFragment> childRequestManagerFragments = new HashSet<>();
@Nullable private SupportRequestManagerFragment rootRequestManagerFragment;
@Nullable private RequestManager requestManager;
@Nullable private Fragment parentFragmentHint;
public SupportRequestManagerFragment() {
this(new ActivityFragmentLifecycle());
}
@VisibleForTesting
@SuppressLint("ValidFragment")
public SupportRequestManagerFragment(@NonNull ActivityFragmentLifecycle lifecycle) {
this.lifecycle = lifecycle;
}
/**
* Sets the current {@link com.bumptech.glide.RequestManager}.
*
* @param requestManager The manager to put.
*/
public void setRequestManager(@Nullable RequestManager requestManager) {
this.requestManager = requestManager;
}
@NonNull
ActivityFragmentLifecycle getGlideLifecycle() {
return lifecycle;
}
/** Returns the current {@link com.bumptech.glide.RequestManager} or null if none is put. */
@Nullable
public RequestManager getRequestManager() {
return requestManager;
}
/**
* Returns the {@link RequestManagerTreeNode} that provides tree traversal methods relative to the
* associated {@link RequestManager}.
*/
@NonNull
public RequestManagerTreeNode getRequestManagerTreeNode() {
return requestManagerTreeNode;
}
private void addChildRequestManagerFragment(SupportRequestManagerFragment child) {
childRequestManagerFragments.add(child);
}
private void removeChildRequestManagerFragment(SupportRequestManagerFragment child) {
childRequestManagerFragments.remove(child);
}
/**
* Returns the set of fragments that this RequestManagerFragment's parent is a parent to. (i.e.
* our parent is the fragment that we are annotating).
*/
@Synthetic
@NonNull
Set<SupportRequestManagerFragment> getDescendantRequestManagerFragments() {
if (rootRequestManagerFragment == null) {
return Collections.emptySet();
} else if (equals(rootRequestManagerFragment)) {
return Collections.unmodifiableSet(childRequestManagerFragments);
} else {
Set<SupportRequestManagerFragment> descendants = new HashSet<>();
for (SupportRequestManagerFragment fragment :
rootRequestManagerFragment.getDescendantRequestManagerFragments()) {
if (isDescendant(fragment.getParentFragmentUsingHint())) {
descendants.add(fragment);
}
}
return Collections.unmodifiableSet(descendants);
}
}
/**
* Sets a hint for which fragment is our parent which allows the fragment to return correct
* information about its parents before pending fragment transactions have been executed.
*/
void setParentFragmentHint(@Nullable Fragment parentFragmentHint) {
this.parentFragmentHint = parentFragmentHint;
if (parentFragmentHint == null || parentFragmentHint.getContext() == null) {
return;
}
FragmentManager rootFragmentManager = getRootFragmentManager(parentFragmentHint);
if (rootFragmentManager == null) {
return;
}
registerFragmentWithRoot(parentFragmentHint.getContext(), rootFragmentManager);
}
@Nullable
private static FragmentManager getRootFragmentManager(@NonNull Fragment fragment) {
while (fragment.getParentFragment() != null) {
fragment = fragment.getParentFragment();
}
return fragment.getFragmentManager();
}
@Nullable
private Fragment getParentFragmentUsingHint() {
Fragment fragment = getParentFragment();
return fragment != null ? fragment : parentFragmentHint;
}
/** Returns true if the fragment is a descendant of our parent. */
private boolean isDescendant(@NonNull Fragment fragment) {
Fragment root = getParentFragmentUsingHint();
Fragment parentFragment;
while ((parentFragment = fragment.getParentFragment()) != null) {
if (parentFragment.equals(root)) {
return true;
}
fragment = fragment.getParentFragment();
}
return false;
}
private void registerFragmentWithRoot(
@NonNull Context context, @NonNull FragmentManager fragmentManager) {
unregisterFragmentWithRoot();
rootRequestManagerFragment =
Glide.get(context)
.getRequestManagerRetriever()
.getSupportRequestManagerFragment(context, fragmentManager);
if (!equals(rootRequestManagerFragment)) {
rootRequestManagerFragment.addChildRequestManagerFragment(this);
}
}
private void unregisterFragmentWithRoot() {
if (rootRequestManagerFragment != null) {
rootRequestManagerFragment.removeChildRequestManagerFragment(this);
rootRequestManagerFragment = null;
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
FragmentManager rootFragmentManager = getRootFragmentManager(this);
if (rootFragmentManager == null) {
if (Log.isLoggable(TAG, Log.WARN)) {
// Not expected to occur; ancestor fragments should be attached before descendants.
Log.w(TAG, "Unable to register fragment with root, ancestor detached");
}
return;
}
try {
registerFragmentWithRoot(getContext(), rootFragmentManager);
} catch (IllegalStateException e) {
// OnAttach can be called after the activity is destroyed, see #497.
if (Log.isLoggable(TAG, Log.WARN)) {
Log.w(TAG, "Unable to register fragment with root", e);
}
}
}
@Override
public void onDetach() {
super.onDetach();
parentFragmentHint = null;
unregisterFragmentWithRoot();
}
@Override
public void onStart() {
super.onStart();
lifecycle.onStart();
}
@Override
public void onStop() {
super.onStop();
lifecycle.onStop();
}
@Override
public void onDestroy() {
super.onDestroy();
lifecycle.onDestroy();
unregisterFragmentWithRoot();
}
@Override
public String toString() {
return super.toString() + "{parent=" + getParentFragmentUsingHint() + "}";
}
private class SupportFragmentRequestManagerTreeNode implements RequestManagerTreeNode {
@Synthetic
SupportFragmentRequestManagerTreeNode() {}
@NonNull
@Override
public Set<RequestManager> getDescendants() {
Set<SupportRequestManagerFragment> descendantFragments =
getDescendantRequestManagerFragments();
Set<RequestManager> descendants = new HashSet<>(descendantFragments.size());
for (SupportRequestManagerFragment fragment : descendantFragments) {
if (fragment.getRequestManager() != null) {
descendants.add(fragment.getRequestManager());
}
}
return descendants;
}
@Override
public String toString() {
return super.toString() + "{fragment=" + SupportRequestManagerFragment.this + "}";
}
}
}
|
package p005cm.aptoide.p006pt.autoupdate;
import org.jacoco.agent.p025rt.internal_8ff85ea.Offline;
import p026rx.p027b.C0128a;
/* renamed from: cm.aptoide.pt.autoupdate.AutoUpdateService$loadAutoUpdateModel$3 */
/* compiled from: AutoUpdateService.kt */
final class AutoUpdateService$loadAutoUpdateModel$3 implements C0128a {
private static transient /* synthetic */ boolean[] $jacocoData;
final /* synthetic */ AutoUpdateService this$0;
private static /* synthetic */ boolean[] $jacocoInit() {
boolean[] zArr = $jacocoData;
if (zArr != null) {
return zArr;
}
boolean[] probes = Offline.getProbes(9015366680056195411L, "cm/aptoide/pt/autoupdate/AutoUpdateService$loadAutoUpdateModel$3", 2);
$jacocoData = probes;
return probes;
}
AutoUpdateService$loadAutoUpdateModel$3(AutoUpdateService autoUpdateService) {
boolean[] $jacocoInit = $jacocoInit();
this.this$0 = autoUpdateService;
$jacocoInit[1] = true;
}
public final void call() {
boolean[] $jacocoInit = $jacocoInit();
AutoUpdateService.access$setLoading$p(this.this$0, false);
$jacocoInit[0] = true;
}
}
|
package org.dhis2.fhir.adapter.dhis.tracker.program;
/*
* Copyright (c) 2004-2018, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
public enum EventStatus
{
SKIPPED,
VISITED,
COMPLETED,
SCHEDULE,
OVERDUE,
ACTIVE
}
|
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2007, 2008 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.cluster.impl;
/**
* database methods.
*/
public interface ClusterServiceSql
{
/**
* returns the sql statement for deleting locks for a given session from the sakai_locks table.
*/
String getDeleteLocksSql();
/**
* @return the SQL statement to find lock records belonging to closed or deleted sessions
*/
String getOrphanedLockSessionsSql();
/**
* returns the sql statement for deleting a server from the sakai_cluster table.
*/
String getDeleteServerSql();
/**
* returns the sql statement for inserting a server id into the sakai_cluster table.
*/
String getInsertServerSql();
/**
* returns the sql statement for obtaining a list of expired sakai servers from the sakai_cluster table. <br/>br/>
*
* @param timeout
* how long (in seconds) we give an app server to respond before it is considered lost.
*/
String getListExpiredServers(long timeout);
/**
* returns the sql statement for obtaining a list of sakai servers from the sakai_cluster table in server_id order.
*/
String getListServersSql();
/**
* returns the sql statement for retrieving a particular server from the sakai_cluster table.
*/
String getReadServerSql();
/**
* returns the sql statement for updating a server in the sakai_cluster table.
*/
String getUpdateServerSql();
/**
* returns the sql statement for listing the servers and their status from the sakai_cluster table.
*/
String getListServerStatusSql();
/**
* returns the current timestamp.
*/
String sqlTimestamp();
}
|
package de.deadlocker8.budgetmaster.unit;
import de.deadlocker8.budgetmaster.Main;
import de.deadlocker8.budgetmaster.accounts.AccountService;
import de.deadlocker8.budgetmaster.accounts.AccountType;
import de.deadlocker8.budgetmaster.filter.FilterConfiguration;
import de.deadlocker8.budgetmaster.integration.helpers.SeleniumTest;
import de.deadlocker8.budgetmaster.transactions.Transaction;
import de.deadlocker8.budgetmaster.transactions.TransactionService;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.transaction.annotation.Transactional;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(classes = Main.class)
@Import(TransactionServiceDatabaseTest.TestDatabaseConfiguration.class)
@ActiveProfiles("test")
@SeleniumTest
@Transactional
class TransactionServiceDatabaseTest
{
@TestConfiguration
static class TestDatabaseConfiguration
{
@Value("classpath:repeating_with_tags.mv.db")
private Resource databaseResource;
@Bean
@Primary
public DataSource dataSource() throws IOException
{
final String folderName = databaseResource.getFile().getAbsolutePath().replace(".mv.db", "");
String jdbcString = "jdbc:h2:/" + folderName + ";DB_CLOSE_ON_EXIT=TRUE";
return DataSourceBuilder.create().username("sa").password("").url(jdbcString).driverClassName("org.h2.Driver").build();
}
}
@Autowired
private TransactionService transactionService;
@Autowired
private AccountService accountService;
@Test
void test_deleteAll()
{
transactionService.deleteAll();
assertThat(transactionService.getRepository().findAll()).isEmpty();
}
@Test
void test_getTransactionsForAccount_specificAccount()
{
DateTime date1 = DateTime.parse("2020-04-30", DateTimeFormat.forPattern("yyyy-MM-dd"));
FilterConfiguration filterConfiguration = new FilterConfiguration(true, true, true, true, true, null, null, "");
List<Transaction> transactions = transactionService.getTransactionsForAccount(accountService.getRepository().findByName("Second Account"), date1, DateTime.now(), filterConfiguration);
assertThat(transactions).hasSize(2);
assertThat(transactions.get(0)).hasFieldOrPropertyWithValue("ID", 9); // transfer
assertThat(transactions.get(1)).hasFieldOrPropertyWithValue("ID", 37); // normal transaction
}
@Test
void test_getTransactionsForAccount_all()
{
DateTime date1 = DateTime.parse("2020-04-30", DateTimeFormat.forPattern("yyyy-MM-dd"));
FilterConfiguration filterConfiguration = new FilterConfiguration(true, true, true, true, true, null, null, "");
List<Transaction> transactions = transactionService.getTransactionsForAccount(accountService.getRepository().findAllByType(AccountType.ALL).get(0), date1, DateTime.now(), filterConfiguration);
assertThat(transactions).hasSize(7);
}
@Test
void test_getTransactionsForAccountUntilDate()
{
DateTime date1 = DateTime.parse("2020-04-30", DateTimeFormat.forPattern("yyyy-MM-dd"));
DateTime date2 = DateTime.parse("2020-05-20", DateTimeFormat.forPattern("yyyy-MM-dd"));
FilterConfiguration filterConfiguration = new FilterConfiguration(true, true, true, true, true, null, null, "");
List<Transaction> transactions = transactionService.getTransactionsForAccount(accountService.getRepository().findByName("Default Account"), date1, date2, filterConfiguration);
assertThat(transactions).hasSize(2);
}
@Test
void test_getTransactionsForMonthAndYear()
{
FilterConfiguration filterConfiguration = new FilterConfiguration(true, true, true, true, true, null, null, "");
List<Transaction> transactions = transactionService.getTransactionsForMonthAndYear(accountService.getRepository().findByName("Default Account"), 6, 2020, false, filterConfiguration);
assertThat(transactions).hasSize(1);
}
}
|
package io.github.cbadenes.crosslingual.data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Badenes Olmedo, Carlos <cbadenes@fi.upm.es>
*/
public class Text {
private static final Logger LOG = LoggerFactory.getLogger(Text.class);
private String text;
public Text() {
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
|
package zaizai.com;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.ajguan.R;
import com.ajguan.library.EasyRefreshLayout;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import zaizai.com.View.RefreshHeaderView;
public class EasyFragment extends Fragment {
private View rootView;
private EasyRefreshLayout easyRefreshLayout;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private SimpleAdapter adapter;
public EasyFragment() {
// Required empty public constructor
}
private void initListener() {
easyRefreshLayout.addEasyEvent(new EasyRefreshLayout.EasyEvent() {
@Override
public void onLoadMore() {
final List<String> list = new ArrayList<>();
for (int i = 0; i < 5; i++) {
list.add("this is new load data >>>>" + new Date().toLocaleString());
}
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
easyRefreshLayout.closeLoadView();
int postion = adapter.getData().size();
adapter.getData().addAll(list);
adapter.notifyDataSetChanged();
recyclerView.scrollToPosition(postion);
}
}, 500);
}
@Override
public void onRefreshing() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
List<String> list = new ArrayList<>();
for (int i = 0; i < 20; i++) {
list.add("this is refresh data >>>" + new Date().toLocaleString());
}
adapter.setNewData(list);
easyRefreshLayout.refreshComplete();
Toast.makeText(getContext(), "refresh success", Toast.LENGTH_SHORT).show();
}
}, 1000);
}
});
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_easy, container, false);
easyRefreshLayout = (EasyRefreshLayout) rootView.findViewById(R.id.easylayout);
easyRefreshLayout.setRefreshHeadView(new RefreshHeaderView(getActivity()));
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter = new SimpleAdapter();
recyclerView.setAdapter(adapter);
initData();
initListener();
return rootView;
}
private void initData() {
List<String> list = new ArrayList<>();
for (int i = 0; i < 20; i++) {
list.add("EasyRefreshLayout index :" + i);
}
adapter.getData().addAll(list);
adapter.notifyDataSetChanged();
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public void onDetach() {
super.onDetach();
}
}
|
package duelistmod.cards;
import com.megacrit.cardcrawl.cards.AbstractCard;
import com.megacrit.cardcrawl.characters.AbstractPlayer;
import com.megacrit.cardcrawl.core.CardCrawlGame;
import com.megacrit.cardcrawl.dungeons.AbstractDungeon;
import com.megacrit.cardcrawl.localization.CardStrings;
import com.megacrit.cardcrawl.monsters.AbstractMonster;
import com.megacrit.cardcrawl.orbs.*;
import duelistmod.DuelistMod;
import duelistmod.abstracts.DuelistCard;
import duelistmod.patches.AbstractCardEnum;
import duelistmod.powers.*;
import duelistmod.variables.Tags;
public class LightningRodLord extends DuelistCard
{
// TEXT DECLARATION
public static final String ID = DuelistMod.makeID("LightningRodLord");
private static final CardStrings cardStrings = CardCrawlGame.languagePack.getCardStrings(ID);
public static final String IMG = DuelistMod.makeCardPath("LightningRodLord.png");
public static final String NAME = cardStrings.NAME;
public static final String DESCRIPTION = cardStrings.DESCRIPTION;
public static final String UPGRADE_DESCRIPTION = cardStrings.UPGRADE_DESCRIPTION;
// /TEXT DECLARATION/
// STAT DECLARATION
private static final CardRarity RARITY = CardRarity.UNCOMMON;
private static final CardTarget TARGET = CardTarget.ALL_ENEMY;
private static final CardType TYPE = CardType.ATTACK;
public static final CardColor COLOR = AbstractCardEnum.DUELIST_MONSTERS;
private static final int COST = 1;
// /STAT DECLARATION/
public LightningRodLord() {
super(ID, NAME, IMG, COST, DESCRIPTION, TYPE, COLOR, RARITY, TARGET);
this.baseDamage = this.damage = 12;
this.tributes = this.baseTributes = 4;
this.magicNumber = this.baseMagicNumber = 2;
this.secondMagic = this.baseSecondMagic = 2;
this.tags.add(Tags.MONSTER);
this.misc = 0;
this.originalName = this.name;
}
// Actions the card should do.
@Override
public void use(AbstractPlayer p, AbstractMonster m)
{
tribute();
int lightning = 0;
if (p.hasOrb())
{
lightning = p.maxOrbs - p.filledOrbCount();
if (lightning > 0)
{
for (int i = 0; i < lightning; i++)
{
AbstractOrb l = new Lightning();
channel(l);
m = AbstractDungeon.getRandomMonster();
if (m != null) { attack(m); }
}
}
}
else
{
lightning = p.maxOrbs;
if (lightning > 0)
{
for (int i = 0; i < lightning; i++)
{
AbstractOrb l = new Lightning();
channel(l);
m = AbstractDungeon.getRandomMonster();
if (m != null) { attack(m); }
}
}
}
applyPowerToSelf(new FocusDownPower(p, p, this.secondMagic, this.magicNumber));
}
// Which card to return when making a copy of this card.
@Override
public AbstractCard makeCopy() {
return new LightningRodLord();
}
// Upgraded stats.
@Override
public void upgrade()
{
if (!this.upgraded)
{
this.upgradeName();
this.upgradeTributes(-1);
this.upgradeSecondMagic(-1);
this.rawDescription = UPGRADE_DESCRIPTION;
this.initializeDescription();
}
}
@Override
public void onTribute(DuelistCard tributingCard)
{
}
@Override
public void onResummon(int summons) {
// TODO Auto-generated method stub
}
@Override
public void summonThis(int summons, DuelistCard c, int var) {
// TODO Auto-generated method stub
}
@Override
public void summonThis(int summons, DuelistCard c, int var, AbstractMonster m) {
// TODO Auto-generated method stub
}
@Override
public String getID() {
return ID;
}
@Override
public void optionSelected(AbstractPlayer arg0, AbstractMonster arg1, int arg2) {
// TODO Auto-generated method stub
}
}
|
package org.generation.blogPessoal.model;
public class UserLogin {
private String nome;
private String usuario;
private String senha;
private String token;
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getUsuario() {
return usuario;
}
public void setUsuario(String usuario) {
this.usuario = usuario;
}
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
|
/*
* Copyright 2018 Alfresco, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.activiti.runtime.api.cmd.result;
import org.activiti.runtime.api.cmd.SendSignal;
public interface SendSignalResult extends CommandResult<SendSignal> {
}
|
import java.util.Scanner;
public class PlaceTest {
//returns true if p1 is equidistant from p2 and p3
public static boolean sameDistance(Place p1, Place p2, Place p3)
{
return p1.distance(p2) == p1.distance(p3);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the x-coordinate for point 1: ");
double x1 = scanner.nextDouble();
System.out.print("Enter the y-coordinate for point 1: ");
double y1 = scanner.nextDouble();
System.out.print("Enter the x-coordinate for point 2: ");
double x2 = scanner.nextDouble();
System.out.print("Enter the y-coordinate for point 2: ");
double y2 = scanner.nextDouble();
System.out.print("Enter the x-coordinate for point 3: ");
double x3 = scanner.nextDouble();
System.out.print("Enter the y-coordinate for point 3: ");
double y3 = scanner.nextDouble();
Point p1 = new Point(x1, y1), p2= new Point(x2, y2), p3 = new Point(x3, y3);
boolean isEqual = sameDistance(p1, p2, p3);
String output = "Points " + p1 + ", " + p2 + ", and " + p3 + " are ";
if (!isEqual){
output += "not ";
}
output += "the same distance apart.";
System.out.println(output);
}
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.transport.mqtt.auto;
import org.apache.activemq.transport.mqtt.MQTTTest;
/**
* Run the basic tests with the NIO Transport.
*/
public class MQTTAutoNioTest extends MQTTTest {
@Override
public String getProtocolScheme() {
return "auto+nio";
}
@Override
public boolean isUseSSL() {
return false;
}
}
|
// Copyright 2017 Archos SA
//
// 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.archos.mediacenter.video.leanback;
/**
* Created by alexandre on 02/11/15.
*/
public class CompatibleCursorLoaderConverter {
}
|
package com.codebroker.core;
import akka.actor.typed.ActorSystem;
import com.codebroker.api.AppListener;
import com.codebroker.api.IGameWorld;
import com.codebroker.api.internal.IService;
import com.codebroker.core.actortype.message.IGameRootSystemMessage;
import com.codebroker.util.PropertiesWrapper;
import java.util.Optional;
/**
* 上下文解析器.
*/
public final class ContextResolver {
private static KernelContext context;
private static IGameWorld gameWorld;
private ContextResolver() {
}
public static PropertiesWrapper getPropertiesWrapper() {
return context.getPropertiesWrapper();
}
public static AppListener getAppListener() {
return context.getAppListener();
}
public static <T> Optional<T> getManager(Class<T> type) {
return context.getManager(type);
}
public static <T> Optional<T> getComponent(Class<T> type) {
return context.getComponent(type);
}
static KernelContext getContext() {
return context;
}
static void setTaskState(KernelContext ctx) {
context = ctx;
}
public static void setManager(IService service) {
context.setManager(service);
}
public static ActorSystem<IGameRootSystemMessage> getActorSystem() {
return context.getActorSystem();
}
public static IGameWorld getGameWorld() {
return gameWorld;
}
public static void setGameWorld(IGameWorld gameWorld) {
ContextResolver.gameWorld = gameWorld;
}
public static void setComponent(IService service) {
context.setComponent(service);
}
}
|
package pers.husen.highdsa.constants;
/**
* Description http请求常量
* <p>
* Author 何明胜
* <p>
* Created at 2018/05/13 16:09
* <p>
* Version 1.0.0
*/
public class HttpConstants {
/** 登录基础url */
public static final String BASE_URL = "http://223.3.89.104:8080/highdsa-restful-app/";
//public static final String BASE_URL = "http:// 192.168.42.88:8081/highdsa-restful-app/";
/** 登录 */
public static final String URL_LOGIN = BASE_URL + "app/v1/login/phone";
/** 退出登录 */
public static final String URL_LOGOUT = BASE_URL + "app/v1/logout";
/** 发送验证码 */
public static final String URL_SEND_CODE = BASE_URL + "sms/v1/captcha";
/** 校验验证码 */
public static final String URL_VALIDATE_CODE = BASE_URL + "sms/v1/validate";
/** 校验验证码 */
public static final String URL_REGISTER_USER = BASE_URL + "register/v1/user";
/** 找回密码 */
public static final String URL_FORGET_PASSWORD = BASE_URL + "app/v1/password";
/** 获取个人信息 */
public static final String URL_USER_INFO = BASE_URL + "app/v1/user/info/phone";
}
|
package com.atommiddleware.cloud.core.annotation;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import org.apache.dubbo.common.bytecode.CustomizedLoaderClassPath;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.boot.WebApplicationType;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import com.atommiddleware.cloud.api.annotation.ParamAttribute;
import com.atommiddleware.cloud.api.annotation.PathMapping;
import com.atommiddleware.cloud.core.annotation.BaseApiWrapper.ParamFromType;
import com.atommiddleware.cloud.core.config.DubboReferenceConfig;
import com.atommiddleware.cloud.core.config.DubboReferenceConfigProperties;
import com.atommiddleware.cloud.core.context.DubboApiContext;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtField;
import javassist.CtMethod;
import javassist.NotFoundException;
import javassist.bytecode.AnnotationsAttribute;
import javassist.bytecode.ClassFile;
import javassist.bytecode.ConstPool;
import javassist.bytecode.annotation.Annotation;
import javassist.bytecode.annotation.BooleanMemberValue;
public class DefaultDubboApiWrapperFactory extends AbstractDubboApiWrapperFactory {
private static AtomicLong WRAPPER_CLASS_COUNTER = new AtomicLong(0);
private static final Map<ClassLoader, ClassPool> POOL_MAP = new ConcurrentHashMap<ClassLoader, ClassPool>(); //ClassLoader - ClassPool
public static ClassPool getClassPool(ClassLoader loader) {
if (loader == null) {
return ClassPool.getDefault();
}
ClassPool pool = POOL_MAP.get(loader);
if (pool == null) {
pool = new ClassPool(true);
pool.appendClassPath(new CustomizedLoaderClassPath(loader));
POOL_MAP.put(loader, pool);
}
return pool;
}
@Override
public Class<?> make(String id, Class<?> interfaceClass,
DubboReferenceConfigProperties dubboReferenceConfigProperties, WebApplicationType webApplicationType)
throws CannotCompileException, NotFoundException, IllegalArgumentException, IllegalAccessException,
IOException {
final Map<String, Class<?>> mapClasses = DubboApiContext.MAP_CLASSES;
final Map<String, Map<Integer, List<ParamInfo>>> mapParamInfo = DubboApiContext.MAP_PARAM_INFO;
List<PathMappingMethodInfo> listPathMappingMethodInfo = new ArrayList<PathMappingMethodInfo>();
Arrays.stream(interfaceClass.getMethods()).forEach(o -> {
PathMapping pathMapping = AnnotationUtils.findAnnotation(o, PathMapping.class);
if (null != pathMapping) {
if (DubboApiContext.PATTERNS_REQUESTMETHOD.containsKey(pathMapping.path())) {
throw new IllegalArgumentException("pathPatterns:[" + pathMapping.path() + "] repeat");
}
DubboApiContext.PATTERNS_REQUESTMETHOD.put(pathMapping.path(), pathMapping.requestMethod());
PathMappingMethodInfo pathMappingMethodInfo = new PathMappingMethodInfo(o, pathMapping);
if (o.getParameters().length > 0) {
String[] strParamNames = getMethodParamName(o);
Parameter[] parameters = o.getParameters();
Class<?>[] typeParameters = o.getParameterTypes();
int i = 0;
boolean isSimpleType = true;
boolean isAllChildSimpleType = true;
Class<?> currentType = null;
for (Parameter p : parameters) {
if (!mapClasses.containsKey(typeParameters[i].getName())) {
mapClasses.put(typeParameters[i].getName(), typeParameters[i]);
}
ParamAttribute an = AnnotatedElementUtils.getMergedAnnotation(p, ParamAttribute.class);
if (null != an) {
if (null == strParamNames) {
if (StringUtils.isEmpty(an.name())
&& an.type() != ParamFromType.FROM_BODY.getParamFromType()) {
throw new IllegalArgumentException("ParamAttribute verification exception");
}
}
currentType = typeParameters[i];
isSimpleType = true;
isAllChildSimpleType = true;
if (ClassUtils.isSimpleType(currentType)) {
isSimpleType = true;
isAllChildSimpleType = true;
} else {
isSimpleType = false;
// 遍历所有参数
boolean flag = false;
for (Field f : currentType.getDeclaredFields()) {
flag = f.isAccessible();
f.setAccessible(true);
if (!ClassUtils.isSimpleType(f.getType())) {
isAllChildSimpleType = false;
f.setAccessible(flag);
break;
}
}
if (isAllChildSimpleType) {
// 获取父类属性
for (Field f : currentType.getFields()) {
flag = f.isAccessible();
f.setAccessible(true);
if (!ClassUtils.isSimpleType(f.getType())) {
isAllChildSimpleType = false;
f.setAccessible(flag);
break;
}
}
}
}
// p.get
pathMappingMethodInfo
.getListParamMeta().add(
new ParamMeta(
an.type() == ParamFromType.FROM_BODY.getParamFromType() ? ""
: StringUtils.isEmpty(an.name()) ? strParamNames[i]
: an.name(),
typeParameters[i].getName(), an, isSimpleType,
isAllChildSimpleType));
} else {
throw new IllegalArgumentException("ParamAttribute verification exception");
}
i++;
}
}
listPathMappingMethodInfo.add(pathMappingMethodInfo);
}
});
if (!CollectionUtils.isEmpty(listPathMappingMethodInfo)) {
ClassPool pool =getClassPool(Thread.currentThread().getContextClassLoader());
// id
long idx = WRAPPER_CLASS_COUNTER.getAndIncrement();
// class
CtClass stuClass = pool.makeClass(interfaceClass.getName() + "$atommiddleware" + idx);
if (webApplicationType == WebApplicationType.REACTIVE) {
stuClass.setSuperclass(
pool.getCtClass("com.atommiddleware.cloud.core.annotation.AbstractDubboApiWrapper"));
} else {
stuClass.setSuperclass(
pool.getCtClass("com.atommiddleware.cloud.core.annotation.AbstractDubboApiServletWrapper"));
}
CtConstructor cons = new CtConstructor(new CtClass[] {}, stuClass);
CtField h = new CtField(pool.getCtClass(interfaceClass.getName()), "h", stuClass);
h.setModifiers(Modifier.PRIVATE);
stuClass.addField(h);
DubboReferenceConfig dubboReferenceConfig = dubboReferenceConfigProperties.getDubboRefer().get(id);
ClassFile classFile = stuClass.getClassFile();
ConstPool constPool = classFile.getConstPool();
Annotation dubboReferenceAnnotation = new Annotation(DubboReference.class.getCanonicalName(), constPool);
AnnotationsAttribute annotationsAttribute = new AnnotationsAttribute(constPool,
AnnotationsAttribute.visibleTag);
dubboReferenceAnnotation.addMemberValue("async", new BooleanMemberValue(true, constPool));
if (null != dubboReferenceConfig) {
handlerAnnotaionParams(dubboReferenceConfig, dubboReferenceAnnotation, constPool);
}
annotationsAttribute.addAnnotation(dubboReferenceAnnotation);
h.getFieldInfo().addAttribute(annotationsAttribute);
String handleTypeClass = webApplicationType == WebApplicationType.REACTIVE
? "org.springframework.web.server.ServerWebExchange"
: "javax.servlet.http.HttpServletRequest";
CtMethod ctMethod = new CtMethod(pool.getCtClass("java.util.concurrent.CompletableFuture"), "handler",
new CtClass[] { pool.getCtClass("java.lang.String"), pool.getCtClass(handleTypeClass),
pool.getCtClass("java.lang.Object") },
stuClass);
ctMethod.setModifiers(Modifier.PUBLIC);
StringBuilder strBody = new StringBuilder();
StringBuilder strParamTemp = new StringBuilder();
StringBuilder strParamTempConstructor = new StringBuilder();
strParamTempConstructor.append("{");
strBody.append("{");
for (PathMappingMethodInfo pathMappingMethodInfo : listPathMappingMethodInfo) {
strParamTemp.setLength(0);
String path = pathMappingMethodInfo.getPathMapping().path();
strParamTempConstructor.append(" patterns.add(\"" + path + "\"); ");
strBody.append(" if($1.equals(\"" + path + "\")){");
if (!CollectionUtils.isEmpty(pathMappingMethodInfo.getListParamMeta())) {
List<ParamInfo> listParamInfo = new ArrayList<ParamInfo>();
strBody.append(" java.lang.Object[] params=new java.lang.Object["
+ pathMappingMethodInfo.getListParamMeta().size() + "]; ");
int i = 0;
ParamInfo paramInfo;
for (ParamMeta paramMeta : pathMappingMethodInfo.getListParamMeta()) {
paramInfo = new ParamInfo(i, paramMeta.getParamName(), paramMeta.getParamAttribute().type(),
paramMeta.getParamType(), paramMeta.isSimpleType(), paramMeta.isChildAllSimpleType(),
paramMeta.getParamAttribute().required());
listParamInfo.add(paramInfo);
strParamTemp.append("(" + paramMeta.getParamType() + ")params[" + i + "],");
i++;
}
mapParamInfo.put(path, listParamInfo.stream()
.collect(Collectors.groupingBy(ParamInfo::getParamFromType, Collectors.toList())));
strBody.append(" handlerConvertParams(\"" + path + "\",$2,params,$3); ");
strBody.append(" h." + pathMappingMethodInfo.getMethod().getName() + "(");
strBody.append(strParamTemp.deleteCharAt(strParamTemp.length() - 1).toString());
strBody.append(");");
} else {
strBody.append(" h." + pathMappingMethodInfo.getMethod().getName() + "(");
strBody.append(");");
}
strBody.append("}");
}
strParamTempConstructor.append("}");
strBody.append(" return org.apache.dubbo.rpc.RpcContext.getContext().getCompletableFuture(); ");
strBody.append(" } ");
ctMethod.setBody(strBody.toString());
stuClass.addMethod(ctMethod);
cons.setBody(strParamTempConstructor.toString());
stuClass.addConstructor(cons);
return stuClass.toClass();
}
return null;
}
}
|
package dane.com.gyl.dane;
import android.os.Vibrator;
import android.app.Activity;
import dane.com.gyl.dane.Utilities;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.DragEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
public class JuegoImagenesActivity extends ActionBarActivity implements View.OnTouchListener{
static TextView t;
static HashMap<String, Object> pares = new HashMap<String, Object>();
static MediaPlayer mp1 = null;
static MediaPlayer mp2 = null;
static String letras = null;
static String letra_actual = null;
static int ejercicio = 0;
static String origen = null;
static Boolean patron1YaJugado = false; //Para el juego de imágenes. Indica si las 1eras 3 imágenes ya fueron mostradas.
static Boolean patron2YaJugado = false; //Para el juego de imágenes. Indica si las 2das 3 imágenes ya fueron mostradas.
static Boolean patron3YaJugado = false; //Para el juego de imágenes. Indica si las 3eras 3 imágenes ya fueron mostradas.
static Boolean patron4YaJugado = false; //Para el juego de imágenes. Indica si las 4tas 3 imágenes ya fueron mostradas.
static Boolean patron5YaJugado = false; //Para el juego de imágenes. Indica si las 5tas 3 imágenes ya fueron mostradas.
static ImageButton botonAvanzar = null;
static ImageButton botonHome = null;
static Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_juego_imagenes);
botonAvanzar = (ImageButton) findViewById(R.id.botonAvanzar);
botonAvanzar.setVisibility(View.INVISIBLE);
context = getApplicationContext();
botonHome = (ImageButton) findViewById(R.id.botonHome);
//Recuperar parámetros.
Bundle b = getIntent().getExtras();
letras = b.getString("letras");
letra_actual = b.getString("letra");
ejercicio = b.getInt("ejercicio");
origen = b.getString("origen");
patron1YaJugado = b.getBoolean("patron1YaJugado");
patron2YaJugado = b.getBoolean("patron2YaJugado");
patron3YaJugado = b.getBoolean("patron3YaJugado");
patron4YaJugado = b.getBoolean("patron4YaJugado");
patron5YaJugado = b.getBoolean("patron5YaJugado");
//Leer las dimensiones de la pantalla en uso
DisplayMetrics metrics = new DisplayMetrics();
WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(metrics);
int screenHeight = metrics.heightPixels; //1920 en Samsung S4
int screenWidth = metrics.widthPixels;
View view = this.findViewById(android.R.id.content);
//Evaluar qué letras mostrar en el banner superior.
if(letras.equals("dts")){
t = (TextView) findViewById(R.id.letra1);
t.setText("D");
t = (TextView) findViewById(R.id.letra2);
t.setText("T");
t = (TextView) findViewById(R.id.letra3);
t.setText("S");
t = (TextView) findViewById(R.id.letra4);
t.setVisibility(View.INVISIBLE);
}
TextView titulo = (TextView) findViewById(R.id.titulo);
//Iluminar letra y ejercicio en banner superior.
switch(letra_actual){
case "m": t = (TextView) findViewById(R.id.letra1); break;
case "n": t = (TextView) findViewById(R.id.letra2); titulo.setText(R.string.descripcion_imagenes2); break;
case "p": t = (TextView) findViewById(R.id.letra3); titulo.setText(R.string.descripcion_imagenes); break;
case "l": t = (TextView) findViewById(R.id.letra4); titulo.setText(R.string.descripcion_imagenes2); break;
case "d": t = (TextView) findViewById(R.id.letra1); titulo.setText(R.string.descripcion_imagenes); break;
case "t": t = (TextView) findViewById(R.id.letra2); titulo.setText(R.string.descripcion_imagenes); break;
case "s": t = (TextView) findViewById(R.id.letra3); titulo.setText(R.string.descripcion_imagenes); break;
}
t.setTextColor(Color.parseColor("#F3E624"));
switch(ejercicio) {
case 1: t = (TextView) findViewById(R.id.ejercicio_1); break;
case 2: t = (TextView) findViewById(R.id.ejercicio_2); break;
case 3: t = (TextView) findViewById(R.id.ejercicio_3); break;
}
//Toast.makeText(getApplicationContext(),"ejercicio: "+ejercicio+", letra: "+letra_actual, Toast.LENGTH_LONG).show();
t.setTextColor(Color.parseColor("#F3E624"));
//Definir sonidos.
mp2 = MediaPlayer.create(this, R.raw.misc049);
ImageView imagen1 = (ImageView) findViewById(R.id.imagen1);
ImageView imagen2 = (ImageView) findViewById(R.id.imagen2);
ImageView imagen3 = (ImageView) findViewById(R.id.imagen3);
ImageView letra = (ImageView) findViewById(R.id.letra);
ArrayList<Integer> correctImages = new ArrayList<Integer>();
ArrayList<Integer> allImages = new ArrayList<Integer>();
for(int i=1;i<=60;i++){
allImages.add(i);
}
t = (TextView) findViewById(R.id.resultado);
ArrayList<Integer> candidateImages = new ArrayList<Integer>();
imagen1.getLayoutParams().width = screenWidth/2 - 30;
imagen1.getLayoutParams().height = screenWidth/2 - 30;
imagen2.getLayoutParams().width = screenWidth/2 - 30;
imagen2.getLayoutParams().height = screenWidth/2 - 30;
imagen3.getLayoutParams().width = screenWidth/2 - 30;
imagen3.getLayoutParams().height = screenWidth/2 - 30;
titulo.setTextSize(Utilities.convertFromDp(40, view));
letra.getLayoutParams().height = (int) ((screenHeight/2 - 30) * .3);
titulo.setText(titulo.getText() + " " + letra_actual.toUpperCase()+ ".");
List<Integer> wrongOnes = new ArrayList<Integer>();
wrongOnes = allImages;
int correctOne = 0;
Random aleatorio = new Random();
int nroAleatorio = 0;
wrongOnes = new ArrayList<Integer>();
ArrayList patronesSinJugar = new ArrayList();
if(!patron1YaJugado){ patronesSinJugar.add(0); }
if(!patron2YaJugado){ patronesSinJugar.add(1); }
if(!patron3YaJugado){ patronesSinJugar.add(2); }
if(!patron4YaJugado){ patronesSinJugar.add(3); }
if(!patron5YaJugado){ patronesSinJugar.add(4); }
nroAleatorio = (int) patronesSinJugar.get(aleatorio.nextInt(patronesSinJugar.size()));
switch(letra_actual) {
case("m"):
switch(nroAleatorio) {
case 1: correctImages.add(1); wrongOnes.add(2); wrongOnes.add(4); patron2YaJugado = true; break; //Moto - Calabaza - Puerta
case 2: correctImages.add(34); wrongOnes.add(22); wrongOnes.add(42); patron3YaJugado = true; break; //Muñeca - Jugo Naranja - Reloj
case 3: correctImages.add(28); wrongOnes.add(26); wrongOnes.add(23); patron4YaJugado = true; break; //Mariposa - Lapiz - Limón
case 4: correctImages.add(30); wrongOnes.add(21); wrongOnes.add(49); patron5YaJugado = true; break; //Mesa - Gato - Taza
case 0: correctImages.add(33); wrongOnes.add(52); wrongOnes.add(54); patron1YaJugado = true; break; //Mono - Tenedor - Toalla
}
letra.setImageResource(R.drawable.m_amarilla); break;
case("n"):
switch(nroAleatorio) {
case 1: correctImages.add(6); wrongOnes.add(3); wrongOnes.add(5); patron2YaJugado = true; break; //sartén – lapicera - fideos
case 2: correctImages.add(24); wrongOnes.add(66); wrongOnes.add(67); patron3YaJugado = true; break; //cuaderno – león – bebé de juguete
case 3: correctImages.add(68); wrongOnes.add(69); wrongOnes.add(70); patron4YaJugado = true; break; //víbora- camión - remera
case 4: correctImages.add(71); wrongOnes.add(72); wrongOnes.add(73); patron5YaJugado = true; break; //elefante – cinturón - jarra
case 0: correctImages.add(74); wrongOnes.add(75); wrongOnes.add(76); patron1YaJugado = true; break; //avión – ojota - vestido
}
letra.setImageResource(R.drawable.n_amarilla); break;
case("p"):
switch(nroAleatorio) {
case 1: correctImages.add(35); wrongOnes.add(31); wrongOnes.add(41); patron2YaJugado = true; break; //Pan - Microondas - Oso Peluche
case 2: correctImages.add(40); wrongOnes.add(16); wrongOnes.add(50); patron3YaJugado = true; break; //Pino - Galletas - Teléfono
case 3: correctImages.add(39); wrongOnes.add(58); wrongOnes.add(51); patron4YaJugado = true; break; //Pijama - Zapatilla - TV
case 4: correctImages.add(38); wrongOnes.add(12); wrongOnes.add(13); patron5YaJugado = true; break; //Perro - Campera - Guitarra
case 0: correctImages.add(37); wrongOnes.add(8); wrongOnes.add(9); patron1YaJugado = true; break; //Pelota - Flor - Banana
}
letra.setImageResource(R.drawable.p_amarillo); break;
case("l"):
switch(nroAleatorio) {
case 1: correctImages.add(32); wrongOnes.add(65); wrongOnes.add(10); patron2YaJugado = true; break; //Miel - Nube - Cuchara
case 2: correctImages.add(11); wrongOnes.add(36); wrongOnes.add(46); patron3YaJugado = true; break; //Caracol - Pato - Silla
case 3: correctImages.add(7); wrongOnes.add(27); wrongOnes.add(14); patron4YaJugado = true; break; //Arbol - Manzana - Auto
case 4: correctImages.add(62); wrongOnes.add(61); wrongOnes.add(63); patron5YaJugado = true; break; //Papel - Bicicleta - Jirafa
case 0: correctImages.add(47); wrongOnes.add(25); wrongOnes.add(64); patron1YaJugado = true; break; //Sol - Hipopótamo - Libro
}
letra.setImageResource(R.drawable.l_amarilla); break;
case("d"):
switch(nroAleatorio) {
case 1: correctImages.add(59); wrongOnes.add(77); wrongOnes.add(78); patron2YaJugado = true; break; //dados – crayón – chupete
case 2: correctImages.add(15); wrongOnes.add(79); wrongOnes.add(80); patron3YaJugado = true; break; //conejo – zanahoria - delantal
case 3: correctImages.add(19); wrongOnes.add(58); wrongOnes.add(26); patron4YaJugado = true; break; //dinosaurio – zapatillas - limón
case 4: correctImages.add(20); wrongOnes.add(81); wrongOnes.add(14); patron5YaJugado = true; break; //pantalón – durazno – auto
case 0: correctImages.add(18); wrongOnes.add(82); wrongOnes.add(83); patron1YaJugado = true; break; //frutilla – dientes - hamaca
}
letra.setImageResource(R.drawable.d_amarilla); break;
case("t"):
switch(nroAleatorio) {
case 1: correctImages.add(55); wrongOnes.add(28); wrongOnes.add(41); patron2YaJugado = true; break; //tobogán – mariposa – oso de peluche
case 2: correctImages.add(53); wrongOnes.add(84); wrongOnes.add(60); patron3YaJugado = true; break; //anteojos – tijera – pantuflas
case 3: correctImages.add(49); wrongOnes.add(27); wrongOnes.add(85); patron4YaJugado = true; break; //taza – manzana – bermuda
case 4: correctImages.add(86); wrongOnes.add(87); wrongOnes.add(23); patron5YaJugado = true; break; //tractor – pepino – lápiz
case 0: correctImages.add(56); wrongOnes.add(29); wrongOnes.add(17); patron1YaJugado = true; break; //cartera – tomate - delfín
}
letra.setImageResource(R.drawable.t_amarilla); break;
case("s"):
//nroAleatorio = aleatorio.nextInt(5);
switch(nroAleatorio) {
case 1: correctImages.add(45); wrongOnes.add(88); wrongOnes.add(35); patron2YaJugado = true; break; //calesita - sapo – pan
case 2: correctImages.add(44); wrongOnes.add(54); wrongOnes.add(8); patron3YaJugado = true; break; //sandía – toalla – flor
case 3: correctImages.add(43); wrongOnes.add(21); wrongOnes.add(30); patron4YaJugado = true; break; //sal (salero) – gato – mesa
case 4: correctImages.add(48); wrongOnes.add(89); wrongOnes.add(90); patron5YaJugado = true; break; //jabón – ballena - sopa
case 0: correctImages.add(46); wrongOnes.add(70); wrongOnes.add(57); patron1YaJugado = true; break; //remera – torta - silla
}
letra.setImageResource(R.drawable.s_amarilla); break;
}
//Definir una única imagen correcta.
Collections.shuffle(correctImages);
correctOne = correctImages.get(0);
//Definir imágenes incorrectas.
wrongOnes.removeAll(correctImages);
Collections.shuffle(wrongOnes);
//Definir imagenes candidatas a mostrarse.
candidateImages.add(correctOne);
for(int i=1;i<3;i++){
candidateImages.add(wrongOnes.get(i-1));
}
Collections.shuffle(candidateImages);
imagen1.setImageResource(traerImagen(candidateImages.get(0)));
imagen1.setTag(candidateImages.get(0));
if(candidateImages.get(0) == correctOne){
pares.put(letra_actual, imagen1);
}
imagen2.setImageResource(traerImagen(candidateImages.get(1)));
imagen2.setTag(candidateImages.get(1));
if(candidateImages.get(1) == correctOne){
pares.put(letra_actual, imagen2);
}
imagen3.setImageResource(traerImagen(candidateImages.get(2)));
imagen3.setTag(candidateImages.get(2));
if(candidateImages.get(2) == correctOne){
pares.put(letra_actual, imagen3);
}
//Toast.makeText(getApplicationContext(),images.toString()+" "+images.get(1).toString(), Toast.LENGTH_LONG).show();
//Listeners drag and drop.
imagen1.setOnTouchListener((View.OnTouchListener) this);
imagen2.setOnTouchListener((View.OnTouchListener) this);
imagen3.setOnTouchListener((View.OnTouchListener) this);
findViewById(R.id.letra).setOnDragListener(new MiDrag());
botonAvanzar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
abrirProxima();
}
});
botonHome.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
origen = null;
abrirProxima();
}
});
}
/*@Override
public void onBackPressed() {
}*/
private int traerImagen(int n){
switch(n){
case 1: return R.drawable.moto; //M
case 2: return R.drawable.zapallo; //M
case 3: return R.drawable.lapicera; //N
case 4: return R.drawable.puerta; //M
case 5: return R.drawable.fideos; //N
case 6: return R.drawable.sarten; //N
case 7: return R.drawable.arbol; //L
case 8: return R.drawable.flor; //P
case 9: return R.drawable.banana; //P
case 10: return R.drawable.cuchara; //L
case 11: return R.drawable.caracol; //L
case 12: return R.drawable.campera; //P
case 13: return R.drawable.guitarra; //P
case 14: return R.drawable.auto; //L
case 15: return R.drawable.delantal; //D
case 16: return R.drawable.galletas; //P
case 17: return R.drawable.delfin; //T
case 18: return R.drawable.dientes; //D
case 19: return R.drawable.dinosaurio; //D
case 20: return R.drawable.durazno; //D
case 21: return R.drawable.gato; //M
case 22: return R.drawable.jugo_de_naranja; //M
case 23: return R.drawable.lapiz; //M
case 24: return R.drawable.leon; //N
case 25: return R.drawable.libro; //L
case 26: return R.drawable.limon; //M
case 27: return R.drawable.manzana; //L
case 28: return R.drawable.mariposa; //M
case 29: return R.drawable.cartera; //T
case 30: return R.drawable.mesa; //M
case 31: return R.drawable.microondas; //P
case 32: return R.drawable.miel; //L
case 33: return R.drawable.mono; //M
case 34: return R.drawable.muneca; //M
case 35: return R.drawable.pan; //S
case 36: return R.drawable.pato; //L
case 37: return R.drawable.pelota; //P
case 38: return R.drawable.perro; //P
case 39: return R.drawable.pijama; //P
case 40: return R.drawable.pino; //P
case 41: return R.drawable.oso_de_peluche; //P
case 42: return R.drawable.reloj; //M
case 43: return R.drawable.salero; //S
case 44: return R.drawable.sandia; //S
case 45: return R.drawable.sapo; //S
case 46: return R.drawable.silla; //L
case 47: return R.drawable.sol; //L
case 48: return R.drawable.sopa; //S
case 49: return R.drawable.taza; //M
case 50: return R.drawable.telefono; //P
case 51: return R.drawable.tv; //P
case 52: return R.drawable.tenedor; //M
case 53: return R.drawable.tijera; //T
case 54: return R.drawable.toallas; //S
case 55: return R.drawable.tobogan; //T
case 56: return R.drawable.tomate; //T
case 57: return R.drawable.torta; //S
case 58: return R.drawable.zapatillas; //P, D
case 59: return R.drawable.dados; //D
case 60: return R.drawable.pantuflas; //T
case 61: return R.drawable.bicicleta; //L
case 62: return R.drawable.papel; //L
case 63: return R.drawable.jirafa; //L
case 64: return R.drawable.hipopotamo; //L
case 65: return R.drawable.nube; //L
case 66: return R.drawable.cuaderno; //N
case 67: return R.drawable.bebe_de_juguete; //N
case 68: return R.drawable.camion; //N
case 69: return R.drawable.vibora; //N
case 70: return R.drawable.remera; //N
case 71: return R.drawable.cinturon; //N
case 72: return R.drawable.elefante; //N
case 73: return R.drawable.jarra; //N
case 74: return R.drawable.avion; //N
case 75: return R.drawable.ojotas; //N
case 76: return R.drawable.vestido; //N
case 77: return R.drawable.crayon; //D
case 78: return R.drawable.chupete; //D
case 79: return R.drawable.conejo; //D
case 80: return R.drawable.zanahoria; //D
case 81: return R.drawable.pantalon; //D
case 82: return R.drawable.frutillas; //D
case 83: return R.drawable.hamaca; //D
case 84: return R.drawable.anteojos; //T
case 85: return R.drawable.bermuda; //T
case 86: return R.drawable.tractor; //T
case 87: return R.drawable.pepino; //T
case 88: return R.drawable.calesita; //S
case 89: return R.drawable.jabon; //S
case 90: return R.drawable.ballena; //S
}
return R.drawable.calabaza;
}
private int traerSonido(int n){
switch(n){
case 1: return R.raw.sonido_moto;
case 2: return R.raw.sonido_zapallo;
case 3: return R.raw.sonido_lapicera;
case 4: return R.raw.sonido_puerta;
case 5: return R.raw.sonido_fideos;
case 6: return R.raw.sonido_sarten;
case 7: return R.raw.sonido_arbol;
case 8: return R.raw.sonido_flor;
case 9: return R.raw.sonido_banana;
case 10: return R.raw.sonido_cuchara;
case 11: return R.raw.sonido_caracol;
case 12: return R.raw.sonido_campera;
case 13: return R.raw.sonido_guitarra;
case 14: return R.raw.sonido_auto;
case 15: return R.raw.sonido_delantal;
case 16: return R.raw.sonido_galletas;
case 17: return R.raw.sonido_delfin;
case 18: return R.raw.sonido_dientes;
case 19: return R.raw.sonido_dinosaurio;
case 20: return R.raw.sonido_durazno;
case 21: return R.raw.sonido_gato;
case 22: return R.raw.sonido_jugo_de_naranja;
case 23: return R.raw.sonido_lapiz;
case 24: return R.raw.sonido_leon;
case 25: return R.raw.sonido_libro;
case 26: return R.raw.sonido_limon;
case 27: return R.raw.sonido_manzana;
case 28: return R.raw.sonido_mariposa;
case 29: return R.raw.sonido_cartera;
case 30: return R.raw.sonido_mesa;
case 31: return R.raw.sonido_microondas;
case 32: return R.raw.sonido_miel;
case 33: return R.raw.sonido_mono;
case 34: return R.raw.sonido_muneca;
case 35: return R.raw.sonido_pan;
case 36: return R.raw.sonido_pato;
case 37: return R.raw.sonido_pelota;
case 38: return R.raw.sonido_perro;
case 39: return R.raw.sonido_pijama;
case 40: return R.raw.sonido_pino;
case 41: return R.raw.sonido_oso_de_peluche;
case 42: return R.raw.sonido_reloj;
case 43: return R.raw.sonido_salero;
case 44: return R.raw.sonido_sandia;
case 45: return R.raw.sonido_sapo;
case 46: return R.raw.sonido_silla;
case 47: return R.raw.sonido_sol;
case 48: return R.raw.sonido_sopa;
case 49: return R.raw.sonido_taza;
case 50: return R.raw.sonido_telefono;
case 51: return R.raw.sonido_televisor;
case 52: return R.raw.sonido_tenedor;
case 53: return R.raw.sonido_tijera;
case 54: return R.raw.sonido_toalla;
case 55: return R.raw.sonido_tobogan;
case 56: return R.raw.sonido_tomate;
case 57: return R.raw.sonido_torta;
case 58: return R.raw.sonido_zapatillas;
case 59: return R.raw.sonido_dados;
case 60: return R.raw.sonido_pantuflas;
case 61: return R.raw.sonido_bicicleta;
case 62: return R.raw.sonido_papel;
case 63: return R.raw.sonido_jirafa;
case 64: return R.raw.sonido_hipopotamo;
case 65: return R.raw.sonido_nube;
case 66: return R.raw.sonido_cuaderno;
case 67: return R.raw.sonido_bebe_de_juguete;
case 68: return R.raw.sonido_camion;
case 69: return R.raw.sonido_vibora;
case 70: return R.raw.sonido_remera;
case 71: return R.raw.sonido_cinturon;
case 72: return R.raw.sonido_elefante;
case 73: return R.raw.sonido_jarra;
case 74: return R.raw.sonido_avion;
case 75: return R.raw.sonido_ojota;
case 76: return R.raw.sonido_vestido;
case 77: return R.raw.sonido_crayon;
case 78: return R.raw.sonido_chupete;
case 79: return R.raw.sonido_conejo;
case 80: return R.raw.sonido_zanahoria;
case 81: return R.raw.sonido_pantalon;
case 82: return R.raw.sonido_frutilla;
case 83: return R.raw.sonido_hamaca;
case 84: return R.raw.sonido_anteojos;
case 85: return R.raw.sonido_bermuda;
case 86: return R.raw.sonido_tractor;
case 87: return R.raw.sonido_pepino;
case 88: return R.raw.sonido_calesita;
case 89: return R.raw.sonido_jabon;
case 90: return R.raw.sonido_ballena;
}
return 0;
}
public boolean onTouch(View objeto, MotionEvent evento){
if(evento.getAction() == MotionEvent.ACTION_DOWN){
JuegoImagenesActivity.t.setText("");
ClipData datos = ClipData.newPlainText("","");
View.DragShadowBuilder objeto_sombra = new View.DragShadowBuilder(objeto);
objeto.startDrag(datos, objeto_sombra, objeto, 0);
int imageIndex = (Integer) objeto_sombra.getView().getTag();
if(traerSonido(imageIndex)>0){
//Toast.makeText(getApplicationContext(),"on touch "+imageIndex+" "+objeto_sombra.getView().getTag(), Toast.LENGTH_LONG).show();
//Anular sonidos previos.
if (mp1!=null && mp1.isPlaying()) {
mp1.stop();
mp1.release();
}
//Definir sonido.
mp1 = MediaPlayer.create(this, traerSonido(imageIndex));
mp1.setVolume((float) 0.3, (float) 0.3);
//mp1.start();
}
return true;
}
else{
return false;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_juego_imagenes, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
Intent intent = null;
switch (id){
case R.id.action_menu:
intent = new Intent(this,MenuActivity.class);
startActivity(intent);
break;
case R.id.exit_app:
intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
break;
}
return super.onOptionsItemSelected(item);
}
private void abrirProxima(){
Intent intent = null;
Bundle b = new Bundle();
if(patron1YaJugado && patron2YaJugado && patron3YaJugado && patron4YaJugado && patron5YaJugado) {
if(origen==null || origen.equals("")) {
intent = new Intent(this,MenuActivity.class);
} else{
intent = new Intent(this, ElegirJuegoActivity.class);
}
b.putString("letras", letras);
b.putString("letra", letra_actual);
b.putString("origen", null);
b.putInt("ejercicio", 0);
intent.putExtras(b);
}else{
if(origen==null || origen.equals("")) {
intent = new Intent(this,MenuActivity.class);
ejercicio = 0; origen = null;
} else {
intent = new Intent(this, JuegoImagenesActivity.class);
b.putBoolean("patron1YaJugado", patron1YaJugado);
b.putBoolean("patron2YaJugado", patron2YaJugado);
b.putBoolean("patron3YaJugado", patron3YaJugado);
b.putBoolean("patron4YaJugado", patron4YaJugado);
b.putBoolean("patron5YaJugado", patron5YaJugado);
ejercicio++;
}
b.putString("origen", origen);
b.putString("letras", letras);
b.putString("letra", letra_actual);
b.putInt("ejercicio", ejercicio);
intent.putExtras(b);
}
startActivity(intent);
}
}
final class MiDrag extends JuegoImagenesActivity implements View.OnDragListener{
public boolean onDrag(View contenedor_nuevo, DragEvent evento){
switch (evento.getAction()){
case DragEvent.ACTION_DRAG_ENTERED:
break;
case DragEvent.ACTION_DRAG_EXITED:
break;
case DragEvent.ACTION_DROP:
View objeto = (View) evento.getLocalState();
if(JuegoImagenesActivity.pares.containsValue(objeto)){
//Toast.makeText(context, "¡CORRECTO!", Toast.LENGTH_SHORT).show();
if (mp2.isPlaying()) {
mp2.stop();
mp2.release();
}
mp2.setVolume((float) 1, (float) 1);
//mp2.start();
objeto.setBackgroundResource(0);
objeto.setVisibility(View.INVISIBLE);
JuegoImagenesActivity.botonAvanzar.setVisibility(View.VISIBLE);
}else{
Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
if(v.hasVibrator()){
// Vibrar por 500 milisegundos
v.vibrate(500);
}
}
break;
default:
break;
}
return true;
}
}
|
package rakkis157.excessive_realism.item;
import net.fabricmc.fabric.api.client.itemgroup.FabricItemGroupBuilder;
import net.minecraft.item.ItemGroup;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.util.Identifier;
import rakkis157.excessive_realism.ExcessiveRealism;
public class ERItemGroup {
public static final ItemGroup GROUP = FabricItemGroupBuilder.build(new Identifier(ExcessiveRealism.MOD_ID, "group"),
() -> new ItemStack(Items.RAW_IRON));
}
|
package com.simsi.testing.calcul.e2e;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import io.github.bonigarcia.wdm.WebDriverManager;
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class StudentMultiplicationJourneyE2E {
@LocalServerPort
private Integer port;
private WebDriver webDriver = null;
private String baseUrl;
@BeforeAll
public static void setUpFirefoxDriver() {
WebDriverManager.firefoxdriver().setup();
}
@BeforeEach
public void setUpWebDriver() {
webDriver = new FirefoxDriver();
baseUrl = "http://localhost:" + port + "/calculator";
}
@AfterEach
public void quitWebDriver() {
if (webDriver != null) {
webDriver.quit();
}
}
@Test
public void aStudentUsesTheCalculatorToMultiplyTwoBySixteen() {
// GIVEN
webDriver.get(baseUrl);
final WebElement leftField = webDriver.findElement(By.id("left"));
final WebElement typeDropdown = webDriver.findElement(By.id("type"));
final WebElement rightField = webDriver.findElement(By.id("right"));
final WebElement submitButton = webDriver.findElement(By.id("submit"));
// WHEN
leftField.sendKeys("2");
typeDropdown.sendKeys("x");
rightField.sendKeys("16");
submitButton.click();
// THEN
final WebDriverWait waiter = new WebDriverWait(webDriver, 5);
final WebElement solutionElement = waiter.until(
ExpectedConditions.presenceOfElementLocated(By.id("solution")));
final String solution = solutionElement.getText();
assertThat(solution).isEqualTo("32"); // 2 x 16
}
}
|
package com.epam.esm.exception;
public class EntityIsNotExistException extends RuntimeException {
/**
* Constructs a new runtime exception with {@code null} as its
* detail message. The cause is not initialized, and may subsequently be
* initialized by a call to {@link #initCause}.
*/
public EntityIsNotExistException() {
}
/**
* Constructs a new runtime exception with the specified detail message.
* The cause is not initialized, and may subsequently be initialized by a
* call to {@link #initCause}.
*
* @param message the detail message. The detail message is saved for
* later retrieval by the {@link #getMessage()} method.
*/
public EntityIsNotExistException(String message) {
super(message);
}
/**
* Constructs a new runtime exception with the specified detail message and
* cause. <p>Note that the detail message associated with
* {@code cause} is <i>not</i> automatically incorporated in
* this runtime exception's detail message.
*
* @param message the detail message (which is saved for later retrieval
* by the {@link #getMessage()} method).
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A {@code null} value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
* @since 1.4
*/
public EntityIsNotExistException(String message, Throwable cause) {
super(message, cause);
}
/**
* Constructs a new runtime exception with the specified cause and a
* detail message of {@code (cause==null ? null : cause.toString())}
* (which typically contains the class and detail message of
* {@code cause}). This constructor is useful for runtime exceptions
* that are little more than wrappers for other throwables.
*
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A {@code null} value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
* @since 1.4
*/
public EntityIsNotExistException(Throwable cause) {
super(cause);
}
}
|
/*
* MIT License
*
* Copyright (c) 2019-2020 Yoann CAPLAIN
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.blackdread.lib.restfilter.demo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
/**
* <p>Created on 2019/07/09.</p>
*
* @author Yoann CAPLAIN
*/
@Repository
public interface ChildRepository extends JpaRepository<ChildEntity, Long>, JpaSpecificationExecutor<ChildEntity> {
}
|
package de.metas.vertical.healthcare_ch.forum_datenaustausch_ch.invoice_xversion.request.model.payload.body.tiers;
import lombok.Builder;
import lombok.NonNull;
import lombok.Value;
import javax.annotation.Nullable;
import de.metas.vertical.healthcare_ch.forum_datenaustausch_ch.invoice_xversion.model.commontypes.XmlCompany;
import de.metas.vertical.healthcare_ch.forum_datenaustausch_ch.invoice_xversion.model.commontypes.XmlPerson;
/*
* #%L
* vertical-healthcare_ch.invoice_gateway.forum_datenaustausch_ch.invoice_commons
* %%
* Copyright (C) 2018 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
@Value
@Builder
public class XmlReferrer
{
@NonNull
String eanParty;
@Nullable
String zsr;
@Nullable
String specialty;
@Nullable
XmlCompany company;
@Nullable
XmlPerson person;
}
|
/*******************************************************************************
** Entropy.java
** Part of the Java Mutual Information toolbox
**
** Author: Adam Pocock
** Created: 20/1/2012
**
** Copyright 2012 Adam Pocock, The University Of Manchester
** www.cs.manchester.ac.uk
**
** This file is part of MIToolboxJava.
**
** MIToolboxJava is free software: you can redistribute it and/or modify
** it under the terms of the GNU Lesser General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** MIToolboxJava is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public License
** along with MIToolboxJava. If not, see <http://www.gnu.org/licenses/>.
**
*******************************************************************************/
package JavaMI;
/**
* Implements common discrete Shannon Entropy functions.
* Provides: univariate entropy H(X),
* conditional entropy H(X|Y),
* joint entropy H(X,Y).
* Defaults to log_2, and so the entropy is calculated in bits.
* @author apocock
*/
public abstract class Entropy
{
public static double LOG_BASE = 2.0;
private Entropy() {}
/**
* Calculates the univariate entropy H(X) from a vector.
* Uses histograms to estimate the probability distributions, and thus the entropy.
* The entropy is bounded 0 ≤ H(X) ≤ log |X|, where log |X| is the log of the number
* of states in the random variable X.
*
* @param dataVector Input vector (X). It is discretised to the floor of each value before calculation.
* @return The entropy H(X).
*/
public static double calculateEntropy(double[] dataVector)
{
ProbabilityState state = new ProbabilityState(dataVector);
double entropy = 0.0;
for (Double prob : state.probMap.values())
{
if (prob > 0)
{
entropy -= prob * Math.log(prob);
}
}
entropy /= Math.log(LOG_BASE);
return entropy;
}//calculateEntropy(double [])
/**
* Calculates the conditional entropy H(X|Y) from two vectors.
* X = dataVector, Y = conditionVector.
* Uses histograms to estimate the probability distributions, and thus the entropy.
* The conditional entropy is bounded 0 ≤ H(X|Y) ≤ H(X).
*
* @param dataVector Input vector (X). It is discretised to the floor of each value before calculation.
* @param conditionVector Input vector (Y). It is discretised to the floor of each value before calculation.
* @return The conditional entropy H(X|Y).
*/
public strictfp static double calculateConditionalEntropy(double[] dataVector, double[] conditionVector)
{
JointProbabilityState state = new JointProbabilityState(dataVector,conditionVector);
int numFirstStates = state.firstMaxVal;
double jointValue, condValue;
double condEntropy = 0.0;
for (Integer key : state.jointProbMap.keySet())
{
jointValue = state.jointProbMap.get(key);
condValue = state.secondProbMap.get(key / numFirstStates);
if ((jointValue > 0) && (condValue > 0))
{
condEntropy -= jointValue * Math.log(jointValue / condValue);
}
}
condEntropy /= Math.log(LOG_BASE);
return condEntropy;
}//calculateConditionalEntropy(double [],double [])
/**
* Calculates the joint entropy H(X,Y) from two vectors.
* The order of the input vectors is irrelevant.
* Uses histograms to estimate the probability distributions, and thus the entropy.
* The joint entropy is bounded 0 ≤ H(X,Y) ≤ log |XY|, where log |XY| is the log of
* the number of states in the joint random variable XY.
*
* @param firstVector Input vector. It is discretised to the floor of each value before calculation.
* @param secondVector Input vector. It is discretised to the floor of each value before calculation.
* @return The joint entropy H(X,Y).
*/
public static double calculateJointEntropy(double[] firstVector, double[] secondVector)
{
JointProbabilityState state = new JointProbabilityState(firstVector,secondVector);
double entropy = 0.0;
for (Double prob : state.jointProbMap.values())
{
if (prob > 0)
{
entropy -= prob * Math.log(prob);
}
}
entropy /= Math.log(LOG_BASE);
return entropy;
}//calculateJointEntropy(double [],double [])
}//class Entropy
|
package com.example.exercise.myfavoritemovies.com.example.exercise.myfavoritemovies.Model;
import java.util.HashMap;
import java.util.Map;
public class VideoDetail {
private String id;
private String iso6391;
private String iso31661;
private String key;
private String name;
private String site;
private Integer size;
private String type;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getIso6391() {
return iso6391;
}
public void setIso6391(String iso6391) {
this.iso6391 = iso6391;
}
public String getIso31661() {
return iso31661;
}
public void setIso31661(String iso31661) {
this.iso31661 = iso31661;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSite() {
return site;
}
public void setSite(String site) {
this.site = site;
}
public Integer getSize() {
return size;
}
public void setSize(Integer size) {
this.size = size;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
|
package src;
import club.cybet.utils.Constants;
import org.junit.Test;
import org.web3j.abi.datatypes.Address;
import org.web3j.abi.datatypes.Type;
import org.web3j.abi.datatypes.generated.Uint256;
import org.web3j.crypto.CipherException;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.ECKeyPair;
import org.web3j.crypto.WalletUtils;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.methods.response.Web3ClientVersion;
import org.web3j.protocol.http.HttpService;
import org.web3j.tx.gas.ContractGasProvider;
import org.web3j.tx.gas.DefaultGasProvider;
import src.wrappers.Crowdsale;
import src.wrappers.CyBetToken;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.text.DecimalFormat;
/**
* cybet-api (src)
* Created by: cybet
* On: 25 Oct, 2018 10/25/18 10:35 AM
**/
public class Ethereum {
private Web3j web3;
private Credentials credentials;
private ContractGasProvider gasProvider;
public Ethereum(){
this.web3 = Web3j.build(new HttpService(Constants.getInfuraLink()));
this.gasProvider = new DefaultGasProvider();
try {
this.credentials = WalletUtils.loadCredentials(
Constants.getEthWalletPassword(),
Constants.getEthWalletFilePath()
);
} catch (IOException | CipherException e) {
this.credentials = null;
e.printStackTrace();
}
}
@Test public void testInfura() throws Exception {
CyBetToken cyBetToken = CyBetToken.load(
Constants.CONTRACT_ADDR_CYBET_TOKEN,
web3, credentials, gasProvider
);
Crowdsale crowdsale = Crowdsale.load(
Constants.CONTRACT_ADDR_CROWDSALE,
web3, credentials, gasProvider
);
BigInteger result = cyBetToken.balanceOf("0x1E554a1786dD070E181D2b0A33633143A3039dcC").send();
System.out.println(formatCyBetToken(result));
System.out.println(credentials.getAddress());
}
@Test public void deployCyBet() throws Exception {
CyBetToken cyBetToken = CyBetToken.deploy(
web3, credentials, gasProvider
).send();
System.out.println("Validity: "+cyBetToken.isValid());
System.out.println("Address: "+cyBetToken.getContractAddress());
}
@Test public void deployCrowdsale() throws Exception {
Crowdsale crowdsale = Crowdsale.deploy(
web3, credentials, gasProvider, "0xa221bc3332656ed6f599600d7a075b1c2acab34b"
).send();
System.out.println("Validity: "+crowdsale.isValid());
System.out.println("Address: "+crowdsale.getContractAddress()); //0x382a896dcc05186befd6baeef41b2a9369eec304
}
private String formatCyBetToken(BigInteger value){
DecimalFormat formatter = new DecimalFormat("#,###.0000");
return new DecimalFormat("#,###.0000").format(
value.divide(new BigInteger("1000000000000000000"))) + " CYBT";
}
}
|
/******************************************************************************
* Copyright 2009-2018 Exactpro (Exactpro Systems Limited)
*
* 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.exactpro.sf.configuration;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.exactpro.sf.aml.Dictionaries;
import com.exactpro.sf.aml.Dictionary;
import com.exactpro.sf.aml.DictionarySettings;
import com.exactpro.sf.aml.generator.AlertCollector;
import com.exactpro.sf.center.IVersion;
import com.exactpro.sf.center.impl.PluginLoader;
import com.exactpro.sf.common.impl.messages.AbstractMessageFactory;
import com.exactpro.sf.common.impl.messages.DefaultMessageFactory;
import com.exactpro.sf.common.impl.messages.DummyMessageFactory;
import com.exactpro.sf.common.messages.IMessageFactory;
import com.exactpro.sf.common.messages.structures.IDictionaryStructure;
import com.exactpro.sf.common.messages.structures.loaders.IDictionaryStructureLoader;
import com.exactpro.sf.common.messages.structures.loaders.XmlDictionaryStructureLoader;
import com.exactpro.sf.common.util.EPSCommonException;
import com.exactpro.sf.configuration.suri.SailfishURI;
import com.exactpro.sf.configuration.suri.SailfishURIException;
import com.exactpro.sf.configuration.suri.SailfishURIRule;
import com.exactpro.sf.configuration.suri.SailfishURIUtils;
import com.exactpro.sf.configuration.workspace.FolderType;
import com.exactpro.sf.configuration.workspace.IWorkspaceDispatcher;
import com.exactpro.sf.configuration.workspace.WorkspaceSecurityException;
import com.exactpro.sf.configuration.workspace.WorkspaceStructureException;
import com.exactpro.sf.scriptrunner.ManagerUtils;
import com.exactpro.sf.scriptrunner.ScriptRunException;
import com.exactpro.sf.scriptrunner.utilitymanager.UtilityClass;
import com.exactpro.sf.scriptrunner.utilitymanager.UtilityInfo;
import com.exactpro.sf.scriptrunner.utilitymanager.UtilityManager;
import com.exactpro.sf.scriptrunner.utilitymanager.exceptions.UtilityManagerException;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.SetMultimap;
public class DictionaryManager implements IDictionaryManager, ILoadableManager {
private static final Logger logger = LoggerFactory.getLogger(DictionaryManager.class);
private final IWorkspaceDispatcher workspaceDispatcher;
private final UtilityManager utilityManager;
// URI -> file_name (relative to DICTIONARIES)
private final Map<SailfishURI, String> location = new HashMap<>();
// URI -> DictionarySettings
private final Map<SailfishURI, DictionarySettings> dictSettings = new HashMap<>();
// URI -> DictionaryStructure
private final Map<SailfishURI, IDictionaryStructure> dicts = new HashMap<>();
// URI -> IMessageFactory
private final Map<SailfishURI, IMessageFactory> factories = new HashMap<>();
// plugin alias -> list of dictionary URI's
private final SetMultimap<String, SailfishURI> pluginDictTitles = HashMultimap.create();
private long dictLoadedCounter;
private final Map<SailfishURI, Long> dictionaryIds = new ConcurrentHashMap<>();
private final List<IDictionaryManagerListener> eventListeners;
public DictionaryManager(IWorkspaceDispatcher workspaceDispatcher, UtilityManager utilityManager) {
this.workspaceDispatcher = Objects.requireNonNull(workspaceDispatcher, "workspaceDispatcher cannot be null");
this.utilityManager = Objects.requireNonNull(utilityManager, "utilityManager cannot be null");
this.eventListeners = new CopyOnWriteArrayList<>();
}
@Override
public synchronized Set<SailfishURI> getDictionaryURIs() {
return new HashSet<>(location.keySet());
}
@Override
public synchronized Set<SailfishURI> getDictionaryURIs(String pluginAlias) {
if(pluginAlias == null || !pluginDictTitles.containsKey(pluginAlias)) {
logger.error("Dictionary titles for plugin alias '{}' not found", pluginAlias);
return null;
}
return pluginDictTitles.get(pluginAlias);
}
@Override
public synchronized List<SailfishURI> getCachedDictURIs() {
return new ArrayList<>(dicts.keySet());
}
@Override
public synchronized Map<SailfishURI, String> getDictionaryLocations() {
return new HashMap<>(location);
}
@Override
public void load(ILoadableManagerContext context) {
try {
ClassLoader loader = context.getClassLoaders()[0];
InputStream stream = context.getResourceStream();
String dictionaryFolderPath = context.getResourceFolder();
IVersion version = context.getVersion();
JAXBContext jc = JAXBContext.newInstance(Dictionaries.class);
Unmarshaller u = jc.createUnmarshaller();
JAXBElement<Dictionaries> root = u.unmarshal(new StreamSource(stream), Dictionaries.class);
Dictionaries dictionaries = root.getValue();
for (Dictionary dict : dictionaries.getDictionary()) {
if (dict.getTitle() == null) {
throw new EPSCommonException("Null Title in config " + stream);
}
SailfishURI dictionaryURI = new SailfishURI(version.getAlias(), null, SailfishURIUtils.sanitize(dict.getTitle()));
DictionarySettings settings = dictSettings.get(dictionaryURI);
pluginDictTitles.put(dictionaryURI.getPluginAlias(), dictionaryURI);
if (settings == null) {
settings = new DictionarySettings();
settings.setURI(dictionaryURI);
dictSettings.put(dictionaryURI, settings);
}
for (String className : dict.getUtilityClassName()){
try {
UtilityClass utilityClass = utilityManager.load(loader, className, version);
for(String utilityClassAlias : utilityClass.getClassAliases()) {
SailfishURI utilityClassURI = new SailfishURI(version.getAlias(), utilityClassAlias);
settings.addUtilityClassURI(utilityClassURI);
}
} catch (UtilityManagerException e) {
if (context.getVersion().isLightweight()) {
logger.warn("Can't load utility class '{}'", className, e);
} else {
throw e;
}
}
}
for (String utilityURI : dict.getUtilityURI()) {
SailfishURI uri = SailfishURI.parse(utilityURI, SailfishURIRule.REQUIRE_PLUGIN, SailfishURIRule.REQUIRE_CLASS);
if (utilityManager.getUtilityClassByURI(uri) == null) {
logger.warn("SailfishURI {} is not registered", uri);
} else {
settings.addUtilityClassURI(uri);
}
}
String currentResource = location.get(dictionaryURI);
String resource = dict.getResource();
if (resource == null) {
logger.warn("resource (xml dictionary) not specified for dictionary {}", dictionaryURI);
} else {
resource = dictionaryFolderPath + File.separator + resource;
if (currentResource != null && !currentResource.equals(resource)) {
logger.warn("Resources '{}' wasn't sent, because current value '{}' not null", resource, currentResource);
} else {
location.put(dictionaryURI, resource);
}
}
String factoryClassName = dict.getFactoryClassName();
if (factoryClassName != null) {
if (settings.getFactoryClass() != null && !settings.getFactoryClass().getCanonicalName().equals(factoryClassName)) {
logger.warn("Factory class '{}' wasn't sent, because current value '{}' not null", factoryClassName, settings.getFactoryClass());
} else {
try {
@SuppressWarnings("unchecked")
Class<? extends IMessageFactory> factoryClass = (Class<? extends IMessageFactory>) loader.loadClass(factoryClassName);
settings.setFactoryClass(factoryClass);
} catch (ClassNotFoundException e) {
logger.warn("{} dictionary has incorrect factory [{}]. DefaultMessageFactory will be used",
dict.getTitle(), dict.getFactoryClassName());
}
}
}
}
} catch (JAXBException | SailfishURIException e) {
throw new EPSCommonException("Failed to load dictionary", e);
}
}
@Override
public void finalize(ILoadableManagerContext context) throws Exception {
// TODO Auto-generated method stub
}
@Override
public synchronized IDictionaryStructure getDictionary(SailfishURI uri) throws RuntimeException {
IDictionaryStructure dict = SailfishURIUtils.getMatchingValue(uri, dicts, SailfishURIRule.REQUIRE_RESOURCE);
if (dict == null) {
this.dictLoadedCounter++;
dictionaryIds.put(uri, dictLoadedCounter);
String resource = SailfishURIUtils.getMatchingValue(uri, location, SailfishURIRule.REQUIRE_RESOURCE);
if (resource == null) {
throw new RuntimeException("No dictionary found for URI: " + uri);
}
dict = createMessageDictionary(resource);
if (dict == null) {
throw new RuntimeException("Can not create dictionary for URI: " + uri +", resource = "+resource);
}
dicts.put(uri, dict);
logger.info("Dictionary {} was loaded", uri);
}
return dict;
}
@Override
public synchronized DictionarySettings getSettings(SailfishURI uri) {
return SailfishURIUtils.getMatchingValue(uri, dictSettings, SailfishURIRule.REQUIRE_RESOURCE);
}
@Override
public synchronized IMessageFactory getMessageFactory(SailfishURI uri) {
IMessageFactory factory = SailfishURIUtils.getMatchingValue(uri, factories, SailfishURIRule.REQUIRE_RESOURCE);
if (factory == null) {
factory = ObjectUtils.defaultIfNull(loadFactory(uri), DefaultMessageFactory.getFactory());
factories.put(uri, factory);
}
return factory;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for(Entry<SailfishURI, IDictionaryStructure> e : dicts.entrySet()) {
if(sb.length() > 0) {
sb.append(", ");
}
sb.append(e.getKey());
sb.append(" = ");
sb.append(e.getValue().getNamespace());
}
return sb.toString();
}
@Override
public synchronized void invalidateDictionaries(SailfishURI ... uris) {
if (uris == null || uris.length == 0) {
dicts.clear();
dictionaryIds.clear();
factories.clear();
invalidateEvent(Collections.unmodifiableSet(dicts.keySet()));
logger.info("All dictionaries have been invalidated");
} else {
for (SailfishURI uri : uris) {
dicts.remove(uri);
dictionaryIds.remove(uri);
factories.remove(uri);
}
invalidateEvent(new HashSet<>(Arrays.asList(uris)));
StringBuilder builder = new StringBuilder("Dictionaries ")
.append(Arrays.toString(uris))
.append(" have been invalidated");
logger.info("{}", builder);
}
}
private IMessageFactory loadFactory(SailfishURI uri) {
try {
IMessageFactory iMessageFactory = null;
DictionarySettings settings = SailfishURIUtils.getMatchingValue(uri, dictSettings, SailfishURIRule.REQUIRE_RESOURCE);
if((settings != null) && (settings.getFactoryClass() != null)) {
Class<? extends IMessageFactory> clazz = settings.getFactoryClass();
iMessageFactory = clazz.newInstance();
} else {
iMessageFactory = new AbstractMessageFactory() {
@Override
public String getProtocol() {
return "Unknown";
}
};
}
iMessageFactory.init(uri, getDictionary(uri));
return iMessageFactory;
} catch (Exception e) {
logger.warn("Can not create message factory for SailfishURI: " + uri, e);
}
return null;
}
private synchronized void createDictionary(String filename, DictionarySettings settings, boolean overwrite) {
Objects.requireNonNull(filename, "Dictionary file is null");
Objects.requireNonNull(settings, "Dictionary settings is null");
Objects.requireNonNull(settings.getURI(), "Dictionary Sailfish URI is null");
SailfishURI uri = settings.getURI();
if(getDictionaryURIs().contains(uri)) {
if (!overwrite) {
throw new EPSCommonException(String.format("Concurrent dictionary registration with SailfishURI: '%s' and name: '%s' already exists", uri, filename));
}
invalidateDictionaries(uri);
return;
}
Dictionary dictionary = new Dictionary();
dictionary.setTitle(uri.getResourceName());
dictionary.setResource(filename);
for (SailfishURI suri : settings.getUtilityClassURIs()) {
dictionary.getUtilityURI().add(suri.toString());
}
Dictionaries dictionaries = null;
if(workspaceDispatcher.exists(FolderType.CFG, PluginLoader.CUSTOM_DICTIONARIES_XML)) {
try {
File customDictionariesXml = workspaceDispatcher.getFile(FolderType.CFG, PluginLoader.CUSTOM_DICTIONARIES_XML);
JAXBContext jc = JAXBContext.newInstance(Dictionaries.class);
Unmarshaller u = jc.createUnmarshaller();
dictionaries = (Dictionaries) u.unmarshal(customDictionariesXml);
} catch (Exception e) {
throw new RuntimeException("Can't read " + PluginLoader.CUSTOM_DICTIONARIES_XML, e);
}
} else {
dictionaries = new Dictionaries();
}
dictionaries.getDictionary().add(dictionary);
try {
File customDictionariesXml = workspaceDispatcher.createFile(FolderType.CFG, true, PluginLoader.CUSTOM_DICTIONARIES_XML);
JAXBContext jc = JAXBContext.newInstance(Dictionaries.class);
Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal(dictionaries, customDictionariesXml);
} catch (Exception e) {
throw new RuntimeException("Can't write to " + PluginLoader.CUSTOM_DICTIONARIES_XML, e);
}
dictSettings.put(uri, settings);
location.put(uri, "cfg" + File.separator + "dictionaries" + File.separator + filename);
pluginDictTitles.put(ObjectUtils.defaultIfNull(uri.getPluginAlias(), IVersion.GENERAL), uri);
createEvent(uri);
}
/**
*
* Load dictionary from xml/xsd file
* @param pathName file path (relative to {ROOT})
* @return
*/
@Override
public IDictionaryStructure createMessageDictionary(String pathName) throws RuntimeException {
try {
IDictionaryStructureLoader loader = createStructureLoader(pathName);
File targetFile = workspaceDispatcher.getFile(FolderType.ROOT, pathName);
try (InputStream in = new BufferedInputStream(new FileInputStream(targetFile))) {
return loader.load(in);
}
} catch (Exception e) {
throw new ScriptRunException("Could not create dictionary [" + pathName + "]", e);
}
}
@Override
public IMessageFactory createMessageFactory() {
return DefaultMessageFactory.getFactory();
}
@Override
public UtilityInfo getUtilityInfo(SailfishURI dictionaryURI, SailfishURI utilityURI, Class<?>... argTypes) throws SailfishURIException {
if(utilityURI.isAbsolute()) {
return utilityManager.getUtilityInfo(utilityURI, argTypes);
}
DictionarySettings settings = SailfishURIUtils.getMatchingValue(dictionaryURI, dictSettings, SailfishURIRule.REQUIRE_RESOURCE);
if(settings == null) {
return null;
}
for(SailfishURI utilityClassURI : settings.getUtilityClassURIs()) {
UtilityInfo utilityInfo = utilityManager.getUtilityInfo(utilityURI.merge(utilityClassURI), argTypes);
if(utilityInfo != null) {
return utilityInfo;
}
}
return null;
}
@Override
public UtilityInfo getUtilityInfo(SailfishURI dictionaryURI, SailfishURI utilityURI, long line, long uid, String column, AlertCollector alertCollector, Class<?>... argTypes) throws SailfishURIException {
if (utilityURI.isAbsolute()) {
return utilityManager.getUtilityInfo(utilityURI, argTypes);
}
DictionarySettings settings = SailfishURIUtils.getMatchingValue(dictionaryURI, dictSettings, SailfishURIRule.REQUIRE_RESOURCE);
if (settings == null) {
return null;
}
return ManagerUtils.getUtilityInfo(settings.getUtilityClassURIs(), utilityManager, utilityURI, line, uid, column, alertCollector, argTypes);
}
@Override
public Set<SailfishURI> getUtilityURIs(SailfishURI dictionaryURI) {
DictionarySettings settings = SailfishURIUtils.getMatchingValue(dictionaryURI, dictSettings, SailfishURIRule.REQUIRE_RESOURCE);
if (settings == null) {
return Collections.emptySet();
}
Set<SailfishURI> result = new HashSet<>();
for (SailfishURI utilityClassURI : settings.getUtilityClassURIs()) {
Set<UtilityInfo> infos = utilityManager.getUtilityInfos(utilityClassURI);
for (UtilityInfo info : infos) {
result.add(info.getURI());
}
}
return result;
}
@Override
public long getDictionaryId(SailfishURI uri) {
return SailfishURIUtils.getMatchingValue(uri, dictionaryIds, SailfishURIRule.REQUIRE_RESOURCE);
}
@Override
public void subscribeForEvents(IDictionaryManagerListener listener){
eventListeners.add(listener);
}
@Override
public void unSubscribeForEvents(IDictionaryManagerListener listener){
eventListeners.remove(listener);
}
public void invalidateEvent(Set<SailfishURI> uris) {
for (IDictionaryManagerListener listener : eventListeners) {
try {
listener.invalidateEvent(uris);
} catch (RuntimeException e) {
logger.error(e.getMessage(), e);
}
}
}
public void createEvent(SailfishURI uri) {
for (IDictionaryManagerListener listener : eventListeners){
listener.createEvent(uri);
}
}
@Override
public IDictionaryRegistrator registerDictionary(String title, boolean overwrite) throws WorkspaceStructureException, WorkspaceSecurityException {
SailfishURI suri;
try {
suri = new SailfishURI(IVersion.GENERAL, null, title);
} catch (SailfishURIException e) {
throw new EPSCommonException(String.format("Name '%s' is incorrect", title));
}
synchronized (this) {
if(!overwrite && getDictionaryURIs().contains(suri)) {
throw new EPSCommonException(String.format("Dictionary with title %s and suri %s already registred", title, suri));
}
}
Path relativePath = Paths.get("cfg", "dictionaries", title + ".xml");
workspaceDispatcher.createFile(FolderType.ROOT, overwrite, relativePath.toString());
return new DictionaryRegistrator(suri, relativePath, overwrite);
}
private IDictionaryStructureLoader createStructureLoader(String pathName) throws FileNotFoundException, WorkspaceSecurityException {
String extension = FilenameUtils.getExtension(pathName);
if ("xml".equals(extension.toLowerCase())) {
return new XmlDictionaryStructureLoader();
}
throw new EPSCommonException("Unresolved dictionary extension: '" + extension + "'");
}
private class DictionaryRegistrator implements IDictionaryRegistrator {
private final DictionarySettings dictionarySettings;
private final boolean overwrite;
private final Path relativePath;
public DictionaryRegistrator(SailfishURI dictionarySURI, Path relativePath, boolean overwrite) {
this.relativePath = relativePath;
this.overwrite = overwrite;
this.dictionarySettings = new DictionarySettings();
dictionarySettings.setURI(dictionarySURI);
dictionarySettings.setFactoryClass(DummyMessageFactory.class);
}
@Override
public SailfishURI registrate() {
try {
createDictionary(relativePath.getFileName().toString(), dictionarySettings, overwrite);
} catch (Exception e) {
throw new EPSCommonException(String.format("Could not create dictionary with SailfishURI: '%s'", dictionarySettings.getURI()), e);
}
return dictionarySettings.getURI();
}
@Override
public String getPath() {
return relativePath.toString();
}
@Override
public IDictionaryRegistrator addUtilityClassURI(SailfishURI uri) {
dictionarySettings.addUtilityClassURI(uri);
return this;
}
@Override
public IDictionaryRegistrator addUtilityClassURI(Collection<SailfishURI> uri) {
for (SailfishURI sailfishURI : uri) {
addUtilityClassURI(sailfishURI);
}
return this;
}
@Override
public IDictionaryRegistrator setFactoryClass(Class<? extends IMessageFactory> factoryClass) {
dictionarySettings.setFactoryClass(factoryClass);
return this;
}
}
}
|
package bg.bas.iinf.sinus.wicket.common;
import org.apache.wicket.ajax.IAjaxCallDecorator;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.model.IModel;
/**
* Disabling Ajax link
* @author hok
*
* @param <T>
*/
public abstract class DisablingAjaxLink<T> extends AjaxLink<T> {
private static final long serialVersionUID = -7817810863719722935L;
public DisablingAjaxLink(String id, IModel<T> model) {
super(id, model);
}
public DisablingAjaxLink(String id) {
super(id);
}
/* (non-Javadoc)
* disable/enable pri natiskane
*
* @see org.apache.wicket.ajax.markup.html.form.AjaxButton#getAjaxCallDecorator()
*/
@Override
protected IAjaxCallDecorator getAjaxCallDecorator() {
return new DisablingLinkAjaxCallDecorator();
}
}
|
package com.github.walterfan.devaid.algorithm;
/******************************************************************************
* Compilation: javac In.java
* Execution: java In (basic test --- see source for required files)
* Dependencies: none
*
* Reads in data of various types from standard input, files, and URLs.
*
******************************************************************************/
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.Socket;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Locale;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.regex.Pattern;
/**
* <i>Input</i>. This class provides methods for reading strings
* and numbers from standard input, file input, URLs, and sockets.
* <p>
* The Locale used is: language = English, country = US. This is consistent
* with the formatting conventions with Java floating-point literals,
* command-line arguments (via {@link Double#parseDouble(String)})
* and standard output.
* <p>
* For additional documentation, see
* <a href="http://introcs.cs.princeton.edu/31datatype">Section 3.1</a> of
* <i>Computer Science: An Interdisciplinary Approach</i>
* by Robert Sedgewick and Kevin Wayne.
* <p>
* Like {@link Scanner}, reading a token also consumes preceding Java
* whitespace, reading a full line consumes
* the following end-of-line delimeter, while reading a character consumes
* nothing extra.
* <p>
* Whitespace is defined in {@link Character#isWhitespace(char)}. Newlines
* consist of \n, \r, \r\n, and Unicode hex code points 0x2028, 0x2029, 0x0085;
* see <a href="http://www.docjar.com/html/api/java/util/Scanner.java.html">
* Scanner.java</a> (NB: Java 6u23 and earlier uses only \r, \r, \r\n).
*
* @author David Pritchard
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public final class In {
///// begin: section (1 of 2) of code duplicated from In to StdIn.
// assume Unicode UTF-8 encoding
private static final String CHARSET_NAME = "UTF-8";
// assume language = English, country = US for consistency with System.out.
private static final Locale LOCALE = Locale.US;
// the default token separator; we maintain the invariant that this value
// is held by the scanner's delimiter between calls
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\p{javaWhitespace}+");
// makes whitespace characters significant
private static final Pattern EMPTY_PATTERN = Pattern.compile("");
// used to read the entire input. source:
// http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html
private static final Pattern EVERYTHING_PATTERN = Pattern.compile("\\A");
//// end: section (1 of 2) of code duplicated from In to StdIn.
private Scanner scanner;
/**
* Initializes an input stream from standard input.
*/
public In() {
scanner = new Scanner(new BufferedInputStream(System.in), CHARSET_NAME);
scanner.useLocale(LOCALE);
}
/**
* Initializes an input stream from a socket.
*
* @param socket the socket
* @throws IllegalArgumentException if cannot open {@code socket}
* @throws IllegalArgumentException if {@code socket} is {@code null}
*/
public In(Socket socket) {
if (socket == null) throw new IllegalArgumentException("socket argument is null");
try {
InputStream is = socket.getInputStream();
scanner = new Scanner(new BufferedInputStream(is), CHARSET_NAME);
scanner.useLocale(LOCALE);
}
catch (IOException ioe) {
throw new IllegalArgumentException("Could not open " + socket, ioe);
}
}
/**
* Initializes an input stream from a URL.
*
* @param url the URL
* @throws IllegalArgumentException if cannot open {@code url}
* @throws IllegalArgumentException if {@code url} is {@code null}
*/
public In(URL url) {
if (url == null) throw new IllegalArgumentException("url argument is null");
try {
URLConnection site = url.openConnection();
InputStream is = site.getInputStream();
scanner = new Scanner(new BufferedInputStream(is), CHARSET_NAME);
scanner.useLocale(LOCALE);
}
catch (IOException ioe) {
throw new IllegalArgumentException("Could not open " + url, ioe);
}
}
/**
* Initializes an input stream from a file.
*
* @param file the file
* @throws IllegalArgumentException if cannot open {@code file}
* @throws IllegalArgumentException if {@code file} is {@code null}
*/
public In(File file) {
if (file == null) throw new IllegalArgumentException("file argument is null");
try {
// for consistency with StdIn, wrap with BufferedInputStream instead of use
// file as argument to Scanner
FileInputStream fis = new FileInputStream(file);
scanner = new Scanner(new BufferedInputStream(fis), CHARSET_NAME);
scanner.useLocale(LOCALE);
}
catch (IOException ioe) {
throw new IllegalArgumentException("Could not open " + file, ioe);
}
}
/**
* Initializes an input stream from a filename or web page name.
*
* @param name the filename or web page name
* @throws IllegalArgumentException if cannot open {@code name} as
* a file or URL
* @throws IllegalArgumentException if {@code name} is {@code null}
*/
public In(String name) {
if (name == null) throw new IllegalArgumentException("argument is null");
try {
// first try to read file from local file system
File file = new File(name);
if (file.exists()) {
// for consistency with StdIn, wrap with BufferedInputStream instead of use
// file as argument to Scanner
FileInputStream fis = new FileInputStream(file);
scanner = new Scanner(new BufferedInputStream(fis), CHARSET_NAME);
scanner.useLocale(LOCALE);
return;
}
// next try for files included in jar
URL url = getClass().getResource(name);
// try this as well
if (url == null) {
url = getClass().getClassLoader().getResource(name);
}
// or URL from web
if (url == null) {
url = new URL(name);
}
URLConnection site = url.openConnection();
// in order to set User-Agent, replace above line with these two
// HttpURLConnection site = (HttpURLConnection) url.openConnection();
// site.addRequestProperty("User-Agent", "Mozilla/4.76");
InputStream is = site.getInputStream();
scanner = new Scanner(new BufferedInputStream(is), CHARSET_NAME);
scanner.useLocale(LOCALE);
}
catch (IOException ioe) {
throw new IllegalArgumentException("Could not open " + name, ioe);
}
}
/**
* Initializes an input stream from a given {@link Scanner} source; use with
* {@code new Scanner(String)} to read from a string.
* <p>
* Note that this does not create a defensive copy, so the
* scanner will be mutated as you read on.
*
* @param scanner the scanner
* @throws IllegalArgumentException if {@code scanner} is {@code null}
*/
public In(Scanner scanner) {
if (scanner == null) throw new IllegalArgumentException("scanner argument is null");
this.scanner = scanner;
}
/**
* Returns true if this input stream exists.
*
* @return {@code true} if this input stream exists; {@code false} otherwise
*/
public boolean exists() {
return scanner != null;
}
//// begin: section (2 of 2) of code duplicated from In to StdIn,
//// with all methods changed from "public" to "public static".
/**
* Returns true if input stream is empty (except possibly whitespace).
* Use this to know whether the next call to {@link #readString()},
* {@link #readDouble()}, etc will succeed.
*
* @return {@code true} if this input stream is empty (except possibly whitespace);
* {@code false} otherwise
*/
public boolean isEmpty() {
return !scanner.hasNext();
}
/**
* Returns true if this input stream has a next line.
* Use this method to know whether the
* next call to {@link #readLine()} will succeed.
* This method is functionally equivalent to {@link #hasNextChar()}.
*
* @return {@code true} if this input stream has more input (including whitespace);
* {@code false} otherwise
*/
public boolean hasNextLine() {
return scanner.hasNextLine();
}
/**
* Returns true if this input stream has more input (including whitespace).
* Use this method to know whether the next call to {@link #readChar()} will succeed.
* This method is functionally equivalent to {@link #hasNextLine()}.
*
* @return {@code true} if this input stream has more input (including whitespace);
* {@code false} otherwise
*/
public boolean hasNextChar() {
scanner.useDelimiter(EMPTY_PATTERN);
boolean result = scanner.hasNext();
scanner.useDelimiter(WHITESPACE_PATTERN);
return result;
}
/**
* Reads and returns the next line in this input stream.
*
* @return the next line in this input stream; {@code null} if no such line
*/
public String readLine() {
String line;
try {
line = scanner.nextLine();
}
catch (NoSuchElementException e) {
line = null;
}
return line;
}
/**
* Reads and returns the next character in this input stream.
*
* @return the next {@code char} in this input stream
* @throws NoSuchElementException if the input stream is empty
*/
public char readChar() {
scanner.useDelimiter(EMPTY_PATTERN);
try {
String ch = scanner.next();
assert ch.length() == 1 : "Internal (Std)In.readChar() error!"
+ " Please contact the authors.";
scanner.useDelimiter(WHITESPACE_PATTERN);
return ch.charAt(0);
}
catch (NoSuchElementException e) {
throw new NoSuchElementException("attempts to read a 'char' value from input stream, but there are no more tokens available");
}
}
/**
* Reads and returns the remainder of this input stream, as a string.
*
* @return the remainder of this input stream, as a string
*/
public String readAll() {
if (!scanner.hasNextLine())
return "";
String result = scanner.useDelimiter(EVERYTHING_PATTERN).next();
// not that important to reset delimeter, since now scanner is empty
scanner.useDelimiter(WHITESPACE_PATTERN); // but let's do it anyway
return result;
}
/**
* Reads the next token from this input stream and returns it as a {@code String}.
*
* @return the next {@code String} in this input stream
* @throws NoSuchElementException if the input stream is empty
*/
public String readString() {
try {
return scanner.next();
}
catch (NoSuchElementException e) {
throw new NoSuchElementException("attempts to read a 'String' value from input stream, but there are no more tokens available");
}
}
/**
* Reads the next token from this input stream, parses it as a {@code int},
* and returns the {@code int}.
*
* @return the next {@code int} in this input stream
* @throws NoSuchElementException if the input stream is empty
* @throws InputMismatchException if the next token cannot be parsed as an {@code int}
*/
public int readInt() {
try {
return scanner.nextInt();
}
catch (InputMismatchException e) {
String token = scanner.next();
throw new InputMismatchException("attempts to read an 'int' value from input stream, but the next token is \"" + token + "\"");
}
catch (NoSuchElementException e) {
throw new NoSuchElementException("attemps to read an 'int' value from input stream, but there are no more tokens available");
}
}
/**
* Reads the next token from this input stream, parses it as a {@code double},
* and returns the {@code double}.
*
* @return the next {@code double} in this input stream
* @throws NoSuchElementException if the input stream is empty
* @throws InputMismatchException if the next token cannot be parsed as a {@code double}
*/
public double readDouble() {
try {
return scanner.nextDouble();
}
catch (InputMismatchException e) {
String token = scanner.next();
throw new InputMismatchException("attempts to read a 'double' value from input stream, but the next token is \"" + token + "\"");
}
catch (NoSuchElementException e) {
throw new NoSuchElementException("attemps to read a 'double' value from input stream, but there are no more tokens available");
}
}
/**
* Reads the next token from this input stream, parses it as a {@code float},
* and returns the {@code float}.
*
* @return the next {@code float} in this input stream
* @throws NoSuchElementException if the input stream is empty
* @throws InputMismatchException if the next token cannot be parsed as a {@code float}
*/
public float readFloat() {
try {
return scanner.nextFloat();
}
catch (InputMismatchException e) {
String token = scanner.next();
throw new InputMismatchException("attempts to read a 'float' value from input stream, but the next token is \"" + token + "\"");
}
catch (NoSuchElementException e) {
throw new NoSuchElementException("attemps to read a 'float' value from input stream, but there are no more tokens available");
}
}
/**
* Reads the next token from this input stream, parses it as a {@code long},
* and returns the {@code long}.
*
* @return the next {@code long} in this input stream
* @throws NoSuchElementException if the input stream is empty
* @throws InputMismatchException if the next token cannot be parsed as a {@code long}
*/
public long readLong() {
try {
return scanner.nextLong();
}
catch (InputMismatchException e) {
String token = scanner.next();
throw new InputMismatchException("attempts to read a 'long' value from input stream, but the next token is \"" + token + "\"");
}
catch (NoSuchElementException e) {
throw new NoSuchElementException("attemps to read a 'long' value from input stream, but there are no more tokens available");
}
}
/**
* Reads the next token from this input stream, parses it as a {@code short},
* and returns the {@code short}.
*
* @return the next {@code short} in this input stream
* @throws NoSuchElementException if the input stream is empty
* @throws InputMismatchException if the next token cannot be parsed as a {@code short}
*/
public short readShort() {
try {
return scanner.nextShort();
}
catch (InputMismatchException e) {
String token = scanner.next();
throw new InputMismatchException("attempts to read a 'short' value from input stream, but the next token is \"" + token + "\"");
}
catch (NoSuchElementException e) {
throw new NoSuchElementException("attemps to read a 'short' value from input stream, but there are no more tokens available");
}
}
/**
* Reads the next token from this input stream, parses it as a {@code byte},
* and returns the {@code byte}.
* <p>
* To read binary data, use {@link BinaryIn}.
*
* @return the next {@code byte} in this input stream
* @throws NoSuchElementException if the input stream is empty
* @throws InputMismatchException if the next token cannot be parsed as a {@code byte}
*/
public byte readByte() {
try {
return scanner.nextByte();
}
catch (InputMismatchException e) {
String token = scanner.next();
throw new InputMismatchException("attempts to read a 'byte' value from input stream, but the next token is \"" + token + "\"");
}
catch (NoSuchElementException e) {
throw new NoSuchElementException("attemps to read a 'byte' value from input stream, but there are no more tokens available");
}
}
/**
* Reads the next token from this input stream, parses it as a {@code boolean}
* (interpreting either {@code "true"} or {@code "1"} as {@code true},
* and either {@code "false"} or {@code "0"} as {@code false}).
*
* @return the next {@code boolean} in this input stream
* @throws NoSuchElementException if the input stream is empty
* @throws InputMismatchException if the next token cannot be parsed as a {@code boolean}
*/
public boolean readBoolean() {
try {
String token = readString();
if ("true".equalsIgnoreCase(token)) return true;
if ("false".equalsIgnoreCase(token)) return false;
if ("1".equals(token)) return true;
if ("0".equals(token)) return false;
throw new InputMismatchException("attempts to read a 'boolean' value from input stream, but the next token is \"" + token + "\"");
}
catch (NoSuchElementException e) {
throw new NoSuchElementException("attempts to read a 'boolean' value from input stream, but there are no more tokens available");
}
}
/**
* Reads all remaining tokens from this input stream and returns them as
* an array of strings.
*
* @return all remaining tokens in this input stream, as an array of strings
*/
public String[] readAllStrings() {
// we could use readAll.trim().split(), but that's not consistent
// since trim() uses characters 0x00..0x20 as whitespace
String[] tokens = WHITESPACE_PATTERN.split(readAll());
if (tokens.length == 0 || tokens[0].length() > 0)
return tokens;
String[] decapitokens = new String[tokens.length-1];
for (int i = 0; i < tokens.length-1; i++)
decapitokens[i] = tokens[i+1];
return decapitokens;
}
/**
* Reads all remaining lines from this input stream and returns them as
* an array of strings.
*
* @return all remaining lines in this input stream, as an array of strings
*/
public String[] readAllLines() {
ArrayList<String> lines = new ArrayList<String>();
while (hasNextLine()) {
lines.add(readLine());
}
return lines.toArray(new String[lines.size()]);
}
/**
* Reads all remaining tokens from this input stream, parses them as integers,
* and returns them as an array of integers.
*
* @return all remaining lines in this input stream, as an array of integers
*/
public int[] readAllInts() {
String[] fields = readAllStrings();
int[] vals = new int[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Integer.parseInt(fields[i]);
return vals;
}
/**
* Reads all remaining tokens from this input stream, parses them as longs,
* and returns them as an array of longs.
*
* @return all remaining lines in this input stream, as an array of longs
*/
public long[] readAllLongs() {
String[] fields = readAllStrings();
long[] vals = new long[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Long.parseLong(fields[i]);
return vals;
}
/**
* Reads all remaining tokens from this input stream, parses them as doubles,
* and returns them as an array of doubles.
*
* @return all remaining lines in this input stream, as an array of doubles
*/
public double[] readAllDoubles() {
String[] fields = readAllStrings();
double[] vals = new double[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Double.parseDouble(fields[i]);
return vals;
}
///// end: section (2 of 2) of code duplicated from In to StdIn */
/**
* Closes this input stream.
*/
public void close() {
scanner.close();
}
/**
* Reads all integers from a file and returns them as
* an array of integers.
*
* @param filename the name of the file
* @return the integers in the file
* @deprecated Replaced by {@code new In(filename)}.{@link #readAllInts()}.
*/
@Deprecated
public static int[] readInts(String filename) {
return new In(filename).readAllInts();
}
/**
* Reads all doubles from a file and returns them as
* an array of doubles.
*
* @param filename the name of the file
* @return the doubles in the file
* @deprecated Replaced by {@code new In(filename)}.{@link #readAllDoubles()}.
*/
@Deprecated
public static double[] readDoubles(String filename) {
return new In(filename).readAllDoubles();
}
/**
* Reads all strings from a file and returns them as
* an array of strings.
*
* @param filename the name of the file
* @return the strings in the file
* @deprecated Replaced by {@code new In(filename)}.{@link #readAllStrings()}.
*/
@Deprecated
public static String[] readStrings(String filename) {
return new In(filename).readAllStrings();
}
/**
* Reads all integers from standard input and returns them
* an array of integers.
*
* @return the integers on standard input
* @deprecated Replaced by {@link StdIn#readAllInts()}.
*/
@Deprecated
public static int[] readInts() {
return new In().readAllInts();
}
/**
* Reads all doubles from standard input and returns them as
* an array of doubles.
*
* @return the doubles on standard input
* @deprecated Replaced by {@link StdIn#readAllDoubles()}.
*/
@Deprecated
public static double[] readDoubles() {
return new In().readAllDoubles();
}
/**
* Reads all strings from standard input and returns them as
* an array of strings.
*
* @return the strings on standard input
* @deprecated Replaced by {@link StdIn#readAllStrings()}.
*/
@Deprecated
public static String[] readStrings() {
return new In().readAllStrings();
}
/**
* Unit tests the {@code In} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
In in;
String urlName = "http://introcs.cs.princeton.edu/stdlib/InTest.txt";
// read from a URL
System.out.println("readAll() from URL " + urlName);
System.out.println("---------------------------------------------------------------------------");
try {
in = new In(urlName);
System.out.println(in.readAll());
}
catch (IllegalArgumentException e) {
System.out.println(e);
}
System.out.println();
// read one line at a time from URL
System.out.println("readLine() from URL " + urlName);
System.out.println("---------------------------------------------------------------------------");
try {
in = new In(urlName);
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
}
catch (IllegalArgumentException e) {
System.out.println(e);
}
System.out.println();
// read one string at a time from URL
System.out.println("readString() from URL " + urlName);
System.out.println("---------------------------------------------------------------------------");
try {
in = new In(urlName);
while (!in.isEmpty()) {
String s = in.readString();
System.out.println(s);
}
}
catch (IllegalArgumentException e) {
System.out.println(e);
}
System.out.println();
// read one line at a time from file in current directory
System.out.println("readLine() from current directory");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("./InTest.txt");
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
}
catch (IllegalArgumentException e) {
System.out.println(e);
}
System.out.println();
// read one line at a time from file using relative path
System.out.println("readLine() from relative path");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("../stdlib/InTest.txt");
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
}
catch (IllegalArgumentException e) {
System.out.println(e);
}
System.out.println();
// read one char at a time
System.out.println("readChar() from file");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("InTest.txt");
while (!in.isEmpty()) {
char c = in.readChar();
System.out.print(c);
}
}
catch (IllegalArgumentException e) {
System.out.println(e);
}
System.out.println();
System.out.println();
// read one line at a time from absolute OS X / Linux path
System.out.println("readLine() from absolute OS X / Linux path");
System.out.println("---------------------------------------------------------------------------");
in = new In("/n/fs/introcs/www/java/stdlib/InTest.txt");
try {
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
}
catch (IllegalArgumentException e) {
System.out.println(e);
}
System.out.println();
// read one line at a time from absolute Windows path
System.out.println("readLine() from absolute Windows path");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("G:\\www\\introcs\\stdlib\\InTest.txt");
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
System.out.println();
}
catch (IllegalArgumentException e) {
System.out.println(e);
}
System.out.println();
}
}
/******************************************************************************
* Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
|
package com.autowatch.antiseptic;
import androidx.annotation.NonNull;
import com.bumptech.glide.load.Options;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.model.ModelLoader;
import com.bumptech.glide.load.model.ModelLoaderFactory;
import com.bumptech.glide.load.model.MultiModelLoaderFactory;
import java.io.InputStream;
import okhttp3.Call;
import okhttp3.OkHttpClient;
/** A simple model loader for fetching media over http/https using OkHttp. */
public class OkHttpUrlLoader implements ModelLoader<GlideUrl, InputStream> {
private final Call.Factory client;
// Public API.
@SuppressWarnings("WeakerAccess")
public OkHttpUrlLoader(@NonNull Call.Factory client) {
this.client = client;
}
@Override
public boolean handles(@NonNull GlideUrl url) {
return true;
}
@Override
public LoadData<InputStream> buildLoadData(
@NonNull GlideUrl model, int width, int height, @NonNull Options options) {
return new LoadData<>(model, new OkHttpStreamFetcher(client, model));
}
/** The default factory for {@link OkHttpUrlLoader}s. */
// Public API.
@SuppressWarnings("WeakerAccess")
public static class Factory implements ModelLoaderFactory<GlideUrl, InputStream> {
private static volatile Call.Factory internalClient;
private final Call.Factory client;
private static Call.Factory getInternalClient() {
if (internalClient == null) {
synchronized (Factory.class) {
if (internalClient == null) {
internalClient = new OkHttpClient();
}
}
}
return internalClient;
}
/** Constructor for a new Factory that runs requests using a static singleton client. */
public Factory() {
this(getInternalClient());
}
/**
* Constructor for a new Factory that runs requests using given client.
*
* @param client this is typically an instance of {@code OkHttpClient}.
*/
public Factory(@NonNull Call.Factory client) {
this.client = client;
}
@NonNull
@Override
public ModelLoader<GlideUrl, InputStream> build(MultiModelLoaderFactory multiFactory) {
return new OkHttpUrlLoader(client);
}
@Override
public void teardown() {
// Do nothing, this instance doesn't own the client.
}
}
}
|
/***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2012-2013 Karol Bucek <self@kares.org>
* Copyright (c) 2006-2011 Nick Sieger <nick@nicksieger.com>
* Copyright (c) 2006-2007 Ola Bini <ola.bini@gmail.com>
* Copyright (c) 2008-2009 Thomas E Enebo <enebo@acm.org>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
***** END LICENSE BLOCK *****/
package arjdbc.jdbc;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.Reader;
import java.io.StringReader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Array;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.SQLXML;
import java.sql.Statement;
import java.sql.Date;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.SQLRecoverableException;
import java.sql.SQLTransientException;
import java.sql.Savepoint;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.TimeZone;
import arjdbc.util.StringHelper;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyBasicObject;
import org.jruby.RubyBignum;
import org.jruby.RubyBoolean;
import org.jruby.RubyClass;
import org.jruby.RubyException;
import org.jruby.RubyFixnum;
import org.jruby.RubyHash;
import org.jruby.RubyIO;
import org.jruby.RubyInteger;
import org.jruby.RubyModule;
import org.jruby.RubyNumeric;
import org.jruby.RubyObject;
import org.jruby.RubyString;
import org.jruby.RubySymbol;
import org.jruby.RubyTime;
import org.jruby.anno.JRubyMethod;
import org.jruby.exceptions.RaiseException;
import org.jruby.ext.bigdecimal.RubyBigDecimal;
import org.jruby.ext.date.RubyDate;
import org.jruby.ext.date.RubyDateTime;
import org.jruby.javasupport.JavaEmbedUtils;
import org.jruby.javasupport.JavaUtil;
import org.jruby.runtime.Block;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.builtin.Variable;
import org.jruby.runtime.callsite.CachingCallSite;
import org.jruby.runtime.callsite.FunctionalCachingCallSite;
import org.jruby.runtime.component.VariableEntry;
import org.jruby.util.ByteList;
import org.jruby.util.SafePropertyAccessor;
import org.jruby.util.TypeConverter;
import arjdbc.util.DateTimeUtils;
import arjdbc.util.ObjectSupport;
import arjdbc.util.StringCache;
import static arjdbc.jdbc.DataSourceConnectionFactory.*;
import static arjdbc.util.StringHelper.*;
import static org.jruby.RubyTime.getLocalTimeZone;
/**
* Most of our ActiveRecord::ConnectionAdapters::JdbcConnection implementation.
*/
public class RubyJdbcConnection extends RubyObject {
private static final long serialVersionUID = 3803945791317576818L;
private static final String[] TABLE_TYPE = new String[] { "TABLE" };
private static final String[] TABLE_TYPES = new String[] { "TABLE", "VIEW", "SYNONYM" };
private ConnectionFactory connectionFactory;
private IRubyObject config;
private IRubyObject adapter; // the AbstractAdapter instance we belong to
private volatile boolean connected = true;
private RubyClass attributeClass;
private boolean lazy = false; // final once set on initialize
private boolean jndi; // final once set on initialize
private boolean configureConnection = true; // final once initialized
private int fetchSize = 0; // 0 = JDBC default
protected RubyJdbcConnection(Ruby runtime, RubyClass metaClass) {
super(runtime, metaClass);
attributeClass = runtime.getModule("ActiveModel").getClass("Attribute");
}
private static final ObjectAllocator ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
return new RubyJdbcConnection(runtime, klass);
}
};
public static RubyClass createJdbcConnectionClass(final Ruby runtime) {
final RubyClass JdbcConnection = getConnectionAdapters(runtime).
defineClassUnder("JdbcConnection", runtime.getObject(), ALLOCATOR);
JdbcConnection.defineAnnotatedMethods(RubyJdbcConnection.class);
return JdbcConnection;
}
public static RubyClass getJdbcConnection(final Ruby runtime) {
return (RubyClass) getConnectionAdapters(runtime).getConstantAt("JdbcConnection");
}
protected static RubyModule ActiveRecord(ThreadContext context) {
return context.runtime.getModule("ActiveRecord");
}
public static RubyClass getBase(final Ruby runtime) {
return (RubyClass) runtime.getModule("ActiveRecord").getConstantAt("Base");
}
/**
* @param runtime
* @return <code>ActiveRecord::Result</code>
*/
public static RubyClass getResult(final Ruby runtime) {
return (RubyClass) runtime.getModule("ActiveRecord").getConstantAt("Result");
}
/**
* @param runtime
* @return <code>ActiveRecord::ConnectionAdapters</code>
*/
public static RubyModule getConnectionAdapters(final Ruby runtime) {
return (RubyModule) runtime.getModule("ActiveRecord").getConstantAt("ConnectionAdapters");
}
/**
* @param runtime
* @return <code>ActiveRecord::ConnectionAdapters::IndexDefinition</code>
*/
protected static RubyClass getIndexDefinition(final Ruby runtime) {
return getConnectionAdapters(runtime).getClass("IndexDefinition");
}
/**
* @param runtime
* @return <code>ActiveRecord::ConnectionAdapters::ForeignKeyDefinition</code>
* @note only since AR 4.2
*/
protected static RubyClass getForeignKeyDefinition(final Ruby runtime) {
return getConnectionAdapters(runtime).getClass("ForeignKeyDefinition");
}
/**
* @param runtime
* @return <code>ActiveRecord::JDBCError</code>
*/
protected static RubyClass getJDBCError(final Ruby runtime) {
return runtime.getModule("ActiveRecord").getClass("JDBCError");
}
/**
* @param runtime
* @return <code>ActiveRecord::ConnectionNotEstablished</code>
*/
protected static RubyClass getConnectionNotEstablished(final Ruby runtime) {
return runtime.getModule("ActiveRecord").getClass("ConnectionNotEstablished");
}
/**
* @param runtime
* @return <code>ActiveRecord::NoDatabaseError</code>
*/
protected static RubyClass getNoDatabaseError(final Ruby runtime) {
return runtime.getModule("ActiveRecord").getClass("NoDatabaseError");
}
/**
* @param runtime
* @return <code>ActiveRecord::TransactionIsolationError</code>
*/
protected static RubyClass getTransactionIsolationError(final Ruby runtime) {
return (RubyClass) runtime.getModule("ActiveRecord").getConstant("TransactionIsolationError");
}
@JRubyMethod(name = "transaction_isolation", alias = "get_transaction_isolation")
public IRubyObject get_transaction_isolation(final ThreadContext context) {
return withConnection(context, connection -> {
final int level = connection.getTransactionIsolation();
final String isolationSymbol = formatTransactionIsolationLevel(level);
if ( isolationSymbol == null ) return context.nil;
return context.runtime.newSymbol(isolationSymbol);
});
}
@JRubyMethod(name = "transaction_isolation=", alias = "set_transaction_isolation")
public IRubyObject set_transaction_isolation(final ThreadContext context, final IRubyObject isolation) {
return withConnection(context, connection -> {
final int level;
if ( isolation.isNil() ) {
level = connection.getMetaData().getDefaultTransactionIsolation();
}
else {
level = mapTransactionIsolationLevel(isolation);
}
connection.setTransactionIsolation(level);
final String isolationSymbol = formatTransactionIsolationLevel(level);
if ( isolationSymbol == null ) return context.nil;
return context.runtime.newSymbol(isolationSymbol);
});
}
public static String formatTransactionIsolationLevel(final int level) {
if ( level == Connection.TRANSACTION_READ_UNCOMMITTED ) return "read_uncommitted"; // 1
if ( level == Connection.TRANSACTION_READ_COMMITTED ) return "read_committed"; // 2
if ( level == Connection.TRANSACTION_REPEATABLE_READ ) return "repeatable_read"; // 4
if ( level == Connection.TRANSACTION_SERIALIZABLE ) return "serializable"; // 8
if ( level == 0 ) return null;
throw new IllegalArgumentException("unexpected transaction isolation level: " + level);
}
/*
def transaction_isolation_levels
{
read_uncommitted: "READ UNCOMMITTED",
read_committed: "READ COMMITTED",
repeatable_read: "REPEATABLE READ",
serializable: "SERIALIZABLE"
}
end
*/
public static int mapTransactionIsolationLevel(final IRubyObject isolation) {
final Object isolationString;
if ( isolation instanceof RubySymbol ) {
isolationString = ((RubySymbol) isolation).asJavaString(); // RubySymbol (interned)
}
else {
isolationString = isolation.asString().toString().toLowerCase(Locale.ENGLISH).intern();
}
if ( isolationString == "read_uncommitted" ) return Connection.TRANSACTION_READ_UNCOMMITTED; // 1
if ( isolationString == "read_committed" ) return Connection.TRANSACTION_READ_COMMITTED; // 2
if ( isolationString == "repeatable_read" ) return Connection.TRANSACTION_REPEATABLE_READ; // 4
if ( isolationString == "serializable" ) return Connection.TRANSACTION_SERIALIZABLE; // 8
throw new IllegalArgumentException(
"unexpected isolation level: " + isolation + " (" + isolationString + ")"
);
}
@JRubyMethod(name = "supports_transaction_isolation?", optional = 1)
public IRubyObject supports_transaction_isolation_p(final ThreadContext context,
final IRubyObject[] args) throws SQLException {
final IRubyObject isolation = args.length > 0 ? args[0] : null;
return withConnection(context, (Callable<IRubyObject>) connection -> {
final DatabaseMetaData metaData = connection.getMetaData();
final boolean supported;
if ( isolation != null && ! isolation.isNil() ) {
final int level = mapTransactionIsolationLevel(isolation);
supported = metaData.supportsTransactionIsolationLevel(level);
}
else {
final int level = metaData.getDefaultTransactionIsolation();
supported = level > Connection.TRANSACTION_NONE; // > 0
}
return context.runtime.newBoolean(supported);
});
}
@JRubyMethod(name = {"begin", "transaction"}, required = 1) // optional isolation argument for AR-4.0
public IRubyObject begin(final ThreadContext context, final IRubyObject isolation) {
try { // handleException == false so we can handle setTXIsolation
return withConnection(context, false, connection -> beginTransaction(context, connection, isolation == context.nil ? null : isolation));
} catch (SQLException e) {
return handleException(context, e);
}
}
@JRubyMethod(name = {"begin", "transaction"}) // optional isolation argument for AR-4.0
public IRubyObject begin(final ThreadContext context) {
try { // handleException == false so we can handle setTXIsolation
return withConnection(context, false, connection -> beginTransaction(context, connection, null));
} catch (SQLException e) {
return handleException(context, e);
}
}
protected IRubyObject beginTransaction(final ThreadContext context, final Connection connection,
final IRubyObject isolation) throws SQLException {
if ( isolation != null ) {
setTransactionIsolation(context, connection, isolation);
}
if ( connection.getAutoCommit() ) connection.setAutoCommit(false);
return context.nil;
}
protected void setTransactionIsolation(final ThreadContext context, final Connection connection,
final IRubyObject isolation) throws SQLException {
final int level = mapTransactionIsolationLevel(isolation);
try {
connection.setTransactionIsolation(level);
}
catch (SQLException e) {
RubyClass txError = ActiveRecord(context).getClass("TransactionIsolationError");
if ( txError != null ) throw wrapException(context, txError, e);
throw e; // let it roll - will be wrapped into a JDBCError (non 4.0)
}
}
@JRubyMethod(name = "commit")
public IRubyObject commit(final ThreadContext context) {
try {
final Connection connection = getConnectionInternal(true);
if ( ! connection.getAutoCommit() ) {
try {
connection.commit();
resetSavepoints(context, connection); // if any
return context.runtime.newBoolean(true);
}
finally {
connection.setAutoCommit(true);
}
}
return context.nil;
}
catch (SQLException e) {
return handleException(context, e);
}
}
@JRubyMethod(name = "rollback")
public IRubyObject rollback(final ThreadContext context) {
try {
final Connection connection = getConnectionInternal(true);
if ( ! connection.getAutoCommit() ) {
try {
connection.rollback();
resetSavepoints(context, connection); // if any
return context.tru;
} finally {
connection.setAutoCommit(true);
}
}
return context.nil;
}
catch (SQLException e) {
return handleException(context, e);
}
}
@JRubyMethod(name = "supports_savepoints?")
public IRubyObject supports_savepoints_p(final ThreadContext context) throws SQLException {
return withConnection(context, (Callable<IRubyObject>) connection -> {
final DatabaseMetaData metaData = connection.getMetaData();
return context.runtime.newBoolean( metaData.supportsSavepoints() );
});
}
@JRubyMethod(name = "create_savepoint") // not used
public IRubyObject create_savepoint(final ThreadContext context) {
return create_savepoint(context, context.nil);
}
@JRubyMethod(name = "create_savepoint", required = 1)
public IRubyObject create_savepoint(final ThreadContext context, IRubyObject name) {
try {
final Connection connection = getConnectionInternal(true);
connection.setAutoCommit(false);
final Savepoint savepoint ;
// NOTE: this will auto-start a DB transaction even invoked outside
// of a AR (Ruby) transaction (`transaction { ... create_savepoint }`)
// it would be nice if AR knew about this TX although that's kind of
// "really advanced" functionality - likely not to be implemented ...
if ( name != context.nil ) {
savepoint = connection.setSavepoint(name.toString());
}
else {
savepoint = connection.setSavepoint();
name = RubyString.newString( context.runtime, Integer.toString( savepoint.getSavepointId() ));
}
getSavepoints(context).put(name, savepoint);
return name;
}
catch (SQLException e) {
return handleException(context, e);
}
}
@JRubyMethod(name = "rollback_savepoint", required = 1)
public IRubyObject rollback_savepoint(final ThreadContext context, final IRubyObject name) {
if (name == context.nil) throw context.runtime.newArgumentError("nil savepoint name given");
try {
final Connection connection = getConnectionInternal(true);
Savepoint savepoint = getSavepoints(context).get(name);
if ( savepoint == null ) {
throw context.runtime.newRuntimeError("could not rollback savepoint: '" + name + "' (not set)");
}
connection.rollback(savepoint);
return context.nil;
}
catch (SQLException e) {
return handleException(context, e);
}
}
@JRubyMethod(name = "release_savepoint", required = 1)
public IRubyObject release_savepoint(final ThreadContext context, final IRubyObject name) {
if (name == context.nil) throw context.runtime.newArgumentError("nil savepoint name given");
try {
Object savepoint = getSavepoints(context).remove(name);
if (savepoint == null) throw newSavepointNotSetError(context, name, "release");
// NOTE: RubyHash.remove does not convert to Java as get does :
if (!(savepoint instanceof Savepoint)) {
savepoint = ((IRubyObject) savepoint).toJava(Savepoint.class);
}
final Connection connection = getConnectionInternal(true);
releaseSavepoint(connection, (Savepoint) savepoint);
return context.nil;
}
catch (SQLException e) {
return handleException(context, e);
}
}
// MSSQL doesn't support releasing savepoints so we make it possible to override the actual release action
protected void releaseSavepoint(final Connection connection, final Savepoint savepoint) throws SQLException {
connection.releaseSavepoint(savepoint);
}
protected static RuntimeException newSavepointNotSetError(final ThreadContext context, final IRubyObject name, final String op) {
RubyClass StatementInvalid = ActiveRecord(context).getClass("StatementInvalid");
return context.runtime.newRaiseException(StatementInvalid, "could not " + op + " savepoint: '" + name + "' (not set)");
}
// NOTE: this is iternal API - not to be used by user-code !
@JRubyMethod(name = "marked_savepoint_names")
public IRubyObject marked_savepoint_names(final ThreadContext context) {
@SuppressWarnings("unchecked")
final Map<IRubyObject, Savepoint> savepoints = getSavepoints(false);
if ( savepoints != null ) {
final RubyArray names = context.runtime.newArray(savepoints.size());
for ( Map.Entry<IRubyObject, ?> entry : savepoints.entrySet() ) {
names.append( entry.getKey() ); // keys are RubyString instances
}
return names;
}
return context.runtime.newEmptyArray();
}
protected Map<IRubyObject, Savepoint> getSavepoints(final ThreadContext context) {
return getSavepoints(true);
}
@SuppressWarnings("unchecked")
private Map<IRubyObject, Savepoint> getSavepoints(final boolean init) {
if ( hasInternalVariable("savepoints") ) {
return (Map<IRubyObject, Savepoint>) getInternalVariable("savepoints");
}
if ( init ) {
Map<IRubyObject, Savepoint> savepoints = new LinkedHashMap<>(4);
setInternalVariable("savepoints", savepoints);
return savepoints;
}
return null;
}
protected boolean resetSavepoints(final ThreadContext context, final Connection connection) throws SQLException {
if ( hasInternalVariable("savepoints") ) {
removeInternalVariable("savepoints");
return true;
}
return false;
}
@JRubyMethod(required = 2)
public final IRubyObject initialize(final ThreadContext context, final IRubyObject config, final IRubyObject adapter) {
doInitialize(context, config, adapter);
return this;
}
protected void doInitialize(final ThreadContext context, final IRubyObject config, final IRubyObject adapter) {
this.config = config;
this.adapter = adapter;
this.jndi = setupConnectionFactory(context);
this.lazy = jndi; // JNDIs are lazy by default otherwise eager
try {
if (adapter == null || adapter == context.nil) {
warn(context, "adapter not set, please pass adapter on JdbcConnection#initialize(config, adapter)");
}
if (!lazy) setConnection(newConnection());
}
catch (SQLException e) {
String message = e.getMessage();
if ( message == null ) message = e.getSQLState();
throw wrapException(context, e, message);
}
IRubyObject value = getConfigValue(context, "configure_connection");
if ( value == context.nil ) this.configureConnection = true;
else {
this.configureConnection = value != context.fals;
}
IRubyObject jdbcFetchSize = getConfigValue(context, "jdbc_fetch_size");
if (jdbcFetchSize != context.nil) {
this.fetchSize = RubyNumeric.fix2int(jdbcFetchSize);
}
}
@JRubyMethod(name = "adapter")
public IRubyObject adapter(final ThreadContext context) {
return adapter == null ? context.nil : adapter;
}
@JRubyMethod(name = "connection_factory")
public IRubyObject connection_factory() {
return convertJavaToRuby( getConnectionFactory() );
}
@JRubyMethod(name = "connection_factory=", required = 1)
public IRubyObject set_connection_factory(final IRubyObject factory) {
setConnectionFactory( (ConnectionFactory) factory.toJava(ConnectionFactory.class) );
return factory;
}
private void configureConnection() {
if ( ! configureConnection ) return; // return false;
if ( adapter != null && ! adapter.isNil() ) {
if ( adapter.respondsTo("configure_connection") ) {
final ThreadContext context = getRuntime().getCurrentContext();
adapter.callMethod(context, "configure_connection");
}
}
}
@JRubyMethod(name = "configure_connection")
public IRubyObject configure_connection(final ThreadContext context) {
if ( ! lazy || getConnectionImpl() != null ) configureConnection();
return context.nil;
}
@JRubyMethod(name = "jdbc_connection", alias = "connection")
public final IRubyObject connection(final ThreadContext context) {
return convertJavaToRuby( connectionImpl(context) );
}
@JRubyMethod(name = "jdbc_connection", alias = "connection", required = 1)
public final IRubyObject connection(final ThreadContext context, final IRubyObject unwrap) {
if ( unwrap == context.nil || unwrap == context.fals ) {
return connection(context);
}
Connection connection = connectionImpl(context);
try {
if ( connection.isWrapperFor(Connection.class) ) {
return convertJavaToRuby( connection.unwrap(Connection.class) );
}
}
catch (AbstractMethodError | SQLException e) {
debugStackTrace(context, e);
warn(context, "driver/pool connection does not support unwrapping: " + e);
}
return convertJavaToRuby( connection );
}
private Connection connectionImpl(final ThreadContext context) {
Connection connection = getConnection(false);
if ( connection == null ) {
synchronized (this) {
connection = getConnection(false);
if ( connection == null ) {
reconnect(context);
connection = getConnection(false);
}
}
}
return connection;
}
@JRubyMethod(name = "active?", alias = "valid?")
public RubyBoolean active_p(final ThreadContext context) {
if ( ! connected ) return context.fals;
if (jndi) {
// for JNDI the data-source / pool is supposed to
// manage connections for us thus no valid check!
boolean active = getConnectionFactory() != null;
return context.runtime.newBoolean( active );
}
final Connection connection = getConnection(false);
if ( connection == null ) return context.fals; // unlikely
return context.runtime.newBoolean( isConnectionValid(context, connection) );
}
@JRubyMethod(name = "really_valid?")
public RubyBoolean really_valid_p(final ThreadContext context) {
final Connection connection = getConnection(true);
if (connection == null) return context.fals;
return context.runtime.newBoolean(isConnectionValid(context, connection));
}
@JRubyMethod(name = "disconnect!")
public synchronized IRubyObject disconnect(final ThreadContext context) {
setConnection(null); connected = false;
return context.nil;
}
@JRubyMethod(name = "reconnect!")
public synchronized IRubyObject reconnect(final ThreadContext context) {
try {
connectImpl( ! lazy ); connected = true;
}
catch (SQLException e) {
debugStackTrace(context, e);
handleException(context, e);
}
return context.nil;
}
private void connectImpl(final boolean forceConnection) throws SQLException {
setConnection( forceConnection ? newConnection() : null );
if (forceConnection) {
if (getConnectionImpl() == null) throw new SQLException("Didn't get a connection. Wrong URL?");
configureConnection();
}
}
@JRubyMethod(name = "read_only?")
public IRubyObject is_read_only(final ThreadContext context) {
try {
final Connection connection = getConnectionInternal(false);
if (connection != null) {
return context.runtime.newBoolean(connection.isReadOnly());
}
} catch (SQLException e) {
return handleException(context, e);
}
return context.nil;
}
@JRubyMethod(name = "read_only=")
public IRubyObject set_read_only(final ThreadContext context, final IRubyObject flag) {
try {
final Connection connection = getConnectionInternal(true);
connection.setReadOnly( flag.isTrue() );
return context.runtime.newBoolean( connection.isReadOnly() );
} catch (SQLException e) {
return handleException(context, e);
}
}
@JRubyMethod(name = { "open?" /* "conn?" */ })
public IRubyObject open_p(final ThreadContext context) {
try {
final Connection connection = getConnectionInternal(false);
if (connection == null) return context.fals;
// NOTE: isClosed method generally cannot be called to determine
// whether a connection to a database is valid or invalid ...
return context.runtime.newBoolean(!connection.isClosed());
} catch (SQLException e) {
return handleException(context, e);
}
}
@JRubyMethod(name = "close")
public IRubyObject close(final ThreadContext context) {
final Connection connection = getConnection(false);
if (connection == null) return context.fals;
try {
if (connection.isClosed()) return context.fals;
setConnection(null); // does connection.close();
} catch (Exception e) {
debugStackTrace(context, e);
return context.nil;
}
// ActiveRecord expects a closed connection to not try and re-open a connection
// whereas JNDI expects that.
if (!jndi) disconnect(context);
return context.tru;
}
@JRubyMethod(name = "database_name")
public IRubyObject database_name(final ThreadContext context) {
return withConnection(context, connection -> {
String name = connection.getCatalog();
if ( name == null ) {
name = connection.getMetaData().getUserName();
if ( name == null ) return context.nil;
}
return context.runtime.newString(name);
});
}
@JRubyMethod(name = "execute", required = 1)
public IRubyObject execute(final ThreadContext context, final IRubyObject sql) {
final String query = sqlString(sql);
return withConnection(context, connection -> {
Statement statement = null;
try {
statement = createStatement(context, connection);
// For DBs that do support multiple statements, lets return the last result set
// to be consistent with AR
boolean hasResultSet = doExecute(statement, query);
int updateCount = statement.getUpdateCount();
IRubyObject result = context.nil; // If no results, return nil
ResultSet resultSet;
while (hasResultSet || updateCount != -1) {
if (hasResultSet) {
resultSet = statement.getResultSet();
// Unfortunately the result set gets closed when getMoreResults()
// is called, so we have to process the result sets as we get them
// this shouldn't be an issue in most cases since we're only getting 1 result set anyways
result = mapExecuteResult(context, connection, resultSet);
resultSet.close();
} else {
result = context.runtime.newFixnum(updateCount);
}
// Check to see if there is another result set
hasResultSet = statement.getMoreResults();
updateCount = statement.getUpdateCount();
}
return result;
} catch (final SQLException e) {
debugErrorSQL(context, query);
throw e;
} finally {
close(statement);
}
});
}
protected Statement createStatement(final ThreadContext context, final Connection connection)
throws SQLException {
final Statement statement = connection.createStatement();
IRubyObject escapeProcessing = getConfigValue(context, "statement_escape_processing");
// NOTE: disable (driver) escape processing by default, it's not really
// needed for AR statements ... if users need it they might configure :
if ( escapeProcessing == context.nil ) {
statement.setEscapeProcessing(false);
}
else {
statement.setEscapeProcessing(escapeProcessing.isTrue());
}
if (fetchSize != 0) statement.setFetchSize(fetchSize);
return statement;
}
/**
* Execute a query using the given statement.
* @param statement
* @param query
* @return true if the first result is a <code>ResultSet</code>;
* false if it is an update count or there are no results
* @throws SQLException
*/
protected boolean doExecute(final Statement statement, final String query) throws SQLException {
return statement.execute(query);
}
protected IRubyObject mapExecuteResult(final ThreadContext context,
final Connection connection, final ResultSet resultSet) throws SQLException{
return mapQueryResult(context, connection, resultSet);
}
private static String[] createStatementPk(IRubyObject pk) {
String[] statementPk;
if (pk instanceof RubyArray) {
RubyArray ary = (RubyArray) pk;
int size = ary.size();
statementPk = new String[size];
for (int i = 0; i < size; i++) {
statementPk[i] = sqlString(ary.eltInternal(i));
}
} else {
statementPk = new String[] { sqlString(pk) };
}
return statementPk;
}
/**
* Executes an INSERT SQL statement
* @param context
* @param sql
* @param pk Rails PK
* @return ActiveRecord::Result
* @throws SQLException
*/
@JRubyMethod(name = "execute_insert_pk", required = 2)
public IRubyObject execute_insert_pk(final ThreadContext context, final IRubyObject sql, final IRubyObject pk) {
return withConnection(context, connection -> {
Statement statement = null;
final String query = sqlString(sql);
try {
statement = createStatement(context, connection);
if (pk == context.nil || pk == context.fals || !supportsGeneratedKeys(connection)) {
statement.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
} else {
statement.executeUpdate(query, createStatementPk(pk));
}
return mapGeneratedKeys(context, connection, statement);
} catch (final SQLException e) {
debugErrorSQL(context, query);
throw e;
} finally {
close(statement);
}
});
}
@Deprecated
@JRubyMethod(name = "execute_insert", required = 1)
public IRubyObject execute_insert(final ThreadContext context, final IRubyObject sql) {
return execute_insert_pk(context, sql, context.nil);
}
/**
* Executes an INSERT SQL statement using a prepared statement
* @param context
* @param sql
* @param binds RubyArray of values to be bound to the query
* @param pk Rails PK
* @return ActiveRecord::Result
* @throws SQLException
*/
@JRubyMethod(name = "execute_insert_pk", required = 3)
public IRubyObject execute_insert_pk(final ThreadContext context, final IRubyObject sql, final IRubyObject binds,
final IRubyObject pk) {
return withConnection(context, connection -> {
PreparedStatement statement = null;
final String query = sqlString(sql);
try {
if (pk == context.nil || pk == context.fals || !supportsGeneratedKeys(connection)) {
statement = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
} else {
statement = connection.prepareStatement(query, createStatementPk(pk));
}
setStatementParameters(context, connection, statement, (RubyArray) binds);
statement.executeUpdate();
return mapGeneratedKeys(context, connection, statement);
} catch (final SQLException e) {
debugErrorSQL(context, query);
throw e;
} finally {
close(statement);
}
});
}
@Deprecated
@JRubyMethod(name = "execute_insert", required = 2)
public IRubyObject execute_insert(final ThreadContext context, final IRubyObject binds, final IRubyObject sql) {
return execute_insert_pk(context, sql, binds, context.nil);
}
/**
* Executes an UPDATE (DELETE) SQL statement
* @param context
* @param sql
* @return affected row count
* @throws SQLException
*/
@JRubyMethod(name = {"execute_update", "execute_delete"}, required = 1)
public IRubyObject execute_update(final ThreadContext context, final IRubyObject sql) {
return withConnection(context, (Callable<IRubyObject>) connection -> {
Statement statement = null;
final String query = sqlString(sql);
try {
statement = createStatement(context, connection);
final int rowCount = statement.executeUpdate(query);
return context.runtime.newFixnum(rowCount);
} catch (final SQLException e) {
debugErrorSQL(context, query);
throw e;
} finally {
close(statement);
}
});
}
/**
* Executes an UPDATE (DELETE) SQL using a prepared statement
* @param context
* @param sql
* @return affected row count
* @throws SQLException
*
* @see #execute_update(ThreadContext, IRubyObject)
*/
@JRubyMethod(name = {"execute_prepared_update", "execute_prepared_delete"}, required = 2)
public IRubyObject execute_prepared_update(final ThreadContext context, final IRubyObject sql, final IRubyObject binds) {
return withConnection(context, (Callable<IRubyObject>) connection -> {
PreparedStatement statement = null;
final String query = sqlString(sql);
try {
statement = connection.prepareStatement(query);
setStatementParameters(context, connection, statement, (RubyArray) binds);
final int rowCount = statement.executeUpdate();
return context.runtime.newFixnum(rowCount);
} catch (final SQLException e) {
debugErrorSQL(context, query);
throw e;
} finally {
close(statement);
}
});
}
/**
* This is the same as execute_query but it will return a list of hashes.
*
* @see RubyJdbcConnection#execute_query(ThreadContext, IRubyObject)
* @param context which context this method is executing on.
* @param args arguments being supplied to this method.
* @param block (optional) block to yield row values (Hash(name: value))
* @return List of Hash(name: value) unless block is given.
* @throws SQLException when a database error occurs<
*/
@JRubyMethod(required = 1, optional = 2)
public IRubyObject execute_query_raw(final ThreadContext context, final IRubyObject[] args, final Block block) {
final String query = sqlString( args[0] ); // sql
final RubyArray binds;
final int maxRows;
// args: (sql), (sql, max_rows), (sql, binds), (sql, max_rows, binds)
switch (args.length) {
case 2:
if (args[1] instanceof RubyNumeric) { // (sql, max_rows)
maxRows = RubyNumeric.fix2int(args[1]);
binds = null;
} else { // (sql, binds)
maxRows = 0;
binds = (RubyArray) TypeConverter.checkArrayType(context, args[1]);
}
break;
case 3: // (sql, max_rows, binds)
maxRows = RubyNumeric.fix2int(args[1]);
binds = (RubyArray) TypeConverter.checkArrayType(context, args[2]);
break;
default: // (sql) 1-arg
maxRows = 0;
binds = null;
break;
}
return doExecuteQueryRaw(context, query, maxRows, block, binds);
}
private IRubyObject doExecuteQueryRaw(final ThreadContext context,
final String query, final int maxRows, final Block block, final RubyArray binds) {
return withConnection(context, connection -> {
Statement statement = null; boolean hasResult;
try {
if ( binds == null || binds.isEmpty()) { // plain statement
statement = createStatement(context, connection);
statement.setMaxRows(maxRows); // zero means there is no limit
hasResult = statement.execute(query);
}
else {
final PreparedStatement prepStatement;
statement = prepStatement = connection.prepareStatement(query);
if (fetchSize != 0) statement.setFetchSize(fetchSize);
statement.setMaxRows(maxRows); // zero means there is no limit
setStatementParameters(context, connection, prepStatement, binds);
hasResult = prepStatement.execute();
}
if (block.isGiven()) {
if (hasResult) {
// yield(id1, name1) ... row 1 result data
// yield(id2, name2) ... row 2 result data
return yieldResultRows(context, connection, statement.getResultSet(), block);
}
return context.nil;
}
if (hasResult) {
return mapToRawResult(context, connection, statement.getResultSet(), false);
}
return context.runtime.newEmptyArray();
}
catch (final SQLException e) {
debugErrorSQL(context, query);
throw e;
}
finally {
close(statement);
}
});
}
protected static String sqlString(final IRubyObject sql) {
return sql.convertToString().decodeString();
}
/**
* Executes a query and returns the (AR) result
*
* @param context which context this method is executing on
* @param sql the query to execute
* @return a Ruby <code>ActiveRecord::Result</code> instance
* @throws SQLException when a database error occurs
*/
@JRubyMethod(required = 1)
public IRubyObject execute_query(final ThreadContext context, final IRubyObject sql) {
return withConnection(context, connection -> {
Statement statement = null;
final String query = sqlString(sql);
try {
statement = createStatement(context, connection);
// At least until AR 5.1 #exec_query still gets called for things that don't return results in some cases :(
if (statement.execute(query)) {
return mapQueryResult(context, connection, statement.getResultSet());
}
return newEmptyResult(context);
} catch (final SQLException e) {
debugErrorSQL(context, query);
throw e;
} finally {
close(statement);
}
});
}
@JRubyMethod(required = 1)
public IRubyObject get_first_value(final ThreadContext context, final IRubyObject sql) {
return withConnection(context, connection -> {
Statement statement = null;
final String query = sqlString(sql);
try {
statement = createStatement(context, connection);
statement.execute(query);
ResultSet rs = statement.getResultSet();
if (rs == null || !rs.next()) return context.nil;
return jdbcToRuby(context, context.getRuntime(), 1, rs.getMetaData().getColumnType(1), rs);
} catch (final SQLException e) {
debugErrorSQL(context, query);
throw e;
} finally {
close(statement);
}
});
}
/**
* Prepares a query, returns a wrapped PreparedStatement. This takes care of exception wrapping
* @param context which context this method is executing on.
* @param sql the query to prepare-
* @return a Ruby <code>PreparedStatement</code>
*/
@JRubyMethod(required = 1)
public IRubyObject prepare_statement(final ThreadContext context, final IRubyObject sql) {
return withConnection(context, connection -> {
final String query = sql.convertToString().getUnicodeValue();
PreparedStatement statement = connection.prepareStatement(query);
if (fetchSize != 0) statement.setFetchSize(fetchSize);
return JavaUtil.convertJavaToRuby(context.runtime, statement);
});
}
// Called from exec_query in abstract/database_statements
/**
* Executes a query and returns the (AR) result. There are three parameters:
* <ul>
* <li>sql - String of sql</li>
* <li>binds - Array of bindings for a prepared statement</li>
* <li>cached_statement - A prepared statement object that should be used instead of creating a new statement</li>
* </ul>
*
* @param context which context this method is executing on.
* @param sql the query to execute.
* @param binds an array of values to be set as parameters
* @param cachedStatement a wrapped <code>PreparedStatement</code> to use instead of creating a new <code>Statement</code>
* @return a Ruby <code>ActiveRecord::Result</code> instance
* @throws SQLException when a database error occurs
*/
@JRubyMethod(required = 3)
public IRubyObject execute_prepared_query(final ThreadContext context, final IRubyObject sql,
final IRubyObject binds, final IRubyObject cachedStatement) {
return withConnection(context, connection -> {
final boolean cached = !(cachedStatement == null || cachedStatement.isNil());
String query = null;
PreparedStatement statement = null;
try {
if (cached) {
statement = (PreparedStatement) JavaEmbedUtils.rubyToJava(cachedStatement);
} else {
query = sql.convertToString().getUnicodeValue();
statement = connection.prepareStatement(query);
if (fetchSize != 0) statement.setFetchSize(fetchSize);
}
setStatementParameters(context, connection, statement, (RubyArray) binds);
if (statement.execute()) {
ResultSet resultSet = statement.getResultSet();
IRubyObject results = mapQueryResult(context, connection, resultSet);
resultSet.close();
return results;
} else {
return newEmptyResult(context);
}
} catch (final SQLException e) {
if (query == null) query = sql.convertToString().getUnicodeValue();
debugErrorSQL(context, query);
throw e;
} finally {
if ( cached ) {
statement.clearParameters();
} else {
close(statement);
}
}
});
}
protected IRubyObject mapQueryResult(final ThreadContext context,
final Connection connection, final ResultSet resultSet) throws SQLException {
final ColumnData[] columns = extractColumns(context, connection, resultSet, false);
return mapToResult(context, connection, resultSet, columns);
}
@JRubyMethod(name = "supported_data_types")
public IRubyObject supported_data_types(final ThreadContext context) throws SQLException {
final Connection connection = getConnection(true);
final ResultSet typeDesc = connection.getMetaData().getTypeInfo();
final IRubyObject types;
try {
types = mapToRawResult(context, connection, typeDesc, true);
}
finally { close(typeDesc); }
return types;
}
@JRubyMethod(name = "primary_keys", required = 1)
public IRubyObject primary_keys(ThreadContext context, IRubyObject tableName) throws SQLException {
@SuppressWarnings("unchecked")
List<IRubyObject> primaryKeys = (List) primaryKeys(context, tableName.toString());
return context.runtime.newArray(primaryKeys);
}
protected static final int PRIMARY_KEYS_COLUMN_NAME = 4;
private List<RubyString> primaryKeys(final ThreadContext context, final String tableName) {
return withConnection(context, connection -> {
final String _tableName = caseConvertIdentifierForJdbc(connection, tableName);
final TableName table = extractTableName(connection, null, null, _tableName);
return primaryKeys(context, connection, table);
});
}
protected List<RubyString> primaryKeys(final ThreadContext context,
final Connection connection, final TableName table) throws SQLException {
final DatabaseMetaData metaData = connection.getMetaData();
ResultSet resultSet = null;
final List<RubyString> keyNames = new ArrayList<>();
try {
resultSet = metaData.getPrimaryKeys(table.catalog, table.schema, table.name);
final Ruby runtime = context.runtime;
while ( resultSet.next() ) {
String columnName = resultSet.getString(PRIMARY_KEYS_COLUMN_NAME);
columnName = caseConvertIdentifierForRails(connection, columnName);
keyNames.add( RubyString.newUnicodeString(runtime, columnName) );
}
}
finally { close(resultSet); }
return keyNames;
}
@JRubyMethod(name = "tables", required = 0, optional = 4)
public IRubyObject tables(final ThreadContext context, final IRubyObject[] args) {
switch ( args.length ) {
case 0: // ()
return tables(context, null, null, null, TABLE_TYPE);
case 1: // (catalog)
return tables(context, toStringOrNull(args[0]), null, null, TABLE_TYPE);
case 2: // (catalog, schemaPattern)
return tables(context, toStringOrNull(args[0]), toStringOrNull(args[1]), null, TABLE_TYPE);
case 3: // (catalog, schemaPattern, tablePattern)
return tables(context, toStringOrNull(args[0]), toStringOrNull(args[1]), toStringOrNull(args[2]), TABLE_TYPE);
}
return tables(context, toStringOrNull(args[0]), toStringOrNull(args[1]), toStringOrNull(args[2]), getTypes(args[3]));
}
protected IRubyObject tables(final ThreadContext context,
final String catalog, final String schemaPattern, final String tablePattern, final String[] types) {
return withConnection(context, connection -> matchTables(context, connection, catalog, schemaPattern, tablePattern, types, false));
}
protected String[] getTableTypes() {
return TABLE_TYPES;
}
@JRubyMethod(name = "table_exists?")
public IRubyObject table_exists_p(final ThreadContext context, IRubyObject table) {
if ( table.isNil() ) {
throw context.runtime.newArgumentError("nil table name");
}
final String tableName = table.toString();
return tableExists(context, null, tableName);
}
@JRubyMethod(name = "table_exists?")
public IRubyObject table_exists_p(final ThreadContext context, IRubyObject table, IRubyObject schema) {
if ( table.isNil() ) {
throw context.runtime.newArgumentError("nil table name");
}
final String tableName = table.toString();
final String defaultSchema = schema.isNil() ? null : schema.toString();
return tableExists(context, defaultSchema, tableName);
}
protected IRubyObject tableExists(final ThreadContext context,
final String defaultSchema, final String tableName) {
return withConnection(context, connection -> {
final TableName components = extractTableName(connection, defaultSchema, tableName);
return context.runtime.newBoolean( tableExists(context, connection, components) );
});
}
@JRubyMethod(name = {"columns", "columns_internal"}, required = 1, optional = 2)
public RubyArray columns_internal(final ThreadContext context, final IRubyObject[] args)
throws SQLException {
return withConnection(context, connection -> {
ResultSet columns = null;
try {
final String tableName = args[0].toString();
// optionals (NOTE: catalog argumnet was never used before 1.3.0) :
final String catalog = args.length > 1 ? toStringOrNull(args[1]) : null;
final String defaultSchema = args.length > 2 ? toStringOrNull(args[2]) : null;
final TableName components;
components = extractTableName(connection, catalog, defaultSchema, tableName);
if ( ! tableExists(context, connection, components) ) {
throw new SQLException("table: " + tableName + " does not exist");
}
final DatabaseMetaData metaData = connection.getMetaData();
columns = metaData.getColumns(components.catalog, components.schema, components.name, null);
return mapColumnsResult(context, metaData, components, columns);
}
finally {
close(columns);
}
});
}
@JRubyMethod(name = "indexes")
public IRubyObject indexes(final ThreadContext context, IRubyObject tableName, IRubyObject name) {
return indexes(context, toStringOrNull(tableName), toStringOrNull(name), null);
}
@JRubyMethod(name = "indexes")
public IRubyObject indexes(final ThreadContext context, IRubyObject tableName, IRubyObject name, IRubyObject schemaName) {
return indexes(context, toStringOrNull(tableName), toStringOrNull(name), toStringOrNull(schemaName));
}
// NOTE: metaData.getIndexInfo row mappings :
protected static final int INDEX_INFO_TABLE_NAME = 3;
protected static final int INDEX_INFO_NON_UNIQUE = 4;
protected static final int INDEX_INFO_NAME = 6;
protected static final int INDEX_INFO_COLUMN_NAME = 9;
/**
* Default JDBC introspection for index metadata on the JdbcConnection.
*
* JDBC index metadata is denormalized (multiple rows may be returned for
* one index, one row per column in the index), so a simple block-based
* filter like that used for tables doesn't really work here. Callers
* should filter the return from this method instead.
*/
protected IRubyObject indexes(final ThreadContext context, final String tableName, final String name, final String schemaName) {
return withConnection(context, (Callable<IRubyObject>) connection -> {
final Ruby runtime = context.runtime;
final RubyClass IndexDefinition = getIndexDefinition(context);
String _tableName = caseConvertIdentifierForJdbc(connection, tableName);
String _schemaName = caseConvertIdentifierForJdbc(connection, schemaName);
final TableName table = extractTableName(connection, null, _schemaName, _tableName);
final List<RubyString> primaryKeys = primaryKeys(context, connection, table);
ResultSet indexInfoSet = null;
final RubyArray indexes = RubyArray.newArray(runtime, 8);
try {
final DatabaseMetaData metaData = connection.getMetaData();
indexInfoSet = metaData.getIndexInfo(table.catalog, table.schema, table.name, false, true);
String currentIndex = null;
while ( indexInfoSet.next() ) {
String indexName = indexInfoSet.getString(INDEX_INFO_NAME);
if ( indexName == null ) continue;
RubyArray currentColumns = null;
indexName = caseConvertIdentifierForRails(metaData, indexName);
final String columnName = indexInfoSet.getString(INDEX_INFO_COLUMN_NAME);
final RubyString rubyColumnName = cachedString(
context, caseConvertIdentifierForRails(metaData, columnName)
);
if ( primaryKeys.contains(rubyColumnName) ) continue;
// We are working on a new index
if ( ! indexName.equals(currentIndex) ) {
currentIndex = indexName;
String indexTableName = indexInfoSet.getString(INDEX_INFO_TABLE_NAME);
indexTableName = caseConvertIdentifierForRails(metaData, indexTableName);
final boolean nonUnique = indexInfoSet.getBoolean(INDEX_INFO_NON_UNIQUE);
IRubyObject[] args = new IRubyObject[] {
cachedString(context, indexTableName), // table_name
cachedString(context, indexName), // index_name
nonUnique ? context.fals : context.tru, // unique
currentColumns = RubyArray.newArray(runtime, 4) // [] column names
// orders, (since AR 3.2) where, type, using (AR 4.0)
};
indexes.append( IndexDefinition.newInstance(context, args, Block.NULL_BLOCK) ); // IndexDefinition.new
}
// one or more columns can be associated with an index
if ( currentColumns != null ) currentColumns.append(rubyColumnName);
}
return indexes;
} finally { close(indexInfoSet); }
});
}
protected RubyClass getIndexDefinition(final ThreadContext context) {
final RubyClass adapterClass = adapter.getMetaClass();
IRubyObject IDef = adapterClass.getConstantAt("IndexDefinition");
return IDef != null ? (RubyClass) IDef : getIndexDefinition(context.runtime);
}
@JRubyMethod
public IRubyObject foreign_keys(final ThreadContext context, IRubyObject table_name) {
return foreignKeys(context, table_name.toString(), null, null);
}
protected IRubyObject foreignKeys(final ThreadContext context, final String tableName, final String schemaName, final String catalog) {
return withConnection(context, (Callable<IRubyObject>) connection -> {
final Ruby runtime = context.runtime;
final RubyClass FKDefinition = getForeignKeyDefinition(context);
String _tableName = caseConvertIdentifierForJdbc(connection, tableName);
String _schemaName = caseConvertIdentifierForJdbc(connection, schemaName);
final TableName table = extractTableName(connection, catalog, _schemaName, _tableName);
ResultSet fkInfoSet = null;
final List<IRubyObject> fKeys = new ArrayList<>(8);
try {
final DatabaseMetaData metaData = connection.getMetaData();
fkInfoSet = metaData.getImportedKeys(table.catalog, table.schema, table.name);
while ( fkInfoSet.next() ) {
final RubyHash options = RubyHash.newHash(runtime);
String fkName = fkInfoSet.getString("FK_NAME");
if (fkName != null) {
fkName = caseConvertIdentifierForRails(metaData, fkName);
options.put(runtime.newSymbol("name"), fkName);
}
String columnName = fkInfoSet.getString("FKCOLUMN_NAME");
options.put(runtime.newSymbol("column"), caseConvertIdentifierForRails(metaData, columnName));
columnName = fkInfoSet.getString("PKCOLUMN_NAME");
options.put(runtime.newSymbol("primary_key"), caseConvertIdentifierForRails(metaData, columnName));
String fkTableName = fkInfoSet.getString("FKTABLE_NAME");
fkTableName = caseConvertIdentifierForRails(metaData, fkTableName);
String pkTableName = fkInfoSet.getString("PKTABLE_NAME");
pkTableName = caseConvertIdentifierForRails(metaData, pkTableName);
final String onDelete = extractForeignKeyRule( fkInfoSet.getInt("DELETE_RULE") );
if ( onDelete != null ) options.op_aset(context, runtime.newSymbol("on_delete"), runtime.newSymbol(onDelete));
final String onUpdate = extractForeignKeyRule( fkInfoSet.getInt("UPDATE_RULE") );
if ( onUpdate != null ) options.op_aset(context, runtime.newSymbol("on_update"), runtime.newSymbol(onUpdate));
IRubyObject from_table = cachedString(context, fkTableName);
IRubyObject to_table = cachedString(context, pkTableName);
fKeys.add( FKDefinition.newInstance(context, from_table, to_table, options, Block.NULL_BLOCK) ); // ForeignKeyDefinition.new
}
return runtime.newArray(fKeys);
} finally { close(fkInfoSet); }
});
}
protected String extractForeignKeyRule(final int rule) {
switch (rule) {
case DatabaseMetaData.importedKeyNoAction : return null ;
case DatabaseMetaData.importedKeyCascade : return "cascade" ;
case DatabaseMetaData.importedKeySetNull : return "nullify" ;
case DatabaseMetaData.importedKeySetDefault: return "default" ;
}
return null;
}
protected RubyClass getForeignKeyDefinition(final ThreadContext context) {
final RubyClass adapterClass = adapter.getMetaClass();
IRubyObject FKDef = adapterClass.getConstantAt("ForeignKeyDefinition");
return FKDef != null ? (RubyClass) FKDef : getForeignKeyDefinition(context.runtime);
}
@JRubyMethod(name = "supports_foreign_keys?")
public IRubyObject supports_foreign_keys_p(final ThreadContext context) throws SQLException {
return withConnection(context, (Callable<IRubyObject>) connection -> {
final DatabaseMetaData metaData = connection.getMetaData();
return context.runtime.newBoolean( metaData.supportsIntegrityEnhancementFacility() );
});
}
@JRubyMethod(name = "supports_views?")
public IRubyObject supports_views_p(final ThreadContext context) throws SQLException {
return withConnection(context, (Callable<IRubyObject>) connection -> {
final DatabaseMetaData metaData = connection.getMetaData();
final ResultSet tableTypes = metaData.getTableTypes();
try {
while ( tableTypes.next() ) {
if ( "VIEW".equalsIgnoreCase( tableTypes.getString(1) ) ) {
return context.runtime.newBoolean( true );
}
}
}
finally {
close(tableTypes);
}
return context.runtime.newBoolean( false );
});
}
@JRubyMethod(name = "with_jdbc_connection", alias = "with_connection_retry_guard", frame = true)
public IRubyObject with_jdbc_connection(final ThreadContext context, final Block block) {
return withConnection(context, connection -> block.call(context, convertJavaToRuby(connection)));
}
/*
* (binary?, column_name, table_name, id_key, id_value, value)
*/
@Deprecated
@JRubyMethod(name = "write_large_object", required = 6)
public IRubyObject write_large_object(final ThreadContext context, final IRubyObject[] args)
throws SQLException {
final boolean binary = args[0].isTrue();
final String columnName = args[1].toString();
final String tableName = args[2].toString();
final String idKey = args[3].toString();
final IRubyObject idVal = args[4];
final IRubyObject lobValue = args[5];
int count = updateLobValue(context, tableName, columnName, null, idKey, idVal, null, lobValue, binary);
return context.runtime.newFixnum(count);
}
@JRubyMethod(name = "update_lob_value", required = 3)
public IRubyObject update_lob_value(final ThreadContext context,
final IRubyObject record, final IRubyObject column, final IRubyObject value)
throws SQLException {
final boolean binary = // column.type == :binary
column.callMethod(context, "type").toString() == (Object) "binary";
final IRubyObject recordClass = record.callMethod(context, "class");
final IRubyObject adapter = recordClass.callMethod(context, "connection");
IRubyObject columnName = column.callMethod(context, "name");
columnName = adapter.callMethod(context, "quote_column_name", columnName);
IRubyObject tableName = recordClass.callMethod(context, "table_name");
tableName = adapter.callMethod(context, "quote_table_name", tableName);
final IRubyObject idKey = recordClass.callMethod(context, "primary_key"); // 'id'
// callMethod(context, "quote", primaryKey);
final IRubyObject idColumn = // record.class.columns_hash['id']
recordClass.callMethod(context, "columns_hash").callMethod(context, "[]", idKey);
final IRubyObject id = record.callMethod(context, "id"); // record.id
final int count = updateLobValue(context,
tableName.toString(), columnName.toString(), column,
idKey.toString(), id, idColumn, value, binary
);
return context.runtime.newFixnum(count);
}
private int updateLobValue(final ThreadContext context,
final String tableName, final String columnName, final IRubyObject column,
final String idKey, final IRubyObject idValue, final IRubyObject idColumn,
final IRubyObject value, final boolean binary) {
final String sql = "UPDATE "+ tableName +" SET "+ columnName +" = ? WHERE "+ idKey +" = ?" ;
// TODO: Fix this, the columns don't have the info needed to handle this anymore
// currently commented out so that it will compile
return withConnection(context, connection -> {
PreparedStatement statement = null;
try {
statement = connection.prepareStatement(sql);
/*
if ( binary ) { // blob
setBlobParameter(context, connection, statement, 1, value, column, Types.BLOB);
}
else { // clob
setClobParameter(context, connection, statement, 1, value, column, Types.CLOB);
}
setStatementParameter(context, context.runtime, connection, statement, 2, idValue, idColumn);
*/
return statement.executeUpdate();
}
finally { close(statement); }
});
}
protected String caseConvertIdentifierForRails(final Connection connection, final String value)
throws SQLException {
if ( value == null ) return null;
return caseConvertIdentifierForRails(connection.getMetaData(), value);
}
/**
* Convert an identifier coming back from the database to a case which Rails is expecting.
*
* Assumption: Rails identifiers will be quoted for mixed or will stay mixed
* as identifier names in Rails itself. Otherwise, they expect identifiers to
* be lower-case. Databases which store identifiers uppercase should be made
* lower-case.
*
* Assumption 2: It is always safe to convert all upper case names since it appears that
* some adapters do not report StoresUpper/Lower/Mixed correctly (am I right postgres/mysql?).
*/
protected static String caseConvertIdentifierForRails(final DatabaseMetaData metaData, final String value)
throws SQLException {
if ( value == null ) return null;
return metaData.storesUpperCaseIdentifiers() ? value.toLowerCase() : value;
}
protected String caseConvertIdentifierForJdbc(final Connection connection, final String value)
throws SQLException {
if ( value == null ) return null;
return caseConvertIdentifierForJdbc(connection.getMetaData(), value);
}
/**
* Convert an identifier destined for a method which cares about the databases internal
* storage case. Methods like DatabaseMetaData.getPrimaryKeys() needs the table name to match
* the internal storage name. Arbitrary queries and the like DO NOT need to do this.
*/
protected static String caseConvertIdentifierForJdbc(final DatabaseMetaData metaData, final String value)
throws SQLException {
if ( value == null ) return null;
if ( metaData.storesUpperCaseIdentifiers() ) {
return value.toUpperCase();
}
else if ( metaData.storesLowerCaseIdentifiers() ) {
return value.toLowerCase();
}
return value;
}
// internal helper exported on ArJdbc @JRubyMethod(meta = true)
public static IRubyObject with_meta_data_from_data_source_if_any(final ThreadContext context,
final IRubyObject self, final IRubyObject config, final Block block) {
final IRubyObject ds_or_name = rawDataSourceOrName(context, config);
if ( ds_or_name == null ) return context.fals;
final javax.sql.DataSource dataSource;
final Object dsOrName = ds_or_name.toJava(Object.class);
if ( dsOrName instanceof javax.sql.DataSource ) {
dataSource = (javax.sql.DataSource) dsOrName;
}
else {
try {
dataSource = (javax.sql.DataSource) getInitialContext().lookup( dsOrName.toString() );
}
catch (Exception e) { // javax.naming.NamingException
throw wrapException(context, context.runtime.getRuntimeError(), e);
}
}
Connection connection = null;
try {
connection = dataSource.getConnection();
final DatabaseMetaData metaData = connection.getMetaData();
return block.call(context, JavaUtil.convertJavaToRuby(context.runtime, metaData));
}
catch (SQLException e) {
throw wrapSQLException(context, getJDBCError(context.runtime), e, null);
}
finally { close(connection); }
}
@JRubyMethod(name = "jndi_config?", meta = true)
public static IRubyObject jndi_config_p(final ThreadContext context,
final IRubyObject self, final IRubyObject config) {
return context.runtime.newBoolean( isJndiConfig(context, config) );
}
private static IRubyObject rawDataSourceOrName(final ThreadContext context, final IRubyObject config) {
// config[:jndi] || config[:data_source]
final Ruby runtime = context.runtime;
IRubyObject configValue;
if ( config.getClass() == RubyHash.class ) { // "optimized" version
final RubyHash configHash = ((RubyHash) config);
configValue = configHash.fastARef(runtime.newSymbol("jndi"));
if ( configValue == null ) {
configValue = configHash.fastARef(runtime.newSymbol("data_source"));
}
}
else {
configValue = config.callMethod(context, "[]", runtime.newSymbol("jndi"));
if ( configValue == context.nil ) configValue = null;
if ( configValue == null ) {
configValue = config.callMethod(context, "[]", runtime.newSymbol("data_source"));
}
}
if ( configValue == null || configValue == context.nil || configValue == context.fals ) {
return null;
}
return configValue;
}
private static boolean isJndiConfig(final ThreadContext context, final IRubyObject config) {
return rawDataSourceOrName(context, config) != null;
}
@JRubyMethod(name = "jndi_lookup", meta = true)
public static IRubyObject jndi_lookup(final ThreadContext context,
final IRubyObject self, final IRubyObject name) {
try {
final Object bound = getInitialContext().lookup( name.toString() );
return JavaUtil.convertJavaToRuby(context.runtime, bound);
}
catch (Exception e) { // javax.naming.NamingException
if ( e instanceof RaiseException ) throw (RaiseException) e;
throw wrapException(context, context.runtime.getNameError(), e);
}
}
private ConnectionFactory setDriverFactory(final ThreadContext context) {
final IRubyObject url = getConfigValue(context, "url");
final IRubyObject driver = getConfigValue(context, "driver");
final IRubyObject username = getConfigValue(context, "username");
final IRubyObject password = getConfigValue(context, "password");
final IRubyObject driver_instance = getConfigValue(context, "driver_instance");
if ( url.isNil() || ( driver.isNil() && driver_instance.isNil() ) ) {
final Ruby runtime = context.runtime;
final RubyClass errorClass = getConnectionNotEstablished( runtime );
throw runtime.newRaiseException(errorClass, "adapter requires :driver class and jdbc :url");
}
final String jdbcURL = buildURL(context, url);
final ConnectionFactory factory;
if ( driver_instance != null && ! driver_instance.isNil() ) {
final Object driverInstance = driver_instance.toJava(Object.class);
if ( driverInstance instanceof DriverWrapper ) {
setConnectionFactory(factory = new DriverConnectionFactory(
(DriverWrapper) driverInstance, jdbcURL,
( username.isNil() ? null : username.toString() ),
( password.isNil() ? null : password.toString() )
));
return factory;
}
else {
setConnectionFactory(factory = new RubyConnectionFactory(
driver_instance, context.runtime.newString(jdbcURL),
( username.isNil() ? username : username.asString() ),
( password.isNil() ? password : password.asString() )
));
return factory;
}
}
final String user = username.isNil() ? null : username.toString();
final String pass = password.isNil() ? null : password.toString();
final DriverWrapper driverWrapper = newDriverWrapper(context, driver.toString());
setConnectionFactory(factory = new DriverConnectionFactory(driverWrapper, jdbcURL, user, pass));
return factory;
}
protected DriverWrapper newDriverWrapper(final ThreadContext context, final String driver) throws RaiseException {
try {
return new DriverWrapper(context.runtime, driver, resolveDriverProperties(context));
}
//catch (ClassNotFoundException e) {
// throw wrapException(context, context.runtime.getNameError(), e, "cannot load driver class " + driver);
//}
catch (ExceptionInInitializerError e) {
throw wrapException(context, context.runtime.getNameError(), e, "cannot initialize driver class " + driver);
}
catch (LinkageError e) {
throw wrapException(context, context.runtime.getNameError(), e, "cannot link driver class " + driver);
}
catch (ClassCastException e) {
throw wrapException(context, context.runtime.getNameError(), e);
}
catch (IllegalAccessException e) { throw wrapException(context, e); }
catch (InstantiationException e) {
throw wrapException(context, e.getCause() != null ? e.getCause() : e);
}
catch (SecurityException e) {
throw wrapException(context, context.runtime.getSecurityError(), e);
}
}
@Deprecated // no longer used - only kept for API compatibility
@JRubyMethod(visibility = Visibility.PRIVATE)
public IRubyObject jdbc_url(final ThreadContext context) {
final IRubyObject url = getConfigValue(context, "url");
return context.runtime.newString( buildURL(context, url) );
}
protected String buildURL(final ThreadContext context, final IRubyObject url) {
IRubyObject options = getConfigValue(context, "options");
if ( options == context.nil ) options = null;
// NOTE: else should print a deprecation warning - should use properties: instead
return DriverWrapper.buildURL(url, (Map) options);
}
private Properties resolveDriverProperties(final ThreadContext context) {
IRubyObject properties = getConfigValue(context, "properties");
if ( properties == context.nil ) return null;
Map<?, ?> propertiesJava = (Map) properties.toJava(Map.class);
if ( propertiesJava instanceof Properties ) {
return (Properties) propertiesJava;
}
final Properties props = new Properties();
for ( Map.Entry entry : propertiesJava.entrySet() ) {
props.setProperty(entry.getKey().toString(), entry.getValue().toString());
}
return props;
}
private ConnectionFactory setDataSourceFactory(final ThreadContext context) {
final javax.sql.DataSource dataSource; final String lookupName;
IRubyObject value = getConfigValue(context, "data_source");
if ( value == context.nil ) {
value = getConfigValue(context, "jndi");
lookupName = value.toString();
dataSource = DataSourceConnectionFactory.lookupDataSource(context, lookupName);
}
else {
dataSource = (javax.sql.DataSource) value.toJava(javax.sql.DataSource.class);
lookupName = null;
}
ConnectionFactory factory = new DataSourceConnectionFactory(dataSource, lookupName);
setConnectionFactory(factory);
return factory;
}
private static transient IRubyObject defaultConfig;
private static volatile boolean defaultConfigJndi;
private static transient ConnectionFactory defaultConnectionFactory;
/**
* @return whether the connection factory is JNDI based
*/
private boolean setupConnectionFactory(final ThreadContext context) {
if ( defaultConfig == null ) {
synchronized(RubyJdbcConnection.class) {
if ( defaultConfig == null ) {
final boolean jndi = isJndiConfig(context, config);
if ( jndi ) {
defaultConnectionFactory = setDataSourceFactory(context);
}
else {
defaultConnectionFactory = setDriverFactory(context);
}
defaultConfigJndi = jndi; defaultConfig = config;
return jndi;
}
}
}
if ( defaultConfig != null && ( defaultConfig == config || defaultConfig.eql(config) ) ) {
setConnectionFactory( defaultConnectionFactory );
return defaultConfigJndi;
}
if ( isJndiConfig(context, config) ) {
setDataSourceFactory(context); return true;
}
else {
setDriverFactory(context); return false;
}
}
@JRubyMethod(name = "jndi?", alias = "jndi_connection?")
public RubyBoolean jndi_p(final ThreadContext context) {
return context.runtime.newBoolean(jndi);
}
protected boolean isJndi() { return this.jndi; }
@JRubyMethod(name = "config")
public IRubyObject config() { return config; }
public IRubyObject getConfig() { return this.config; }
protected final IRubyObject getConfigValue(final ThreadContext context, final String key) {
final RubySymbol keySym = context.runtime.newSymbol(key);
if ( config instanceof RubyHash ) {
final IRubyObject value = ((RubyHash) config).fastARef(keySym);
return value == null ? context.nil : value;
}
return config.callMethod(context, "[]", keySym);
}
protected final IRubyObject setConfigValue(final ThreadContext context,
final String key, final IRubyObject value) {
final RubySymbol keySym = context.runtime.newSymbol(key);
if ( config instanceof RubyHash ) {
return ((RubyHash) config).op_aset(context, keySym, value);
}
return config.callMethod(context, "[]=", new IRubyObject[] { keySym, value });
}
protected final IRubyObject setConfigValueIfNotSet(final ThreadContext context,
final String key, final IRubyObject value) {
final RubySymbol keySym = context.runtime.newSymbol(key);
if ( config instanceof RubyHash ) {
final IRubyObject setValue = ((RubyHash) config).fastARef(keySym);
if ( setValue != null ) return setValue;
return ((RubyHash) config).op_aset(context, keySym, value);
}
final IRubyObject setValue = config.callMethod(context, "[]", keySym);
if ( setValue != context.nil ) return setValue;
return config.callMethod(context, "[]=", new IRubyObject[] { keySym, value });
}
private static String toStringOrNull(final IRubyObject arg) {
return arg.isNil() ? null : arg.toString();
}
protected final IRubyObject getAdapter() { return this.adapter; }
protected RubyClass getJdbcColumnClass(final ThreadContext context) {
return (RubyClass) adapter.callMethod(context, "jdbc_column_class");
}
protected ConnectionFactory getConnectionFactory() throws RaiseException {
if ( connectionFactory == null ) {
// NOTE: only for (backwards) compatibility (to be deleted) :
IRubyObject connection_factory = getInstanceVariable("@connection_factory");
if ( connection_factory == null ) {
throw getRuntime().newRuntimeError("@connection_factory not set");
}
connectionFactory = (ConnectionFactory) connection_factory.toJava(ConnectionFactory.class);
}
return connectionFactory;
}
public void setConnectionFactory(ConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}
protected Connection newConnection() throws SQLException {
return getConnectionFactory().newConnection();
}
private static String[] getTypes(final IRubyObject typeArg) {
if ( typeArg instanceof RubyArray ) {
final RubyArray typesArr = (RubyArray) typeArg;
final String[] types = new String[typesArr.size()];
for ( int i = 0; i < types.length; i++ ) {
types[i] = typesArr.eltInternal(i).toString();
}
return types;
}
return new String[] { typeArg.toString() }; // expect a RubyString
}
/**
* Maps a query result into a <code>ActiveRecord</code> result.
* @param context
* @param connection
* @param resultSet
* @param columns
* @return expected to return a <code>ActiveRecord::Result</code>
* @throws SQLException
*/
protected IRubyObject mapToResult(final ThreadContext context, final Connection connection,
final ResultSet resultSet, final ColumnData[] columns) throws SQLException {
final Ruby runtime = context.runtime;
final RubyArray resultRows = runtime.newArray();
while (resultSet.next()) {
resultRows.append(mapRow(context, runtime, columns, resultSet, this));
}
return newResult(context, columns, resultRows);
}
protected IRubyObject jdbcToRuby(
final ThreadContext context, final Ruby runtime,
final int column, final int type, final ResultSet resultSet)
throws SQLException {
try {
switch (type) {
case Types.BLOB:
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
return streamToRuby(context, runtime, resultSet, column);
case Types.CLOB:
case Types.NCLOB: // JDBC 4.0
return readerToRuby(context, runtime, resultSet, column);
case Types.LONGVARCHAR:
case Types.LONGNVARCHAR: // JDBC 4.0
return readerToRuby(context, runtime, resultSet, column);
case Types.TINYINT:
case Types.SMALLINT:
case Types.INTEGER:
return integerToRuby(context, runtime, resultSet, column);
case Types.REAL:
case Types.FLOAT:
case Types.DOUBLE:
return doubleToRuby(context, runtime, resultSet, column);
case Types.BIGINT:
return bigIntegerToRuby(context, runtime, resultSet, column);
case Types.NUMERIC:
case Types.DECIMAL:
return decimalToRuby(context, runtime, resultSet, column);
case Types.DATE:
return dateToRuby(context, runtime, resultSet, column);
case Types.TIME:
return timeToRuby(context, runtime, resultSet, column);
case Types.TIMESTAMP:
return timestampToRuby(context, runtime, resultSet, column);
case Types.BIT:
return bitToRuby(context, runtime, resultSet, column);
case Types.BOOLEAN:
return booleanToRuby(context, runtime, resultSet, column);
case Types.SQLXML: // JDBC 4.0
return xmlToRuby(context, runtime, resultSet, column);
case Types.ARRAY: // we handle JDBC Array into (Ruby) []
return arrayToRuby(context, runtime, resultSet, column);
case Types.NULL:
return context.nil;
// NOTE: (JDBC) exotic stuff just cause it's so easy with JRuby :)
case Types.JAVA_OBJECT:
case Types.OTHER:
return objectToRuby(context, runtime, resultSet, column);
// (default) String
case Types.CHAR:
case Types.VARCHAR:
case Types.NCHAR: // JDBC 4.0
case Types.NVARCHAR: // JDBC 4.0
default:
return stringToRuby(context, runtime, resultSet, column);
}
// NOTE: not mapped types :
//case Types.DISTINCT:
//case Types.STRUCT:
//case Types.REF:
//case Types.DATALINK:
}
catch (IOException e) {
throw new SQLException(e.getMessage(), e);
}
}
/**
* Converts an integer column into a Ruby integer.
* @param context current thread context
* @param runtime current thread context
* @param resultSet the jdbc result set to pull the value from
* @param column the index of the column to convert
* @return RubyNil if NULL or RubyInteger if there is a value
* @throws SQLException if it failes to retrieve the value from the result set
*/
protected IRubyObject integerToRuby(final ThreadContext context,
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException {
final long value = resultSet.getLong(column);
if ( value == 0 && resultSet.wasNull() ) return context.nil;
return runtime.newFixnum(value);
}
/**
* Converts an double column into a Ruby integer.
* @param context current thread context
* @param runtime the ruby runtime
* @param resultSet the jdbc result set to pull the value from
* @param column the index of the column to convert
* @return RubyNil if NULL or RubyInteger if there is a value
* @throws SQLException if it failes to retrieve the value from the result set
*/
protected IRubyObject doubleToRuby(final ThreadContext context,
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException {
final double value = resultSet.getDouble(column);
if ( value == 0 && resultSet.wasNull() ) return context.nil;
return runtime.newFloat(value);
}
/**
* Converts a string column into a Ruby string
* @param context current thread context
* @param runtime the ruby runtime
* @param resultSet the jdbc result set to pull the value from
* @param column the index of the column to convert
* @return RubyNil if NULL or RubyString if there is a value
* @throws SQLException if it failes to retrieve the value from the result set
*/
protected IRubyObject stringToRuby(final ThreadContext context,
final Ruby runtime, final ResultSet resultSet, final int column) throws SQLException {
final String value = resultSet.getString(column);
if ( value == null ) return context.nil;
return newDefaultInternalString(runtime, value);
}
protected static IRubyObject bytesToRubyString(final ThreadContext context,
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException { // optimized String -> byte[]
final byte[] value = resultSet.getBytes(column);
if ( value == null ) return context.nil;
return newDefaultInternalString(runtime, value);
}
protected IRubyObject bigIntegerToRuby(final ThreadContext context,
final Ruby runtime, final ResultSet resultSet, final int column) throws SQLException {
final String value = resultSet.getString(column);
if ( value == null ) return context.nil;
return RubyBignum.bignorm(runtime, new BigInteger(value));
}
protected IRubyObject decimalToRuby(final ThreadContext context,
final Ruby runtime, final ResultSet resultSet, final int column) throws SQLException {
final BigDecimal value = resultSet.getBigDecimal(column);
if ( value == null ) return context.nil;
return new org.jruby.ext.bigdecimal.RubyBigDecimal(runtime, value);
}
protected static Boolean rawDateTime;
static {
final String dateTimeRaw = SafePropertyAccessor.getProperty("arjdbc.datetime.raw");
if ( dateTimeRaw != null ) {
rawDateTime = Boolean.parseBoolean(dateTimeRaw);
}
// NOTE: we do this since it will have a different value depending on
// AR version - since 4.0 false by default otherwise will be true ...
}
@JRubyMethod(name = "raw_date_time?", meta = true)
public static IRubyObject useRawDateTime(final ThreadContext context, final IRubyObject self) {
if ( rawDateTime == null ) return context.nil;
return context.runtime.newBoolean(rawDateTime);
}
@JRubyMethod(name = "raw_date_time=", meta = true)
public static IRubyObject setRawDateTime(final IRubyObject self, final IRubyObject value) {
if ( value instanceof RubyBoolean ) {
rawDateTime = ((RubyBoolean) value).isTrue();
}
else {
rawDateTime = value.isNil() ? null : Boolean.TRUE;
}
return value;
}
protected IRubyObject dateToRuby(final ThreadContext context,
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException {
final Date value = resultSet.getDate(column);
if ( value == null ) {
// FIXME: Do we really need this wasNull check here?
return resultSet.wasNull() ? context.nil : RubyString.newEmptyString(runtime);
}
if ( rawDateTime != null && rawDateTime) {
return RubyString.newString(runtime, DateTimeUtils.dateToString(value));
}
return DateTimeUtils.newDateAsTime(context, value, DateTimeZone.UTC).callMethod(context, "to_date");
}
protected IRubyObject timeToRuby(final ThreadContext context,
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException {
final Time value = resultSet.getTime(column);
if ( value == null ) {
return resultSet.wasNull() ? context.nil : RubyString.newEmptyString(runtime);
}
if ( rawDateTime != null && rawDateTime) {
return RubyString.newString(runtime, DateTimeUtils.timeToString(value));
}
return DateTimeUtils.newDummyTime(context, value, getDefaultTimeZone(context));
}
protected IRubyObject timestampToRuby(final ThreadContext context,
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException {
final Timestamp value = resultSet.getTimestamp(column);
if ( value == null ) {
return resultSet.wasNull() ? context.nil : RubyString.newEmptyString(runtime);
}
if ( rawDateTime != null && rawDateTime) {
return RubyString.newString(runtime, DateTimeUtils.timestampToString(value));
}
// NOTE: with 'raw' String AR's Type::DateTime does put the time in proper time-zone
// while when returning a Time object it just adjusts usec (apply_seconds_precision)
// yet for custom SELECTs to work (SELECT created_at ... ) and for compatibility we
// should be returning Time (by default) - AR does this by adjusting mysql2/pg returns
return DateTimeUtils.newTime(context, value, getDefaultTimeZone(context));
}
protected static Boolean rawBoolean;
static {
final String booleanRaw = SafePropertyAccessor.getProperty("arjdbc.boolean.raw");
if ( booleanRaw != null ) {
rawBoolean = Boolean.parseBoolean(booleanRaw);
}
}
@JRubyMethod(name = "raw_boolean?", meta = true)
public static IRubyObject useRawBoolean(final ThreadContext context, final IRubyObject self) {
if ( rawBoolean == null ) return context.nil;
return context.runtime.newBoolean(rawBoolean);
}
@JRubyMethod(name = "raw_boolean=", meta = true)
public static IRubyObject setRawBoolean(final IRubyObject self, final IRubyObject value) {
if ( value instanceof RubyBoolean ) {
rawBoolean = ((RubyBoolean) value).isTrue();
}
else {
rawBoolean = value.isNil() ? null : Boolean.TRUE;
}
return value;
}
/**
* Converts a bit column to its Ruby equivalent.
* Defaults to treating it as a boolean value.
* @param context current thread context
* @param runtime current instance of Ruby.
* @param resultSet the jdbc result set to pull the value from
* @param column the index of the column to convert
* @return RubyNil if NULL or RubyBoolean if there is a value
* @throws SQLException if it failes to retrieve the value from the result set
*/
protected IRubyObject bitToRuby(final ThreadContext context, final Ruby runtime, final ResultSet resultSet,
int column) throws SQLException {
return booleanToRuby(context, runtime, resultSet, column);
}
protected IRubyObject booleanToRuby(final ThreadContext context,
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException {
if ( rawBoolean != null && rawBoolean) {
final String value = resultSet.getString(column);
if ( value == null /* && resultSet.wasNull() */ ) return context.nil;
return RubyString.newUnicodeString(runtime, value);
}
final boolean value = resultSet.getBoolean(column);
if (!value && resultSet.wasNull()) return context.nil;
return runtime.newBoolean(value);
}
protected static int streamBufferSize = 1024;
protected IRubyObject streamToRuby(final ThreadContext context,
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException, IOException {
final InputStream stream = resultSet.getBinaryStream(column);
if (stream == null) return context.nil;
try {
final int buffSize = streamBufferSize;
final ByteList bytes = new ByteList(buffSize);
readBytes(bytes, stream, buffSize);
return runtime.newString(bytes);
} finally {
stream.close();
}
}
/**
* Converts a column that is handled as a Reader object into a Ruby string
* @param context current thread context
* @param runtime the ruby runtime
* @param resultSet the jdbc result set to pull the value from
* @param column the index of the column to convert
* @return RubyNil if NULL or RubyString if there is a value
* @throws SQLException if it failes to retrieve the value from the result set
*/
protected IRubyObject readerToRuby(final ThreadContext context,
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException, IOException {
final Reader reader = resultSet.getCharacterStream(column);
try {
if ( reader == null ) return context.nil;
final int bufSize = streamBufferSize;
final StringBuilder string = new StringBuilder(bufSize);
final char[] buf = new char[bufSize];
for (int len = reader.read(buf); len != -1; len = reader.read(buf)) {
string.append(buf, 0, len);
}
return newDefaultInternalString(runtime, string);
}
finally { if ( reader != null ) reader.close(); }
}
/**
* Converts the column into a RubyObject
* @param context current thread context
* @param runtime the ruby runtime
* @param resultSet the jdbc result set to pull the value from
* @param column the index of the column to convert
* @return RubyNil if NULL or RubyObject if there is a value
* @throws SQLException if it failes to retrieve the value from the result set
*/
protected IRubyObject objectToRuby(final ThreadContext context,
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException {
final Object value = resultSet.getObject(column);
if ( value == null ) return context.nil;
return JavaUtil.convertJavaToRuby(runtime, value);
}
protected IRubyObject arrayToRuby(final ThreadContext context,
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException {
final Array value = resultSet.getArray(column);
try {
if ( value == null ) return context.nil;
final RubyArray array = runtime.newArray();
final ResultSet arrayResult = value.getResultSet(); // 1: index, 2: value
final int baseType = value.getBaseType();
if (baseType == Types.OTHER) {
/*
* If the base type is other, we may not have enough
* information to correctly convert it so return it
* as a string so it can be parsed on the Ruby side.
* If we send it back as an array, AR assumes it has already
* been parsed and doesn't try to cast the values inside the array.
* This is primarly due to not being able to recognize json
* strings in postgres but would apply to any custom type that couldn't be converted.
* This won't work for multi-dimensional arrays of type other, but since
* we currently don't support them that shouldn't be a problem.
*/
return stringToRuby(context, runtime, resultSet, column);
}
while ( arrayResult.next() ) {
array.append( jdbcToRuby(context, runtime, 2, baseType, arrayResult) );
}
arrayResult.close();
return array;
}
finally { if ( value != null ) value.free(); }
}
/**
* Converts an XML column into a Ruby string
* @param context current thread context
* @param runtime the ruby runtime
* @param resultSet the jdbc result set to pull the value from
* @param column the index of the column to convert
* @return RubyNil if NULL or RubyString if there is a value
* @throws SQLException if it failes to retrieve the value from the result set
*/
protected IRubyObject xmlToRuby(final ThreadContext context,
final Ruby runtime, final ResultSet resultSet, final int column)
throws SQLException {
final SQLXML xml = resultSet.getSQLXML(column);
try {
if ( xml == null ) return context.nil;
return RubyString.newInternalFromJavaExternal(runtime, xml.getString());
}
finally { if ( xml != null ) xml.free(); }
}
protected void setStatementParameters(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final RubyArray binds) throws SQLException {
for ( int i = 0; i < binds.getLength(); i++ ) {
setStatementParameter(context, connection, statement, i + 1, binds.eltInternal(i));
}
}
// Set the prepared statement attributes based on the passed in Attribute object
protected void setStatementParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, IRubyObject attribute) throws SQLException {
final IRubyObject value;
final int type;
if (attributeClass.isInstance(attribute)) {
type = jdbcTypeForAttribute(context, attribute);
value = valueForDatabase(context, attribute);
} else {
type = jdbcTypeForPrimitiveAttribute(context, attribute);
value = attribute;
}
// All the set methods were calling this first so save a method call in the nil case
if ( value == context.nil ) {
statement.setNull(index, type);
return;
}
switch (type) {
case Types.TINYINT:
case Types.SMALLINT:
case Types.INTEGER:
setIntegerParameter(context, connection, statement, index, value, attribute, type);
break;
case Types.BIGINT:
setBigIntegerParameter(context, connection, statement, index, value, attribute, type);
break;
case Types.REAL:
case Types.FLOAT:
case Types.DOUBLE:
setDoubleParameter(context, connection, statement, index, value, attribute, type);
break;
case Types.NUMERIC:
case Types.DECIMAL:
setDecimalParameter(context, connection, statement, index, value, attribute, type);
break;
case Types.DATE:
setDateParameter(context, connection, statement, index, value, attribute, type);
break;
case Types.TIME:
setTimeParameter(context, connection, statement, index, value, attribute, type);
break;
case Types.TIMESTAMP:
setTimestampParameter(context, connection, statement, index, value, attribute, type);
break;
case Types.BIT:
case Types.BOOLEAN:
setBooleanParameter(context, connection, statement, index, value, attribute, type);
break;
case Types.SQLXML:
setXmlParameter(context, connection, statement, index, value, attribute, type);
break;
case Types.ARRAY:
setArrayParameter(context, connection, statement, index, value, attribute, type);
break;
case Types.JAVA_OBJECT:
case Types.OTHER:
setObjectParameter(context, connection, statement, index, value, attribute, type);
break;
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
case Types.BLOB:
setBlobParameter(context, connection, statement, index, value, attribute, type);
break;
case Types.CLOB:
case Types.NCLOB: // JDBC 4.0
setClobParameter(context, connection, statement, index, value, attribute, type);
break;
case Types.CHAR:
case Types.VARCHAR:
case Types.NCHAR: // JDBC 4.0
case Types.NVARCHAR: // JDBC 4.0
default:
setStringParameter(context, connection, statement, index, value, attribute, type);
}
}
protected static final Map<String, Integer> JDBC_TYPE_FOR = new HashMap<>(32, 1);
static {
JDBC_TYPE_FOR.put("string", Types.VARCHAR);
JDBC_TYPE_FOR.put("text", Types.CLOB);
JDBC_TYPE_FOR.put("integer", Types.INTEGER);
JDBC_TYPE_FOR.put("float", Types.FLOAT);
JDBC_TYPE_FOR.put("real", Types.REAL);
JDBC_TYPE_FOR.put("decimal", Types.DECIMAL);
JDBC_TYPE_FOR.put("date", Types.DATE);
JDBC_TYPE_FOR.put("time", Types.TIME);
JDBC_TYPE_FOR.put("datetime", Types.TIMESTAMP);
JDBC_TYPE_FOR.put("timestamp", Types.TIMESTAMP);
JDBC_TYPE_FOR.put("boolean", Types.BOOLEAN);
JDBC_TYPE_FOR.put("array", Types.ARRAY);
JDBC_TYPE_FOR.put("xml", Types.SQLXML);
// also mapping standard SQL names :
JDBC_TYPE_FOR.put("bit", Types.BIT);
JDBC_TYPE_FOR.put("tinyint", Types.TINYINT);
JDBC_TYPE_FOR.put("smallint", Types.SMALLINT);
JDBC_TYPE_FOR.put("bigint", Types.BIGINT);
JDBC_TYPE_FOR.put("int", Types.INTEGER);
JDBC_TYPE_FOR.put("double", Types.DOUBLE);
JDBC_TYPE_FOR.put("numeric", Types.NUMERIC);
JDBC_TYPE_FOR.put("char", Types.CHAR);
JDBC_TYPE_FOR.put("varchar", Types.VARCHAR);
JDBC_TYPE_FOR.put("binary", Types.BINARY);
JDBC_TYPE_FOR.put("varbinary", Types.VARBINARY);
//JDBC_TYPE_FOR.put("struct", Types.STRUCT);
JDBC_TYPE_FOR.put("blob", Types.BLOB);
JDBC_TYPE_FOR.put("clob", Types.CLOB);
JDBC_TYPE_FOR.put("nchar", Types.NCHAR);
JDBC_TYPE_FOR.put("nvarchar", Types.NVARCHAR);
JDBC_TYPE_FOR.put("nclob", Types.NCLOB);
}
protected int jdbcTypeForAttribute(final ThreadContext context,
final IRubyObject attribute) throws SQLException {
final String internedType = internedTypeFor(context, attribute);
final Integer sqlType = jdbcTypeFor(internedType);
if ( sqlType != null ) {
return sqlType;
}
return Types.OTHER; // -1 as well as 0 are used in Types
}
protected String internedTypeForPrimitive(final ThreadContext context, final IRubyObject value) throws SQLException {
if (value instanceof RubyString) {
return "string";
}
if (value instanceof RubyInteger) {
return "integer";
}
if (value instanceof RubyNumeric) {
return "float";
}
if (value instanceof RubyTime || value instanceof RubyDateTime) {
return "timestamp";
}
if (value instanceof RubyDate) {
return "date";
}
if (value instanceof RubyBoolean) {
return "boolean";
}
return "string";
}
protected Integer jdbcTypeForPrimitiveAttribute(final ThreadContext context,
final IRubyObject attribute) throws SQLException {
final String internedType = internedTypeForPrimitive(context, attribute);
return jdbcTypeFor(internedType);
}
protected Integer jdbcTypeFor(final String type) {
return JDBC_TYPE_FOR.get(type);
}
// ActiveRecord::Attribute#type (mostly sub-classes e.g. ActiveRecord::Attribute::WithCastValue)
protected static IRubyObject attributeType(final ThreadContext context, final IRubyObject attribute) {
// NOTE: a piece of (premature) optimalization - cause we can and AR 5.x does not mind
return ((RubyBasicObject) attribute).getInstanceVariable("@type"); // attribute.callMethod(context, "type");
}
protected static IRubyObject attributeSQLType(final ThreadContext context, final IRubyObject attribute) {
final IRubyObject type = attributeType(context, attribute);
if (type != null) return type.callMethod(context, "type");
return context.nil;
}
private final CachingCallSite value_site = new FunctionalCachingCallSite("value"); // AR::Attribute#value
protected String internedTypeFor(final ThreadContext context, final IRubyObject attribute) throws SQLException {
final IRubyObject type = attributeSQLType(context, attribute);
if ( type != context.nil ) return type.asJavaString();
final IRubyObject value = value_site.call(context, attribute, attribute);
return internedTypeForPrimitive(context, value);
}
protected final RubyTime timeInDefaultTimeZone(final ThreadContext context, final IRubyObject value) {
return timeInDefaultTimeZone(context, DateTimeUtils.toTime(context, value));
}
protected final RubyTime timeInDefaultTimeZone(final ThreadContext context, final RubyTime time) {
final DateTimeZone defaultZone = getDefaultTimeZone(context);
if (defaultZone == time.getDateTime().getZone()) return time;
final DateTime adjustedDateTime = time.getDateTime().withZone(defaultZone);
final RubyTime timeInDefaultTZ = new RubyTime(context.runtime, context.runtime.getTime(), adjustedDateTime);
timeInDefaultTZ.setNSec(time.getNSec());
return timeInDefaultTZ;
}
protected final DateTime dateTimeInDefaultTimeZone(final ThreadContext context, final DateTime dateTime) {
final DateTimeZone defaultZone = getDefaultTimeZone(context);
if (defaultZone == dateTime.getZone()) return dateTime;
return dateTime.withZone(defaultZone);
}
public static RubyTime toTime(final ThreadContext context, final IRubyObject value) {
return DateTimeUtils.toTime(context, value);
}
protected boolean isDefaultTimeZoneUTC(final ThreadContext context) {
return "utc".equalsIgnoreCase( default_timezone(context) );
}
protected DateTimeZone getDefaultTimeZone(final ThreadContext context) {
return isDefaultTimeZoneUTC(context) ? DateTimeZone.UTC : getLocalTimeZone(context.runtime); // handles ENV['TZ']
}
private String default_timezone(final ThreadContext context) {
final RubyClass base = getBase(context.runtime);
return default_timezone.call(context, base, base).asJavaString(); // :utc (or :local)
}
// ActiveRecord::Base.default_timezone
private final CachingCallSite default_timezone = new FunctionalCachingCallSite("default_timezone");
protected void setIntegerParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, final IRubyObject value,
final IRubyObject attribute, final int type) throws SQLException {
if ( value instanceof RubyBignum ) { // e.g. HSQLDB / H2 report JDBC type 4
setBigIntegerParameter(context, connection, statement, index, (RubyBignum) value, attribute, type);
}
else if ( value instanceof RubyNumeric ) {
statement.setLong(index, RubyNumeric.num2long(value));
}
else {
statement.setLong(index, value.convertToInteger("to_i").getLongValue());
}
}
protected void setBigIntegerParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, final IRubyObject value,
final IRubyObject attribute, final int type) throws SQLException {
if ( value instanceof RubyBignum ) {
setLongOrDecimalParameter(statement, index, ((RubyBignum) value).getValue());
}
else if ( value instanceof RubyFixnum ) {
statement.setLong(index, ((RubyFixnum) value).getLongValue());
}
else {
setLongOrDecimalParameter(statement, index, value.convertToInteger("to_i").getBigIntegerValue());
}
}
protected static void setLongOrDecimalParameter(final PreparedStatement statement,
final int index, final BigInteger value) throws SQLException {
if ( value.bitLength() <= 63 ) {
statement.setLong(index, value.longValue());
}
else {
statement.setBigDecimal(index, new BigDecimal(value));
}
}
protected void setDoubleParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, final IRubyObject value,
final IRubyObject attribute, final int type) throws SQLException {
if ( value instanceof RubyNumeric ) {
statement.setDouble(index, ((RubyNumeric) value).getDoubleValue());
}
else {
statement.setDouble(index, value.convertToFloat().getDoubleValue());
}
}
protected void setDecimalParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, final IRubyObject value,
final IRubyObject attribute, final int type) throws SQLException {
if (value instanceof RubyBigDecimal) {
statement.setBigDecimal(index, ((RubyBigDecimal) value).getValue());
}
else if ( value instanceof RubyInteger ) {
statement.setBigDecimal(index, new BigDecimal(((RubyInteger) value).getBigIntegerValue()));
}
else if ( value instanceof RubyNumeric ) {
statement.setDouble(index, ((RubyNumeric) value).getDoubleValue());
}
else { // e.g. `BigDecimal '42.00000000000000000001'`
statement.setBigDecimal(index,
RubyBigDecimal.newInstance(context, context.runtime.getModule("BigDecimal"), value).getValue());
}
}
protected void setTimestampParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, IRubyObject value,
final IRubyObject attribute, final int type) throws SQLException {
final RubyTime timeValue = DateTimeUtils.toTime(context, value);
final DateTime dateTime = dateTimeInDefaultTimeZone(context, timeValue.getDateTime());
final Timestamp timestamp = new Timestamp(dateTime.getMillis());
// 1942-11-30T01:02:03.123_456
if (timeValue.getNSec() > 0) timestamp.setNanos((int) (timestamp.getNanos() + timeValue.getNSec()));
statement.setTimestamp(index, timestamp, getCalendar(dateTime.getZone()));
}
protected static Calendar getCalendar(final DateTimeZone zone) { // final java.util.Date hint
if (DateTimeZone.UTC == zone) return getCalendarUTC();
if (DateTimeZone.getDefault() == zone) return new GregorianCalendar();
return getCalendarInstance( zone.getID() );
}
private static Calendar getCalendarInstance(final String ID) {
return Calendar.getInstance( TimeZone.getTimeZone(ID) );
}
private static Calendar getCalendarUTC() {
return getCalendarInstance("GMT");
}
protected void setTimeParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, IRubyObject value,
final IRubyObject attribute, final int type) throws SQLException {
final RubyTime timeValue = timeInDefaultTimeZone(context, value);
final DateTime dateTime = timeValue.getDateTime();
final Time time = new Time(dateTime.getMillis()); // has millis precision
statement.setTime(index, time, getCalendar(dateTime.getZone()));
//if ( value instanceof RubyString ) {
// statement.setString(index, value.toString()); // assume local time-zone
//}
//else { // DateTime ( ActiveSupport::TimeWithZone.to_time )
// final RubyFloat timeValue = value.convertToFloat(); // to_f
// final Time time = new Time((long) timeValue.getDoubleValue() * 1000);
// // java.sql.Time is expected to be only up to (milli) second precision
// statement.setTime(index, time, getCalendarUTC());
//}
}
protected void setDateParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, IRubyObject value,
final IRubyObject attribute, final int type) throws SQLException {
if ( ! "Date".equals(value.getMetaClass().getName()) && value.respondsTo("to_date") ) {
value = value.callMethod(context, "to_date");
}
if (value instanceof RubyDate) {
RubyDate rubyDate = (RubyDate) value;
statement.setDate(index, rubyDate.toJava(Date.class));
return;
}
// NOTE: assuming Date#to_s does right ...
statement.setDate(index, Date.valueOf(value.toString()));
}
protected void setBooleanParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, final IRubyObject value,
final IRubyObject attribute, final int type) throws SQLException {
statement.setBoolean(index, value.isTrue());
}
protected void setStringParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, final IRubyObject value,
final IRubyObject attribute, final int type) throws SQLException {
statement.setString(index, value.asString().toString());
}
protected void setArrayParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, final IRubyObject value,
final IRubyObject attribute, final int type) throws SQLException {
final String typeName = resolveArrayBaseTypeName(context, attribute);
final IRubyObject valueForDB = value.callMethod(context, "values");
Array array = connection.createArrayOf(typeName, ((RubyArray) valueForDB).toArray());
statement.setArray(index, array);
}
protected String resolveArrayBaseTypeName(final ThreadContext context, final IRubyObject attribute) throws SQLException {
// This shouldn't return nil at this point because we know we have an array typed attribute
final RubySymbol type = (RubySymbol) attributeSQLType(context, attribute);
// For some reason the driver doesn't like "character varying" as a type
if ( type.eql(context.runtime.newSymbol("string")) ) return "varchar";
final RubyHash nativeTypes = (RubyHash) adapter.callMethod(context, "native_database_types");
// e.g. `integer: { name: 'integer' }`
final RubyHash typeInfo = (RubyHash) nativeTypes.op_aref(context, type);
return typeInfo.op_aref(context, context.runtime.newSymbol("name")).toString();
}
protected void setXmlParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, final IRubyObject value,
final IRubyObject attribute, final int type) throws SQLException {
SQLXML xml = connection.createSQLXML();
xml.setString(value.asString().toString());
statement.setSQLXML(index, xml);
}
protected void setBlobParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, final IRubyObject value,
final IRubyObject attribute, final int type) throws SQLException {
if ( value instanceof RubyIO ) { // IO/File
// JDBC 4.0: statement.setBlob(index, ((RubyIO) value).getInStream());
statement.setBinaryStream(index, ((RubyIO) value).getInStream());
}
else { // should be a RubyString
final ByteList blob = value.asString().getByteList();
statement.setBytes(index, blob.bytes());
// JDBC 4.0 :
//statement.setBlob(index,
// new ByteArrayInputStream(bytes.unsafeBytes(), bytes.getBegin(), bytes.getRealSize())
//);
}
}
protected void setClobParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, final IRubyObject value,
final IRubyObject attribute, final int type) throws SQLException {
if ( value instanceof RubyIO ) { // IO/File
statement.setClob(index, new InputStreamReader(((RubyIO) value).getInStream()));
}
else { // should be a RubyString
final String clob = value.asString().decodeString();
statement.setCharacterStream(index, new StringReader(clob), clob.length());
// JDBC 4.0 :
//statement.setClob(index, new StringReader(clob));
}
}
protected void setObjectParameter(final ThreadContext context,
final Connection connection, final PreparedStatement statement,
final int index, IRubyObject value,
final IRubyObject attribute, final int type) throws SQLException {
statement.setObject(index, value.toJava(Object.class));
}
/**
* Returns a connection (might cause a reconnect if there's none).
* @param required set to true if a connection is required to exists (e.g. on commit)
* @return connection
* @throws <code>ActiveRecord::ConnectionNotEstablished</code> if disconnected
* @throws <code>ActiveRecord::JDBCError</code> if not connected and connecting fails with a SQL exception
*/
protected Connection getConnection(final boolean required) throws RaiseException {
try {
return getConnectionInternal(required);
}
catch (SQLException e) {
throw wrapException(getRuntime().getCurrentContext(), e);
}
}
protected Connection getConnectionInternal(final boolean required) throws SQLException {
Connection connection = getConnectionImpl();
if (connection == null && required) {
if (!connected) handleNotConnected(); // raise ConnectionNotEstablished
synchronized (this) {
connection = getConnectionImpl();
if ( connection == null ) {
connectImpl(true); // throws SQLException
connection = getConnectionImpl();
}
}
}
return connection;
}
private void handleNotConnected() {
final Ruby runtime = getRuntime();
final RubyClass errorClass = getConnectionNotEstablished( runtime );
throw runtime.newRaiseException(errorClass, "no connection available");
}
/**
* @note might return null if connection is lazy
* @return current JDBC connection
*/
protected final Connection getConnectionImpl() {
return (Connection) dataGetStruct(); // synchronized
}
private void setConnection(final Connection connection) {
close( getConnectionImpl() ); // close previously open connection if there is one
dataWrapStruct(connection);
if ( connection != null ) logDriverUsed(connection);
}
protected boolean isConnectionValid(final ThreadContext context, final Connection connection) {
if ( connection == null ) return false;
Statement statement = null;
try {
final String aliveSQL = getAliveSQL(context);
final int aliveTimeout = getAliveTimeout(context);
if ( aliveSQL != null ) { // expect a SELECT/CALL SQL statement
statement = createStatement(context, connection);
statement.setQueryTimeout(aliveTimeout); // 0 - no timeout
statement.execute(aliveSQL);
return true; // connection alive
}
return connection.isValid(aliveTimeout); // isValid(0) (default) means no timeout applied
}
catch (Exception e) {
debugMessage(context.runtime, "connection considered not valid due: ", e);
return false;
}
catch (AbstractMethodError e) { // non-JDBC 4.0 driver
warn( context,
"driver does not support checking if connection isValid()" +
" please make sure you're using a JDBC 4.0 compilant driver or" +
" set `connection_alive_sql: ...` in your database configuration" );
debugStackTrace(context, e);
throw e;
}
finally { close(statement); }
}
private static final String NIL_ALIVE_SQL = new String(); // no set value marker
private transient String aliveSQL = null;
private String getAliveSQL(final ThreadContext context) {
if ( aliveSQL == null ) {
final IRubyObject alive_sql = getConfigValue(context, "connection_alive_sql");
aliveSQL = ( alive_sql == context.nil ) ? NIL_ALIVE_SQL : alive_sql.asString().toString();
}
return aliveSQL == NIL_ALIVE_SQL ? null : aliveSQL;
}
private transient int aliveTimeout = Integer.MIN_VALUE;
/**
* internal API do not depend on it
*/
protected int getAliveTimeout(final ThreadContext context) {
if ( aliveTimeout == Integer.MIN_VALUE ) {
final IRubyObject timeout = getConfigValue(context, "connection_alive_timeout");
return aliveTimeout = timeout == context.nil ? 0 : RubyInteger.fix2int(timeout);
}
return aliveTimeout;
}
private boolean tableExists(final ThreadContext context,
final Connection connection, final TableName tableName) throws SQLException {
final IRubyObject matchedTables =
matchTables(context, connection, tableName.catalog, tableName.schema, tableName.name, getTableTypes(), true);
// NOTE: allow implementers to ignore checkExistsOnly paramater - empty array means does not exists
return matchedTables != null && ! matchedTables.isNil() &&
( ! (matchedTables instanceof RubyArray) || ! ((RubyArray) matchedTables).isEmpty() );
}
@Override
@JRubyMethod
@SuppressWarnings("unchecked")
public IRubyObject inspect() {
final ArrayList<Variable<String>> varList = new ArrayList<>(2);
final Connection connection = getConnectionImpl();
varList.add(new VariableEntry<>( "connection", connection == null ? "null" : connection.toString() ));
//varList.add(new VariableEntry<>( "connectionFactory", connectionFactory == null ? "null" : connectionFactory.toString() ));
return ObjectSupport.inspect(this, (List) varList);
}
/**
* Match table names for given table name (pattern).
* @param context
* @param connection
* @param catalog
* @param schemaPattern
* @param tablePattern
* @param types table types
* @param checkExistsOnly an optimization flag (that might be ignored by sub-classes)
* whether the result really matters if true no need to map table names and a truth-y
* value is sufficient (except for an empty array which is considered that the table
* did not exists).
* @return matched (and Ruby mapped) table names
* @see #mapTables(ThreadContext, Connection, String, String, String, ResultSet)
* @throws SQLException
*/
protected IRubyObject matchTables(final ThreadContext context,
final Connection connection,
final String catalog, final String schemaPattern,
final String tablePattern, final String[] types,
final boolean checkExistsOnly) throws SQLException {
final String _tablePattern = caseConvertIdentifierForJdbc(connection, tablePattern);
final String _schemaPattern = caseConvertIdentifierForJdbc(connection, schemaPattern);
final DatabaseMetaData metaData = connection.getMetaData();
ResultSet tablesSet = null;
try {
tablesSet = metaData.getTables(catalog, _schemaPattern, _tablePattern, types);
if ( checkExistsOnly ) { // only check if given table exists
return tablesSet.next() ? context.tru : null;
}
else {
return mapTables(context, connection, catalog, _schemaPattern, _tablePattern, tablesSet);
}
}
finally { close(tablesSet); }
}
// NOTE java.sql.DatabaseMetaData.getTables :
protected final static int TABLES_TABLE_CAT = 1;
protected final static int TABLES_TABLE_SCHEM = 2;
protected final static int TABLES_TABLE_NAME = 3;
protected final static int TABLES_TABLE_TYPE = 4;
protected RubyArray mapTables(final ThreadContext context, final Connection connection,
final String catalog, final String schemaPattern, final String tablePattern,
final ResultSet tablesSet) throws SQLException {
final RubyArray tables = RubyArray.newArray(context.runtime);
while ( tablesSet.next() ) {
String name = tablesSet.getString(TABLES_TABLE_NAME);
tables.append( cachedString(context, caseConvertIdentifierForRails(connection, name)) );
}
return tables;
}
protected static final int TABLE_NAME = 3;
protected static final int COLUMN_NAME = 4;
protected static final int DATA_TYPE = 5;
protected static final int TYPE_NAME = 6;
protected static final int COLUMN_SIZE = 7;
protected static final int DECIMAL_DIGITS = 9;
protected static final int COLUMN_DEF = 13;
protected static final int IS_NULLABLE = 18;
/**
* Create a string which represents a SQL type usable by Rails from the
* resultSet column meta-data
* @param resultSet
*/
protected String typeFromResultSet(final ResultSet resultSet) throws SQLException {
final int precision = intFromResultSet(resultSet, COLUMN_SIZE);
final int scale = intFromResultSet(resultSet, DECIMAL_DIGITS);
final String type = resultSet.getString(TYPE_NAME);
return formatTypeWithPrecisionAndScale(type, precision, scale);
}
protected static int intFromResultSet(
final ResultSet resultSet, final int column) throws SQLException {
final int precision = resultSet.getInt(column);
return ( precision == 0 && resultSet.wasNull() ) ? -1 : precision;
}
protected static String formatTypeWithPrecisionAndScale(
final String type, final int precision, final int scale) {
if ( precision <= 0 ) return type;
final StringBuilder typeStr = new StringBuilder().append(type);
typeStr.append('(').append(precision); // type += "(" + precision;
if ( scale > 0 ) typeStr.append(',').append(scale); // type += "," + scale;
return typeStr.append(')').toString(); // type += ")";
}
private static IRubyObject defaultValueFromResultSet(final Ruby runtime, final ResultSet resultSet)
throws SQLException {
final String defaultValue = resultSet.getString(COLUMN_DEF);
return defaultValue == null ? runtime.getNil() : RubyString.newInternalFromJavaExternal(runtime, defaultValue);
}
protected RubyArray mapColumnsResult(final ThreadContext context,
final DatabaseMetaData metaData, final TableName components, final ResultSet results)
throws SQLException {
return mapColumnsResult(context, metaData, components, results, getJdbcColumnClass(context));
}
protected RubyArray mapColumnsResult(final ThreadContext context,
final DatabaseMetaData metaData, final TableName components, final ResultSet results,
final RubyClass Column)
throws SQLException {
final Ruby runtime = context.runtime;
final RubyArray columns = RubyArray.newArray(runtime);
while ( results.next() ) {
final String colName = results.getString(COLUMN_NAME);
final RubyString columnName = cachedString(context, caseConvertIdentifierForRails(metaData, colName));
final IRubyObject defaultValue = defaultValueFromResultSet( runtime, results );
final RubyString sqlType = cachedString(context, typeFromResultSet(results));
final RubyBoolean nullable = runtime.newBoolean( ! results.getString(IS_NULLABLE).trim().equals("NO") );
final String tabName = results.getString(TABLE_NAME);
final RubyString tableName = cachedString(context, caseConvertIdentifierForRails(metaData, tabName));
final IRubyObject type_metadata = adapter.callMethod(context, "fetch_type_metadata", sqlType);
// (name, default, sql_type_metadata = nil, null = true, table_name = nil, default_function = nil, collation = nil, comment: nil)
final IRubyObject[] args = new IRubyObject[] {
columnName, defaultValue, type_metadata, nullable, tableName
};
columns.append( Column.newInstance(context, args, Block.NULL_BLOCK) );
}
return columns;
}
private static Collection<String> getPrimaryKeyNames(final DatabaseMetaData metaData,
final TableName components) throws SQLException {
ResultSet primaryKeys = null;
try {
primaryKeys = metaData.getPrimaryKeys(components.catalog, components.schema, components.name);
final List<String> primaryKeyNames = new ArrayList<>(4);
while ( primaryKeys.next() ) {
primaryKeyNames.add( primaryKeys.getString(COLUMN_NAME) );
}
return primaryKeyNames;
}
finally {
close(primaryKeys);
}
}
protected IRubyObject mapGeneratedKeys(final ThreadContext context,
final Connection connection, final Statement statement) throws SQLException {
if (supportsGeneratedKeys(connection)) {
return mapQueryResult(context, connection, statement.getGeneratedKeys());
}
return context.nil; // Adapters should know they don't support it and override this or Adapter#last_inserted_id
}
protected IRubyObject mapGeneratedKeys(
final Ruby runtime, final Connection connection,
final Statement statement, final Boolean singleResult)
throws SQLException {
if ( supportsGeneratedKeys(connection) ) {
ResultSet genKeys = null;
try {
genKeys = statement.getGeneratedKeys();
// drivers might report a non-result statement without keys
// e.g. on derby with SQL: 'SET ISOLATION = SERIALIZABLE'
if ( genKeys == null ) return runtime.getNil();
return doMapGeneratedKeys(runtime, genKeys, singleResult);
}
catch (SQLFeatureNotSupportedException e) {
return null; // statement.getGeneratedKeys()
}
finally { close(genKeys); }
}
return null; // not supported
}
protected final IRubyObject doMapGeneratedKeys(final Ruby runtime,
final ResultSet genKeys, final Boolean singleResult)
throws SQLException {
IRubyObject firstKey = null;
// no generated keys - e.g. INSERT statement for a table that does
// not have and auto-generated ID column :
boolean next = genKeys.next() && genKeys.getMetaData().getColumnCount() > 0;
// singleResult == null - guess if only single key returned
if ( singleResult == null || singleResult) {
if ( next ) {
firstKey = mapGeneratedKey(runtime, genKeys);
if ( singleResult != null || ! genKeys.next() ) {
return firstKey;
}
next = true; // 2nd genKeys.next() returned true
}
else {
/* if ( singleResult != null ) */ return runtime.getNil();
}
}
final RubyArray keys = runtime.newArray();
if ( firstKey != null ) keys.append(firstKey); // singleResult == null
while ( next ) {
keys.append( mapGeneratedKey(runtime, genKeys) );
next = genKeys.next();
}
return keys;
}
protected IRubyObject mapGeneratedKey(final Ruby runtime, final ResultSet genKeys) throws SQLException {
return runtime.newFixnum(genKeys.getLong(1));
}
private transient Boolean supportsGeneratedKeys;
protected boolean supportsGeneratedKeys(final Connection connection) throws SQLException {
Boolean supportsGeneratedKeys = this.supportsGeneratedKeys;
if (supportsGeneratedKeys == null) {
supportsGeneratedKeys = this.supportsGeneratedKeys = connection.getMetaData().supportsGetGeneratedKeys();
}
return supportsGeneratedKeys;
}
/**
* Converts a JDBC result set into an array (rows) of hashes (row).
*
* @param downCase should column names only be in lower case?
*/
@SuppressWarnings("unchecked")
private IRubyObject mapToRawResult(final ThreadContext context,
final Connection connection, final ResultSet resultSet,
final boolean downCase) throws SQLException {
final ColumnData[] columns = extractColumns(context, connection, resultSet, downCase);
final Ruby runtime = context.runtime;
final RubyArray results = runtime.newArray();
// [ { 'col1': 1, 'col2': 2 }, { 'col1': 3, 'col2': 4 } ]
while ( resultSet.next() ) {
results.append(mapRawRow(context, runtime, columns, resultSet, this));
}
return results;
}
private IRubyObject yieldResultRows(final ThreadContext context,
final Connection connection, final ResultSet resultSet,
final Block block) throws SQLException {
final ColumnData[] columns = extractColumns(context, connection, resultSet, false);
final Ruby runtime = context.runtime;
while ( resultSet.next() ) {
final IRubyObject[] blockArgs = new IRubyObject[columns.length];
for ( int i = 0; i < columns.length; i++ ) {
final ColumnData column = columns[i];
blockArgs[i] = jdbcToRuby(context, runtime, column.index, column.type, resultSet);
}
block.call( context, blockArgs );
}
return context.nil; // yielded result rows
}
/**
* Extract columns from result set.
* @param context
* @param connection
* @param resultSet
* @param downCase
* @return columns data
* @throws SQLException
*/
protected ColumnData[] extractColumns(final ThreadContext context,
final Connection connection, final ResultSet resultSet,
final boolean downCase) throws SQLException {
return setupColumns(context, connection, resultSet.getMetaData(), downCase);
}
protected <T> T withConnection(final ThreadContext context, final Callable<T> block)
throws RaiseException {
try {
return withConnection(context, true, block);
}
catch (final SQLException e) {
return handleException(context, e); // should never happen
}
}
private <T> T withConnection(final ThreadContext context, final boolean handleException,
final Callable<T> block) throws RaiseException, SQLException {
Exception exception; int retry = 0; int i = 0;
boolean reconnectOnRetry = true; boolean gotConnection = false;
do {
boolean autoCommit = true; // retry in-case getAutoCommit throws
try {
if ( retry > 0 ) { // we're retrying running the block
if ( reconnectOnRetry ) {
gotConnection = false;
debugMessage(context.runtime, "trying to re-connect using a new connection ...");
connectImpl(true); // force a new connection to be created
}
else {
debugMessage(context.runtime, "re-trying transient failure on same connection ...");
}
}
final Connection connection = getConnectionInternal(false); // getConnection()
if ( connection == null ) {
if ( ! connected ) handleNotConnected(); // raise ConnectionNotEstablished
throw new NoConnectionException();
}
gotConnection = true;
autoCommit = connection.getAutoCommit();
return block.call(connection);
}
catch (final Exception e) { // SQLException or RuntimeException
exception = e;
if ( i == 0 ) retry = 1;
if ( ! gotConnection ) { // SQLException from driver/data-source
reconnectOnRetry = connected;
}
else if (!autoCommit) {
// never retry inside a transaction
break;
}
else if ( isTransient(exception) ) {
reconnectOnRetry = false; // continue;
}
else {
if ( isConnectionValid(context, getConnectionImpl()) ) {
break; // connection not broken yet failed (do not retry)
}
if ( ! isRecoverable(exception) ) break;
reconnectOnRetry = true; // retry calling block again
}
}
} while ( i++ < retry ); // i == 0, retry == 1 means we should retry once
// (retry) loop ended and we did not return ... exception != null
return withConnectionError(context, exception, handleException, gotConnection);
}
// NOTE: this is meant to be internal - seeing this from the outside is a sign smt is not right!
private static class NoConnectionException extends RuntimeException {
@Override
public Throwable fillInStackTrace() { return this; }
}
private <T> T withConnectionError(final ThreadContext context, final Exception exception,
final boolean handleException, final boolean gotConnection) throws SQLException {
if ( handleException ) {
if ( exception instanceof RaiseException ) {
throw (RaiseException) exception;
}
if ( exception instanceof SQLException ) {
if ( ! gotConnection && exception.getCause() != null ) {
return handleException(context, exception.getCause()); // throws
}
return handleException(context, exception); // throws
}
return handleException(context, getCause(exception)); // throws
}
else {
if ( exception instanceof SQLException ) {
throw (SQLException) exception;
}
if ( exception instanceof RuntimeException ) {
throw (RuntimeException) exception;
}
// won't happen - our try block only throws SQL or Runtime exceptions
throw new RuntimeException(exception);
}
}
protected boolean isTransient(final Exception exception) {
return exception instanceof SQLTransientException;
}
protected boolean isRecoverable(final Exception exception) {
return exception instanceof SQLRecoverableException;
// exception instanceof SQLException; // pre JDBC 4.0 drivers?
}
private static Throwable getCause(Throwable exception) {
Throwable cause = exception.getCause();
while (cause != null && cause != exception) {
// SQLException's cause might be DB specific (checked/unchecked) :
if ( exception instanceof SQLException ) break;
exception = cause; cause = exception.getCause();
}
return exception;
}
protected <T> T handleException(final ThreadContext context, Throwable exception) throws RaiseException {
// NOTE: we shall not wrap unchecked (runtime) exceptions into AR::Error
// if it's really a misbehavior of the driver throwing a RuntimeExcepion
// instead of SQLException than this should be overriden for the adapter
if ( exception instanceof RuntimeException ) {
throw (RuntimeException) exception;
}
debugStackTrace(context, exception);
throw wrapException(context, exception);
}
protected RaiseException wrapException(final ThreadContext context, final Throwable exception) {
final Ruby runtime = context.runtime;
if ( exception instanceof SQLException ) {
return wrapException(context, (SQLException) exception, null);
}
if ( exception instanceof RaiseException ) {
return (RaiseException) exception;
}
if ( exception instanceof RuntimeException ) {
return wrapException(context, context.runtime.getRuntimeError(), exception);
}
// NOTE: compat - maybe makes sense or maybe not (e.g. IOException) :
return wrapException(context, getJDBCError(runtime), exception);
}
public static RaiseException wrapException(final ThreadContext context,
final RubyClass errorClass, final Throwable exception) {
return wrapException(context, errorClass, exception, exception.toString());
}
public static RaiseException wrapException(final ThreadContext context,
final RubyClass errorClass, final Throwable exception, final String message) {
final RaiseException error = context.runtime.newRaiseException(errorClass, message);
error.initCause(exception);
return error;
}
protected RaiseException wrapException(final ThreadContext context, final SQLException exception, String message) {
return wrapSQLException(context, getJDBCError(context.runtime), exception, message);
}
protected RaiseException wrapException(final ThreadContext context, final RubyClass errorClass, final SQLException exception) {
return wrapSQLException(context, errorClass, exception, null);
}
private static RaiseException wrapSQLException(final ThreadContext context, final RubyClass errorClass,
final SQLException exception, String message) {
final Ruby runtime = context.runtime;
if ( message == null ) {
message = SQLException.class == exception.getClass() ?
exception.getMessage() : exception.toString(); // useful to easily see type on Ruby side
}
final RaiseException raise = wrapException(context, errorClass, exception, message);
final RubyException error = raise.getException(); // assuming JDBCError internals :
error.setInstanceVariable("@jdbc_exception", JavaEmbedUtils.javaToRuby(runtime, exception));
return raise;
}
protected final RaiseException newNoDatabaseError(final SQLException ex) {
final Ruby runtime = getRuntime();
return wrapException(runtime.getCurrentContext(), getNoDatabaseError(runtime), ex);
}
private IRubyObject convertJavaToRuby(final Object object) {
return JavaUtil.convertJavaToRuby( getRuntime(), object );
}
/**
* Some databases support schemas and others do not.
* For ones which do this method should return true, aiding in decisions regarding schema vs database determination.
*/
protected boolean databaseSupportsSchemas() {
return false;
}
private static final byte[] SELECT = new byte[] { 's','e','l','e','c','t' };
private static final byte[] WITH = new byte[] { 'w','i','t','h' };
private static final byte[] SHOW = new byte[] { 's','h','o','w' };
private static final byte[] CALL = new byte[]{ 'c','a','l','l' };
@JRubyMethod(name = "select?", required = 1, meta = true, frame = false)
public static RubyBoolean select_p(final ThreadContext context,
final IRubyObject self, final IRubyObject sql) {
return context.runtime.newBoolean( isSelect(sql.asString()) );
}
private static boolean isSelect(final RubyString sql) {
final ByteList sqlBytes = sql.getByteList();
return StringHelper.startsWithIgnoreCase(sqlBytes, SELECT) ||
StringHelper.startsWithIgnoreCase(sqlBytes, WITH) ||
StringHelper.startsWithIgnoreCase(sqlBytes, SHOW) ||
StringHelper.startsWithIgnoreCase(sqlBytes, CALL);
}
private static final byte[] INSERT = new byte[] { 'i','n','s','e','r','t' };
@JRubyMethod(name = "insert?", required = 1, meta = true, frame = false)
public static RubyBoolean insert_p(final ThreadContext context,
final IRubyObject self, final IRubyObject sql) {
final ByteList sqlBytes = sql.asString().getByteList();
return context.runtime.newBoolean( startsWithIgnoreCase(sqlBytes, INSERT) );
}
protected static boolean startsWithIgnoreCase(final ByteList bytes, final byte[] start) {
return StringHelper.startsWithIgnoreCase(bytes, start);
}
// maps a AR::Result row
protected static IRubyObject mapRow(final ThreadContext context, final Ruby runtime,
final ColumnData[] columns, final ResultSet resultSet,
final RubyJdbcConnection connection) throws SQLException {
final IRubyObject[] row = new IRubyObject[columns.length];
for (int i = 0; i < columns.length; i++) {
final ColumnData column = columns[i];
row[i] = connection.jdbcToRuby(context, runtime, column.index, column.type, resultSet);
}
return RubyArray.newArrayNoCopy(context.runtime, row);
}
private static IRubyObject mapRawRow(final ThreadContext context, final Ruby runtime,
final ColumnData[] columns, final ResultSet resultSet,
final RubyJdbcConnection connection) throws SQLException {
final RubyHash row = new RubyHash(runtime, columns.length);
for ( int i = 0; i < columns.length; i++ ) {
final ColumnData column = columns[i];
// NOTE: we know keys are always String so maybe we could take it even further ?!
row.fastASetCheckString(runtime, column.getName(context),
connection.jdbcToRuby(context, runtime, column.index, column.type, resultSet)
);
}
return row;
}
protected static IRubyObject newResult(final ThreadContext context, ColumnData[] columns, IRubyObject rows) {
final RubyClass Result = getResult(context.runtime);
return Result.newInstance(context, columnsToArray(context, columns), rows, Block.NULL_BLOCK); // Result.new
}
protected static IRubyObject newEmptyResult(final ThreadContext context) {
final RubyClass Result = getResult(context.runtime);
return Result.newInstance(context, RubyArray.newEmptyArray(context.runtime), RubyArray.newEmptyArray(context.runtime), Block.NULL_BLOCK); // Result.new
}
private static RubyArray columnsToArray(ThreadContext context, ColumnData[] columns) {
final IRubyObject[] cols = new IRubyObject[columns.length];
for ( int i = 0; i < columns.length; i++ ) cols[i] = columns[i].getName(context);
return RubyArray.newArrayNoCopy(context.runtime, cols);
}
protected static final class TableName {
public final String catalog, schema, name;
public TableName(String catalog, String schema, String table) {
this.catalog = catalog;
this.schema = schema;
this.name = table;
}
@Override
public String toString() {
return getClass().getName() + "{catalog=" + catalog + ",schema=" + schema + ",name=" + name + "}";
}
}
/**
* Extract the table name components for the given name e.g. "mycat.sys.entries"
*
* @param connection
* @param catalog (optional) catalog to use if table name does not contain
* the catalog prefix
* @param schema (optional) schema to use if table name does not have one
* @param tableName the table name
* @return (parsed) table name
*
* @throws IllegalArgumentException for invalid table name format
* @throws SQLException
*/
protected TableName extractTableName(
final Connection connection, String catalog, String schema,
final String tableName) throws IllegalArgumentException, SQLException {
final List<String> nameParts = split(tableName, '.');
final int len = nameParts.size();
if ( len > 3 ) {
throw new IllegalArgumentException("table name: " + tableName + " should not contain more than 2 '.'");
}
String name = tableName;
if ( len == 2 ) {
schema = nameParts.get(0); name = nameParts.get(1);
}
else if ( len == 3 ) {
catalog = nameParts.get(0);
schema = nameParts.get(1);
name = nameParts.get(2);
}
if ( schema != null ) {
schema = caseConvertIdentifierForJdbc(connection, schema);
}
name = caseConvertIdentifierForJdbc(connection, name);
if ( schema != null && ! databaseSupportsSchemas() ) {
catalog = schema;
}
if ( catalog == null ) catalog = connection.getCatalog();
return new TableName(catalog, schema, name);
}
protected static List<String> split(final String str, final char sep) {
ArrayList<String> split = new ArrayList<>(4);
int s = 0;
for ( int i = 0; i < str.length(); i++ ) {
if ( str.charAt(i) == sep ) {
split.add( str.substring(s, i) ); s = i + 1;
}
}
if ( s < str.length() ) split.add( str.substring(s) );
return split;
}
protected final TableName extractTableName(
final Connection connection, final String schema,
final String tableName) throws IllegalArgumentException, SQLException {
return extractTableName(connection, null, schema, tableName);
}
protected IRubyObject valueForDatabase(final ThreadContext context, final IRubyObject attribute) {
return attribute.callMethod(context, "value_for_database");
}
// FIXME: This should not be static and will be exposed via api in connection as instance method.
public static final StringCache STRING_CACHE = new StringCache();
protected static RubyString cachedString(final ThreadContext context, final String str) {
return STRING_CACHE.get(context, str);
}
protected static final class ColumnData {
@Deprecated
public RubyString name;
public final int index;
public final int type;
private final String label;
@Deprecated
public ColumnData(RubyString name, int type, int idx) {
this.name = name;
this.type = type;
this.index = idx;
this.label = name.toString();
}
public ColumnData(String label, int type, int idx) {
this.label = label;
this.type = type;
this.index = idx;
}
// NOTE: meant temporary for others to update from accesing name
ColumnData(ThreadContext context, String label, int type, int idx) {
this(label, type, idx);
name = cachedString(context, label);
}
public String getName() {
return label;
}
RubyString getName(final ThreadContext context) {
if ( name != null ) return name;
return name = cachedString(context, label);
}
@Override
public String toString() {
return "'" + label + "'i" + index + "t" + type + "";
}
}
private ColumnData[] setupColumns(
final ThreadContext context,
final Connection connection,
final ResultSetMetaData resultMetaData,
final boolean downCase) throws SQLException {
final int columnCount = resultMetaData.getColumnCount();
final ColumnData[] columns = new ColumnData[columnCount];
for ( int i = 1; i <= columnCount; i++ ) { // metadata is one-based
String name = resultMetaData.getColumnLabel(i);
if ( downCase ) {
name = name.toLowerCase();
} else {
name = caseConvertIdentifierForRails(connection, name);
}
final int columnType = resultMetaData.getColumnType(i);
columns[i - 1] = new ColumnData(context, name, columnType, i);
}
return columns;
}
// JDBC API Helpers :
protected static void close(final Connection connection) {
if ( connection != null ) {
try { connection.close(); }
catch (final Exception e) { /* NOOP */ }
}
}
public static void close(final ResultSet resultSet) {
if (resultSet != null) {
try { resultSet.close(); }
catch (final Exception e) { /* NOOP */ }
}
}
public static void close(final Statement statement) {
if (statement != null) {
try { statement.close(); }
catch (final Exception e) { /* NOOP */ }
}
}
// DEBUG-ing helpers :
private static boolean debug = Boolean.parseBoolean( SafePropertyAccessor.getProperty("arjdbc.debug") );
public static boolean isDebug() { return debug; }
public static boolean isDebug(final Ruby runtime) {
return debug || ( runtime != null && runtime.isDebug() );
}
public static void setDebug(boolean debug) {
RubyJdbcConnection.debug = debug;
}
//public static void debugMessage(final ThreadContext context, final String msg) {
// if ( debug || ( context != null && context.runtime.isDebug() ) ) {
// final PrintStream out = context != null ? context.runtime.getOut() : System.out;
// out.println(msg);
// }
//}
public static void debugMessage(final Ruby runtime, final Object msg) {
if ( isDebug(runtime) ) {
final PrintStream out = runtime != null ? runtime.getOut() : System.out;
out.print("ArJdbc: "); out.println(msg);
}
}
public static void debugMessage(final ThreadContext context, final IRubyObject obj) {
if ( isDebug(context.runtime) ) {
debugMessage(context.runtime, obj.callMethod(context, "inspect"));
}
}
public static void debugMessage(final Ruby runtime, final String msg, final Object e) {
if ( isDebug(runtime) ) {
final PrintStream out = runtime != null ? runtime.getOut() : System.out;
out.print("ArJdbc: "); out.print(msg); out.println(e);
}
}
protected static void debugErrorSQL(final ThreadContext context, final String sql) {
if ( debug || ( context != null && context.runtime.isDebug() ) ) {
final PrintStream out = context != null ? context.runtime.getOut() : System.out;
out.print("ArJdbc: (error) SQL = "); out.println(sql);
}
}
// disables full (Java) traces to be printed while DEBUG is on
private static final Boolean debugStackTrace;
static {
String debugTrace = SafePropertyAccessor.getProperty("arjdbc.debug.trace");
debugStackTrace = debugTrace == null ? null : Boolean.parseBoolean(debugTrace);
}
public static void debugStackTrace(final ThreadContext context, final Throwable e) {
if ( debug || ( context != null && context.runtime.isDebug() ) ) {
final PrintStream out = context != null ? context.runtime.getOut() : System.out;
if ( debugStackTrace == null || debugStackTrace) {
e.printStackTrace(out);
}
else {
out.println(e);
}
}
}
protected void warn(final ThreadContext context, final String message) {
arjdbc.ArJdbcModule.warn(context, message);
}
private static boolean driverUsedLogged;
private void logDriverUsed(final Connection connection) {
if (debug && !driverUsedLogged) {
driverUsedLogged = true;
try {
final DatabaseMetaData meta = connection.getMetaData();
debugMessage(getRuntime(), "using driver " + meta.getDriverVersion());
}
catch (Exception e) {
debugMessage(getRuntime(), "failed to log driver ", e);
}
}
}
}
|
import java.nio.file.Files;
import java.nio.file.Paths;
class Program {
public static void main(String[] args) throws Exception {
Files.write(Paths.get("test.txt"), "example content".getBytes());;
String fileContent = new String(Files.readAllBytes(Paths.get("test.txt")));;
System.out.println(fileContent);
}
}
|
package liquibase.nosql.statement;
/*-
* #%L
* Liquibase NoSql Extension
* %%
* Copyright (C) 2020 Mastercard
* %%
* 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 liquibase.nosql.database.AbstractNoSqlDatabase;
import java.util.List;
public interface NoSqlQueryForListStatement <D extends AbstractNoSqlDatabase, T>{
List<T> queryForList(D database);
}
|
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.chimesdkmessaging.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.chimesdkmessaging.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* UpdateChannelFlowRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class UpdateChannelFlowRequestProtocolMarshaller implements Marshaller<Request<UpdateChannelFlowRequest>, UpdateChannelFlowRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON)
.requestUri("/channel-flows/{channelFlowArn}").httpMethodName(HttpMethodName.PUT).hasExplicitPayloadMember(false).hasPayloadMembers(true)
.serviceName("AmazonChimeSDKMessaging").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public UpdateChannelFlowRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<UpdateChannelFlowRequest> marshall(UpdateChannelFlowRequest updateChannelFlowRequest) {
if (updateChannelFlowRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<UpdateChannelFlowRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING,
updateChannelFlowRequest);
protocolMarshaller.startMarshalling();
UpdateChannelFlowRequestMarshaller.getInstance().marshall(updateChannelFlowRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2020-2030 The XdagJ Developers
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package io.xdag.rpc.netty;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.xdag.rpc.cors.OriginValidator;
import io.xdag.rpc.utils.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
@ChannelHandler.Sharable
public class JsonRpcWeb3FilterHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
private static final Logger logger = LoggerFactory.getLogger("jsonrpc");
private final List<String> rpcHost;
private final InetAddress rpcAddress;
private final List<String> acceptedHosts;
private OriginValidator originValidator;
public JsonRpcWeb3FilterHandler(String corsDomains, InetAddress rpcAddress, List<String> rpcHost) {
this.originValidator = new OriginValidator(corsDomains);
this.rpcHost = rpcHost;
this.rpcAddress = rpcAddress;
this.acceptedHosts = getAcceptedHosts();
}
private List<String> getAcceptedHosts() {
List<String> hosts = new ArrayList<>();
if (isAcceptedAddress(rpcAddress)) {
hosts.add(rpcAddress.getHostName());
hosts.add(rpcAddress.getHostAddress());
} else {
for (String host : rpcHost) {
try {
InetAddress hostAddress = InetAddress.getByName(host);
if (!hostAddress.isAnyLocalAddress()) {
hosts.add(hostAddress.getHostAddress());
hosts.add(hostAddress.getHostName());
} else {
logger.warn("Wildcard address is not allowed on rpc host property {}", hostAddress);
}
} catch (UnknownHostException e) {
logger.warn("Invalid Host defined on rpc.host", e);
}
}
}
return hosts;
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
HttpResponse response;
HttpMethod httpMethod = request.getMethod();
HttpHeaders headers = request.headers();
// when a request has multiple host fields declared it would be equivalent to a comma separated list
// the request will be inmediately rejected since it won't be parsed as a valid URI
// and won't work to match an item on rpc.host
String hostHeader = headers.get(HttpHeaders.Names.HOST);
String parsedHeader = parseHostHeader(hostHeader);
if (!acceptedHosts.contains(parsedHeader)) {
logger.debug("Invalid header HOST {}", hostHeader);
response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST);
ctx.write(response).addListener(ChannelFutureListener.CLOSE);
return;
}
if (HttpMethod.POST.equals(httpMethod)) {
String mimeType = HttpUtils.getMimeType(headers.get(HttpHeaders.Names.CONTENT_TYPE));
String origin = headers.get(HttpHeaders.Names.ORIGIN);
String referer = headers.get(HttpHeaders.Names.REFERER);
if (!"application/json".equals(mimeType) && !"application/json-rpc".equals(mimeType)) {
logger.debug("Unsupported content type");
response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE);
}
else if (origin != null && !this.originValidator.isValidOrigin(origin)) {
logger.debug("Invalid origin");
response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST);
} else if (referer != null && !this.originValidator.isValidReferer(referer)) {
logger.debug("Invalid referer");
response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST);
}
else {
ctx.fireChannelRead(request);
return;
}
} else {
response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_IMPLEMENTED);
}
ctx.write(response).addListener(ChannelFutureListener.CLOSE);
}
private String parseHostHeader(String hostHeader) {
try {
// WORKAROUND: add any scheme to make the resulting URI valid.
URI uri = new URI("my://" + hostHeader); // may throw URISyntaxException
return uri.getHost();
} catch (URISyntaxException e) {
return hostHeader;
}
}
private boolean isAcceptedAddress(final InetAddress address) {
// Check if the address is a valid special local or loop back
if (address.isLoopbackAddress() ) {
return true;
}
// Check if the address is defined on any interface
try {
return !address.isAnyLocalAddress() && NetworkInterface.getByInetAddress(address) != null;
} catch (SocketException se) {
return false;
}
}
}
|
package stacks.queues;
public class Node<T> {
private T value;
private Node next;
public Node(T value) {
this.value = value;
}
public T getValue() {
return value;
}
public Node getNext() {
return next;
}
public void setValue(T value) {
this.value = value;
}
public void setNext(Node next) {
this.next = next;
}
}
|
package pl.grzeslowski.jsupla;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collection;
import static org.assertj.core.api.Assertions.assertThat;
public class PreconditionsTestSizeMin {
@Test
public void shouldReturnCollectionWhenSizeIsInBounds() throws Exception {
// given
final Collection<String> expectedCollection = Arrays.asList("1", "2");
// when
final Collection<String> collection = Preconditions.sizeMin(expectedCollection, 1);
// then
assertThat(collection).isEqualTo(expectedCollection);
}
@Test
public void shouldReturnArrayWhenSizeIsInBounds() throws Exception {
// given
final String[] expectedArray = new String[]{"1", "2"};
// when
final String[] array = Preconditions.sizeMin(expectedArray, 1);
// then
assertThat(array).isEqualTo(expectedArray);
}
@Test
public void shouldReturnCharSequenceWhenSizeIsInBounds() throws Exception {
// given
final CharSequence expectedCharSequence = " ";
// when
final CharSequence charSequence = Preconditions.sizeMin(expectedCharSequence, 1);
// then
assertThat(charSequence).isEqualTo(expectedCharSequence);
}
@Test
public void shouldReturnByteArrayWhenSizeIsInBounds() throws Exception {
// given
final byte[] expectedByteArray = new byte[]{1};
// when
final byte[] bytes = Preconditions.sizeMin(expectedByteArray, 1);
// then
assertThat(bytes).isEqualTo(expectedByteArray);
}
@Test
public void shouldReturnByteArrayWhenSizeIsInLongBounds() throws Exception {
// given
final byte[] expectedByteArray = new byte[]{1};
// when
final byte[] bytes = Preconditions.sizeMin(expectedByteArray, 1L);
// then
assertThat(bytes).isEqualTo(expectedByteArray);
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowIllegalArgumentExceptionWhenSizeIsInBoundsCollection() throws Exception {
// given
final Collection<String> expectedCollection = Arrays.asList("1", "2", "3");
// when
Preconditions.sizeMin(expectedCollection, 5);
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowIllegalArgumentExceptionWhenSizeIsInBoundsArray() throws Exception {
// given
final String[] expectedArray = new String[]{"1", "2", "3"};
// when
Preconditions.sizeMin(expectedArray, 5);
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowIllegalArgumentExceptionWhenSizeIsInBoundsCharSequence() throws Exception {
// given
final CharSequence expectedCharSequence = "123";
// when
Preconditions.sizeMin(expectedCharSequence, 5);
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowIllegalArgumentExceptionWhenSizeIsInBoundsByteArray() throws Exception {
// given
final byte[] expectedByteArray = new byte[]{1, 2, 3};
// when
Preconditions.sizeMin(expectedByteArray, 5);
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowIllegalArgumentExceptionWhenSizeIsInLongBoundsByteArray() throws Exception {
// given
final byte[] expectedByteArray = new byte[]{1, 2, 3};
// when
Preconditions.sizeMin(expectedByteArray, 5L);
}
}
|
// Generated from SQLFileHeader.g4 by ANTLR 4.5.1
package com.psygate.minecraft.spigot.sovereignty.nucleus.grammars;
import org.antlr.v4.runtime.atn.*;
import org.antlr.v4.runtime.dfa.DFA;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.misc.*;
import org.antlr.v4.runtime.tree.*;
import java.util.List;
import java.util.Iterator;
import java.util.ArrayList;
@SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"})
public class SQLFileHeaderParser extends Parser {
static { RuntimeMetaData.checkVersion("4.5.1", RuntimeMetaData.VERSION); }
protected static final DFA[] _decisionToDFA;
protected static final PredictionContextCache _sharedContextCache =
new PredictionContextCache();
public static final int
WS=1, SQL_COMMENT=2, NUMBER=3, HEADER_MARKER=4, TYPE=5, TYPE_MARKER=6,
VERSION_MARKER=7, UPGRADE_MARKER=8;
public static final int
RULE_types = 0, RULE_versions = 1, RULE_upgrades = 2, RULE_header = 3,
RULE_script = 4;
public static final String[] ruleNames = {
"types", "versions", "upgrades", "header", "script"
};
private static final String[] _LITERAL_NAMES = {
};
private static final String[] _SYMBOLIC_NAMES = {
null, "WS", "SQL_COMMENT", "NUMBER", "HEADER_MARKER", "TYPE", "TYPE_MARKER",
"VERSION_MARKER", "UPGRADE_MARKER"
};
public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES);
/**
* @deprecated Use {@link #VOCABULARY} instead.
*/
@Deprecated
public static final String[] tokenNames;
static {
tokenNames = new String[_SYMBOLIC_NAMES.length];
for (int i = 0; i < tokenNames.length; i++) {
tokenNames[i] = VOCABULARY.getLiteralName(i);
if (tokenNames[i] == null) {
tokenNames[i] = VOCABULARY.getSymbolicName(i);
}
if (tokenNames[i] == null) {
tokenNames[i] = "<INVALID>";
}
}
}
@Override
@Deprecated
public String[] getTokenNames() {
return tokenNames;
}
@Override
public Vocabulary getVocabulary() {
return VOCABULARY;
}
@Override
public String getGrammarFileName() { return "SQLFileHeader.g4"; }
@Override
public String[] getRuleNames() { return ruleNames; }
@Override
public String getSerializedATN() { return _serializedATN; }
@Override
public ATN getATN() { return _ATN; }
public SQLFileHeaderParser(TokenStream input) {
super(input);
_interp = new ParserATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache);
}
public static class TypesContext extends ParserRuleContext {
public TerminalNode TYPE_MARKER() { return getToken(SQLFileHeaderParser.TYPE_MARKER, 0); }
public List<TerminalNode> TYPE() { return getTokens(SQLFileHeaderParser.TYPE); }
public TerminalNode TYPE(int i) {
return getToken(SQLFileHeaderParser.TYPE, i);
}
public TypesContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_types; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof SQLFileHeaderListener ) ((SQLFileHeaderListener)listener).enterTypes(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof SQLFileHeaderListener ) ((SQLFileHeaderListener)listener).exitTypes(this);
}
}
public final TypesContext types() throws RecognitionException {
TypesContext _localctx = new TypesContext(_ctx, getState());
enterRule(_localctx, 0, RULE_types);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(10);
match(TYPE_MARKER);
setState(12);
_errHandler.sync(this);
_la = _input.LA(1);
do {
{
{
setState(11);
match(TYPE);
}
}
setState(14);
_errHandler.sync(this);
_la = _input.LA(1);
} while ( _la==TYPE );
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class VersionsContext extends ParserRuleContext {
public TerminalNode VERSION_MARKER() { return getToken(SQLFileHeaderParser.VERSION_MARKER, 0); }
public TerminalNode NUMBER() { return getToken(SQLFileHeaderParser.NUMBER, 0); }
public VersionsContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_versions; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof SQLFileHeaderListener ) ((SQLFileHeaderListener)listener).enterVersions(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof SQLFileHeaderListener ) ((SQLFileHeaderListener)listener).exitVersions(this);
}
}
public final VersionsContext versions() throws RecognitionException {
VersionsContext _localctx = new VersionsContext(_ctx, getState());
enterRule(_localctx, 2, RULE_versions);
try {
enterOuterAlt(_localctx, 1);
{
setState(16);
match(VERSION_MARKER);
setState(17);
match(NUMBER);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class UpgradesContext extends ParserRuleContext {
public TerminalNode UPGRADE_MARKER() { return getToken(SQLFileHeaderParser.UPGRADE_MARKER, 0); }
public List<TerminalNode> NUMBER() { return getTokens(SQLFileHeaderParser.NUMBER); }
public TerminalNode NUMBER(int i) {
return getToken(SQLFileHeaderParser.NUMBER, i);
}
public UpgradesContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_upgrades; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof SQLFileHeaderListener ) ((SQLFileHeaderListener)listener).enterUpgrades(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof SQLFileHeaderListener ) ((SQLFileHeaderListener)listener).exitUpgrades(this);
}
}
public final UpgradesContext upgrades() throws RecognitionException {
UpgradesContext _localctx = new UpgradesContext(_ctx, getState());
enterRule(_localctx, 4, RULE_upgrades);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(19);
match(UPGRADE_MARKER);
setState(21);
_errHandler.sync(this);
_la = _input.LA(1);
do {
{
{
setState(20);
match(NUMBER);
}
}
setState(23);
_errHandler.sync(this);
_la = _input.LA(1);
} while ( _la==NUMBER );
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class HeaderContext extends ParserRuleContext {
public TerminalNode HEADER_MARKER() { return getToken(SQLFileHeaderParser.HEADER_MARKER, 0); }
public HeaderContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_header; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof SQLFileHeaderListener ) ((SQLFileHeaderListener)listener).enterHeader(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof SQLFileHeaderListener ) ((SQLFileHeaderListener)listener).exitHeader(this);
}
}
public final HeaderContext header() throws RecognitionException {
HeaderContext _localctx = new HeaderContext(_ctx, getState());
enterRule(_localctx, 6, RULE_header);
try {
enterOuterAlt(_localctx, 1);
{
setState(25);
match(HEADER_MARKER);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static class ScriptContext extends ParserRuleContext {
public List<HeaderContext> header() {
return getRuleContexts(HeaderContext.class);
}
public HeaderContext header(int i) {
return getRuleContext(HeaderContext.class,i);
}
public List<TypesContext> types() {
return getRuleContexts(TypesContext.class);
}
public TypesContext types(int i) {
return getRuleContext(TypesContext.class,i);
}
public List<VersionsContext> versions() {
return getRuleContexts(VersionsContext.class);
}
public VersionsContext versions(int i) {
return getRuleContext(VersionsContext.class,i);
}
public List<UpgradesContext> upgrades() {
return getRuleContexts(UpgradesContext.class);
}
public UpgradesContext upgrades(int i) {
return getRuleContext(UpgradesContext.class,i);
}
public ScriptContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_script; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof SQLFileHeaderListener ) ((SQLFileHeaderListener)listener).enterScript(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof SQLFileHeaderListener ) ((SQLFileHeaderListener)listener).exitScript(this);
}
}
public final ScriptContext script() throws RecognitionException {
ScriptContext _localctx = new ScriptContext(_ctx, getState());
enterRule(_localctx, 8, RULE_script);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(27);
header();
setState(31);
_errHandler.sync(this);
_la = _input.LA(1);
do {
{
setState(31);
switch (_input.LA(1)) {
case TYPE_MARKER:
{
setState(28);
types();
}
break;
case VERSION_MARKER:
{
setState(29);
versions();
}
break;
case UPGRADE_MARKER:
{
setState(30);
upgrades();
}
break;
default:
throw new NoViableAltException(this);
}
}
setState(33);
_errHandler.sync(this);
_la = _input.LA(1);
} while ( (((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << TYPE_MARKER) | (1L << VERSION_MARKER) | (1L << UPGRADE_MARKER))) != 0) );
setState(35);
header();
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
public static final String _serializedATN =
"\3\u0430\ud6d1\u8206\uad2d\u4417\uaef1\u8d80\uaadd\3\n(\4\2\t\2\4\3\t"+
"\3\4\4\t\4\4\5\t\5\4\6\t\6\3\2\3\2\6\2\17\n\2\r\2\16\2\20\3\3\3\3\3\3"+
"\3\4\3\4\6\4\30\n\4\r\4\16\4\31\3\5\3\5\3\6\3\6\3\6\3\6\6\6\"\n\6\r\6"+
"\16\6#\3\6\3\6\3\6\2\2\7\2\4\6\b\n\2\2\'\2\f\3\2\2\2\4\22\3\2\2\2\6\25"+
"\3\2\2\2\b\33\3\2\2\2\n\35\3\2\2\2\f\16\7\b\2\2\r\17\7\7\2\2\16\r\3\2"+
"\2\2\17\20\3\2\2\2\20\16\3\2\2\2\20\21\3\2\2\2\21\3\3\2\2\2\22\23\7\t"+
"\2\2\23\24\7\5\2\2\24\5\3\2\2\2\25\27\7\n\2\2\26\30\7\5\2\2\27\26\3\2"+
"\2\2\30\31\3\2\2\2\31\27\3\2\2\2\31\32\3\2\2\2\32\7\3\2\2\2\33\34\7\6"+
"\2\2\34\t\3\2\2\2\35!\5\b\5\2\36\"\5\2\2\2\37\"\5\4\3\2 \"\5\6\4\2!\36"+
"\3\2\2\2!\37\3\2\2\2! \3\2\2\2\"#\3\2\2\2#!\3\2\2\2#$\3\2\2\2$%\3\2\2"+
"\2%&\5\b\5\2&\13\3\2\2\2\6\20\31!#";
public static final ATN _ATN =
new ATNDeserializer().deserialize(_serializedATN.toCharArray());
static {
_decisionToDFA = new DFA[_ATN.getNumberOfDecisions()];
for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) {
_decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i);
}
}
}
|
/*
* Copyright (c) 2007-2015 Concurrent, Inc. All Rights Reserved.
*
* Project and contact information: http://www.cascading.org/
*
* This file is part of the Cascading project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cascading.util.cache;
import cascading.flow.FlowProcess;
/**
* Concrete sub-class of {@link cascading.util.cache.BaseCacheFactory} for creating {@link cascading.util.cache.OrderedHashMapCache}
* instances.
*/
public class OrderedHashMapCacheFactory extends BaseCacheFactory
{
@Override
public CascadingCache create( FlowProcess flowProcess )
{
return new OrderedHashMapCache();
}
}
|
package org.codehaus.modello.plugins.xml.metadata;
/*
* Copyright (c) 2004, Codehaus.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import org.codehaus.modello.metadata.InterfaceMetadata;
/**
* @author <a href="mailto:trygvis@inamo.no">Trygve Laugstøl</a>
*/
public class XmlInterfaceMetadata
implements InterfaceMetadata
{
public static final String ID = XmlInterfaceMetadata.class.getName();
}
|
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters;
import org.hyperledger.besu.ethereum.core.BlockHeader;
import java.util.Objects;
import java.util.Optional;
import com.fasterxml.jackson.annotation.JsonCreator;
// Represents a block parameter that can be a special value ("pending", "earliest", "latest") or
// a number formatted as a hex string.
// See: https://github.com/ethereum/wiki/wiki/JSON-RPC#the-default-block-parameter
public class BlockParameter {
private final BlockParameterType type;
private final Optional<Long> number;
public static final BlockParameter EARLIEST = new BlockParameter("earliest");
public static final BlockParameter LATEST = new BlockParameter("latest");
public static final BlockParameter PENDING = new BlockParameter("pending");
@JsonCreator
public BlockParameter(final String value) {
final String normalizedValue = value.toLowerCase();
switch (normalizedValue) {
case "earliest":
type = BlockParameterType.EARLIEST;
number = Optional.of(BlockHeader.GENESIS_BLOCK_NUMBER);
break;
case "latest":
type = BlockParameterType.LATEST;
number = Optional.empty();
break;
case "pending":
type = BlockParameterType.PENDING;
number = Optional.empty();
break;
default:
type = BlockParameterType.NUMERIC;
number = Optional.of(Long.decode(value));
break;
}
}
public BlockParameter(final long value) {
type = BlockParameterType.NUMERIC;
number = Optional.of(value);
}
public Optional<Long> getNumber() {
return number;
}
public boolean isPending() {
return this.type == BlockParameterType.PENDING;
}
public boolean isLatest() {
return this.type == BlockParameterType.LATEST;
}
public boolean isEarliest() {
return this.type == BlockParameterType.EARLIEST;
}
public boolean isNumeric() {
return this.type == BlockParameterType.NUMERIC;
}
@Override
public String toString() {
return "BlockParameter{" + "type=" + type + ", number=" + number + '}';
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BlockParameter that = (BlockParameter) o;
return type == that.type && number.equals(that.number);
}
@Override
public int hashCode() {
return Objects.hash(type, number);
}
private enum BlockParameterType {
EARLIEST,
LATEST,
PENDING,
NUMERIC
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.