hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9237ad946495cd8514ed538bbc844766cf683411 | 957 | java | Java | Screen/Screen.java | minohara/MTRA | 1c5d4706a4750ac33dc533afcd901db5352e9bb4 | [
"MIT"
] | null | null | null | Screen/Screen.java | minohara/MTRA | 1c5d4706a4750ac33dc533afcd901db5352e9bb4 | [
"MIT"
] | null | null | null | Screen/Screen.java | minohara/MTRA | 1c5d4706a4750ac33dc533afcd901db5352e9bb4 | [
"MIT"
] | null | null | null | 35.444444 | 194 | 0.424242 | 998,158 | public class Screen {
public static void main(String[] args) {
String studioName = "a studio";
char sRow = 'A';
char eRow = 'O';
int sCol = 1;
int eCol = 22;
for ( int r = sRow; r < eRow; r++ ) {
for ( int c = sCol; c <= eCol; c++ ) {
if ( r >= 'C' || ( 5 <= c && c <= 18 )) {
double x = 2*(c - (eCol + sCol)/2.0);
if ( c <= 4 ) x -= 2;
else if ( c >= 19 ) x += 2;
System.out.format("insert into seat(`screen_id`, `row`, `column`, `pos_x`, `pos_y`, `pos_z`) values (1, \"%c\", %2d, %3.0f, %3.0f, %3.0f);\n", r, c, x, (r - 'B')*2.0+1, (r - 'B')*1.0);
}
}
}
for ( int c = 1; c <= 16; c++ ) {
double x = 2*(c - (1 + 16)/2.0);
if ( x < 0 ) x -= 2;
else x += 2;
System.out.format("insert into seat(`screen_id`, `row`, `column`, `pos_x`, `pos_y`, `pos_z`) values (1, \"S\", %2d, %3.0f, %3.0f, %3.0f);\n", c, x, 35.0, 17.0);
}
}
}
|
9237ae31f90fbb909b4d7e584b014a930cbb2537 | 1,864 | java | Java | src/main/java/org/seeyou/generator/yaml/YamlLoader.java | hongxiyou/seeyou-openapi-generator | 66a60db45f6390afc207772732bbc936a26025d1 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/seeyou/generator/yaml/YamlLoader.java | hongxiyou/seeyou-openapi-generator | 66a60db45f6390afc207772732bbc936a26025d1 | [
"Apache-2.0"
] | 2 | 2021-12-14T20:38:06.000Z | 2021-12-14T21:19:25.000Z | src/main/java/org/seeyou/generator/yaml/YamlLoader.java | hongxiyou/seeyou-openapi-generator | 66a60db45f6390afc207772732bbc936a26025d1 | [
"Apache-2.0"
] | null | null | null | 23.594937 | 87 | 0.631974 | 998,159 | package org.seeyou.generator.yaml;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.snakeyaml.engine.v1.api.Load;
import org.snakeyaml.engine.v1.api.LoadSettings;
import org.snakeyaml.engine.v1.api.LoadSettingsBuilder;
/**
* Yaml 配置文件加载器,支持 ${} 变量引用
*/
public class YamlLoader {
public static Map<String, Object> load(InputStream input) {
LoadSettings settings = new LoadSettingsBuilder().build();
Load load = new Load(settings);
Object obj = load.loadFromInputStream(input);
Map<String, Object> result = new LinkedHashMap<>();
flatten("", obj, result);
Map<String, Object> result2 = new LinkedHashMap<>();
fillParamsValue(result, result2);
return result2;
}
/**
* 参数扁平化
*
* @param prefix
* @param in
* @param out
*/
private static void flatten(final String prefix, Object in, Map<String, Object> out) {
if (in instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) in;
map.forEach((k, v) -> {
String key = prefix.equals("") ? k : prefix + "." + k;
flatten(key, v, out);
});
} else {
out.put(prefix, in);
}
}
/**
* 变量替换
*
* @param in
* @param out
*/
private static void fillParamsValue(Map<String, Object> in, Map<String, Object> out) {
final Pattern p = Pattern.compile("(\\$\\{\\s*)([\\w\\.]+)(\\s*\\})");
in.forEach((k, v) -> {
if (v instanceof String) {
Matcher m = p.matcher(v.toString());
StringBuffer sb = new StringBuffer();
while (m.find()) {
String group = m.group(2);
Object value = out.get(group);
if (value != null) {
m.appendReplacement(sb, value.toString());
}
}
m.appendTail(sb);
out.put(k, sb.toString());
} else {
out.put(k, v);
}
});
}
}
|
9237ae4e3156378bc07e5625da8ad4e3b235a506 | 147 | java | Java | Hello.java | UncleEngineer/BasicJava | 4ea411eac0897de61f2b566409a89b7732a418bc | [
"MIT"
] | null | null | null | Hello.java | UncleEngineer/BasicJava | 4ea411eac0897de61f2b566409a89b7732a418bc | [
"MIT"
] | null | null | null | Hello.java | UncleEngineer/BasicJava | 4ea411eac0897de61f2b566409a89b7732a418bc | [
"MIT"
] | null | null | null | 24.5 | 47 | 0.70068 | 998,160 | public class Hello {
public static void main(String[] arguments) {
String sawatdee = "Hello Lungtu 555";
System.out.println(sawatdee);
}
} |
9237ae7296f66e78326adc0fde130e199c8cd046 | 3,249 | java | Java | org/apache/commons/logging/impl/ServletContextCleaner.java | MewX/contendo-viewer-v1.6.3 | 69fba3cea4f9a43e48f43148774cfa61b388e7de | [
"Apache-2.0"
] | 2 | 2021-07-16T10:43:25.000Z | 2021-12-15T13:54:10.000Z | org/apache/commons/logging/impl/ServletContextCleaner.java | MewX/contendo-viewer-v1.6.3 | 69fba3cea4f9a43e48f43148774cfa61b388e7de | [
"Apache-2.0"
] | 1 | 2021-10-12T22:24:55.000Z | 2021-10-12T22:24:55.000Z | org/apache/commons/logging/impl/ServletContextCleaner.java | MewX/contendo-viewer-v1.6.3 | 69fba3cea4f9a43e48f43148774cfa61b388e7de | [
"Apache-2.0"
] | null | null | null | 23.715328 | 112 | 0.408433 | 998,161 | /* */ package org.apache.commons.logging.impl;
/* */
/* */ import java.lang.reflect.InvocationTargetException;
/* */ import java.lang.reflect.Method;
/* */ import javax.servlet.ServletContextEvent;
/* */ import javax.servlet.ServletContextListener;
/* */ import org.apache.commons.logging.LogFactory;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public class ServletContextCleaner
/* */ implements ServletContextListener
/* */ {
/* 52 */ private static final Class[] RELEASE_SIGNATURE = new Class[] { ClassLoader.class };
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public void contextDestroyed(ServletContextEvent sce) {
/* 60 */ ClassLoader tccl = Thread.currentThread().getContextClassLoader();
/* */
/* 62 */ Object[] params = new Object[1];
/* 63 */ params[0] = tccl;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* 95 */ ClassLoader loader = tccl;
/* 96 */ while (loader != null) {
/* */
/* */
/* */ try {
/* */
/* 101 */ Class logFactoryClass = loader.loadClass("org.apache.commons.logging.LogFactory");
/* 102 */ Method releaseMethod = logFactoryClass.getMethod("release", RELEASE_SIGNATURE);
/* 103 */ releaseMethod.invoke(null, params);
/* 104 */ loader = logFactoryClass.getClassLoader().getParent();
/* 105 */ } catch (ClassNotFoundException ex) {
/* */
/* */
/* 108 */ loader = null;
/* 109 */ } catch (NoSuchMethodException ex) {
/* */
/* 111 */ System.err.println("LogFactory instance found which does not support release method!");
/* 112 */ loader = null;
/* 113 */ } catch (IllegalAccessException ex) {
/* */
/* 115 */ System.err.println("LogFactory instance found which is not accessable!");
/* 116 */ loader = null;
/* 117 */ } catch (InvocationTargetException ex) {
/* */
/* 119 */ System.err.println("LogFactory instance release method failed!");
/* 120 */ loader = null;
/* */ }
/* */ }
/* */
/* */
/* */
/* */
/* 127 */ LogFactory.release(tccl);
/* */ }
/* */
/* */ public void contextInitialized(ServletContextEvent sce) {}
/* */ }
/* Location: /mnt/r/ConTenDoViewer.jar!/org/apache/commons/logging/impl/ServletContextCleaner.class
* Java compiler version: 2 (46.0)
* JD-Core Version: 1.1.3
*/ |
9237af11fc404760a8dcf209ecc09360275d1698 | 2,882 | java | Java | src/fr/loicdelorme/followUpYourGarden/core/models/Position.java | LoicDelorme/followUpYourGarden | 5f9268d44db42afedfbbe5f85538c82d36c3b878 | [
"MIT"
] | null | null | null | src/fr/loicdelorme/followUpYourGarden/core/models/Position.java | LoicDelorme/followUpYourGarden | 5f9268d44db42afedfbbe5f85538c82d36c3b878 | [
"MIT"
] | null | null | null | src/fr/loicdelorme/followUpYourGarden/core/models/Position.java | LoicDelorme/followUpYourGarden | 5f9268d44db42afedfbbe5f85538c82d36c3b878 | [
"MIT"
] | null | null | null | 17.053254 | 153 | 0.571478 | 998,162 | package fr.loicdelorme.followUpYourGarden.core.models;
/**
* This class allow you to create a two dimensional position.
*
* @author DELORME Loïc
* @version 1.0.0
*/
public class Position implements Comparable<Position>
{
/**
* The X coordinate.
*/
private final int x;
/**
* The Y coordinate.
*/
private final int y;
/**
* The group of plants id.
*/
private final int groupOfPlantsId;
/**
* Create a two dimensional position.
*
* @param x
* A X coordinate.
* @param y
* A Y coordinate.
* @param groupOfPlantsId
* A group of plants id.
*/
public Position(int x, int y, int groupOfPlantsId)
{
this.x = x;
this.y = y;
this.groupOfPlantsId = groupOfPlantsId;
}
/**
* Test if two positions have same coordinates.
*
* @param x
* The X coordinate.
* @param y
* The Y coordinate.
*
* @return True if they have the same coordinates, else False.
*/
public boolean areCoordinatesEquals(int x, int y)
{
return ((this.x == x) && (this.y == y));
}
/**
* Get the X coordinate.
*
* @return The X coordinate.
*/
public int getX()
{
return this.x;
}
/**
* Get the Y coordinate.
*
* @return The Y coordinate.
*/
public int getY()
{
return this.y;
}
/**
* Get the group of plants id.
*
* @return The group of plants id.
*/
public int getGroupOfPlantsId()
{
return this.groupOfPlantsId;
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
StringBuilder representation = new StringBuilder();
representation.append("{X : ").append(this.x).append(", Y : ").append(this.y).append(", groupOfPlantsId : ").append(this.groupOfPlantsId).append("}");
return representation.toString();
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object object)
{
if (this == object)
{
return true;
}
if (object == null)
{
return false;
}
if (!(object instanceof Position))
{
return false;
}
Position position = (Position) object;
if (this.x != position.x)
{
return false;
}
if (this.y != position.y)
{
return false;
}
if (this.groupOfPlantsId != position.groupOfPlantsId)
{
return false;
}
return true;
}
/**
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode()
{
return (this.x + this.y + this.groupOfPlantsId);
}
/**
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
@Override
public int compareTo(Position position)
{
int result = this.x - position.x;
if (result != 0)
{
return result;
}
result = this.y - position.y;
return result;
}
}
|
9237af8b37f7f2eaf5393ba31dadab248a85acee | 1,801 | java | Java | code/iaas/model/src/main/java/io/cattle/platform/core/dao/impl/GenericResourceDaoImpl.java | mbrukman/rancher-cattle | ac7caffb97346f601043458411391d2d00fd6129 | [
"Apache-2.0"
] | null | null | null | code/iaas/model/src/main/java/io/cattle/platform/core/dao/impl/GenericResourceDaoImpl.java | mbrukman/rancher-cattle | ac7caffb97346f601043458411391d2d00fd6129 | [
"Apache-2.0"
] | null | null | null | code/iaas/model/src/main/java/io/cattle/platform/core/dao/impl/GenericResourceDaoImpl.java | mbrukman/rancher-cattle | ac7caffb97346f601043458411391d2d00fd6129 | [
"Apache-2.0"
] | null | null | null | 30.525424 | 93 | 0.732926 | 998,163 | package io.cattle.platform.core.dao.impl;
import java.util.Map;
import javax.inject.Inject;
import io.cattle.platform.core.dao.GenericResourceDao;
import io.cattle.platform.object.ObjectManager;
import io.cattle.platform.object.process.ObjectProcessManager;
import io.cattle.platform.object.process.StandardProcess;
import io.cattle.platform.util.type.CollectionUtils;
public class GenericResourceDaoImpl implements GenericResourceDao {
ObjectManager objectManager;
ObjectProcessManager processManager;
@Override
public <T> T createAndSchedule(Class<T> clz, Map<String, Object> properties) {
T obj = objectManager.create(clz, properties);
processManager.scheduleStandardProcess(StandardProcess.CREATE, obj, properties);
return objectManager.reload(obj);
}
@Override
public <T> T createAndSchedule(Class<T> clz, Object key, Object... values) {
Map<Object,Object> properties = CollectionUtils.asMap(key, values);
return createAndSchedule(clz, objectManager.convertToPropertiesFor(clz, properties));
}
@Override
public <T> T create(Class<T> clz, Map<String, Object> properties) {
T obj = objectManager.create(clz, properties);
processManager.executeStandardProcess(StandardProcess.CREATE, obj, properties);
return objectManager.reload(obj);
}
public ObjectProcessManager getProcessManager() {
return processManager;
}
@Inject
public void setProcessManager(ObjectProcessManager processManager) {
this.processManager = processManager;
}
public ObjectManager getObjectManager() {
return objectManager;
}
@Inject
public void setObjectManager(ObjectManager objectManager) {
this.objectManager = objectManager;
}
}
|
9237b06c0d341c605aac0f723dfa0ba1d9e5f926 | 1,000 | java | Java | src/jdbc/com/java_zdd/jdbc/chapter03/sec03/Demo1.java | 916552375/Nikolas | 386caea1938c6134317728b232d9b766d4e298c6 | [
"Unlicense"
] | null | null | null | src/jdbc/com/java_zdd/jdbc/chapter03/sec03/Demo1.java | 916552375/Nikolas | 386caea1938c6134317728b232d9b766d4e298c6 | [
"Unlicense"
] | null | null | null | src/jdbc/com/java_zdd/jdbc/chapter03/sec03/Demo1.java | 916552375/Nikolas | 386caea1938c6134317728b232d9b766d4e298c6 | [
"Unlicense"
] | null | null | null | 31.25 | 109 | 0.637 | 998,164 | package jdbc.com.java_zdd.jdbc.chapter03.sec03;
import jdbc.model.Book;
import jdbc.com.java_zdd.jdbc.util.DbUtil;
import java.sql.Connection;
import java.sql.Statement;
public class Demo1 {
private static DbUtil dbUtil = new DbUtil();
private static int updateBook(Book book) throws Exception {
Connection conn = dbUtil.getConn();
String sql = "update t_book set bookName= " + "'" + book.getBookName() + "',price=" + book.getPrice()
+",bookTypeId=" + book.getBookTypeId() + " where id=" + book.getId() + ";";
Statement stmt = conn.createStatement();
System.out.println("使用的sql脚本如下:");
System.out.println(sql);
int result = stmt.executeUpdate(sql);
dbUtil.close(stmt, conn);
return result;
}
public static void main(String[] args) throws Exception{
Book book = new Book(26,"神话程序猿大牛蛋","牛蛋哥","男",1024.6f,"男",16);
int result = updateBook(book);
System.out.println(result);
}
}
|
9237b0e77328b0a002ed491777a26e26a8406cc8 | 2,255 | java | Java | app/src/main/java/com/webkul/mobikul/mobikulstandalonepos/fragment/CashDrawerHistoryFragment.java | maxAman/mobikul-standalone-pos-opensource | 263584f6031d149f3dcd2072243c493aaef7d9de | [
"MIT"
] | 27 | 2018-10-12T10:37:02.000Z | 2022-02-24T09:53:48.000Z | app/src/main/java/com/webkul/mobikul/mobikulstandalonepos/fragment/CashDrawerHistoryFragment.java | maxAman/mobikul-standalone-pos-opensource | 263584f6031d149f3dcd2072243c493aaef7d9de | [
"MIT"
] | 2 | 2020-02-07T09:20:31.000Z | 2020-09-22T16:11:56.000Z | app/src/main/java/com/webkul/mobikul/mobikulstandalonepos/fragment/CashDrawerHistoryFragment.java | maxAman/mobikul-standalone-pos-opensource | 263584f6031d149f3dcd2072243c493aaef7d9de | [
"MIT"
] | 38 | 2018-10-10T11:05:26.000Z | 2022-03-03T08:13:19.000Z | 34.692308 | 146 | 0.75122 | 998,165 | package com.webkul.mobikul.mobikulstandalonepos.fragment;
import android.content.Context;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.webkul.mobikul.mobikulstandalonepos.R;
import com.webkul.mobikul.mobikulstandalonepos.adapter.CashDrawerHistoryAdapter;
import com.webkul.mobikul.mobikulstandalonepos.databinding.FragmentCashDrawerHistoryBinding;
import com.webkul.mobikul.mobikulstandalonepos.db.entity.CashDrawerModel;
public class CashDrawerHistoryFragment extends Fragment {
private static final String ARG_PARAM1 = "cashDrawerModelData";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private CashDrawerModel cashDrawerModelData;
private String mParam2;
FragmentCashDrawerHistoryBinding binding;
public CashDrawerHistoryFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
cashDrawerModelData = (CashDrawerModel) getArguments().getSerializable(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_cash_drawer_history, container, false);
return binding.getRoot();
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
binding.setData(cashDrawerModelData);
CashDrawerHistoryAdapter cashDrawerHistoryAdapter = new CashDrawerHistoryAdapter(getActivity(), cashDrawerModelData.getCashDrawerItems());
binding.cashDrawerHistoryRv.setAdapter(cashDrawerHistoryAdapter);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public void onDetach() {
super.onDetach();
}
}
|
9237b0f662adfb9d0f20901fff977ca6122ffcbf | 1,928 | java | Java | src/test/java/com/zejian/structures/Graph/WeightGraph/UnionFind.java | 4017147/DataStructuresAndAlgorithms. | 61109217a270d3a54abe48b7cffb35f0442947d7 | [
"Apache-2.0"
] | 1 | 2020-12-26T04:52:15.000Z | 2020-12-26T04:52:15.000Z | src/test/java/com/zejian/structures/Graph/WeightGraph/UnionFind.java | 4017147/DataStructuresAndAlgorithms. | 61109217a270d3a54abe48b7cffb35f0442947d7 | [
"Apache-2.0"
] | 1 | 2020-12-26T04:57:19.000Z | 2020-12-26T04:57:19.000Z | src/test/java/com/zejian/structures/Graph/WeightGraph/UnionFind.java | 4017147/DataStructuresAndAlgorithms. | 61109217a270d3a54abe48b7cffb35f0442947d7 | [
"Apache-2.0"
] | 1 | 2021-12-06T01:13:18.000Z | 2021-12-06T01:13:18.000Z | 22.418605 | 54 | 0.50778 | 998,166 | package com.zejian.structures.Graph.WeightGraph;
/**
* Created by zejian on 2018/1/30.
* Blog : http://blog.csdn.net/javazejian [原文地址,请尊重原创]
* 并查集,路径压缩 UF
* 主要用于判断是否形成环
*/
public class UnionFind {
private int rank[]; // rank[i]表示以i为根的集合所表示的树的层数
private int parent[];// parent[i]表示第i个元素所指向的父节点
private int count; // 数据个数
public UnionFind(int count){
assert count > 0;
this.count = count;
rank = new int[count];
parent = new int[count];
//初始化所有结点的父结点都指向自己;
for (int i = 0; i <count ; i++) {
parent[i] = i;
rank[i] = 1;
}
}
/**
* 查找某个结点的根结点
* 时间复杂父为O(h) h为树的高度
* @param p
* @return
*/
private int findRoot(int p){
assert( p >= 0 && p < count );
while(p != parent[p]) {
//尝试进行路径压缩
//把p的父结点修改为parent[p]的父结点,从而进行路径压缩
parent[p] = parent[parent[p]];
//p 赋值为 现在的父结点parent[p],进行下一轮循环
p = parent[p];
}
return p;
}
/**
* 判断两个结点是否相连
* 或者查看元素p和元素q是否所属一个集合
* O(h)复杂度, h为树的高度
* @param p
* @param q
* @return
*/
public boolean isConnected(int p , int q){
return findRoot(p) == findRoot(q);
}
/**
* 合并元素p和元素q所属的集合, O(h)复杂度, h为树的高度
* @param p
* @param q
*/
public void unionElements(int p, int q){
int pRoot = findRoot(p);
int qRoot = findRoot(q);
//如果根结点相同说明已关联
if (pRoot == qRoot) return;
//如果pRoot的树层数小于qRoot层数,为了路径更短,将pRoot挂到qRoot树下
if(rank[pRoot] < rank[qRoot]){
parent[pRoot] = qRoot;
}else if(rank[pRoot] > rank[qRoot]){
parent[qRoot] = pRoot;
}else {
// rank[pRoot] == rank[qRoot]
//如果根结点层数相同,随机选择一个并入即可但要更新rank
parent[qRoot] = pRoot;
rank[qRoot]++;
}
}
}
|
9237b279dad4d9ed76d9bce450896dd52215068d | 2,095 | java | Java | UserCPCSI/src/fr/imie/usercpsci/presentation/UserSessionPopulateListener.java | imie-source/CPCSI-N-01-SHARE | 2601cd042977bbe684b230b2540f378f7b03ca20 | [
"MIT"
] | 1 | 2017-09-19T17:46:06.000Z | 2017-09-19T17:46:06.000Z | UserCPCSI/src/fr/imie/usercpsci/presentation/UserSessionPopulateListener.java | imie-source/CPCSI-N-01-SHARE | 2601cd042977bbe684b230b2540f378f7b03ca20 | [
"MIT"
] | null | null | null | UserCPCSI/src/fr/imie/usercpsci/presentation/UserSessionPopulateListener.java | imie-source/CPCSI-N-01-SHARE | 2601cd042977bbe684b230b2540f378f7b03ca20 | [
"MIT"
] | null | null | null | 29.928571 | 74 | 0.663007 | 998,167 | package fr.imie.usercpsci.presentation;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import fr.imie.usercpsci.model.Faction;
import fr.imie.usercpsci.model.UserData;
/**
* Application Lifecycle Listener implementation class UserSessionPopulate
*
*/
@WebListener
public class UserSessionPopulateListener implements HttpSessionListener {
/**
* Default constructor.
*/
public UserSessionPopulateListener() {
// TODO Auto-generated constructor stub
}
/**
* @see HttpSessionListener#sessionCreated(HttpSessionEvent)
*/
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
UserData userData1 = new UserData();
userData1.setNom("Kent");
userData1.setPrenom("Clark");
userData1.setPassw("superman");
userData1.setFaction(Faction.gentil);
UserData userData2 = new UserData();
userData2.setNom("Wayne");
userData2.setPrenom("Bruce");
userData2.setPassw("batman");
userData2.setFaction(Faction.gentil);
UserData userData3 = new UserData();
userData3.setNom("Parker");
userData3.setPrenom("Peter");
userData3.setPassw("spiderman");
userData3.setFaction(Faction.gentil);
UserData userData4 = new UserData();
userData4.setNom("Dent");
userData4.setPrenom("Harvey");
userData4.setPassw("doubleface");
userData4.setFaction(Faction.mechant);
List<UserData> users = new ArrayList<UserData>();
users.add(userData1);
users.add(userData2);
users.add(userData3);
users.add(userData4);
httpSessionEvent.getSession().setAttribute("users", users);
}
/**
* @see HttpSessionListener#sessionDestroyed(HttpSessionEvent)
*/
public void sessionDestroyed(HttpSessionEvent arg0) {
// TODO Auto-generated method stub
}
}
|
9237b29eef7b5776d258de2b828d4f6da06e4e50 | 153,291 | java | Java | src/main/java/com/oracle/truffle/js/builtins/ArrayPrototypeBuiltins.java | pitbox46/graaljs-forge | 369d305ed531f66653b4bf2ce881483639401707 | [
"UPL-1.0"
] | null | null | null | src/main/java/com/oracle/truffle/js/builtins/ArrayPrototypeBuiltins.java | pitbox46/graaljs-forge | 369d305ed531f66653b4bf2ce881483639401707 | [
"UPL-1.0"
] | null | null | null | src/main/java/com/oracle/truffle/js/builtins/ArrayPrototypeBuiltins.java | pitbox46/graaljs-forge | 369d305ed531f66653b4bf2ce881483639401707 | [
"UPL-1.0"
] | null | null | null | 47.218115 | 196 | 0.626046 | 998,168 | /*
* Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* The Universal Permissive License (UPL), Version 1.0
*
* Subject to the condition set forth below, permission is hereby granted to any
* person obtaining a copy of this software, associated documentation and/or
* data (collectively the "Software"), free of charge and under any and all
* copyright rights in the Software, and any and all patent rights owned or
* freely licensable by each licensor hereunder covering either (i) the
* unmodified Software as contributed to or provided by such licensor, or (ii)
* the Larger Works (as defined below), to deal in both
*
* (a) the Software, and
*
* (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
* one is included with the Software each a "Larger Work" to which the Software
* is contributed by such licensors),
*
* without restriction, including without limitation the rights to copy, create
* derivative works of, display, perform, and distribute the Software and make,
* use, sell, offer for sale, import, export, have made, and have sold the
* Software and the Larger Work(s), and to sublicense the foregoing rights on
* either these or other terms.
*
* This license is subject to the following condition:
*
* The above copyright notice and either this complete permission notice or at a
* minimum a reference to the UPL must be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.oracle.truffle.js.builtins;
import static com.oracle.truffle.js.runtime.builtins.JSAbstractArray.arrayGetArrayType;
import static com.oracle.truffle.js.runtime.builtins.JSAbstractArray.arrayGetLength;
import static com.oracle.truffle.js.runtime.builtins.JSAbstractArray.arraySetArrayType;
import static com.oracle.truffle.js.runtime.builtins.JSArrayBufferView.typedArrayGetLength;
import java.util.Arrays;
import java.util.Comparator;
import java.util.EnumSet;
import com.oracle.truffle.api.CompilerDirectives;
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
import com.oracle.truffle.api.Truffle;
import com.oracle.truffle.api.TruffleSafepoint;
import com.oracle.truffle.api.dsl.Cached;
import com.oracle.truffle.api.dsl.Cached.Shared;
import com.oracle.truffle.api.dsl.ImportStatic;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.exception.AbstractTruffleException;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.interop.ExceptionType;
import com.oracle.truffle.api.interop.InteropException;
import com.oracle.truffle.api.interop.InteropLibrary;
import com.oracle.truffle.api.interop.InvalidArrayIndexException;
import com.oracle.truffle.api.interop.UnsupportedMessageException;
import com.oracle.truffle.api.interop.UnsupportedTypeException;
import com.oracle.truffle.api.library.CachedLibrary;
import com.oracle.truffle.api.nodes.DirectCallNode;
import com.oracle.truffle.api.nodes.LoopNode;
import com.oracle.truffle.api.nodes.Node;
import com.oracle.truffle.api.nodes.SlowPathException;
import com.oracle.truffle.api.nodes.UnexpectedResultException;
import com.oracle.truffle.api.object.DynamicObject;
import com.oracle.truffle.api.profiles.BranchProfile;
import com.oracle.truffle.api.profiles.ConditionProfile;
import com.oracle.truffle.api.profiles.ValueProfile;
import com.oracle.truffle.js.builtins.ArrayPrototypeBuiltinsFactory.DeleteAndSetLengthNodeGen;
import com.oracle.truffle.js.builtins.ArrayPrototypeBuiltinsFactory.FlattenIntoArrayNodeGen;
import com.oracle.truffle.js.builtins.ArrayPrototypeBuiltinsFactory.JSArrayAtNodeGen;
import com.oracle.truffle.js.builtins.ArrayPrototypeBuiltinsFactory.JSArrayConcatNodeGen;
import com.oracle.truffle.js.builtins.ArrayPrototypeBuiltinsFactory.JSArrayCopyWithinNodeGen;
import com.oracle.truffle.js.builtins.ArrayPrototypeBuiltinsFactory.JSArrayEveryNodeGen;
import com.oracle.truffle.js.builtins.ArrayPrototypeBuiltinsFactory.JSArrayFillNodeGen;
import com.oracle.truffle.js.builtins.ArrayPrototypeBuiltinsFactory.JSArrayFilterNodeGen;
import com.oracle.truffle.js.builtins.ArrayPrototypeBuiltinsFactory.JSArrayFindIndexNodeGen;
import com.oracle.truffle.js.builtins.ArrayPrototypeBuiltinsFactory.JSArrayFindNodeGen;
import com.oracle.truffle.js.builtins.ArrayPrototypeBuiltinsFactory.JSArrayFlatMapNodeGen;
import com.oracle.truffle.js.builtins.ArrayPrototypeBuiltinsFactory.JSArrayFlatNodeGen;
import com.oracle.truffle.js.builtins.ArrayPrototypeBuiltinsFactory.JSArrayForEachNodeGen;
import com.oracle.truffle.js.builtins.ArrayPrototypeBuiltinsFactory.JSArrayIncludesNodeGen;
import com.oracle.truffle.js.builtins.ArrayPrototypeBuiltinsFactory.JSArrayIndexOfNodeGen;
import com.oracle.truffle.js.builtins.ArrayPrototypeBuiltinsFactory.JSArrayIteratorNodeGen;
import com.oracle.truffle.js.builtins.ArrayPrototypeBuiltinsFactory.JSArrayJoinNodeGen;
import com.oracle.truffle.js.builtins.ArrayPrototypeBuiltinsFactory.JSArrayMapNodeGen;
import com.oracle.truffle.js.builtins.ArrayPrototypeBuiltinsFactory.JSArrayPopNodeGen;
import com.oracle.truffle.js.builtins.ArrayPrototypeBuiltinsFactory.JSArrayPushNodeGen;
import com.oracle.truffle.js.builtins.ArrayPrototypeBuiltinsFactory.JSArrayReduceNodeGen;
import com.oracle.truffle.js.builtins.ArrayPrototypeBuiltinsFactory.JSArrayReverseNodeGen;
import com.oracle.truffle.js.builtins.ArrayPrototypeBuiltinsFactory.JSArrayShiftNodeGen;
import com.oracle.truffle.js.builtins.ArrayPrototypeBuiltinsFactory.JSArraySliceNodeGen;
import com.oracle.truffle.js.builtins.ArrayPrototypeBuiltinsFactory.JSArraySomeNodeGen;
import com.oracle.truffle.js.builtins.ArrayPrototypeBuiltinsFactory.JSArraySortNodeGen;
import com.oracle.truffle.js.builtins.ArrayPrototypeBuiltinsFactory.JSArraySpliceNodeGen;
import com.oracle.truffle.js.builtins.ArrayPrototypeBuiltinsFactory.JSArrayToLocaleStringNodeGen;
import com.oracle.truffle.js.builtins.ArrayPrototypeBuiltinsFactory.JSArrayToStringNodeGen;
import com.oracle.truffle.js.builtins.ArrayPrototypeBuiltinsFactory.JSArrayUnshiftNodeGen;
import com.oracle.truffle.js.nodes.JSGuards;
import com.oracle.truffle.js.nodes.JSNodeUtil;
import com.oracle.truffle.js.nodes.JavaScriptBaseNode;
import com.oracle.truffle.js.nodes.access.CreateObjectNode;
import com.oracle.truffle.js.nodes.access.ForEachIndexCallNode;
import com.oracle.truffle.js.nodes.access.ForEachIndexCallNode.CallbackNode;
import com.oracle.truffle.js.nodes.access.ForEachIndexCallNode.MaybeResult;
import com.oracle.truffle.js.nodes.access.ForEachIndexCallNode.MaybeResultNode;
import com.oracle.truffle.js.nodes.access.GetPrototypeNode;
import com.oracle.truffle.js.nodes.access.IsArrayNode;
import com.oracle.truffle.js.nodes.access.JSHasPropertyNode;
import com.oracle.truffle.js.nodes.access.PropertyGetNode;
import com.oracle.truffle.js.nodes.access.PropertyNode;
import com.oracle.truffle.js.nodes.access.PropertySetNode;
import com.oracle.truffle.js.nodes.access.ReadElementNode;
import com.oracle.truffle.js.nodes.access.WriteElementNode;
import com.oracle.truffle.js.nodes.access.WritePropertyNode;
import com.oracle.truffle.js.nodes.array.ArrayCreateNode;
import com.oracle.truffle.js.nodes.array.ArrayLengthNode.ArrayLengthWriteNode;
import com.oracle.truffle.js.nodes.array.JSArrayDeleteRangeNode;
import com.oracle.truffle.js.nodes.array.JSArrayFirstElementIndexNode;
import com.oracle.truffle.js.nodes.array.JSArrayLastElementIndexNode;
import com.oracle.truffle.js.nodes.array.JSArrayNextElementIndexNode;
import com.oracle.truffle.js.nodes.array.JSArrayPreviousElementIndexNode;
import com.oracle.truffle.js.nodes.array.JSArrayToDenseObjectArrayNode;
import com.oracle.truffle.js.nodes.array.JSGetLengthNode;
import com.oracle.truffle.js.nodes.array.JSSetLengthNode;
import com.oracle.truffle.js.nodes.array.TestArrayNode;
import com.oracle.truffle.js.nodes.binary.JSIdenticalNode;
import com.oracle.truffle.js.nodes.cast.JSToBooleanNode;
import com.oracle.truffle.js.nodes.cast.JSToIntegerAsIntNode;
import com.oracle.truffle.js.nodes.cast.JSToIntegerAsLongNode;
import com.oracle.truffle.js.nodes.cast.JSToObjectNode;
import com.oracle.truffle.js.nodes.cast.JSToStringNode;
import com.oracle.truffle.js.nodes.control.DeletePropertyNode;
import com.oracle.truffle.js.nodes.function.JSBuiltin;
import com.oracle.truffle.js.nodes.function.JSBuiltinNode;
import com.oracle.truffle.js.nodes.function.JSFunctionCallNode;
import com.oracle.truffle.js.nodes.interop.ForeignObjectPrototypeNode;
import com.oracle.truffle.js.nodes.interop.ImportValueNode;
import com.oracle.truffle.js.nodes.unary.IsCallableNode;
import com.oracle.truffle.js.nodes.unary.IsConstructorNode;
import com.oracle.truffle.js.nodes.unary.JSIsArrayNode;
import com.oracle.truffle.js.runtime.Boundaries;
import com.oracle.truffle.js.runtime.Errors;
import com.oracle.truffle.js.runtime.JSArguments;
import com.oracle.truffle.js.runtime.JSConfig;
import com.oracle.truffle.js.runtime.JSContext;
import com.oracle.truffle.js.runtime.JSRealm;
import com.oracle.truffle.js.runtime.JSRuntime;
import com.oracle.truffle.js.runtime.JavaScriptRootNode;
import com.oracle.truffle.js.runtime.Symbol;
import com.oracle.truffle.js.runtime.array.ScriptArray;
import com.oracle.truffle.js.runtime.array.SparseArray;
import com.oracle.truffle.js.runtime.array.TypedArray;
import com.oracle.truffle.js.runtime.array.dyn.AbstractDoubleArray;
import com.oracle.truffle.js.runtime.array.dyn.AbstractIntArray;
import com.oracle.truffle.js.runtime.array.dyn.ConstantByteArray;
import com.oracle.truffle.js.runtime.array.dyn.ConstantDoubleArray;
import com.oracle.truffle.js.runtime.array.dyn.ConstantIntArray;
import com.oracle.truffle.js.runtime.builtins.BuiltinEnum;
import com.oracle.truffle.js.runtime.builtins.JSArray;
import com.oracle.truffle.js.runtime.builtins.JSArrayBuffer;
import com.oracle.truffle.js.runtime.builtins.JSArrayBufferView;
import com.oracle.truffle.js.runtime.builtins.JSArrayObject;
import com.oracle.truffle.js.runtime.builtins.JSFunction;
import com.oracle.truffle.js.runtime.builtins.JSFunctionData;
import com.oracle.truffle.js.runtime.builtins.JSProxy;
import com.oracle.truffle.js.runtime.builtins.JSSlowArray;
import com.oracle.truffle.js.runtime.builtins.JSTypedArrayObject;
import com.oracle.truffle.js.runtime.interop.JSInteropUtil;
import com.oracle.truffle.js.runtime.objects.JSDynamicObject;
import com.oracle.truffle.js.runtime.objects.JSObject;
import com.oracle.truffle.js.runtime.objects.Null;
import com.oracle.truffle.js.runtime.objects.Undefined;
import com.oracle.truffle.js.runtime.util.Pair;
import com.oracle.truffle.js.runtime.util.SimpleArrayList;
import com.oracle.truffle.js.runtime.util.StringBuilderProfile;
/**
* Contains builtins for {@linkplain JSArray}.prototype.
*/
public final class ArrayPrototypeBuiltins extends JSBuiltinsContainer.SwitchEnum<ArrayPrototypeBuiltins.ArrayPrototype> {
public static final JSBuiltinsContainer BUILTINS = new ArrayPrototypeBuiltins();
protected ArrayPrototypeBuiltins() {
super(JSArray.PROTOTYPE_NAME, ArrayPrototype.class);
}
public enum ArrayPrototype implements BuiltinEnum<ArrayPrototype> {
push(1),
pop(0),
slice(2),
shift(0),
unshift(1),
toString(0),
concat(1),
indexOf(1),
lastIndexOf(1),
join(1),
toLocaleString(0),
splice(2),
every(1),
filter(1),
forEach(1),
some(1),
map(1),
sort(1),
reduce(1),
reduceRight(1),
reverse(0),
// ES6 / ES2015
find(1),
findIndex(1),
fill(1),
copyWithin(2),
keys(0),
values(0),
entries(0),
// ES2016
includes(1),
// ES2019
flat(0),
flatMap(1),
// ES2022
at(1);
private final int length;
ArrayPrototype(int length) {
this.length = length;
}
@Override
public int getLength() {
return length;
}
@Override
public int getECMAScriptVersion() {
if (EnumSet.of(find, findIndex, fill, copyWithin, keys, values, entries).contains(this)) {
return JSConfig.ECMAScript2015;
} else if (this == includes) {
return JSConfig.ECMAScript2016;
} else if (EnumSet.of(flat, flatMap).contains(this)) {
return JSConfig.ECMAScript2019;
} else if (this == at) {
return JSConfig.ECMAScript2022;
}
return BuiltinEnum.super.getECMAScriptVersion();
}
}
@Override
protected Object createNode(JSContext context, JSBuiltin builtin, boolean construct, boolean newTarget, ArrayPrototype builtinEnum) {
switch (builtinEnum) {
case push:
return JSArrayPushNodeGen.create(context, builtin, args().withThis().varArgs().createArgumentNodes(context));
case pop:
return JSArrayPopNodeGen.create(context, builtin, args().withThis().createArgumentNodes(context));
case slice:
return JSArraySliceNodeGen.create(context, builtin, false, args().withThis().fixedArgs(2).createArgumentNodes(context));
case shift:
return JSArrayShiftNodeGen.create(context, builtin, args().withThis().createArgumentNodes(context));
case unshift:
return JSArrayUnshiftNodeGen.create(context, builtin, args().withThis().varArgs().createArgumentNodes(context));
case toString:
return JSArrayToStringNodeGen.create(context, builtin, args().withThis().createArgumentNodes(context));
case concat:
return JSArrayConcatNodeGen.create(context, builtin, args().withThis().varArgs().createArgumentNodes(context));
case indexOf:
return JSArrayIndexOfNodeGen.create(context, builtin, false, true, args().withThis().varArgs().createArgumentNodes(context));
case lastIndexOf:
return JSArrayIndexOfNodeGen.create(context, builtin, false, false, args().withThis().varArgs().createArgumentNodes(context));
case join:
return JSArrayJoinNodeGen.create(context, builtin, false, args().withThis().fixedArgs(1).createArgumentNodes(context));
case toLocaleString:
return JSArrayToLocaleStringNodeGen.create(context, builtin, false, args().withThis().createArgumentNodes(context));
case splice:
return JSArraySpliceNodeGen.create(context, builtin, args().withThis().varArgs().createArgumentNodes(context));
case every:
return JSArrayEveryNodeGen.create(context, builtin, false, args().withThis().fixedArgs(2).createArgumentNodes(context));
case filter:
return JSArrayFilterNodeGen.create(context, builtin, false, args().withThis().fixedArgs(2).createArgumentNodes(context));
case forEach:
return JSArrayForEachNodeGen.create(context, builtin, args().withThis().fixedArgs(2).createArgumentNodes(context));
case some:
return JSArraySomeNodeGen.create(context, builtin, false, args().withThis().fixedArgs(2).createArgumentNodes(context));
case map:
return JSArrayMapNodeGen.create(context, builtin, false, args().withThis().fixedArgs(2).createArgumentNodes(context));
case sort:
return JSArraySortNodeGen.create(context, builtin, false, args().withThis().fixedArgs(1).createArgumentNodes(context));
case reduce:
return JSArrayReduceNodeGen.create(context, builtin, false, true, args().withThis().fixedArgs(1).varArgs().createArgumentNodes(context));
case reduceRight:
return JSArrayReduceNodeGen.create(context, builtin, false, false, args().withThis().fixedArgs(1).varArgs().createArgumentNodes(context));
case reverse:
return JSArrayReverseNodeGen.create(context, builtin, args().withThis().createArgumentNodes(context));
case find:
return JSArrayFindNodeGen.create(context, builtin, false, args().withThis().fixedArgs(2).createArgumentNodes(context));
case findIndex:
return JSArrayFindIndexNodeGen.create(context, builtin, false, args().withThis().fixedArgs(2).createArgumentNodes(context));
case fill:
return JSArrayFillNodeGen.create(context, builtin, false, args().withThis().fixedArgs(3).createArgumentNodes(context));
case copyWithin:
return JSArrayCopyWithinNodeGen.create(context, builtin, false, args().withThis().fixedArgs(3).createArgumentNodes(context));
case keys:
return JSArrayIteratorNodeGen.create(context, builtin, JSRuntime.ITERATION_KIND_KEY, args().withThis().createArgumentNodes(context));
case values:
return JSArrayIteratorNodeGen.create(context, builtin, JSRuntime.ITERATION_KIND_VALUE, args().withThis().createArgumentNodes(context));
case entries:
return JSArrayIteratorNodeGen.create(context, builtin, JSRuntime.ITERATION_KIND_KEY_PLUS_VALUE, args().withThis().createArgumentNodes(context));
case includes:
return JSArrayIncludesNodeGen.create(context, builtin, false, args().withThis().fixedArgs(2).createArgumentNodes(context));
case flatMap:
return JSArrayFlatMapNodeGen.create(context, builtin, args().withThis().fixedArgs(2).createArgumentNodes(context));
case flat:
return JSArrayFlatNodeGen.create(context, builtin, args().withThis().fixedArgs(3).createArgumentNodes(context));
case at:
return JSArrayAtNodeGen.create(context, builtin, false, args().withThis().fixedArgs(1).createArgumentNodes(context));
}
return null;
}
public abstract static class BasicArrayOperation extends JSBuiltinNode {
protected final boolean isTypedArrayImplementation; // for reusing array code on TypedArrays
@Child private JSToObjectNode toObjectNode;
@Child private JSGetLengthNode getLengthNode;
@Child private ArraySpeciesConstructorNode arraySpeciesCreateNode;
@Child private IsCallableNode isCallableNode;
protected final BranchProfile errorBranch = BranchProfile.create();
public BasicArrayOperation(JSContext context, JSBuiltin builtin, boolean isTypedArrayImplementation) {
super(context, builtin);
this.isTypedArrayImplementation = isTypedArrayImplementation;
}
public BasicArrayOperation(JSContext context, JSBuiltin builtin) {
this(context, builtin, false);
}
protected final Object toObject(Object target) {
if (toObjectNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
toObjectNode = insert(JSToObjectNode.createToObject(getContext()));
}
return toObjectNode.execute(target);
}
protected long getLength(Object thisObject) {
if (isTypedArrayImplementation) {
// %TypedArray%.prototype.* don't access the "length" property
return typedArrayGetLength((JSTypedArrayObject) thisObject);
} else {
if (getLengthNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
getLengthNode = insert(JSGetLengthNode.create(getContext()));
}
return getLengthNode.executeLong(thisObject);
}
}
protected final Object toObjectOrValidateTypedArray(Object thisObj) {
return isTypedArrayImplementation ? validateTypedArray(thisObj) : toObject(thisObj);
}
protected final boolean isCallable(Object callback) {
if (isCallableNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
isCallableNode = insert(IsCallableNode.create());
}
return isCallableNode.executeBoolean(callback);
}
protected final Object checkCallbackIsFunction(Object callback) {
if (!isCallable(callback)) {
errorBranch.enter();
throw Errors.createTypeErrorNotAFunction(callback, this);
}
return callback;
}
protected final ArraySpeciesConstructorNode getArraySpeciesConstructorNode() {
if (arraySpeciesCreateNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
arraySpeciesCreateNode = insert(ArraySpeciesConstructorNode.create(getContext(), isTypedArrayImplementation));
}
return arraySpeciesCreateNode;
}
protected final void checkHasDetachedBuffer(DynamicObject view) {
if (JSArrayBufferView.hasDetachedBuffer(view, getContext())) {
errorBranch.enter();
throw Errors.createTypeErrorDetachedBuffer();
}
}
/**
* ES2016, 192.168.127.12.1 ValidateTypedArray(O).
*/
protected final JSTypedArrayObject validateTypedArray(Object obj) {
if (!JSArrayBufferView.isJSArrayBufferView(obj)) {
errorBranch.enter();
throw Errors.createTypeErrorArrayBufferViewExpected();
}
JSTypedArrayObject typedArrayObject = (JSTypedArrayObject) obj;
if (JSArrayBufferView.hasDetachedBuffer(typedArrayObject, getContext())) {
errorBranch.enter();
throw Errors.createTypeErrorDetachedBuffer();
}
return typedArrayObject;
}
protected void reportLoopCount(long count) {
reportLoopCount(this, count);
}
public static void reportLoopCount(Node node, long count) {
if (count > 0) {
LoopNode.reportLoopCount(node, count > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) count);
}
}
}
protected static class ArraySpeciesConstructorNode extends JavaScriptBaseNode {
private final boolean isTypedArrayImplementation; // for reusing array code on TypedArrays
@Child private JSFunctionCallNode constructorCall;
@Child private PropertyGetNode getConstructorNode;
@Child private PropertyGetNode getSpeciesNode;
@Child private JSIsArrayNode isArrayNode;
@Child private IsConstructorNode isConstructorNode = IsConstructorNode.create();
@Child private ArrayCreateNode arrayCreateNode;
private final BranchProfile errorBranch = BranchProfile.create();
private final BranchProfile arraySpeciesIsArray = BranchProfile.create();
private final BranchProfile arraySpeciesGetSymbol = BranchProfile.create();
private final BranchProfile differentRealm = BranchProfile.create();
private final BranchProfile defaultConstructorBranch = BranchProfile.create();
private final ConditionProfile arraySpeciesEmpty = ConditionProfile.createBinaryProfile();
private final BranchProfile notAJSObjectBranch = BranchProfile.create();
private final JSContext context;
protected ArraySpeciesConstructorNode(JSContext context, boolean isTypedArrayImplementation) {
this.context = context;
this.isTypedArrayImplementation = isTypedArrayImplementation;
this.isArrayNode = JSIsArrayNode.createIsArray();
this.constructorCall = JSFunctionCallNode.createNew();
}
protected static ArraySpeciesConstructorNode create(JSContext context, boolean isTypedArrayImplementation) {
return new ArraySpeciesConstructorNode(context, isTypedArrayImplementation);
}
protected final Object createEmptyContainer(Object thisObj, long size) {
if (isTypedArrayImplementation) {
return typedArraySpeciesCreate(JSRuntime.expectJSObject(thisObj, notAJSObjectBranch), JSRuntime.longToIntOrDouble(size));
} else {
return arraySpeciesCreate(thisObj, size);
}
}
protected final DynamicObject typedArraySpeciesCreate(DynamicObject thisObj, Object... args) {
DynamicObject constr = speciesConstructor(thisObj, getDefaultConstructor(thisObj));
return typedArrayCreate(constr, args);
}
/**
* 172.16.17.32 TypedArrayCreate().
*/
public final DynamicObject typedArrayCreate(DynamicObject constr, Object... args) {
Object newTypedArray = construct(constr, args);
if (!JSArrayBufferView.isJSArrayBufferView(newTypedArray)) {
errorBranch.enter();
throw Errors.createTypeErrorArrayBufferViewExpected();
}
if (JSArrayBufferView.hasDetachedBuffer((DynamicObject) newTypedArray, context)) {
errorBranch.enter();
throw Errors.createTypeErrorDetachedBuffer();
}
if (args.length == 1 && JSRuntime.isNumber(args[0])) {
if (JSArrayBufferView.typedArrayGetLength((DynamicObject) newTypedArray) < JSRuntime.doubleValue((Number) args[0])) {
errorBranch.enter();
throw Errors.createTypeError("invalid TypedArray created");
}
}
return (DynamicObject) newTypedArray;
}
/**
* ES6, 9.4.2.3 ArraySpeciesCreate(originalArray, length).
*/
protected final Object arraySpeciesCreate(Object originalArray, long length) {
Object ctor = Undefined.instance;
if (isArray(originalArray)) {
arraySpeciesIsArray.enter();
ctor = getConstructorProperty(originalArray);
if (JSDynamicObject.isJSDynamicObject(ctor)) {
DynamicObject ctorObj = (DynamicObject) ctor;
if (JSFunction.isJSFunction(ctorObj) && JSFunction.isConstructor(ctorObj)) {
JSRealm thisRealm = getRealm();
JSRealm ctorRealm = JSFunction.getRealm(ctorObj);
if (thisRealm != ctorRealm) {
differentRealm.enter();
if (ctorRealm.getArrayConstructor() == ctor) {
/*
* If originalArray was created using the standard built-in Array
* constructor for a realm that is not the realm of the running
* execution context, then a new Array is created using the realm of
* the running execution context.
*/
return arrayCreate(length);
}
}
}
if (ctor != Undefined.instance) {
arraySpeciesGetSymbol.enter();
ctor = getSpeciesProperty(ctor);
ctor = ctor == Null.instance ? Undefined.instance : ctor;
}
}
}
if (arraySpeciesEmpty.profile(ctor == Undefined.instance)) {
return arrayCreate(length);
}
if (!isConstructorNode.executeBoolean(ctor)) {
errorBranch.enter();
throw Errors.createTypeErrorNotAConstructor(ctor, context);
}
return construct((DynamicObject) ctor, JSRuntime.longToIntOrDouble(length));
}
protected final boolean isArray(Object thisObj) {
return isArrayNode.execute(thisObj);
}
private Object arrayCreate(long length) {
if (arrayCreateNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
arrayCreateNode = insert(ArrayCreateNode.create(context));
}
return arrayCreateNode.execute(length);
}
protected Object construct(DynamicObject constructor, Object... userArgs) {
Object[] args = JSArguments.createInitial(JSFunction.CONSTRUCT, constructor, userArgs.length);
System.arraycopy(userArgs, 0, args, JSArguments.RUNTIME_ARGUMENT_COUNT, userArgs.length);
return constructorCall.executeCall(args);
}
protected final DynamicObject getDefaultConstructor(DynamicObject thisObj) {
assert JSArrayBufferView.isJSArrayBufferView(thisObj);
TypedArray arrayType = JSArrayBufferView.typedArrayGetArrayType(thisObj);
return getRealm().getArrayBufferViewConstructor(arrayType.getFactory());
}
/**
* Implement 7.3.20 SpeciesConstructor.
*/
protected final DynamicObject speciesConstructor(DynamicObject thisObj, DynamicObject defaultConstructor) {
Object c = getConstructorProperty(thisObj);
if (c == Undefined.instance) {
defaultConstructorBranch.enter();
return defaultConstructor;
}
if (!JSDynamicObject.isJSDynamicObject(c)) {
errorBranch.enter();
throw Errors.createTypeErrorNotAnObject(c);
}
Object speciesConstructor = getSpeciesProperty(c);
if (speciesConstructor == Undefined.instance || speciesConstructor == Null.instance) {
defaultConstructorBranch.enter();
return defaultConstructor;
}
if (!isConstructorNode.executeBoolean(speciesConstructor)) {
errorBranch.enter();
throw Errors.createTypeErrorNotAConstructor(speciesConstructor, context);
}
return (DynamicObject) speciesConstructor;
}
private Object getConstructorProperty(Object obj) {
if (getConstructorNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
getConstructorNode = insert(PropertyGetNode.create(JSObject.CONSTRUCTOR, false, context));
}
return getConstructorNode.getValue(obj);
}
private Object getSpeciesProperty(Object obj) {
if (getSpeciesNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
getSpeciesNode = insert(PropertyGetNode.create(Symbol.SYMBOL_SPECIES, false, context));
}
return getSpeciesNode.getValue(obj);
}
}
public abstract static class JSArrayOperation extends BasicArrayOperation {
public JSArrayOperation(JSContext context, JSBuiltin builtin, boolean isTypedArrayImplementation) {
super(context, builtin, isTypedArrayImplementation);
}
public JSArrayOperation(JSContext context, JSBuiltin builtin) {
super(context, builtin, false);
}
protected static final boolean THROW_ERROR = true;
@Child private JSSetLengthNode setLengthNode;
@Child private WriteElementNode writeNode;
@Child private WriteElementNode writeOwnNode;
@Child private ReadElementNode readNode;
@Child private JSHasPropertyNode hasPropertyNode;
@Child private JSArrayNextElementIndexNode nextElementIndexNode;
@Child private JSArrayPreviousElementIndexNode previousElementIndexNode;
protected void setLength(Object thisObject, int length) {
setLengthIntl(thisObject, length);
}
protected void setLength(Object thisObject, long length) {
setLengthIntl(thisObject, JSRuntime.longToIntOrDouble(length));
}
protected void setLength(Object thisObject, double length) {
setLengthIntl(thisObject, length);
}
private void setLengthIntl(Object thisObject, Object length) {
assert !(length instanceof Long);
if (setLengthNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
setLengthNode = insert(JSSetLengthNode.create(getContext(), THROW_ERROR));
}
setLengthNode.execute(thisObject, length);
}
private ReadElementNode getOrCreateReadNode() {
if (readNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
readNode = insert(ReadElementNode.create(getContext()));
}
return readNode;
}
protected Object read(Object target, int index) {
return getOrCreateReadNode().executeWithTargetAndIndex(target, index);
}
protected Object read(Object target, long index) {
ReadElementNode read = getOrCreateReadNode();
return read.executeWithTargetAndIndex(target, index);
}
private WriteElementNode getOrCreateWriteNode() {
if (writeNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
writeNode = insert(WriteElementNode.create(getContext(), THROW_ERROR));
}
return writeNode;
}
protected void write(Object target, int index, Object value) {
getOrCreateWriteNode().executeWithTargetAndIndexAndValue(target, index, value);
}
protected void write(Object target, long index, Object value) {
WriteElementNode write = getOrCreateWriteNode();
write.executeWithTargetAndIndexAndValue(target, index, value);
}
// represent the 7.3.6 CreateDataPropertyOrThrow(O, P, V)
private WriteElementNode getOrCreateWriteOwnNode() {
if (writeOwnNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
writeOwnNode = insert(WriteElementNode.create(getContext(), THROW_ERROR, true));
}
return writeOwnNode;
}
protected void writeOwn(Object target, int index, Object value) {
getOrCreateWriteOwnNode().executeWithTargetAndIndexAndValue(target, index, value);
}
protected void writeOwn(Object target, long index, Object value) {
WriteElementNode write = getOrCreateWriteOwnNode();
write.executeWithTargetAndIndexAndValue(target, index, value);
}
private JSHasPropertyNode getOrCreateHasPropertyNode() {
if (hasPropertyNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
hasPropertyNode = insert(JSHasPropertyNode.create());
}
return hasPropertyNode;
}
protected boolean hasProperty(Object target, long propertyIdx) {
return getOrCreateHasPropertyNode().executeBoolean(target, propertyIdx);
}
protected boolean hasProperty(Object target, Object propertyName) {
return getOrCreateHasPropertyNode().executeBoolean(target, propertyName);
}
protected long nextElementIndex(Object target, long currentIndex, long length) {
if (nextElementIndexNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
nextElementIndexNode = insert(JSArrayNextElementIndexNode.create(getContext()));
}
return nextElementIndexNode.executeLong(target, currentIndex, length);
}
protected long previousElementIndex(Object target, long currentIndex) {
if (previousElementIndexNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
previousElementIndexNode = insert(JSArrayPreviousElementIndexNode.create(getContext()));
}
return previousElementIndexNode.executeLong(target, currentIndex);
}
protected static final void throwLengthError() {
throw Errors.createTypeError("length too big");
}
}
public abstract static class JSArrayOperationWithToInt extends JSArrayOperation {
public JSArrayOperationWithToInt(JSContext context, JSBuiltin builtin, boolean isTypedArrayImplementation) {
super(context, builtin, isTypedArrayImplementation);
}
public JSArrayOperationWithToInt(JSContext context, JSBuiltin builtin) {
this(context, builtin, false);
}
@Child private JSToIntegerAsLongNode toIntegerAsLongNode;
protected long toIntegerAsLong(Object target) {
if (toIntegerAsLongNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
toIntegerAsLongNode = insert(JSToIntegerAsLongNode.create());
}
return toIntegerAsLongNode.executeLong(target);
}
}
public abstract static class JSArrayPushNode extends JSArrayOperation {
public JSArrayPushNode(JSContext context, JSBuiltin builtin) {
super(context, builtin);
}
@Specialization(guards = {"isJSArray(thisObject)", "args.length == 0"})
protected Object pushArrayNone(DynamicObject thisObject, @SuppressWarnings("unused") Object[] args) {
long len = getLength(thisObject);
setLength(thisObject, len); // could have side effect / throw
if (len >= Integer.MAX_VALUE) {
return (double) len;
} else {
return (int) len;
}
}
@Specialization(guards = {"isJSArray(thisObject)", "args.length == 1"}, rewriteOn = SlowPathException.class)
protected int pushArraySingle(DynamicObject thisObject, Object[] args) throws SlowPathException {
long len = getLength(thisObject);
if (len >= Integer.MAX_VALUE) {
throw JSNodeUtil.slowPathException();
}
int iLen = (int) len;
write(thisObject, iLen, args[0]);
int newLength = iLen + 1;
setLength(thisObject, newLength);
return newLength;
}
@Specialization(guards = {"isJSArray(thisObject)", "args.length == 1"})
protected double pushArraySingleLong(DynamicObject thisObject, Object[] args) {
long len = getLength(thisObject);
checkLength(args, len);
write(thisObject, len, args[0]);
long newLength = len + 1;
setLength(thisObject, newLength);
return newLength;
}
@Specialization(guards = {"isJSArray(thisObject)", "args.length >= 2"}, rewriteOn = SlowPathException.class)
protected int pushArrayAll(DynamicObject thisObject, Object[] args) throws SlowPathException {
long len = getLength(thisObject);
if (len + args.length >= Integer.MAX_VALUE) {
throw JSNodeUtil.slowPathException();
}
int ilen = (int) len;
for (int i = 0; i < args.length; i++) {
write(thisObject, ilen + i, args[i]);
}
setLength(thisObject, ilen + args.length);
return ilen + args.length;
}
@Specialization(guards = {"isJSArray(thisObject)", "args.length >= 2"})
protected double pushArrayAllLong(DynamicObject thisObject, Object[] args) {
long len = getLength(thisObject);
checkLength(args, len);
for (int i = 0; i < args.length; i++) {
write(thisObject, len + i, args[i]);
}
setLength(thisObject, len + args.length);
return (double) len + args.length;
}
@Specialization(guards = "!isJSArray(thisObject)")
protected double pushProperty(Object thisObject, Object[] args) {
Object thisObj = toObject(thisObject);
long len = getLength(thisObj);
checkLength(args, len);
for (int i = 0; i < args.length; i++) {
write(thisObj, len + i, args[i]);
}
long newLength = len + args.length;
setLength(thisObj, newLength);
return newLength;
}
private void checkLength(Object[] args, long len) {
if (len + args.length > JSRuntime.MAX_SAFE_INTEGER) {
errorBranch.enter();
throwLengthError();
}
}
}
public abstract static class JSArrayPopNode extends JSArrayOperation {
public JSArrayPopNode(JSContext context, JSBuiltin builtin) {
super(context, builtin);
}
@Specialization
protected Object popGeneric(Object thisObj,
@Cached("create(getContext())") DeleteAndSetLengthNode deleteAndSetLength,
@Cached("createBinaryProfile()") ConditionProfile lengthIsZero) {
final Object thisObject = toObject(thisObj);
final long length = getLength(thisObject);
if (lengthIsZero.profile(length > 0)) {
long newLength = length - 1;
Object result = read(thisObject, newLength);
deleteAndSetLength.executeVoid(thisObject, newLength);
return result;
} else {
assert length == 0;
setLength(thisObject, 0);
return Undefined.instance;
}
}
}
@ImportStatic({JSRuntime.class, JSConfig.class})
protected abstract static class DeleteAndSetLengthNode extends JavaScriptBaseNode {
protected static final boolean THROW_ERROR = true; // DeletePropertyOrThrow
protected final JSContext context;
protected DeleteAndSetLengthNode(JSContext context) {
this.context = context;
}
public static DeleteAndSetLengthNode create(JSContext context) {
return DeleteAndSetLengthNodeGen.create(context);
}
public abstract void executeVoid(Object target, long newLength);
protected final WritePropertyNode createWritePropertyNode() {
return WritePropertyNode.create(null, JSArray.LENGTH, null, context, THROW_ERROR);
}
protected static boolean isArray(DynamicObject object) {
// currently, must be fast array
return JSArray.isJSFastArray(object);
}
@Specialization(guards = {"isArray(object)", "longIsRepresentableAsInt(longLength)"})
protected static void setArrayLength(DynamicObject object, long longLength,
@Cached("createArrayLengthWriteNode()") ArrayLengthWriteNode arrayLengthWriteNode) {
arrayLengthWriteNode.executeVoid(object, (int) longLength);
}
protected static final ArrayLengthWriteNode createArrayLengthWriteNode() {
return ArrayLengthWriteNode.createSetOrDelete(THROW_ERROR);
}
@Specialization(guards = {"isJSObject(object)", "longIsRepresentableAsInt(longLength)"})
protected static void setIntLength(DynamicObject object, long longLength,
@Cached("create(THROW_ERROR, context)") DeletePropertyNode deletePropertyNode,
@Cached("createWritePropertyNode()") WritePropertyNode setLengthProperty) {
int intLength = (int) longLength;
deletePropertyNode.executeEvaluated(object, intLength);
setLengthProperty.executeIntWithValue(object, intLength);
}
@Specialization(guards = {"isJSObject(object)"}, replaces = "setIntLength")
protected static void setLength(DynamicObject object, long longLength,
@Cached("create(THROW_ERROR, context)") DeletePropertyNode deletePropertyNode,
@Cached("createWritePropertyNode()") WritePropertyNode setLengthProperty,
@Cached("createBinaryProfile()") ConditionProfile indexInIntRangeCondition) {
Object boxedLength = JSRuntime.boxIndex(longLength, indexInIntRangeCondition);
deletePropertyNode.executeEvaluated(object, boxedLength);
setLengthProperty.executeWithValue(object, boxedLength);
}
@Specialization(guards = {"!isJSObject(object)"})
protected static void foreignArray(Object object, long newLength,
@CachedLibrary(limit = "InteropLibraryLimit") InteropLibrary arrays) {
try {
arrays.removeArrayElement(object, newLength);
} catch (UnsupportedMessageException | InvalidArrayIndexException e) {
throw Errors.createTypeErrorInteropException(object, e, "removeArrayElement", null);
}
}
}
public abstract static class JSArraySliceNode extends ArrayForEachIndexCallOperation {
public JSArraySliceNode(JSContext context, JSBuiltin builtin, boolean isTypedArrayImplementation) {
super(context, builtin, isTypedArrayImplementation);
}
private final ConditionProfile sizeIsZero = ConditionProfile.createBinaryProfile();
private final ConditionProfile offsetProfile1 = ConditionProfile.createBinaryProfile();
private final ConditionProfile offsetProfile2 = ConditionProfile.createBinaryProfile();
@Specialization
protected Object sliceGeneric(Object thisObj, Object begin, Object end,
@Cached("create()") JSToIntegerAsLongNode toIntegerAsLong) {
Object thisArrayObj = toObjectOrValidateTypedArray(thisObj);
long len = getLength(thisArrayObj);
long startPos = begin != Undefined.instance ? JSRuntime.getOffset(toIntegerAsLong.executeLong(begin), len, offsetProfile1) : 0;
long endPos;
if (end == Undefined.instance) {
endPos = len;
} else {
endPos = JSRuntime.getOffset(toIntegerAsLong.executeLong(end), len, offsetProfile2);
}
long size = startPos <= endPos ? endPos - startPos : 0;
Object resultArray = getArraySpeciesConstructorNode().createEmptyContainer(thisArrayObj, size);
if (sizeIsZero.profile(size > 0)) {
if (isTypedArrayImplementation) {
checkHasDetachedBuffer((DynamicObject) thisObj);
}
forEachIndexCall(thisArrayObj, null, startPos, startPos, endPos, resultArray);
}
if (!isTypedArrayImplementation) {
setLength(resultArray, size);
}
return resultArray;
}
@Override
protected MaybeResultNode makeMaybeResultNode() {
return new ForEachIndexCallNode.MaybeResultNode() {
@Child private WriteElementNode writeOwnNode = WriteElementNode.create(getContext(), true, true);
@Override
public MaybeResult<Object> apply(long index, Object value, Object callbackResult, Object currentResult) {
long startIndex = (long) callbackResult;
writeOwnNode.executeWithTargetAndIndexAndValue(currentResult, index - startIndex, value);
return MaybeResult.continueResult(currentResult);
}
};
}
@Override
protected CallbackNode makeCallbackNode() {
return null;
}
}
@ImportStatic({JSConfig.class})
public abstract static class JSArrayShiftNode extends JSArrayOperation {
public JSArrayShiftNode(JSContext context, JSBuiltin builtin) {
super(context, builtin);
}
protected static boolean isSparseArray(DynamicObject thisObj) {
return arrayGetArrayType(thisObj) instanceof SparseArray;
}
protected static boolean isArrayWithoutHoles(DynamicObject thisObj, IsArrayNode isArrayNode, TestArrayNode hasHolesNode) {
boolean isArray = isArrayNode.execute(thisObj);
return isArray && !hasHolesNode.executeBoolean(thisObj);
}
@Specialization(guards = {"isArrayWithoutHoles(thisObj, isArrayNode, hasHolesNode)"}, limit = "1")
protected Object shiftWithoutHoles(DynamicObject thisObj,
@Shared("isArray") @Cached("createIsArray()") @SuppressWarnings("unused") IsArrayNode isArrayNode,
@Shared("hasHoles") @Cached("createHasHoles()") @SuppressWarnings("unused") TestArrayNode hasHolesNode,
@Cached("createClassProfile()") ValueProfile arrayTypeProfile,
@Shared("lengthIsZero") @Cached("createBinaryProfile()") ConditionProfile lengthIsZero,
@Cached("createBinaryProfile()") ConditionProfile lengthLargerOne) {
long len = getLength(thisObj);
if (lengthIsZero.profile(len == 0)) {
return Undefined.instance;
} else {
Object firstElement = read(thisObj, 0);
if (lengthLargerOne.profile(len > 1)) {
ScriptArray array = arrayTypeProfile.profile(arrayGetArrayType(thisObj));
arraySetArrayType(thisObj, array.shiftRange(thisObj, 1, errorBranch));
}
setLength(thisObj, len - 1);
return firstElement;
}
}
protected static boolean isArrayWithHoles(DynamicObject thisObj, IsArrayNode isArrayNode, TestArrayNode hasHolesNode) {
boolean isArray = isArrayNode.execute(thisObj);
return isArray && hasHolesNode.executeBoolean(thisObj) && !isSparseArray(thisObj);
}
@Specialization(guards = {"isArrayWithHoles(thisObj, isArrayNode, hasHolesNode)"}, limit = "1")
protected Object shiftWithHoles(DynamicObject thisObj,
@Shared("isArray") @Cached("createIsArray()") @SuppressWarnings("unused") IsArrayNode isArrayNode,
@Shared("hasHoles") @Cached("createHasHoles()") @SuppressWarnings("unused") TestArrayNode hasHolesNode,
@Shared("deleteProperty") @Cached("create(THROW_ERROR, getContext())") DeletePropertyNode deletePropertyNode,
@Shared("lengthIsZero") @Cached("createBinaryProfile()") ConditionProfile lengthIsZero) {
long len = getLength(thisObj);
if (lengthIsZero.profile(len > 0)) {
Object firstElement = read(thisObj, 0);
for (long i = 0; i < len - 1; i++) {
if (hasProperty(thisObj, i + 1)) {
write(thisObj, i, read(thisObj, i + 1));
} else {
deletePropertyNode.executeEvaluated(thisObj, i);
}
}
deletePropertyNode.executeEvaluated(thisObj, len - 1);
setLength(thisObj, len - 1);
reportLoopCount(len - 1);
return firstElement;
} else {
return Undefined.instance;
}
}
@Specialization(guards = {"isArrayNode.execute(thisObj)", "isSparseArray(thisObj)"}, limit = "1")
protected Object shiftSparse(DynamicObject thisObj,
@Shared("isArray") @Cached("createIsArray()") @SuppressWarnings("unused") IsArrayNode isArrayNode,
@Shared("deleteProperty") @Cached("create(THROW_ERROR, getContext())") DeletePropertyNode deletePropertyNode,
@Shared("lengthIsZero") @Cached("createBinaryProfile()") ConditionProfile lengthIsZero,
@Cached("create(getContext())") JSArrayFirstElementIndexNode firstElementIndexNode,
@Cached("create(getContext())") JSArrayLastElementIndexNode lastElementIndexNode) {
long len = getLength(thisObj);
if (lengthIsZero.profile(len > 0)) {
Object firstElement = read(thisObj, 0);
long count = 0;
for (long i = firstElementIndexNode.executeLong(thisObj, len); i <= lastElementIndexNode.executeLong(thisObj, len); i = nextElementIndex(thisObj, i, len)) {
if (i > 0) {
write(thisObj, i - 1, read(thisObj, i));
}
if (!hasProperty(thisObj, i + 1)) {
deletePropertyNode.executeEvaluated(thisObj, i);
}
count++;
}
setLength(thisObj, len - 1);
reportLoopCount(count);
return firstElement;
} else {
return Undefined.instance;
}
}
@Specialization(guards = {"!isJSArray(thisObj)", "!isForeignObject(thisObj)"})
protected Object shiftGeneric(Object thisObj,
@Shared("deleteProperty") @Cached("create(THROW_ERROR, getContext())") DeletePropertyNode deleteNode,
@Shared("lengthIsZero") @Cached("createBinaryProfile()") ConditionProfile lengthIsZero) {
Object thisJSObj = toObject(thisObj);
long len = getLength(thisJSObj);
if (lengthIsZero.profile(len == 0)) {
setLength(thisJSObj, 0);
return Undefined.instance;
}
Object firstObj = read(thisJSObj, 0);
for (long i = 1; i < len; i++) {
if (hasProperty(thisJSObj, i)) {
write(thisJSObj, i - 1, read(thisObj, i));
} else {
deleteNode.executeEvaluated(thisJSObj, i - 1);
}
}
deleteNode.executeEvaluated(thisJSObj, len - 1);
setLength(thisJSObj, len - 1);
reportLoopCount(len);
return firstObj;
}
@Specialization(guards = {"isForeignObject(thisObj)"})
protected Object shiftForeign(Object thisObj,
@CachedLibrary(limit = "InteropLibraryLimit") InteropLibrary arrays,
@Shared("lengthIsZero") @Cached("createBinaryProfile()") ConditionProfile lengthIsZero) {
long len = JSInteropUtil.getArraySize(thisObj, arrays, this);
if (lengthIsZero.profile(len == 0)) {
return Undefined.instance;
}
try {
Object firstObj = arrays.readArrayElement(thisObj, 0);
for (long i = 1; i < len; i++) {
Object val = arrays.readArrayElement(thisObj, i);
arrays.writeArrayElement(thisObj, i - 1, val);
}
arrays.removeArrayElement(thisObj, len - 1);
reportLoopCount(len);
return firstObj;
} catch (UnsupportedMessageException | InvalidArrayIndexException | UnsupportedTypeException e) {
throw Errors.createTypeErrorInteropException(thisObj, e, "shift", this);
}
}
}
public abstract static class JSArrayUnshiftNode extends JSArrayOperation {
public JSArrayUnshiftNode(JSContext context, JSBuiltin builtin) {
super(context, builtin);
}
@Child protected IsArrayNode isArrayNode = IsArrayNode.createIsArray();
@Child protected TestArrayNode hasHolesNode = TestArrayNode.createHasHoles();
protected boolean isFastPath(Object thisObj) {
boolean isArray = isArrayNode.execute(thisObj);
return isArray && !hasHolesNode.executeBoolean((DynamicObject) thisObj);
}
private long unshiftHoleless(DynamicObject thisObj, Object[] args) {
long len = getLength(thisObj);
if (getContext().getEcmaScriptVersion() <= 5 || args.length > 0) {
for (long l = len - 1; l >= 0; l--) {
write(thisObj, l + args.length, read(thisObj, l));
}
for (int i = 0; i < args.length; i++) {
write(thisObj, i, args[i]);
}
reportLoopCount(len + args.length);
}
long newLen = len + args.length;
setLength(thisObj, newLen);
return newLen;
}
@Specialization(guards = "isFastPath(thisObj)", rewriteOn = UnexpectedResultException.class)
protected int unshiftInt(DynamicObject thisObj, Object[] args) throws UnexpectedResultException {
long newLen = unshiftHoleless(thisObj, args);
if (JSRuntime.longIsRepresentableAsInt(newLen)) {
return (int) newLen;
} else {
CompilerDirectives.transferToInterpreterAndInvalidate();
throw new UnexpectedResultException((double) newLen);
}
}
@Specialization(guards = "isFastPath(thisObj)", replaces = "unshiftInt")
protected double unshiftDouble(DynamicObject thisObj, Object[] args) {
return unshiftHoleless(thisObj, args);
}
@Specialization(guards = "!isFastPath(thisObjParam)")
protected double unshiftHoles(Object thisObjParam, Object[] args,
@Cached("create(THROW_ERROR, getContext())") DeletePropertyNode deletePropertyNode,
@Cached("create(getContext())") JSArrayLastElementIndexNode lastElementIndexNode,
@Cached("create(getContext())") JSArrayFirstElementIndexNode firstElementIndexNode) {
Object thisObj = toObject(thisObjParam);
long len = getLength(thisObj);
if (getContext().getEcmaScriptVersion() <= 5 || args.length > 0) {
if (args.length + len > JSRuntime.MAX_SAFE_INTEGER_LONG) {
errorBranch.enter();
throwLengthError();
}
long lastIdx = lastElementIndexNode.executeLong(thisObj, len);
long firstIdx = firstElementIndexNode.executeLong(thisObj, len);
long count = 0;
for (long i = lastIdx; i >= firstIdx; i = previousElementIndex(thisObj, i)) {
count++;
if (hasProperty(thisObj, i)) {
write(thisObj, i + args.length, read(thisObj, i));
if (args.length > 0 && i >= args.length && !hasProperty(thisObj, i - args.length)) {
// delete the source if it is not identical to the sink
// and no other element will copy here later in the loop
deletePropertyNode.executeEvaluated(thisObj, i);
}
}
}
for (int i = 0; i < args.length; i++) {
write(thisObj, i, args[i]);
}
reportLoopCount(count + args.length);
}
long newLen = len + args.length;
setLength(thisObj, newLen);
return newLen;
}
}
public abstract static class JSArrayToStringNode extends BasicArrayOperation {
@Child private PropertyNode joinPropertyNode;
@Child private PropertyNode toStringPropertyNode;
@Child private JSFunctionCallNode callJoinNode;
@Child private JSFunctionCallNode callToStringNode;
@Child private ForeignObjectPrototypeNode foreignObjectPrototypeNode;
@Child private InteropLibrary interopLibrary;
@Child private ImportValueNode importValueNode;
private final ConditionProfile isJSObjectProfile = ConditionProfile.createBinaryProfile();
private static final String JOIN = "join";
public JSArrayToStringNode(JSContext context, JSBuiltin builtin) {
super(context, builtin);
this.joinPropertyNode = PropertyNode.createProperty(context, null, JOIN);
}
private Object getJoinProperty(Object target) {
return joinPropertyNode.executeWithTarget(target);
}
private Object getToStringProperty(Object target) {
if (toStringPropertyNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
toStringPropertyNode = insert(PropertyNode.createProperty(getContext(), null, JSRuntime.TO_STRING));
}
return toStringPropertyNode.executeWithTarget(target);
}
private Object callJoin(Object target, Object function) {
if (callJoinNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
callJoinNode = insert(JSFunctionCallNode.createCall());
}
return callJoinNode.executeCall(JSArguments.createZeroArg(target, function));
}
private Object callToString(Object target, Object function) {
if (callToStringNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
callToStringNode = insert(JSFunctionCallNode.createCall());
}
return callToStringNode.executeCall(JSArguments.createZeroArg(target, function));
}
private DynamicObject getForeignObjectPrototype(Object truffleObject) {
assert JSRuntime.isForeignObject(truffleObject);
if (foreignObjectPrototypeNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
foreignObjectPrototypeNode = insert(ForeignObjectPrototypeNode.create());
}
return foreignObjectPrototypeNode.executeDynamicObject(truffleObject);
}
private InteropLibrary getInterop() {
if (interopLibrary == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
interopLibrary = insert(InteropLibrary.getFactory().createDispatched(JSConfig.InteropLibraryLimit));
}
return interopLibrary;
}
private Object importValue(Object value) {
if (importValueNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
importValueNode = insert(ImportValueNode.create());
}
return importValueNode.executeWithTarget(value);
}
private Object toStringForeign(Object arrayObj) {
InteropLibrary interop = getInterop();
if (interop.isMemberInvocable(arrayObj, JOIN)) {
Object result;
try {
try {
result = interop.invokeMember(arrayObj, JOIN);
} catch (AbstractTruffleException e) {
if (InteropLibrary.getUncached(e).getExceptionType(e) == ExceptionType.RUNTIME_ERROR) {
result = null;
} else {
throw e;
}
}
} catch (InteropException e) {
result = null;
}
if (result != null) {
return importValue(result);
}
}
Object join = getJoinProperty(getForeignObjectPrototype(arrayObj));
if (isCallable(join)) {
return callJoin(arrayObj, join);
} else {
Object toString = getToStringProperty(getRealm().getObjectPrototype());
return callToString(arrayObj, toString);
}
}
@Specialization
protected Object toString(Object thisObj) {
Object arrayObj = toObject(thisObj);
if (isJSObjectProfile.profile(JSDynamicObject.isJSDynamicObject(arrayObj))) {
Object join = getJoinProperty(arrayObj);
if (isCallable(join)) {
return callJoin(arrayObj, join);
} else {
return JSObject.defaultToString((DynamicObject) arrayObj);
}
} else {
return toStringForeign(arrayObj);
}
}
}
public abstract static class JSArrayConcatNode extends JSArrayOperation {
public JSArrayConcatNode(JSContext context, JSBuiltin builtin) {
super(context, builtin);
}
@Child private JSToBooleanNode toBooleanNode;
@Child private JSToStringNode toStringNode;
@Child private JSArrayFirstElementIndexNode firstElementIndexNode;
@Child private JSArrayLastElementIndexNode lastElementIndexNode;
@Child private PropertyGetNode getSpreadableNode;
@Child private JSIsArrayNode isArrayNode;
private final ConditionProfile isFirstSpreadable = ConditionProfile.createBinaryProfile();
private final ConditionProfile hasFirstElements = ConditionProfile.createBinaryProfile();
private final ConditionProfile isSecondSpreadable = ConditionProfile.createBinaryProfile();
private final ConditionProfile hasSecondElements = ConditionProfile.createBinaryProfile();
private final ConditionProfile lengthErrorProfile = ConditionProfile.createBinaryProfile();
private final ConditionProfile hasMultipleArgs = ConditionProfile.createBinaryProfile();
private final ConditionProfile hasOneArg = ConditionProfile.createBinaryProfile();
private final ConditionProfile optimizationsObservable = ConditionProfile.createBinaryProfile();
private final ConditionProfile hasFirstOneElement = ConditionProfile.createBinaryProfile();
private final ConditionProfile hasSecondOneElement = ConditionProfile.createBinaryProfile();
protected boolean toBoolean(Object target) {
if (toBooleanNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
toBooleanNode = insert(JSToBooleanNode.create());
}
return toBooleanNode.executeBoolean(target);
}
protected String toString(Object target) {
if (toStringNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
toStringNode = insert(JSToStringNode.create());
}
return toStringNode.executeString(target);
}
@Specialization
protected DynamicObject concat(Object thisObj, Object[] args) {
Object thisJSObj = toObject(thisObj);
DynamicObject retObj = (DynamicObject) getArraySpeciesConstructorNode().createEmptyContainer(thisJSObj, 0);
long n = concatElementIntl(retObj, thisJSObj, 0, isFirstSpreadable, hasFirstElements, hasFirstOneElement);
long resultLen = concatIntl(retObj, n, args);
// the last set element could be non-existent
setLength(retObj, resultLen);
return retObj;
}
private long concatIntl(DynamicObject retObj, long initialLength, Object[] args) {
long n = initialLength;
if (hasOneArg.profile(args.length == 1)) {
n = concatElementIntl(retObj, args[0], n, isSecondSpreadable, hasSecondElements, hasSecondOneElement);
} else if (hasMultipleArgs.profile(args.length > 1)) {
for (int i = 0; i < args.length; i++) {
n = concatElementIntl(retObj, args[i], n, isSecondSpreadable, hasSecondElements, hasSecondOneElement);
}
}
return n;
}
private long concatElementIntl(DynamicObject retObj, Object el, final long n, final ConditionProfile isSpreadable, final ConditionProfile hasElements,
final ConditionProfile hasOneElement) {
if (isSpreadable.profile(isConcatSpreadable(el))) {
long len2 = getLength(el);
if (hasElements.profile(len2 > 0)) {
return concatSpreadable(retObj, n, el, len2, hasOneElement);
}
} else {
if (lengthErrorProfile.profile(n > JSRuntime.MAX_SAFE_INTEGER)) {
errorBranch.enter();
throwLengthError();
}
writeOwn(retObj, n, el);
return n + 1;
}
return n;
}
private long concatSpreadable(DynamicObject retObj, long n, Object elObj, long len2, final ConditionProfile hasOneElement) {
if (lengthErrorProfile.profile((n + len2) > JSRuntime.MAX_SAFE_INTEGER)) {
errorBranch.enter();
throwLengthError();
}
if (optimizationsObservable.profile(JSProxy.isJSProxy(elObj) || !JSDynamicObject.isJSDynamicObject(elObj))) {
// strictly to the standard implementation; traps could expose optimizations!
for (long k = 0; k < len2; k++) {
if (hasProperty(elObj, k)) {
writeOwn(retObj, n + k, read(elObj, k));
}
}
} else if (hasOneElement.profile(len2 == 1)) {
// fastpath for 1-element entries
if (hasProperty(elObj, 0)) {
writeOwn(retObj, n, read(elObj, 0));
}
} else {
long k = firstElementIndex((DynamicObject) elObj, len2);
long lastI = lastElementIndex((DynamicObject) elObj, len2);
for (; k <= lastI; k = nextElementIndex(elObj, k, len2)) {
writeOwn(retObj, n + k, read(elObj, k));
}
}
return n + len2;
}
// ES2015, 192.168.127.12.1
private boolean isConcatSpreadable(Object el) {
if (el == Undefined.instance || el == Null.instance) {
return false;
}
if (JSDynamicObject.isJSDynamicObject(el)) {
DynamicObject obj = (DynamicObject) el;
Object spreadable = getSpreadableProperty(obj);
if (spreadable != Undefined.instance) {
return toBoolean(spreadable);
}
}
return isArray(el);
}
private boolean isArray(Object object) {
if (isArrayNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
isArrayNode = insert(JSIsArrayNode.createIsArrayLike());
}
return isArrayNode.execute(object);
}
private Object getSpreadableProperty(Object obj) {
if (getSpreadableNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
getSpreadableNode = insert(PropertyGetNode.create(Symbol.SYMBOL_IS_CONCAT_SPREADABLE, false, getContext()));
}
return getSpreadableNode.getValue(obj);
}
private long firstElementIndex(DynamicObject target, long length) {
if (firstElementIndexNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
firstElementIndexNode = insert(JSArrayFirstElementIndexNode.create(getContext()));
}
return firstElementIndexNode.executeLong(target, length);
}
private long lastElementIndex(DynamicObject target, long length) {
if (lastElementIndexNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
lastElementIndexNode = insert(JSArrayLastElementIndexNode.create(getContext()));
}
return lastElementIndexNode.executeLong(target, length);
}
}
public abstract static class JSArrayIndexOfNode extends ArrayForEachIndexCallOperation {
private final boolean isForward;
@Child private JSToIntegerAsLongNode toIntegerNode;
private final BranchProfile arrayWithContentBranch = BranchProfile.create();
private final BranchProfile fromConversionBranch = BranchProfile.create();
public JSArrayIndexOfNode(JSContext context, JSBuiltin builtin, boolean isTypedArrayImplementation, boolean isForward) {
super(context, builtin, isTypedArrayImplementation);
this.isForward = isForward;
}
@Specialization
protected Object indexOf(Object thisObj, Object[] args) {
Object thisJSObject = toObjectOrValidateTypedArray(thisObj);
long len = getLength(thisJSObject);
if (len == 0) {
return -1;
}
arrayWithContentBranch.enter();
Object searchElement = JSRuntime.getArgOrUndefined(args, 0);
Object fromIndex = JSRuntime.getArgOrUndefined(args, 1);
long fromIndexValue = isForward() ? calcFromIndexForward(args, len, fromIndex) : calcFromIndexBackward(args, len, fromIndex);
if (fromIndexValue < 0) {
return -1;
}
return forEachIndexCall(thisJSObject, Undefined.instance, searchElement, fromIndexValue, len, -1);
}
// for indexOf()
private long calcFromIndexForward(Object[] args, long len, Object fromIndex) {
if (args.length <= 1) {
return 0;
} else {
fromConversionBranch.enter();
long fromIndexValue = toInteger(fromIndex);
if (fromIndexValue > len) {
return -1;
}
if (fromIndexValue < 0) {
fromIndexValue += len;
fromIndexValue = (fromIndexValue < 0) ? 0 : fromIndexValue;
}
return fromIndexValue;
}
}
// for lastIndexOf()
private long calcFromIndexBackward(Object[] args, long len, Object fromIndex) {
if (args.length <= 1) {
return len - 1;
} else {
fromConversionBranch.enter();
long fromIndexInt = toInteger(fromIndex);
if (fromIndexInt >= 0) {
return Math.min(fromIndexInt, len - 1);
} else {
return fromIndexInt + len;
}
}
}
private long toInteger(Object operand) {
if (toIntegerNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
toIntegerNode = insert(JSToIntegerAsLongNode.create());
}
return toIntegerNode.executeLong(operand);
}
@Override
protected boolean isForward() {
return isForward;
}
@Override
protected boolean shouldCheckHasProperty() {
return true;
}
@Override
protected final MaybeResultNode makeMaybeResultNode() {
return new ForEachIndexCallNode.MaybeResultNode() {
@Child private JSIdenticalNode doIdenticalNode = JSIdenticalNode.createStrictEqualityComparison();
private final ConditionProfile indexInIntRangeCondition = ConditionProfile.createBinaryProfile();
@Override
public MaybeResult<Object> apply(long index, Object value, Object callbackResult, Object currentResult) {
return doIdenticalNode.executeBoolean(value, callbackResult) ? MaybeResult.returnResult(JSRuntime.boxIndex(index, indexInIntRangeCondition))
: MaybeResult.continueResult(currentResult);
}
};
}
@Override
protected final CallbackNode makeCallbackNode() {
return null;
}
}
public abstract static class JSArrayJoinNode extends JSArrayOperation {
@Child private JSToStringNode separatorToStringNode;
@Child private JSToStringNode elementToStringNode;
private final ConditionProfile separatorNotEmpty = ConditionProfile.createBinaryProfile();
private final ConditionProfile isZero = ConditionProfile.createBinaryProfile();
private final ConditionProfile isOne = ConditionProfile.createBinaryProfile();
private final ConditionProfile isTwo = ConditionProfile.createBinaryProfile();
private final ConditionProfile isSparse = ConditionProfile.createBinaryProfile();
private final BranchProfile growProfile = BranchProfile.create();
private final BranchProfile stackGrowProfile = BranchProfile.create();
private final StringBuilderProfile stringBuilderProfile;
public JSArrayJoinNode(JSContext context, JSBuiltin builtin, boolean isTypedArrayImplementation) {
super(context, builtin, isTypedArrayImplementation);
this.elementToStringNode = JSToStringNode.create();
this.stringBuilderProfile = StringBuilderProfile.create(context.getStringLengthLimit());
}
@Specialization
protected String join(Object thisObj, Object joinStr) {
final Object thisJSObject = toObjectOrValidateTypedArray(thisObj);
final long length = getLength(thisJSObject);
final String joinSeparator = joinStr == Undefined.instance ? "," : getSeparatorToString().executeString(joinStr);
JSRealm realm = getRealm();
if (!realm.joinStackPush(thisObj, stackGrowProfile)) {
// join is in progress on thisObj already => break the cycle
return "";
}
try {
if (isZero.profile(length == 0)) {
return "";
} else if (isOne.profile(length == 1)) {
return joinOne(thisJSObject);
} else {
final boolean appendSep = separatorNotEmpty.profile(joinSeparator.length() > 0);
if (isTwo.profile(length == 2)) {
return joinTwo(thisJSObject, joinSeparator, appendSep);
} else if (isSparse.profile(JSArray.isJSArray(thisJSObject) && arrayGetArrayType((DynamicObject) thisJSObject) instanceof SparseArray)) {
return joinSparse(thisJSObject, length, joinSeparator, appendSep);
} else {
return joinLoop(thisJSObject, length, joinSeparator, appendSep);
}
}
} finally {
realm.joinStackPop();
}
}
private JSToStringNode getSeparatorToString() {
if (separatorToStringNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
separatorToStringNode = insert(JSToStringNode.create());
}
return separatorToStringNode;
}
private String joinOne(Object thisObject) {
Object value = read(thisObject, 0);
return toStringOrEmpty(value);
}
private String joinTwo(Object thisObject, final String joinSeparator, final boolean appendSep) {
String first = toStringOrEmpty(read(thisObject, 0));
String second = toStringOrEmpty(read(thisObject, 1));
long resultLength = first.length() + (appendSep ? joinSeparator.length() : 0L) + second.length();
if (resultLength > getContext().getStringLengthLimit()) {
CompilerDirectives.transferToInterpreter();
throw Errors.createRangeErrorInvalidStringLength();
}
final StringBuilder res = new StringBuilder((int) resultLength);
Boundaries.builderAppend(res, first);
if (appendSep) {
Boundaries.builderAppend(res, joinSeparator);
}
Boundaries.builderAppend(res, second);
return Boundaries.builderToString(res);
}
private String joinLoop(Object thisJSObject, final long length, final String joinSeparator, final boolean appendSep) {
final StringBuilder res = stringBuilderProfile.newStringBuilder();
long i = 0;
while (i < length) {
if (appendSep && i != 0) {
stringBuilderProfile.append(res, joinSeparator);
}
Object value = read(thisJSObject, i);
String str = toStringOrEmpty(value);
stringBuilderProfile.append(res, str);
if (appendSep) {
i++;
} else {
i = nextElementIndex(thisJSObject, i, length);
}
}
return stringBuilderProfile.toString(res);
}
private String toStringOrEmpty(Object value) {
if (isValidEntry(value)) {
return elementToStringNode.executeString(value);
} else {
return "";
}
}
private static boolean isValidEntry(Object value) {
return value != Undefined.instance && value != Null.instance;
}
private String joinSparse(Object thisObject, long length, String joinSeparator, final boolean appendSep) {
SimpleArrayList<Object> converted = SimpleArrayList.create(length);
long calculatedLength = 0;
long i = 0;
while (i < length) {
Object value = read(thisObject, i);
if (isValidEntry(value)) {
String string = elementToStringNode.executeString(value);
int stringLength = string.length();
if (stringLength > 0) {
calculatedLength += stringLength;
converted.add(i, growProfile);
converted.add(string, growProfile);
}
}
i = nextElementIndex(thisObject, i, length);
}
if (appendSep) {
calculatedLength += (length - 1) * joinSeparator.length();
}
if (calculatedLength > getContext().getStringLengthLimit()) {
CompilerDirectives.transferToInterpreter();
throw Errors.createRangeErrorInvalidStringLength();
}
assert calculatedLength <= Integer.MAX_VALUE;
final StringBuilder res = stringBuilderProfile.newStringBuilder((int) calculatedLength);
long lastIndex = 0;
for (int j = 0; j < converted.size(); j += 2) {
long index = (long) converted.get(j);
String value = (String) converted.get(j + 1);
if (appendSep) {
for (long k = lastIndex; k < index; k++) {
stringBuilderProfile.append(res, joinSeparator);
}
}
stringBuilderProfile.append(res, value);
lastIndex = index;
}
if (appendSep) {
for (long k = lastIndex; k < length - 1; k++) {
stringBuilderProfile.append(res, joinSeparator);
}
}
assert res.length() == calculatedLength;
return stringBuilderProfile.toString(res);
}
}
public abstract static class JSArrayToLocaleStringNode extends JSArrayOperation {
private final StringBuilderProfile stringBuilderProfile;
private final BranchProfile stackGrowProfile = BranchProfile.create();
@Child private PropertyGetNode getToLocaleStringNode;
@Child private JSFunctionCallNode callToLocaleStringNode;
public JSArrayToLocaleStringNode(JSContext context, JSBuiltin builtin, boolean isTypedArrayImplementation) {
super(context, builtin, isTypedArrayImplementation);
this.stringBuilderProfile = StringBuilderProfile.create(context.getStringLengthLimit());
}
@Specialization
protected String toLocaleString(VirtualFrame frame, Object thisObj,
@Cached("create()") JSToStringNode toStringNode) {
Object arrayObj = toObjectOrValidateTypedArray(thisObj);
long len = getLength(arrayObj);
if (len == 0) {
return "";
}
JSRealm realm = getRealm();
if (!realm.joinStackPush(thisObj, stackGrowProfile)) {
// join is in progress on thisObj already => break the cycle
return "";
}
try {
Object[] userArguments = JSArguments.extractUserArguments(frame.getArguments());
long k = 0;
StringBuilder r = stringBuilderProfile.newStringBuilder();
while (k < len) {
if (k > 0) {
stringBuilderProfile.append(r, ',');
}
Object nextElement = read(arrayObj, k);
if (nextElement != Null.instance && nextElement != Undefined.instance) {
Object result = callToLocaleString(nextElement, userArguments);
String resultString = toStringNode.executeString(result);
stringBuilderProfile.append(r, resultString);
}
k++;
}
return stringBuilderProfile.toString(r);
} finally {
realm.joinStackPop();
}
}
private Object callToLocaleString(Object nextElement, Object[] userArguments) {
if (getToLocaleStringNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
getToLocaleStringNode = insert(PropertyGetNode.create("toLocaleString", false, getContext()));
callToLocaleStringNode = insert(JSFunctionCallNode.createCall());
}
Object toLocaleString = getToLocaleStringNode.getValue(nextElement);
return callToLocaleStringNode.executeCall(JSArguments.create(nextElement, toLocaleString, userArguments));
}
}
public abstract static class JSArraySpliceNode extends JSArrayOperationWithToInt {
@Child private DeletePropertyNode deletePropertyNode; // DeletePropertyOrThrow
private final BranchProfile branchA = BranchProfile.create();
private final BranchProfile branchB = BranchProfile.create();
private final BranchProfile branchDelete = BranchProfile.create();
private final BranchProfile objectBranch = BranchProfile.create();
private final ConditionProfile argsLength0Profile = ConditionProfile.createBinaryProfile();
private final ConditionProfile argsLength1Profile = ConditionProfile.createBinaryProfile();
private final ConditionProfile offsetProfile = ConditionProfile.createBinaryProfile();
private final BranchProfile needMoveDeleteBranch = BranchProfile.create();
private final BranchProfile needInsertBranch = BranchProfile.create();
@Child private InteropLibrary arrayInterop;
public JSArraySpliceNode(JSContext context, JSBuiltin builtin) {
super(context, builtin);
this.deletePropertyNode = DeletePropertyNode.create(THROW_ERROR, context);
}
@Specialization
protected DynamicObject splice(Object thisArg, Object[] args,
@Cached("create(getContext())") SpliceJSArrayNode spliceJSArray) {
Object thisObj = toObject(thisArg);
long len = getLength(thisObj);
long actualStart = JSRuntime.getOffset(toIntegerAsLong(JSRuntime.getArgOrUndefined(args, 0)), len, offsetProfile);
long insertCount;
long actualDeleteCount;
if (argsLength0Profile.profile(args.length == 0)) {
insertCount = 0;
actualDeleteCount = 0;
} else if (argsLength1Profile.profile(args.length == 1)) {
insertCount = 0;
actualDeleteCount = len - actualStart;
} else {
assert args.length >= 2;
insertCount = args.length - 2;
long deleteCount = toIntegerAsLong(JSRuntime.getArgOrUndefined(args, 1));
actualDeleteCount = Math.min(Math.max(deleteCount, 0), len - actualStart);
}
if (len + insertCount - actualDeleteCount > JSRuntime.MAX_SAFE_INTEGER_LONG) {
errorBranch.enter();
throwLengthError();
}
DynamicObject aObj = (DynamicObject) getArraySpeciesConstructorNode().createEmptyContainer(thisObj, actualDeleteCount);
if (actualDeleteCount > 0) {
// copy deleted elements into result array
branchDelete.enter();
spliceRead(thisObj, actualStart, actualDeleteCount, aObj, len);
}
setLength(aObj, actualDeleteCount);
long itemCount = insertCount;
boolean isJSArray = JSArray.isJSArray(thisObj);
if (isJSArray) {
DynamicObject dynObj = (DynamicObject) thisObj;
ScriptArray arrayType = arrayGetArrayType(dynObj);
spliceJSArray.execute(dynObj, len, actualStart, actualDeleteCount, itemCount, arrayType, this);
} else if (JSDynamicObject.isJSDynamicObject(thisObj)) {
objectBranch.enter();
spliceJSObject(thisObj, len, actualStart, actualDeleteCount, itemCount);
} else {
spliceForeignArray(thisObj, len, actualStart, actualDeleteCount, itemCount);
}
if (itemCount > 0) {
needInsertBranch.enter();
spliceInsert(thisObj, actualStart, args);
}
long newLength = len - actualDeleteCount + itemCount;
setLength(thisObj, newLength);
reportLoopCount(len);
return aObj;
}
abstract static class SpliceJSArrayNode extends JavaScriptBaseNode {
final JSContext context;
SpliceJSArrayNode(JSContext context) {
this.context = context;
}
abstract void execute(DynamicObject array, long len, long actualStart, long actualDeleteCount, long itemCount, ScriptArray arrayType, JSArraySpliceNode parent);
@Specialization(guards = {"cachedArrayType.isInstance(arrayType)"}, limit = "5")
static void doCached(DynamicObject array, long len, long actualStart, long actualDeleteCount, long itemCount, ScriptArray arrayType, JSArraySpliceNode parent,
@Cached("arrayType") ScriptArray cachedArrayType,
@Cached GetPrototypeNode getPrototypeNode,
@Cached ConditionProfile arrayElementwise) {
if (arrayElementwise.profile(parent.mustUseElementwise(array, cachedArrayType.cast(arrayType), getPrototypeNode))) {
parent.spliceJSArrayElementwise(array, len, actualStart, actualDeleteCount, itemCount);
} else {
parent.spliceJSArrayBlockwise(array, actualStart, actualDeleteCount, itemCount, cachedArrayType.cast(arrayType));
}
}
@Specialization(replaces = "doCached")
static void doUncached(DynamicObject array, long len, long actualStart, long actualDeleteCount, long itemCount, ScriptArray arrayType, JSArraySpliceNode parent,
@Cached GetPrototypeNode getPrototypeNode,
@Cached ConditionProfile arrayElementwise) {
if (arrayElementwise.profile(parent.mustUseElementwise(array, arrayType, getPrototypeNode))) {
parent.spliceJSArrayElementwise(array, len, actualStart, actualDeleteCount, itemCount);
} else {
parent.spliceJSArrayBlockwise(array, actualStart, actualDeleteCount, itemCount, arrayType);
}
}
}
final boolean mustUseElementwise(DynamicObject obj, ScriptArray array, GetPrototypeNode getPrototypeNode) {
return array instanceof SparseArray ||
array.isLengthNotWritable() ||
getPrototypeNode.executeJSObject(obj) != getRealm().getArrayPrototype() ||
!getContext().getArrayPrototypeNoElementsAssumption().isValid() ||
(!getContext().getFastArrayAssumption().isValid() && JSSlowArray.isJSSlowArray(obj));
}
private void spliceRead(Object thisObj, long actualStart, long actualDeleteCount, DynamicObject aObj, long length) {
long kPlusStart = actualStart;
if (!hasProperty(thisObj, kPlusStart)) {
kPlusStart = nextElementIndex(thisObj, kPlusStart, length);
}
while (kPlusStart < (actualDeleteCount + actualStart)) {
Object fromValue = read(thisObj, kPlusStart);
writeOwn(aObj, kPlusStart - actualStart, fromValue);
kPlusStart = nextElementIndex(thisObj, kPlusStart, length);
}
}
private void spliceInsert(Object thisObj, long actualStart, Object[] args) {
final int itemOffset = 2;
for (int i = itemOffset; i < args.length; i++) {
write(thisObj, actualStart + i - itemOffset, args[i]);
}
}
private void spliceJSObject(Object thisObj, long len, long actualStart, long actualDeleteCount, long itemCount) {
if (itemCount < actualDeleteCount) {
branchA.enter();
spliceJSObjectShrink(thisObj, len, actualStart, actualDeleteCount, itemCount);
} else if (itemCount > actualDeleteCount) {
branchB.enter();
spliceJSObjectMove(thisObj, len, actualStart, actualDeleteCount, itemCount);
}
}
private void spliceJSObjectMove(Object thisObj, long len, long actualStart, long actualDeleteCount, long itemCount) {
for (long k = len - actualDeleteCount; k > actualStart; k--) {
spliceMoveValue(thisObj, (k + actualDeleteCount - 1), (k + itemCount - 1));
}
}
private void spliceJSObjectShrink(Object thisObj, long len, long actualStart, long actualDeleteCount, long itemCount) {
for (long k = actualStart; k < len - actualDeleteCount; k++) {
spliceMoveValue(thisObj, (k + actualDeleteCount), (k + itemCount));
}
for (long k = len; k > len - actualDeleteCount + itemCount; k--) {
deletePropertyNode.executeEvaluated(thisObj, k - 1);
}
}
private void spliceMoveValue(Object thisObj, long fromIndex, long toIndex) {
if (hasProperty(thisObj, fromIndex)) {
Object val = read(thisObj, fromIndex);
write(thisObj, toIndex, val);
} else {
needMoveDeleteBranch.enter();
deletePropertyNode.executeEvaluated(thisObj, toIndex);
}
}
final void spliceJSArrayElementwise(DynamicObject thisObj, long len, long actualStart, long actualDeleteCount, long itemCount) {
assert JSArray.isJSArray(thisObj); // contract
if (itemCount < actualDeleteCount) {
branchA.enter();
spliceJSArrayElementwiseWalkUp(thisObj, len, actualStart, actualDeleteCount, itemCount);
} else if (itemCount > actualDeleteCount) {
branchB.enter();
spliceJSArrayElementwiseWalkDown(thisObj, len, actualStart, actualDeleteCount, itemCount);
}
}
private void spliceJSArrayElementwiseWalkDown(DynamicObject thisObj, long len, long actualStart, long actualDeleteCount, long itemCount) {
long k = len - 1;
long delta = itemCount - actualDeleteCount;
while (k > (actualStart + actualDeleteCount - 1)) {
spliceMoveValue(thisObj, k, k + delta);
if ((k - delta) > (actualStart + actualDeleteCount - 1) && !hasProperty(thisObj, k - delta)) {
// previousElementIndex lets us not visit all elements, thus this delete
deletePropertyNode.executeEvaluated(thisObj, k);
}
k = previousElementIndex(thisObj, k);
}
}
private void spliceJSArrayElementwiseWalkUp(DynamicObject thisObj, long len, long actualStart, long actualDeleteCount, long itemCount) {
long k = actualStart + actualDeleteCount;
long delta = itemCount - actualDeleteCount;
while (k < len) {
spliceMoveValue(thisObj, k, k + delta);
if ((k - delta) < len && !hasProperty(thisObj, k - delta)) {
// nextElementIndex lets us not visit all elements, thus this delete
deletePropertyNode.executeEvaluated(thisObj, k);
}
k = nextElementIndex(thisObj, k, len);
}
k = len - 1;
while (k >= len + delta) {
deletePropertyNode.executeEvaluated(thisObj, k);
k = previousElementIndex(thisObj, k);
}
}
final void spliceJSArrayBlockwise(DynamicObject thisObj, long actualStart, long actualDeleteCount, long itemCount, ScriptArray array) {
assert JSArray.isJSArray(thisObj); // contract
if (itemCount < actualDeleteCount) {
branchA.enter();
arraySetArrayType(thisObj, array.removeRange(thisObj, actualStart + itemCount, actualStart + actualDeleteCount, errorBranch));
} else if (itemCount > actualDeleteCount) {
branchB.enter();
arraySetArrayType(thisObj, array.addRange(thisObj, actualStart, (int) (itemCount - actualDeleteCount)));
}
}
private void spliceForeignArray(Object thisObj, long len, long actualStart, long actualDeleteCount, long itemCount) {
InteropLibrary arrays = arrayInterop;
if (arrays == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
this.arrayInterop = arrays = insert(InteropLibrary.getFactory().createDispatched(JSConfig.InteropLibraryLimit));
}
try {
if (itemCount < actualDeleteCount) {
branchA.enter();
spliceForeignArrayShrink(thisObj, len, actualStart, actualDeleteCount, itemCount, arrays);
} else if (itemCount > actualDeleteCount) {
branchB.enter();
spliceForeignArrayMove(thisObj, len, actualStart, actualDeleteCount, itemCount, arrays);
}
} catch (UnsupportedMessageException | InvalidArrayIndexException | UnsupportedTypeException e) {
throw Errors.createTypeErrorInteropException(thisObj, e, "splice", this);
}
}
private static void spliceForeignArrayMove(Object thisObj, long len, long actualStart, long actualDeleteCount, long itemCount, InteropLibrary arrays)
throws UnsupportedMessageException, InvalidArrayIndexException, UnsupportedTypeException {
for (long k = len - actualDeleteCount; k > actualStart; k--) {
spliceForeignMoveValue(thisObj, (k + actualDeleteCount - 1), (k + itemCount - 1), arrays);
}
}
private static void spliceForeignArrayShrink(Object thisObj, long len, long actualStart, long actualDeleteCount, long itemCount, InteropLibrary arrays)
throws UnsupportedMessageException, InvalidArrayIndexException, UnsupportedTypeException {
for (long k = actualStart; k < len - actualDeleteCount; k++) {
spliceForeignMoveValue(thisObj, (k + actualDeleteCount), (k + itemCount), arrays);
}
for (long k = len; k > len - actualDeleteCount + itemCount; k--) {
arrays.removeArrayElement(thisObj, k - 1);
}
}
private static void spliceForeignMoveValue(Object thisObj, long fromIndex, long toIndex, InteropLibrary arrays)
throws UnsupportedMessageException, InvalidArrayIndexException, UnsupportedTypeException {
Object val = arrays.readArrayElement(thisObj, fromIndex);
arrays.writeArrayElement(thisObj, toIndex, val);
}
}
public abstract static class ArrayForEachIndexCallOperation extends JSArrayOperation {
public ArrayForEachIndexCallOperation(JSContext context, JSBuiltin builtin, boolean isTypedArrayImplementation) {
super(context, builtin, isTypedArrayImplementation);
}
public ArrayForEachIndexCallOperation(JSContext context, JSBuiltin builtin) {
this(context, builtin, false);
}
protected static class DefaultCallbackNode extends ForEachIndexCallNode.CallbackNode {
@Child protected JSFunctionCallNode callNode = JSFunctionCallNode.createCall();
protected final ConditionProfile indexInIntRangeCondition = ConditionProfile.createBinaryProfile();
@Override
public Object apply(long index, Object value, Object target, Object callback, Object callbackThisArg, Object currentResult) {
return callNode.executeCall(JSArguments.create(callbackThisArg, callback, value, JSRuntime.boxIndex(index, indexInIntRangeCondition), target));
}
}
@Child private ForEachIndexCallNode forEachIndexNode;
protected final Object forEachIndexCall(Object arrayObj, Object callbackObj, Object thisArg, long fromIndex, long length, Object initialResult) {
if (forEachIndexNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
forEachIndexNode = insert(makeForEachIndexCallNode());
}
return forEachIndexNode.executeForEachIndex(arrayObj, callbackObj, thisArg, fromIndex, length, initialResult);
}
private ForEachIndexCallNode makeForEachIndexCallNode() {
return ForEachIndexCallNode.create(getContext(), makeCallbackNode(), makeMaybeResultNode(), isForward(), shouldCheckHasProperty());
}
protected boolean isForward() {
return true;
}
protected boolean shouldCheckHasProperty() {
return !isTypedArrayImplementation;
}
protected CallbackNode makeCallbackNode() {
return new DefaultCallbackNode();
}
protected abstract MaybeResultNode makeMaybeResultNode();
}
public abstract static class JSArrayEveryNode extends ArrayForEachIndexCallOperation {
public JSArrayEveryNode(JSContext context, JSBuiltin builtin, boolean isTypedArrayImplementation) {
super(context, builtin, isTypedArrayImplementation);
}
@Specialization
protected boolean every(Object thisObj, Object callback, Object thisArg) {
Object thisJSObj = toObjectOrValidateTypedArray(thisObj);
long length = getLength(thisJSObj);
Object callbackFn = checkCallbackIsFunction(callback);
return (boolean) forEachIndexCall(thisJSObj, callbackFn, thisArg, 0, length, true);
}
@Override
protected MaybeResultNode makeMaybeResultNode() {
return new ForEachIndexCallNode.MaybeResultNode() {
@Child private JSToBooleanNode toBooleanNode = JSToBooleanNode.create();
@Override
public MaybeResult<Object> apply(long index, Object value, Object callbackResult, Object currentResult) {
return toBooleanNode.executeBoolean(callbackResult) ? MaybeResult.continueResult(currentResult) : MaybeResult.returnResult(false);
}
};
}
}
public abstract static class JSArrayFilterNode extends ArrayForEachIndexCallOperation {
private final ValueProfile arrayTypeProfile = ValueProfile.createClassProfile();
private final ValueProfile resultArrayTypeProfile = ValueProfile.createClassProfile();
public JSArrayFilterNode(JSContext context, JSBuiltin builtin, boolean isTypedArrayImplementation) {
super(context, builtin, isTypedArrayImplementation);
}
@Specialization
protected DynamicObject filter(Object thisObj, Object callback, Object thisArg) {
Object thisJSObj = toObjectOrValidateTypedArray(thisObj);
long length = getLength(thisJSObj);
Object callbackFn = checkCallbackIsFunction(callback);
DynamicObject resultArray;
if (isTypedArrayImplementation) {
resultArray = JSArray.createEmpty(getContext(), getRealm(), 0);
} else {
resultArray = (DynamicObject) getArraySpeciesConstructorNode().arraySpeciesCreate(thisJSObj, 0);
}
forEachIndexCall(thisJSObj, callbackFn, thisArg, 0, length, new FilterState(resultArray, 0));
if (isTypedArrayImplementation) {
return getTypedResult((DynamicObject) thisJSObj, resultArray);
} else {
return resultArray;
}
}
private DynamicObject getTypedResult(DynamicObject thisJSObj, DynamicObject resultArray) {
long resultLen = arrayGetLength(resultArray);
Object obj = getArraySpeciesConstructorNode().typedArraySpeciesCreate(thisJSObj, JSRuntime.longToIntOrDouble(resultLen));
if (!JSDynamicObject.isJSDynamicObject(obj)) {
errorBranch.enter();
throw Errors.createTypeErrorNotAnObject(obj);
}
DynamicObject typedResult = (DynamicObject) obj;
TypedArray typedArray = arrayTypeProfile.profile(JSArrayBufferView.typedArrayGetArrayType(typedResult));
ScriptArray array = resultArrayTypeProfile.profile(arrayGetArrayType(resultArray));
for (long i = 0; i < resultLen; i++) {
typedArray.setElement(typedResult, i, array.getElement(resultArray, i), true);
TruffleSafepoint.poll(this);
}
return typedResult;
}
static final class FilterState {
final DynamicObject resultArray;
long toIndex;
FilterState(DynamicObject resultArray, long toIndex) {
this.resultArray = resultArray;
this.toIndex = toIndex;
}
}
@Override
protected MaybeResultNode makeMaybeResultNode() {
return new ForEachIndexCallNode.MaybeResultNode() {
@Child private JSToBooleanNode toBooleanNode = JSToBooleanNode.create();
@Child private WriteElementNode writeOwnNode = WriteElementNode.create(getContext(), true, true);
@Override
public MaybeResult<Object> apply(long index, Object value, Object callbackResult, Object currentResult) {
if (toBooleanNode.executeBoolean(callbackResult)) {
FilterState filterState = (FilterState) currentResult;
writeOwnNode.executeWithTargetAndIndexAndValue(filterState.resultArray, filterState.toIndex++, value);
}
return MaybeResult.continueResult(currentResult);
}
};
}
}
public abstract static class JSArrayForEachNode extends ArrayForEachIndexCallOperation {
public JSArrayForEachNode(JSContext context, JSBuiltin builtin) {
super(context, builtin);
}
@Specialization
protected Object forEach(Object thisObj, Object callback, Object thisArg) {
Object thisJSObj = toObject(thisObj);
long length = getLength(thisJSObj);
Object callbackFn = checkCallbackIsFunction(callback);
return forEachIndexCall(thisJSObj, callbackFn, thisArg, 0, length, Undefined.instance);
}
@Override
protected MaybeResultNode makeMaybeResultNode() {
return new ForEachIndexCallNode.MaybeResultNode() {
@Override
public MaybeResult<Object> apply(long index, Object value, Object callbackResult, Object currentResult) {
return MaybeResult.continueResult(currentResult);
}
};
}
}
public abstract static class JSArraySomeNode extends ArrayForEachIndexCallOperation {
public JSArraySomeNode(JSContext context, JSBuiltin builtin, boolean isTypedArrayImplementation) {
super(context, builtin, isTypedArrayImplementation);
}
@Specialization
protected boolean some(Object thisObj, Object callback, Object thisArg) {
Object thisJSObj = toObjectOrValidateTypedArray(thisObj);
long length = getLength(thisJSObj);
Object callbackFn = checkCallbackIsFunction(callback);
return (boolean) forEachIndexCall(thisJSObj, callbackFn, thisArg, 0, length, false);
}
@Override
protected MaybeResultNode makeMaybeResultNode() {
return new ForEachIndexCallNode.MaybeResultNode() {
@Child private JSToBooleanNode toBooleanNode = JSToBooleanNode.create();
@Override
public MaybeResult<Object> apply(long index, Object value, Object callbackResult, Object currentResult) {
return toBooleanNode.executeBoolean(callbackResult) ? MaybeResult.returnResult(true) : MaybeResult.continueResult(currentResult);
}
};
}
}
public abstract static class JSArrayMapNode extends ArrayForEachIndexCallOperation {
public JSArrayMapNode(JSContext context, JSBuiltin builtin, boolean isTypedArrayImplementation) {
super(context, builtin, isTypedArrayImplementation);
}
@Specialization
protected Object map(Object thisObj, Object callback, Object thisArg) {
Object thisJSObj = toObjectOrValidateTypedArray(thisObj);
long length = getLength(thisJSObj);
Object callbackFn = checkCallbackIsFunction(callback);
Object resultArray = getArraySpeciesConstructorNode().createEmptyContainer(thisJSObj, length);
return forEachIndexCall(thisJSObj, callbackFn, thisArg, 0, length, resultArray);
}
@Override
protected MaybeResultNode makeMaybeResultNode() {
return new ForEachIndexCallNode.MaybeResultNode() {
@Child private WriteElementNode writeOwnNode = WriteElementNode.create(getContext(), true, true);
@Override
public MaybeResult<Object> apply(long index, Object value, Object callbackResult, Object currentResult) {
writeOwnNode.executeWithTargetAndIndexAndValue(currentResult, index, callbackResult);
return MaybeResult.continueResult(currentResult);
}
};
}
}
public abstract static class FlattenIntoArrayNode extends JavaScriptBaseNode {
private static final class InnerFlattenCallNode extends JavaScriptRootNode {
@Child private FlattenIntoArrayNode flattenNode;
InnerFlattenCallNode(JSContext context, FlattenIntoArrayNode flattenNode) {
super(context.getLanguage(), null, null);
this.flattenNode = flattenNode;
}
@Override
public Object execute(VirtualFrame frame) {
Object[] arguments = frame.getArguments();
DynamicObject resultArray = (DynamicObject) arguments[0];
Object element = arguments[1];
long elementLen = (long) arguments[2];
long targetIndex = (long) arguments[3];
long depth = (long) arguments[4];
return flattenNode.flatten(resultArray, element, elementLen, targetIndex, depth, null, null);
}
}
protected final JSContext context;
protected final boolean withMapCallback;
@Child private ForEachIndexCallNode forEachIndexNode;
@Child private JSToObjectNode toObjectNode;
@Child private JSGetLengthNode getLengthNode;
protected FlattenIntoArrayNode(JSContext context, boolean withMapCallback) {
this.context = context;
this.withMapCallback = withMapCallback;
}
public static FlattenIntoArrayNode create(JSContext context, boolean withCallback) {
return FlattenIntoArrayNodeGen.create(context, withCallback);
}
protected abstract long executeLong(DynamicObject target, Object source, long sourceLen, long start, long depth, Object callback, Object thisArg);
@Specialization
protected long flatten(DynamicObject target, Object source, long sourceLen, long start, long depth, Object callback, Object thisArg) {
boolean callbackUndefined = callback == null;
FlattenState flattenState = new FlattenState(target, start, depth, callbackUndefined);
Object thisJSObj = toObject(source);
forEachIndexCall(thisJSObj, callback, thisArg, 0, sourceLen, flattenState);
return flattenState.targetIndex;
}
protected final Object forEachIndexCall(Object arrayObj, Object callbackObj, Object thisArg, long fromIndex, long length, Object initialResult) {
if (forEachIndexNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
forEachIndexNode = insert(makeForEachIndexCallNode());
}
return forEachIndexNode.executeForEachIndex(arrayObj, callbackObj, thisArg, fromIndex, length, initialResult);
}
private ForEachIndexCallNode makeForEachIndexCallNode() {
return ForEachIndexCallNode.create(context, makeCallbackNode(), makeMaybeResultNode(), true, true);
}
protected CallbackNode makeCallbackNode() {
return withMapCallback ? new ArrayForEachIndexCallOperation.DefaultCallbackNode() : null;
}
protected final Object toObject(Object target) {
if (toObjectNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
toObjectNode = insert(JSToObjectNode.createToObject(context));
}
return toObjectNode.execute(target);
}
protected long getLength(Object thisObject) {
if (getLengthNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
getLengthNode = insert(JSGetLengthNode.create(context));
}
return getLengthNode.executeLong(thisObject);
}
static final class FlattenState {
final DynamicObject resultArray;
final boolean callbackUndefined;
final long depth;
long targetIndex;
FlattenState(DynamicObject result, long toIndex, long depth, boolean callbackUndefined) {
this.resultArray = result;
this.callbackUndefined = callbackUndefined;
this.targetIndex = toIndex;
this.depth = depth;
}
}
protected MaybeResultNode makeMaybeResultNode() {
return new ForEachIndexCallNode.MaybeResultNode() {
protected final BranchProfile errorBranch = BranchProfile.create();
@Child private WriteElementNode writeOwnNode = WriteElementNode.create(context, true, true);
@Child private DirectCallNode innerFlattenCall;
@Override
public MaybeResult<Object> apply(long index, Object originalValue, Object callbackResult, Object resultState) {
boolean shouldFlatten = false;
FlattenState state = (FlattenState) resultState;
Object value = state.callbackUndefined ? originalValue : callbackResult;
if (state.depth > 0) {
shouldFlatten = JSRuntime.isArray(value);
}
if (shouldFlatten) {
long elementLen = getLength(toObject(value));
state.targetIndex = makeFlattenCall(state.resultArray, value, elementLen, state.targetIndex, state.depth - 1);
} else {
if (state.targetIndex >= JSRuntime.MAX_SAFE_INTEGER_LONG) { // 2^53-1
errorBranch.enter();
throw Errors.createTypeError("Index out of bounds in flatten into array");
}
writeOwnNode.executeWithTargetAndIndexAndValue(state.resultArray, state.targetIndex++, value);
}
return MaybeResult.continueResult(resultState);
}
private long makeFlattenCall(DynamicObject targetArray, Object element, long elementLength, long targetIndex, long depth) {
if (innerFlattenCall == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
JSFunctionData flattenFunctionData = context.getOrCreateBuiltinFunctionData(JSContext.BuiltinFunctionKey.ArrayFlattenIntoArray, c -> createOrGetFlattenCallFunctionData(c));
innerFlattenCall = insert(DirectCallNode.create(flattenFunctionData.getCallTarget()));
}
return (long) innerFlattenCall.call(targetArray, element, elementLength, targetIndex, depth);
}
};
}
private static JSFunctionData createOrGetFlattenCallFunctionData(JSContext context) {
return JSFunctionData.createCallOnly(context,
Truffle.getRuntime().createCallTarget(new InnerFlattenCallNode(context, FlattenIntoArrayNode.create(context, false))), 0, "");
}
}
public abstract static class JSArrayFlatMapNode extends JSArrayOperation {
public JSArrayFlatMapNode(JSContext context, JSBuiltin builtin) {
super(context, builtin, false);
}
@Specialization
protected Object flatMap(Object thisObj, Object callback, Object thisArg,
@Cached("createFlattenIntoArrayNode(getContext())") FlattenIntoArrayNode flattenIntoArrayNode) {
Object thisJSObj = toObject(thisObj);
long length = getLength(thisJSObj);
Object callbackFn = checkCallbackIsFunction(callback);
Object resultArray = getArraySpeciesConstructorNode().createEmptyContainer(thisJSObj, 0);
flattenIntoArrayNode.flatten((DynamicObject) resultArray, thisJSObj, length, 0, 1, callbackFn, thisArg);
return resultArray;
}
protected static final FlattenIntoArrayNode createFlattenIntoArrayNode(JSContext context) {
return FlattenIntoArrayNodeGen.create(context, true);
}
}
public abstract static class JSArrayFlatNode extends JSArrayOperation {
@Child private JSToIntegerAsIntNode toIntegerNode;
public JSArrayFlatNode(JSContext context, JSBuiltin builtin) {
super(context, builtin, false);
}
@Specialization
protected Object flat(Object thisObj, Object depth,
@Cached("createFlattenIntoArrayNode(getContext())") FlattenIntoArrayNode flattenIntoArrayNode) {
Object thisJSObj = toObject(thisObj);
long length = getLength(thisJSObj);
long depthNum = (depth == Undefined.instance) ? 1 : toIntegerAsInt(depth);
Object resultArray = getArraySpeciesConstructorNode().createEmptyContainer(thisJSObj, 0);
flattenIntoArrayNode.flatten((DynamicObject) resultArray, thisJSObj, length, 0, depthNum, null, null);
return resultArray;
}
private int toIntegerAsInt(Object depth) {
if (toIntegerNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
toIntegerNode = insert(JSToIntegerAsIntNode.create());
}
return toIntegerNode.executeInt(depth);
}
protected static final FlattenIntoArrayNode createFlattenIntoArrayNode(JSContext context) {
return FlattenIntoArrayNodeGen.create(context, false);
}
}
public abstract static class JSArrayFindNode extends JSArrayOperation {
@Child private JSToBooleanNode toBooleanNode = JSToBooleanNode.create();
@Child private JSFunctionCallNode callNode = JSFunctionCallNode.createCall();
public JSArrayFindNode(JSContext context, JSBuiltin builtin, boolean isTypedArrayImplementation) {
super(context, builtin, isTypedArrayImplementation);
}
private Object callPredicate(Object function, Object target, Object value, double index, Object thisObj) {
return callNode.executeCall(JSArguments.create(target, function, value, index, thisObj));
}
@Specialization
protected Object find(Object thisObj, Object callback, Object thisArg) {
Object thisJSObj = toObjectOrValidateTypedArray(thisObj);
long length = getLength(thisJSObj);
Object callbackFn = checkCallbackIsFunction(callback);
for (long idx = 0; idx < length; idx++) {
Object value = read(thisObj, idx);
Object callbackResult = callPredicate(callbackFn, thisArg, value, idx, thisJSObj);
boolean testResult = toBooleanNode.executeBoolean(callbackResult);
if (testResult) {
reportLoopCount(idx);
return value;
}
}
reportLoopCount(length);
return Undefined.instance;
}
}
public abstract static class JSArrayFindIndexNode extends JSArrayOperation {
@Child private JSToBooleanNode toBooleanNode = JSToBooleanNode.create();
@Child private JSFunctionCallNode callNode = JSFunctionCallNode.createCall();
public JSArrayFindIndexNode(JSContext context, JSBuiltin builtin, boolean isTypedArrayImplementation) {
super(context, builtin, isTypedArrayImplementation);
}
private Object callPredicate(Object function, Object target, Object value, double index, Object thisObj) {
return callNode.executeCall(JSArguments.create(target, function, value, index, thisObj));
}
@Specialization
protected Object findIndex(Object thisObj, Object callback, Object thisArg) {
Object thisJSObj = toObjectOrValidateTypedArray(thisObj);
long length = getLength(thisJSObj);
Object callbackFn = checkCallbackIsFunction(callback);
for (long idx = 0; idx < length; idx++) {
Object value = read(thisObj, idx);
Object callbackResult = callPredicate(callbackFn, thisArg, value, idx, thisJSObj);
boolean testResult = toBooleanNode.executeBoolean(callbackResult);
if (testResult) {
reportLoopCount(idx);
return JSRuntime.positiveLongToIntOrDouble(idx);
}
}
reportLoopCount(length);
return -1;
}
}
public abstract static class JSArraySortNode extends JSArrayOperation {
@Child private DeletePropertyNode deletePropertyNode; // DeletePropertyOrThrow
private final ConditionProfile isSparse = ConditionProfile.create();
private final BranchProfile hasCompareFnBranch = BranchProfile.create();
private final BranchProfile noCompareFnBranch = BranchProfile.create();
private final BranchProfile growProfile = BranchProfile.create();
@Child private InteropLibrary interopNode;
@Child private ImportValueNode importValueNode;
public JSArraySortNode(JSContext context, JSBuiltin builtin, boolean isTypedArrayImplementation) {
super(context, builtin, isTypedArrayImplementation);
}
@Specialization(guards = {"!isTypedArrayImplementation", "isJSFastArray(thisObj)"}, assumptions = "getContext().getArrayPrototypeNoElementsAssumption()")
protected DynamicObject sortArray(final DynamicObject thisObj, final Object compare,
@Cached("create(getContext())") JSArrayToDenseObjectArrayNode arrayToObjectArrayNode,
@Cached("create(getContext(), true)") JSArrayDeleteRangeNode arrayDeleteRangeNode) {
checkCompareFunction(compare);
long len = getLength(thisObj);
if (len < 2) {
// nothing to do
return thisObj;
}
ScriptArray scriptArray = arrayGetArrayType(thisObj);
Object[] array = arrayToObjectArrayNode.executeObjectArray(thisObj, scriptArray, len);
sortIntl(getComparator(thisObj, compare), array);
reportLoopCount(len); // best effort guess, let's not go for n*log(n)
for (int i = 0; i < array.length; i++) {
write(thisObj, i, array[i]);
}
if (isSparse.profile(array.length < len)) {
arrayDeleteRangeNode.execute(thisObj, scriptArray, array.length, len);
}
return thisObj;
}
private void delete(Object obj, Object i) {
if (deletePropertyNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
JSContext context = getContext();
deletePropertyNode = insert(DeletePropertyNode.create(true, context));
}
deletePropertyNode.executeEvaluated(obj, i);
}
@Specialization
protected Object sort(Object thisObj, final Object comparefn,
@Cached("createBinaryProfile()") ConditionProfile isJSObject) {
checkCompareFunction(comparefn);
Object thisJSObj = toObjectOrValidateTypedArray(thisObj);
if (isJSObject.profile(JSDynamicObject.isJSDynamicObject(thisJSObj))) {
return sortJSObject(comparefn, (DynamicObject) thisJSObj);
} else {
return sortForeignObject(comparefn, thisJSObj);
}
}
private DynamicObject sortJSObject(final Object comparefn, DynamicObject thisJSObj) {
long len = getLength(thisJSObj);
if (len == 0) {
// nothing to do
return thisJSObj;
}
Object[] array = jsobjectToArray(thisJSObj, len);
Comparator<Object> comparator = getComparator(thisJSObj, comparefn);
if (isTypedArrayImplementation && comparefn == Undefined.instance) {
assert comparator == null;
prepareForDefaultComparator(array);
}
sortIntl(comparator, array);
reportLoopCount(len);
for (int i = 0; i < array.length; i++) {
write(thisJSObj, i, array[i]);
}
if (isSparse.profile(array.length < len)) {
deleteGenericElements(thisJSObj, array.length, len);
}
return thisJSObj;
}
public Object sortForeignObject(Object comparefn, Object thisObj) {
assert JSGuards.isForeignObject(thisObj);
long len = getLength(thisObj);
if (len < 2) {
// nothing to do
return thisObj;
}
if (len >= Integer.MAX_VALUE) {
errorBranch.enter();
throw Errors.createRangeErrorInvalidArrayLength();
}
Object[] array = foreignArrayToObjectArray(thisObj, (int) len);
Comparator<Object> comparator = getComparator(thisObj, comparefn);
sortIntl(comparator, array);
reportLoopCount(len);
for (int i = 0; i < array.length; i++) {
write(thisObj, i, array[i]);
}
return thisObj;
}
private void checkCompareFunction(Object compare) {
if (!(compare == Undefined.instance || isCallable(compare))) {
errorBranch.enter();
throw Errors.createTypeError("The comparison function must be either a function or undefined");
}
}
private Comparator<Object> getComparator(Object thisObj, Object compare) {
if (compare == Undefined.instance) {
noCompareFnBranch.enter();
return getDefaultComparator(thisObj);
} else {
assert isCallable(compare);
hasCompareFnBranch.enter();
DynamicObject arrayBufferObj = isTypedArrayImplementation && JSArrayBufferView.isJSArrayBufferView(thisObj) ? JSArrayBufferView.getArrayBuffer((DynamicObject) thisObj) : null;
return new SortComparator(compare, arrayBufferObj);
}
}
private Comparator<Object> getDefaultComparator(Object thisObj) {
if (isTypedArrayImplementation) {
return null; // use Comparable.compareTo (equivalent to Comparator.naturalOrder())
} else {
if (JSArray.isJSArray(thisObj)) {
ScriptArray array = arrayGetArrayType((DynamicObject) thisObj);
if (array instanceof AbstractIntArray || array instanceof ConstantByteArray || array instanceof ConstantIntArray) {
return JSArray.DEFAULT_JSARRAY_INTEGER_COMPARATOR;
} else if (array instanceof AbstractDoubleArray || array instanceof ConstantDoubleArray) {
return JSArray.DEFAULT_JSARRAY_DOUBLE_COMPARATOR;
}
}
return JSArray.DEFAULT_JSARRAY_COMPARATOR;
}
}
/**
* In a generic JSObject, this deletes all elements between the actual "size" (i.e., number
* of non-empty elements) and the "length" (value of the property). I.e., it cleans up
* garbage remaining after sorting all elements to lower indices (in case there are holes).
*/
private void deleteGenericElements(Object obj, long fromIndex, long toIndex) {
for (long index = fromIndex; index < toIndex; index++) {
delete(obj, index);
}
}
@TruffleBoundary
private static void sortIntl(Comparator<Object> comparator, Object[] array) {
try {
Arrays.sort(array, comparator);
} catch (IllegalArgumentException e) {
// Collections.sort throws IllegalArgumentException when
// Comparison method violates its general contract
// See ECMA spec 192.168.127.12 Array.prototype.sort (comparefn).
// If "comparefn" is not undefined and is not a consistent
// comparison function for the elements of this array, the
// behaviour of sort is implementation-defined.
}
}
private static void prepareForDefaultComparator(Object[] array) {
// Default comparator (based on Comparable.compareTo) cannot be used
// for elements of different type (for example, Integer.compareTo()
// accepts Integers only, not Doubles).
boolean needsConversion = false;
Class<?> clazz = array[0].getClass();
for (Object element : array) {
Class<?> c = element.getClass();
if (clazz != c) {
needsConversion = true;
break;
}
}
if (needsConversion) {
for (int i = 0; i < array.length; i++) {
array[i] = JSRuntime.toDouble(array[i]);
}
}
}
private class SortComparator implements Comparator<Object> {
private final Object compFnObj;
private final DynamicObject arrayBufferObj;
private final boolean isFunction;
SortComparator(Object compFnObj, DynamicObject arrayBufferObj) {
this.compFnObj = compFnObj;
this.arrayBufferObj = arrayBufferObj;
this.isFunction = JSFunction.isJSFunction(compFnObj);
}
@Override
public int compare(Object arg0, Object arg1) {
if (arg0 == Undefined.instance) {
if (arg1 == Undefined.instance) {
return 0;
}
return 1;
} else if (arg1 == Undefined.instance) {
return -1;
}
Object retObj;
if (isFunction) {
retObj = JSFunction.call((DynamicObject) compFnObj, Undefined.instance, new Object[]{arg0, arg1});
} else {
retObj = JSRuntime.call(compFnObj, Undefined.instance, new Object[]{arg0, arg1});
}
int res = convertResult(retObj);
if (isTypedArrayImplementation) {
if (!getContext().getTypedArrayNotDetachedAssumption().isValid() && JSArrayBuffer.isDetachedBuffer(arrayBufferObj)) {
errorBranch.enter();
throw Errors.createTypeErrorDetachedBuffer();
}
}
return res;
}
private int convertResult(Object retObj) {
if (retObj instanceof Integer) {
return (int) retObj;
} else {
double d = JSRuntime.toDouble(retObj);
if (d < 0) {
return -1;
} else if (d > 0) {
return 1;
} else {
// +/-0 or NaN
return 0;
}
}
}
}
@TruffleBoundary
private Object[] jsobjectToArray(DynamicObject thisObj, long len) {
SimpleArrayList<Object> list = SimpleArrayList.create(len);
for (long k = 0; k < len; k++) {
if (JSObject.hasProperty(thisObj, k)) {
list.add(JSObject.get(thisObj, k), growProfile);
}
}
return list.toArray();
}
private Object[] foreignArrayToObjectArray(Object thisObj, int len) {
InteropLibrary interop = interopNode;
ImportValueNode importValue = importValueNode;
if (interop == null || importValue == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
interopNode = interop = insert(InteropLibrary.getFactory().createDispatched(JSConfig.InteropLibraryLimit));
importValueNode = importValue = insert(ImportValueNode.create());
}
Object[] array = new Object[len];
for (int index = 0; index < len; index++) {
array[index] = JSInteropUtil.readArrayElementOrDefault(thisObj, index, Undefined.instance, interop, importValue, this);
}
return array;
}
}
public abstract static class JSArrayReduceNode extends ArrayForEachIndexCallOperation {
private final boolean isForward;
public JSArrayReduceNode(JSContext context, JSBuiltin builtin, boolean isTypedArrayImplementation, boolean isForward) {
super(context, builtin, isTypedArrayImplementation);
this.isForward = isForward;
}
private final BranchProfile findInitialValueBranch = BranchProfile.create();
@Child private ForEachIndexCallNode forEachIndexFindInitialNode;
@Specialization
protected Object reduce(Object thisObj, Object callback, Object... initialValueOpt) {
Object thisJSObj = toObjectOrValidateTypedArray(thisObj);
long length = getLength(thisJSObj);
Object callbackFn = checkCallbackIsFunction(callback);
Object currentValue = initialValueOpt.length > 0 ? initialValueOpt[0] : null;
long currentIndex = isForward() ? 0 : length - 1;
if (currentValue == null) {
findInitialValueBranch.enter();
Pair<Long, Object> res = findInitialValue(thisJSObj, currentIndex, length);
currentIndex = res.getFirst() + (isForward() ? 1 : -1);
currentValue = res.getSecond();
}
return forEachIndexCall(thisJSObj, callbackFn, Undefined.instance, currentIndex, length, currentValue);
}
@Override
protected boolean isForward() {
return isForward;
}
@SuppressWarnings("unchecked")
protected final Pair<Long, Object> findInitialValue(Object arrayObj, long fromIndex, long length) {
if (length >= 0) {
Pair<Long, Object> res = (Pair<Long, Object>) getForEachIndexFindInitialNode().executeForEachIndex(arrayObj, null, null, fromIndex, length, null);
if (res != null) {
return res;
}
}
errorBranch.enter();
throw reduceNoInitialValueError();
}
private ForEachIndexCallNode getForEachIndexFindInitialNode() {
if (forEachIndexFindInitialNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
forEachIndexFindInitialNode = insert(ForEachIndexCallNode.create(getContext(), null, new ForEachIndexCallNode.MaybeResultNode() {
@Override
public MaybeResult<Object> apply(long index, Object value, Object callbackResult, Object currentResult) {
return MaybeResult.returnResult(new Pair<>(index, value));
}
}, isForward(), shouldCheckHasProperty()));
}
return forEachIndexFindInitialNode;
}
@Override
protected CallbackNode makeCallbackNode() {
return new DefaultCallbackNode() {
@Override
public Object apply(long index, Object value, Object target, Object callback, Object callbackThisArg, Object currentResult) {
return callNode.executeCall(JSArguments.create(callbackThisArg, callback, currentResult, value, JSRuntime.boxIndex(index, indexInIntRangeCondition), target));
}
};
}
@Override
protected MaybeResultNode makeMaybeResultNode() {
return new ForEachIndexCallNode.MaybeResultNode() {
@Override
public MaybeResult<Object> apply(long index, Object value, Object callbackResult, Object currentResult) {
return MaybeResult.continueResult(callbackResult);
}
};
}
@TruffleBoundary
protected static RuntimeException reduceNoInitialValueError() {
throw Errors.createTypeError("Reduce of empty array with no initial value");
}
}
public abstract static class JSArrayFillNode extends JSArrayOperationWithToInt {
private final ConditionProfile offsetProfile1 = ConditionProfile.createBinaryProfile();
private final ConditionProfile offsetProfile2 = ConditionProfile.createBinaryProfile();
public JSArrayFillNode(JSContext context, JSBuiltin builtin, boolean isTypedArrayImplementation) {
super(context, builtin, isTypedArrayImplementation);
}
@Specialization
protected Object fill(Object thisObj, Object value, Object start, Object end) {
Object thisJSObj = toObjectOrValidateTypedArray(thisObj);
long len = getLength(thisJSObj);
long lStart = JSRuntime.getOffset(toIntegerAsLong(start), len, offsetProfile1);
long lEnd = end == Undefined.instance ? len : JSRuntime.getOffset(toIntegerAsLong(end), len, offsetProfile2);
for (long idx = lStart; idx < lEnd; idx++) {
write(thisJSObj, idx, value);
TruffleSafepoint.poll(this);
}
reportLoopCount(lEnd - lStart);
return thisJSObj;
}
}
public abstract static class JSArrayCopyWithinNode extends JSArrayOperationWithToInt {
@Child private DeletePropertyNode deletePropertyNode; // DeletePropertyOrThrow
private final ConditionProfile offsetProfile1 = ConditionProfile.createBinaryProfile();
private final ConditionProfile offsetProfile2 = ConditionProfile.createBinaryProfile();
private final ConditionProfile offsetProfile3 = ConditionProfile.createBinaryProfile();
public JSArrayCopyWithinNode(JSContext context, JSBuiltin builtin, boolean isTypedArrayImplementation) {
super(context, builtin, isTypedArrayImplementation);
this.deletePropertyNode = DeletePropertyNode.create(THROW_ERROR, context);
}
@Specialization
protected Object copyWithin(Object thisObj, Object target, Object start, Object end) {
Object obj = toObjectOrValidateTypedArray(thisObj);
long len = getLength(obj);
long to = JSRuntime.getOffset(toIntegerAsLong(target), len, offsetProfile1);
long from = JSRuntime.getOffset(toIntegerAsLong(start), len, offsetProfile2);
long finalIdx;
if (end == Undefined.instance) {
finalIdx = len;
} else {
finalIdx = JSRuntime.getOffset(toIntegerAsLong(end), len, offsetProfile3);
}
long count = Math.min(finalIdx - from, len - to);
long expectedCount = count;
if (count > 0) {
if (isTypedArrayImplementation) {
checkHasDetachedBuffer((DynamicObject) thisObj);
}
long direction;
if (from < to && to < (from + count)) {
direction = -1;
from = from + count - 1;
to = to + count - 1;
} else {
direction = 1;
}
while (count > 0) {
if (isTypedArrayImplementation || hasProperty(obj, from)) {
Object fromVal = read(obj, from);
write(obj, to, fromVal);
} else {
deletePropertyNode.executeEvaluated(obj, to);
}
from += direction;
to += direction;
count--;
TruffleSafepoint.poll(this);
}
reportLoopCount(expectedCount);
}
return obj;
}
}
public abstract static class JSArrayIncludesNode extends JSArrayOperationWithToInt {
public JSArrayIncludesNode(JSContext context, JSBuiltin builtin, boolean isTypedArrayImplementation) {
super(context, builtin, isTypedArrayImplementation);
}
@Specialization
protected boolean includes(Object thisValue, Object searchElement, Object fromIndex,
@Cached("createSameValueZero()") JSIdenticalNode identicalNode) {
Object thisObj = toObjectOrValidateTypedArray(thisValue);
long len = getLength(thisObj);
if (len == 0) {
return false;
}
long n = toIntegerAsLong(fromIndex);
long k;
if (n >= 0) {
k = n;
} else {
k = len + n;
if (k < 0) {
k = 0;
}
}
if (!identicalNode.executeBoolean(searchElement, searchElement)) {
return true;
}
long startIdx = k;
while (k < len) {
Object currentElement = read(thisObj, k);
if (identicalNode.executeBoolean(searchElement, currentElement)) {
reportLoopCount(k - startIdx);
return true;
}
k++;
TruffleSafepoint.poll(this);
}
reportLoopCount(len - startIdx);
return false;
}
}
public abstract static class JSArrayReverseNode extends JSArrayOperation {
@Child private TestArrayNode hasHolesNode;
@Child private DeletePropertyNode deletePropertyNode;
private final ConditionProfile bothExistProfile = ConditionProfile.createBinaryProfile();
private final ConditionProfile onlyUpperExistsProfile = ConditionProfile.createBinaryProfile();
private final ConditionProfile onlyLowerExistsProfile = ConditionProfile.createBinaryProfile();
public JSArrayReverseNode(JSContext context, JSBuiltin builtin) {
super(context, builtin);
this.hasHolesNode = TestArrayNode.createHasHoles();
}
private boolean deleteProperty(Object array, long index) {
if (deletePropertyNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
deletePropertyNode = insert(DeletePropertyNode.create(true, getContext()));
}
return deletePropertyNode.executeEvaluated(array, index);
}
@Specialization
protected Object reverseJSArray(JSArrayObject thisObj) {
return reverse(thisObj, true);
}
@Specialization(replaces = "reverseJSArray")
protected Object reverseGeneric(Object thisObj) {
final Object array = toObject(thisObj);
return reverse(array, JSArray.isJSArray(array));
}
private Object reverse(Object array, boolean isArray) {
final long length = getLength(array);
long lower = 0;
long upper = length - 1;
boolean hasHoles = isArray && hasHolesNode.executeBoolean((DynamicObject) array);
while (lower < upper) {
boolean lowerExists;
boolean upperExists;
Object lowerValue = null;
Object upperValue = null;
if (getContext().getEcmaScriptVersion() < 6) { // ES5 expects GET before HAS
lowerValue = read(array, lower);
upperValue = read(array, upper);
lowerExists = lowerValue != Undefined.instance || hasProperty(array, lower);
upperExists = upperValue != Undefined.instance || hasProperty(array, upper);
} else { // ES6 expects HAS before GET and tries GET only if HAS succeeds
lowerExists = hasProperty(array, lower);
if (lowerExists) {
lowerValue = read(array, lower);
}
upperExists = hasProperty(array, upper);
if (upperExists) {
upperValue = read(array, upper);
}
}
if (bothExistProfile.profile(lowerExists && upperExists)) {
write(array, lower, upperValue);
write(array, upper, lowerValue);
} else if (onlyUpperExistsProfile.profile(!lowerExists && upperExists)) {
write(array, lower, upperValue);
deleteProperty(array, upper);
} else if (onlyLowerExistsProfile.profile(lowerExists && !upperExists)) {
deleteProperty(array, lower);
write(array, upper, lowerValue);
} else {
assert !lowerExists && !upperExists; // No action required.
}
if (hasHoles) {
long nextLower = nextElementIndex(array, lower, length);
long nextUpper = previousElementIndex(array, upper);
if ((length - nextLower - 1) >= nextUpper) {
lower = nextLower;
upper = length - lower - 1;
} else {
lower = length - nextUpper - 1;
upper = nextUpper;
}
} else {
lower++;
upper--;
}
TruffleSafepoint.poll(this);
}
reportLoopCount(lower);
return array;
}
}
public static class CreateArrayIteratorNode extends JavaScriptBaseNode {
private final int iterationKind;
@Child private CreateObjectNode.CreateObjectWithPrototypeNode createObjectNode;
@Child private PropertySetNode setNextIndexNode;
@Child private PropertySetNode setIteratedObjectNode;
@Child private PropertySetNode setIterationKindNode;
protected CreateArrayIteratorNode(JSContext context, int iterationKind) {
this.iterationKind = iterationKind;
this.createObjectNode = CreateObjectNode.createOrdinaryWithPrototype(context);
this.setIteratedObjectNode = PropertySetNode.createSetHidden(JSRuntime.ITERATED_OBJECT_ID, context);
this.setNextIndexNode = PropertySetNode.createSetHidden(JSRuntime.ITERATOR_NEXT_INDEX, context);
this.setIterationKindNode = PropertySetNode.createSetHidden(JSArray.ARRAY_ITERATION_KIND_ID, context);
}
public static CreateArrayIteratorNode create(JSContext context, int iterationKind) {
return new CreateArrayIteratorNode(context, iterationKind);
}
public DynamicObject execute(VirtualFrame frame, Object array) {
assert JSGuards.isJSObject(array) || JSGuards.isForeignObject(array);
DynamicObject iterator = createObjectNode.execute(frame, getRealm().getArrayIteratorPrototype());
setIteratedObjectNode.setValue(iterator, array);
setNextIndexNode.setValue(iterator, 0L);
setIterationKindNode.setValueInt(iterator, iterationKind);
return iterator;
}
}
public abstract static class JSArrayIteratorNode extends JSBuiltinNode {
@Child private CreateArrayIteratorNode createArrayIteratorNode;
public JSArrayIteratorNode(JSContext context, JSBuiltin builtin, int iterationKind) {
super(context, builtin);
this.createArrayIteratorNode = CreateArrayIteratorNode.create(context, iterationKind);
}
@Specialization(guards = "isJSObject(thisObj)")
protected DynamicObject doJSObject(VirtualFrame frame, DynamicObject thisObj) {
return createArrayIteratorNode.execute(frame, thisObj);
}
@Specialization(guards = "!isJSObject(thisObj)")
protected DynamicObject doNotJSObject(VirtualFrame frame, Object thisObj,
@Cached("createToObject(getContext())") JSToObjectNode toObjectNode) {
return createArrayIteratorNode.execute(frame, toObjectNode.execute(thisObj));
}
}
public abstract static class JSArrayAtNode extends JSArrayOperationWithToInt {
public JSArrayAtNode(JSContext context, JSBuiltin builtin, boolean isTypedArrayImplementation) {
super(context, builtin, isTypedArrayImplementation);
}
@Specialization
protected Object at(Object thisObj, Object index) {
final Object o = toObjectOrValidateTypedArray(thisObj);
final long length = getLength(o);
long relativeIndex = toIntegerAsLong(index);
long k;
if (relativeIndex >= 0) {
k = relativeIndex;
} else {
k = length + relativeIndex;
}
if (k < 0 || k >= length) {
return Undefined.instance;
}
return read(o, k);
}
}
}
|
9237b38eee8fec0416420a302470b14c5f8980bc | 1,763 | java | Java | com.ibm.wala.util/src/com/ibm/wala/fixpoint/BooleanVariable.java | nithinvnath/PAVProject | 806e30fd089a9b324ae626c61438a80db40a8b0a | [
"MIT"
] | 10 | 2019-11-06T06:13:54.000Z | 2020-08-24T08:06:10.000Z | com.ibm.wala.util/src/com/ibm/wala/fixpoint/BooleanVariable.java | nithinvnath/PAVProject | 806e30fd089a9b324ae626c61438a80db40a8b0a | [
"MIT"
] | null | null | null | com.ibm.wala.util/src/com/ibm/wala/fixpoint/BooleanVariable.java | nithinvnath/PAVProject | 806e30fd089a9b324ae626c61438a80db40a8b0a | [
"MIT"
] | 2 | 2020-08-24T08:06:14.000Z | 2021-05-14T09:29:13.000Z | 22.316456 | 81 | 0.589336 | 998,169 | /*******************************************************************************
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.wala.fixpoint;
/**
* A boolean variable for dataflow analysis.
*/
public class BooleanVariable extends AbstractVariable<BooleanVariable> {
private boolean B;
public BooleanVariable() {
}
/**
* @param b initial value for this variable
*/
public BooleanVariable(boolean b) {
this.B = b;
}
@Override
public void copyState(BooleanVariable other) {
if (other == null) {
throw new IllegalArgumentException("other null");
}
B = other.B;
}
public boolean sameValue(BooleanVariable other) {
if (other == null) {
throw new IllegalArgumentException("other is null");
}
return B == other.B;
}
@Override
public String toString() {
return (B ? "[TRUE]" : "[FALSE]");
}
/**
* @return the value of this variable
*/
public boolean getValue() {
return B;
}
/**
* @param other
* @throws IllegalArgumentException if other is null
*/
public void or(BooleanVariable other) {
if (other == null) {
throw new IllegalArgumentException("other is null");
}
B = B | other.B;
}
public void set(boolean b) {
B = b;
}
@Override
public boolean equals(Object obj) {
return this == obj;
}
}
|
9237b3a70dcbee8ddc608677ce6b698ae69de398 | 2,664 | java | Java | Application/build/generated/source/r/debug/com/example/android/customnotifications/R.java | Brainrj/My_Application | 28c9f5ac19d5b19369eb164c582d14961a1509cf | [
"Apache-2.0"
] | null | null | null | Application/build/generated/source/r/debug/com/example/android/customnotifications/R.java | Brainrj/My_Application | 28c9f5ac19d5b19369eb164c582d14961a1509cf | [
"Apache-2.0"
] | null | null | null | Application/build/generated/source/r/debug/com/example/android/customnotifications/R.java | Brainrj/My_Application | 28c9f5ac19d5b19369eb164c582d14961a1509cf | [
"Apache-2.0"
] | null | null | null | 42.967742 | 70 | 0.726727 | 998,170 | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.example.android.customnotifications;
public final class R {
public static final class attr {
}
public static final class dimen {
public static final int activity_horizontal_margin=0x7f040002;
public static final int activity_vertical_margin=0x7f040003;
public static final int horizontal_page_margin=0x7f040000;
public static final int margin_huge=0x7f040004;
public static final int margin_large=0x7f040005;
public static final int margin_medium=0x7f040006;
public static final int margin_small=0x7f040007;
public static final int margin_tiny=0x7f040008;
public static final int vertical_page_margin=0x7f040001;
}
public static final class drawable {
public static final int ic_launcher=0x7f020000;
public static final int ic_stat_custom=0x7f020001;
public static final int robot=0x7f020002;
public static final int robot_expanded=0x7f020003;
public static final int tile=0x7f020004;
}
public static final class id {
public static final int button=0x7f070002;
public static final int imageView=0x7f070001;
public static final int textView=0x7f070000;
}
public static final class layout {
public static final int notification=0x7f030000;
public static final int notification_expanded=0x7f030001;
public static final int sample_main=0x7f030002;
}
public static final class string {
public static final int app_name=0x7f060000;
public static final int collapsed=0x7f060001;
public static final int collapsed_image=0x7f060002;
public static final int custom_notification=0x7f060003;
public static final int expanded=0x7f060004;
public static final int expanded_image=0x7f060005;
public static final int intro_message=0x7f060006;
public static final int intro_text=0x7f060007;
public static final int show_notification=0x7f060008;
}
public static final class style {
public static final int AppTheme=0x7f050003;
public static final int NotificationContent=0x7f050002;
public static final int Theme_Base=0x7f050001;
public static final int Theme_Sample=0x7f050004;
public static final int Widget=0x7f050005;
public static final int Widget_SampleMessage=0x7f050000;
public static final int Widget_SampleMessageTile=0x7f050006;
}
}
|
9237b41b2a842ae88ff3467e989e85f704f82c14 | 8,488 | java | Java | src/main/java/jp/sourceforge/jindolf/archiver/HttpAccess.java | hironytic/JinArchiver | 9f7b743e243974d3f2c4441e92df987b0f102fd8 | [
"MIT"
] | null | null | null | src/main/java/jp/sourceforge/jindolf/archiver/HttpAccess.java | hironytic/JinArchiver | 9f7b743e243974d3f2c4441e92df987b0f102fd8 | [
"MIT"
] | null | null | null | src/main/java/jp/sourceforge/jindolf/archiver/HttpAccess.java | hironytic/JinArchiver | 9f7b743e243974d3f2c4441e92df987b0f102fd8 | [
"MIT"
] | null | null | null | 30.753623 | 77 | 0.487983 | 998,171 | /*
* downloader
*
* License : The MIT License
* Copyright(c) 2008 olyutorskii
*/
package jp.sourceforge.jindolf.archiver;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.LinkedList;
import java.util.List;
import jp.sourceforge.jindolf.corelib.LandDef;
import jp.sourceforge.jindolf.corelib.LandState;
import jp.sourceforge.jindolf.corelib.PeriodType;
import jp.sourceforge.jindolf.parser.DecodeException;
import jp.sourceforge.jindolf.parser.DecodedContent;
import jp.sourceforge.jindolf.parser.HtmlAdapter;
import jp.sourceforge.jindolf.parser.HtmlParseException;
import jp.sourceforge.jindolf.parser.HtmlParser;
import jp.sourceforge.jindolf.parser.PageType;
import jp.sourceforge.jindolf.parser.SeqRange;
/**
* 人狼HTTPサーバ内のリソース情報を展開する。
*/
public final class HttpAccess{
/**
* 隠しコンストラクタ。
*/
private HttpAccess(){
throw new Error();
}
/**
* 日一覧ページ(エピローグの翌日)のURLを得る。
* @param landDef 国指定
* @param vid 村番号
* @return 一覧ページへのURL
* @throws IOException 入力エラー
*/
public static URL getPeriodListURL(LandDef landDef, int vid)
throws IOException{
StringBuilder urlText = new StringBuilder();
urlText.append(landDef.getCgiURI().toASCIIString());
urlText.append('?').append("vid=").append(vid);
if(landDef.getLandState() == LandState.ACTIVE){
urlText.append('&').append("meslog=");
}
URL result = new URL(urlText.toString());
return result;
}
/**
* 日ページのロード元情報一覧を得る。
* @param landDef 国指定
* @param vid 村番号
* @return ロード元情報一覧
* @throws DecodeException デコードエラー
* @throws HtmlParseException パースエラー
* @throws IOException 入力エラー
*/
public static List<PeriodResource> loadResourceList(LandDef landDef,
int vid)
throws DecodeException,
HtmlParseException,
IOException {
URL url = getPeriodListURL(landDef, vid);
Charset charset = landDef.getEncoding();
InputStream istream = url.openStream();
DecodedContent content = Builder.contentFromStream(charset, istream);
istream.close();
HtmlParser parser = new HtmlParser();
PeriodListHandler handler = new PeriodListHandler(landDef, vid);
parser.setBasicHandler(handler);
parser.setTalkHandler(handler);
parser.setSysEventHandler(handler);
parser.parseAutomatic(content);
List<PeriodResource> result = handler.getResourceList();
return result;
}
/**
* 日一覧パース用ハンドラ。
*/
public static class PeriodListHandler extends HtmlAdapter{
private final LandDef landDef;
private final int vid;
private List<PeriodResource> resourceList = null;
private int progressDays;
private boolean hasDone;
/**
* コンストラクタ。
* @param landDef 国指定
* @param vid 村番号
*/
public PeriodListHandler(LandDef landDef, int vid){
super();
this.landDef = landDef;
this.vid = vid;
return;
}
/**
* 日ページのURL文字列を生成する。
* @param type 日種類
* @param day 日にち
* @return URL文字列
*/
public String getURL(PeriodType type, int day){
String base = this.landDef.getCgiURI().toASCIIString();
base += "?vid=" + this.vid;
if(this.landDef.getLandId().equals("wolfg")){
base += "&meslog=";
String dnum = "000" + (day - 1);
dnum = dnum.substring(dnum.length() - 3);
switch(type){
case PROLOGUE:
base += "000_ready";
break;
case PROGRESS:
base += dnum;
base += "_progress";
break;
case EPILOGUE:
base += dnum;
base += "_party";
break;
default:
assert false;
return null;
}
}else{
base += "&meslog=" + this.vid + "_";
switch(type){
case PROLOGUE:
base += "ready_0";
break;
case PROGRESS:
base += "progress_" + (day - 1);
break;
case EPILOGUE:
base += "party_" + (day - 1);
break;
default:
return null;
}
}
base += "&mes=all";
return base;
}
/**
* PeriodResource一覧を得る。
* @return PeriodResource一覧
*/
public List<PeriodResource> getResourceList(){
return this.resourceList;
}
/**
* {@inheritDoc}
* @param content {@inheritDoc}
* @throws HtmlParseException {@inheritDoc}
*/
@Override
public void startParse(DecodedContent content)
throws HtmlParseException{
this.resourceList = new LinkedList<PeriodResource>();
this.progressDays = 0;
this.hasDone = false;
return;
}
/**
* {@inheritDoc}
* @param type {@inheritDoc}
* @throws HtmlParseException {@inheritDoc}
*/
@Override
public void pageType(PageType type) throws HtmlParseException{
if(type != PageType.PERIOD_PAGE) throw new HtmlParseException();
return;
}
/**
* {@inheritDoc}
* @param content {@inheritDoc}
* @param anchorRange {@inheritDoc}
* @param periodType {@inheritDoc}
* @param day {@inheritDoc}
* @throws HtmlParseException {@inheritDoc}
*/
@Override
public void periodLink(DecodedContent content,
SeqRange anchorRange,
PeriodType periodType,
int day )
throws HtmlParseException{
if(periodType == null){
this.hasDone = true;
}else if(periodType == PeriodType.PROGRESS){
this.progressDays = day;
}
return;
}
/**
* {@inheritDoc}
* @throws HtmlParseException {@inheritDoc}
*/
@Override
public void endParse() throws HtmlParseException{
if( ! this.hasDone ) throw new HtmlParseException();
PeriodResource resource;
String prologueURI = getURL(PeriodType.PROLOGUE, 0);
resource = new PeriodResource(this.landDef,
this.vid,
PeriodType.PROLOGUE,
0,
prologueURI,
0L,
null);
this.resourceList.add(resource);
for(int day = 1; day <= this.progressDays; day++){
String progressURI = getURL(PeriodType.PROGRESS, day);
resource = new PeriodResource(this.landDef,
this.vid,
PeriodType.PROGRESS,
day,
progressURI,
0L,
null);
this.resourceList.add(resource);
}
String epilogueURI = getURL(PeriodType.EPILOGUE,
this.progressDays + 1);
resource = new PeriodResource(this.landDef,
this.vid,
PeriodType.EPILOGUE,
this.progressDays + 1,
epilogueURI,
0L,
null);
this.resourceList.add(resource);
return;
}
}
}
|
9237b58b954ad45a416a1c4e849fe1b203b785eb | 3,587 | java | Java | src/main/java/ivorius/pandorasbox/effects/PBEffectGenConvertToHalloween.java | Brandonbr1/PandorasBox | 1c25837f556e9e8879794e2ce14a68428fb0e8c9 | [
"MIT"
] | 5 | 2015-02-05T22:23:40.000Z | 2019-07-16T16:05:31.000Z | src/main/java/ivorius/pandorasbox/effects/PBEffectGenConvertToHalloween.java | Brandonbr1/PandorasBox | 1c25837f556e9e8879794e2ce14a68428fb0e8c9 | [
"MIT"
] | 11 | 2015-01-19T20:05:27.000Z | 2019-04-28T02:36:43.000Z | src/main/java/ivorius/pandorasbox/effects/PBEffectGenConvertToHalloween.java | Brandonbr1/PandorasBox | 1c25837f556e9e8879794e2ce14a68428fb0e8c9 | [
"MIT"
] | 8 | 2015-01-19T19:41:38.000Z | 2022-03-11T13:21:38.000Z | 36.979381 | 159 | 0.507109 | 998,172 | /*
* Copyright (c) 2014, Lukas Tenbrink.
* http://lukas.axxim.net
*/
package ivorius.pandorasbox.effects;
import ivorius.pandorasbox.entitites.EntityPandorasBox;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import java.util.Random;
/**
* Created by lukas on 30.03.14.
*/
public class PBEffectGenConvertToHalloween extends PBEffectGenerate
{
public PBEffectGenConvertToHalloween()
{
}
public PBEffectGenConvertToHalloween(int time, double range, int unifiedSeed)
{
super(time, range, 2, unifiedSeed);
}
@Override
public void generateOnBlock(World world, EntityPandorasBox entity, Vec3d effectCenter, Random random, int pass, BlockPos pos, double range)
{
if (!world.isRemote)
{
IBlockState blockState = world.getBlockState(pos);
Block block = blockState.getBlock();
if (pass == 0)
{
BlockPos posBelow = pos.down();
IBlockState blockBelowState = world.getBlockState(posBelow);
Block blockBelow = blockBelowState.getBlock();
if (blockBelow.isNormalCube(blockBelowState, world, posBelow) && Blocks.SNOW_LAYER.canPlaceBlockAt(world, pos) && block != Blocks.WATER)
{
if (random.nextInt(5 * 5) == 0)
{
int b = world.rand.nextInt(6);
if (b == 0)
{
setBlockSafe(world, posBelow, Blocks.NETHERRACK.getDefaultState());
setBlockSafe(world, pos, Blocks.FIRE.getDefaultState());
}
else if (b == 1)
{
setBlockSafe(world, pos, Blocks.LIT_PUMPKIN.getDefaultState());
}
else if (b == 2)
{
setBlockSafe(world, pos, Blocks.PUMPKIN.getDefaultState());
}
else if (b == 3)
{
setBlockSafe(world, posBelow, Blocks.FARMLAND.getDefaultState());
setBlockSafe(world, pos, Blocks.PUMPKIN_STEM.getStateFromMeta(world.rand.nextInt(4) + 4));
}
else if (b == 4)
{
setBlockSafe(world, pos, Blocks.CAKE.getDefaultState());
}
else if (b == 5)
{
EntityItem entityItem = new EntityItem(world, pos.getX() + 0.5, pos.getY() + 0.5f, pos.getZ() + 0.5f, new ItemStack(Items.COOKIE));
entityItem.setPickupDelay(20);
world.spawnEntity(entityItem);
}
}
}
}
else
{
if (canSpawnEntity(world, blockState, pos))
{
lazilySpawnEntity(world, entity, random, "PigZombie", 1.0f / (20 * 20), pos);
lazilySpawnEntity(world, entity, random, "Enderman", 1.0f / (20 * 20), pos);
}
}
}
}
}
|
9237b5fcca8006621a661731728bb178af988ccf | 6,707 | java | Java | websocket-client/src/main/java/org/jboss/as/quickstarts/websocket/client/Backend.java | gaol/quickstart | 284e906d8ce4b20163ce4b7f0df8e6934cc77d98 | [
"Apache-2.0"
] | 1 | 2018-02-10T20:36:45.000Z | 2018-02-10T20:36:45.000Z | websocket-client/src/main/java/org/jboss/as/quickstarts/websocket/client/Backend.java | gaol/quickstart | 284e906d8ce4b20163ce4b7f0df8e6934cc77d98 | [
"Apache-2.0"
] | null | null | null | websocket-client/src/main/java/org/jboss/as/quickstarts/websocket/client/Backend.java | gaol/quickstart | 284e906d8ce4b20163ce4b7f0df8e6934cc77d98 | [
"Apache-2.0"
] | 2 | 2016-11-13T06:30:33.000Z | 2016-11-24T08:06:19.000Z | 36.650273 | 186 | 0.727896 | 998,173 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2015, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This 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 2.1 of
* the License, or (at your option) any later version.
*
* This software 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 this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.quickstarts.websocket.client;
import static java.lang.String.format;
import java.io.*;
import java.net.URI;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.logging.*;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.*;
import javax.inject.Inject;
import javax.json.*;
import javax.net.ssl.SSLContext;
import javax.websocket.*;
/**
* @author <a href="http://monospacesoftware.com">Paul Cowan</a>
*/
// This class is the WebSocket client
@ApplicationScoped
public class Backend extends Endpoint implements MessageHandler.Whole<SessionMessage> {
private Logger log = Logger.getLogger(Backend.class.getName());
private String echoServerUrl = "wss://echo.websocket.org";
@Inject
@ToFrontend
private Event<SessionMessage> frontendTrigger;
@Inject
@ToBroadcast
private Event<String> broadcastTrigger;
private ClientEndpointConfig config;
private Session session;
private ConnectionGate connectionGate = new ConnectionGate();
@PostConstruct
public void init() {
List<Class<? extends Encoder>> encoders = new ArrayList<>();
encoders.add(SessionMessageEncoder.class);
List<Class<? extends Decoder>> decoders = new ArrayList<>();
decoders.add(SessionMessageDecoder.class);
config = ClientEndpointConfig.Builder.create()
//.encoders(Arrays.asList(SessionMessageEncoder.class)) // too bad this doesn't work...
.encoders(encoders)
.decoders(decoders)
.build();
try {
config.getUserProperties().put("io.undertow.websocket.SSL_CONTEXT", SSLContext.getDefault());
} catch (NoSuchAlgorithmException e) {
log.log(Level.SEVERE, format("Failed to deploy backend endpoint: %s", e.getMessage()), e);
}
// To use secure WebSocket (wss://) we must supply an SSLContext via the ClientEndpointConfig
// Unfortunately there is no API standard way to do this, so it's being set here via a user property which is Undertow specific.
// Additionally, there is no connectToServer method that accepts an annotated Object and a ClientEndpointConfig
// Therefore we're forced to use the method that accepts an Endpoint instance, so we're forced to implement Endpoint, making annotations irrelevant.
connect();
}
public void connect() {
broadcastTrigger.fire(format("Connecting to backend %s", echoServerUrl));
try {
ContainerProvider.getWebSocketContainer().connectToServer(this, config, URI.create(echoServerUrl));
} catch (Exception e) {
broadcastTrigger.fire(format("Failed to connect to backend %s: %s", echoServerUrl, e.getMessage()));
}
}
@Override
public void onOpen(Session session, EndpointConfig config) {
this.session = session;
session.addMessageHandler(SessionMessage.class, this);
broadcastTrigger.fire(format("Opened backend session %s", session.getId()));
connectionGate.connected();
}
@Override
public void onClose(Session session, CloseReason closeReason) {
connectionGate.disconnected();
broadcastTrigger.fire(format("Closed backend session %s due to %s", session.getId(), closeReason.getReasonPhrase()));
connect(); // reconnect; probably should do this asynchronously and add an exponential backoff
}
@Override
public void onError(Session session, Throwable t) {
broadcastTrigger.fire(format("Error from backend session %s: %s", session.getId(), t.getMessage()));
// reconnect?
}
@Override
public void onMessage(SessionMessage message) {
frontendTrigger.fire(new SessionMessage(message.getSessionId(), format("Received message from backend session %s to frontend session %s ", session.getId(), message.getSessionId())));
frontendTrigger.fire(message);
}
public void sendMessage(@Observes @ToBackend SessionMessage message) throws Exception {
connectionGate.waitForConnection(5, TimeUnit.SECONDS);
if (!connectionGate.isConnected()) {
frontendTrigger.fire(new SessionMessage(message.getSessionId(), format("Failed to send frontend session %s message: not connected to backend", message.getSessionId())));
return;
}
frontendTrigger.fire(new SessionMessage(message.getSessionId(), format("Sending message from frontend session %s to backend session %s", message.getSessionId(), session.getId())));
session.getBasicRemote().sendObject(message);
}
// JSON is overkill for this but it's good as an example
public static class SessionMessageEncoder implements Encoder.TextStream<SessionMessage> {
@Override
public void init(EndpointConfig config) {
}
@Override
public void destroy() {
}
@Override
public void encode(SessionMessage object, Writer writer) throws EncodeException, IOException {
JsonObject jsonObject = Json.createObjectBuilder()
.add("sessionId", object.getSessionId())
.add("txt", object.getText())
.build();
Json.createWriter(writer).writeObject(jsonObject);
}
}
// JSON is overkill for this but it's good as an example
public static class SessionMessageDecoder implements Decoder.TextStream<SessionMessage> {
@Override
public void init(EndpointConfig config) {
}
@Override
public void destroy() {
}
@Override
public SessionMessage decode(Reader reader) throws DecodeException, IOException {
JsonObject jsonObject = Json.createReader(reader).readObject();
return new SessionMessage(jsonObject.getString("sessionId"), jsonObject.getString("txt"));
}
}
}
|
9237b7b8e28636ad053cfb662b9a099ddd6419d0 | 14,773 | java | Java | android/src/main/java/dev/flutter/pigeon/Pigeon.java | ManulGoyal/couchify | 3260f204f9f9a7de6fb309e7e09be0712068d161 | [
"BSD-3-Clause"
] | null | null | null | android/src/main/java/dev/flutter/pigeon/Pigeon.java | ManulGoyal/couchify | 3260f204f9f9a7de6fb309e7e09be0712068d161 | [
"BSD-3-Clause"
] | null | null | null | android/src/main/java/dev/flutter/pigeon/Pigeon.java | ManulGoyal/couchify | 3260f204f9f9a7de6fb309e7e09be0712068d161 | [
"BSD-3-Clause"
] | null | null | null | 41.036111 | 130 | 0.576051 | 998,174 | // Autogenerated from Pigeon (v1.0.18), do not edit directly.
// See also: https://pub.dev/packages/pigeon
package dev.flutter.pigeon;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.flutter.plugin.common.BasicMessageChannel;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MessageCodec;
import io.flutter.plugin.common.StandardMessageCodec;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
/** Generated class from Pigeon. */
@SuppressWarnings({"unused", "unchecked", "CodeBlock2Expr", "RedundantSuppression"})
public class Pigeon {
private static class CouchbaseLiteWrapperCodec extends StandardMessageCodec {
public static final CouchbaseLiteWrapperCodec INSTANCE = new CouchbaseLiteWrapperCodec();
private CouchbaseLiteWrapperCodec() {}
}
/** Generated interface from Pigeon that represents a handler of messages from Flutter.*/
public interface CouchbaseLiteWrapper {
String couchbaseLiteInit();
String getDatabasePath(String id);
void openDatabase(String id);
void closeDatabase(String id);
String executeQuery(List<Object> query);
List<Object> resultSetAllResults(String resultSetId);
Map<String, Object> resultSetNext(String resultSetId);
void saveDocument(String databaseId, String documentId, Map<String, Object> document);
Map<String, Object> getDocument(String databaseId, String documentId);
void deleteDatabase(String databaseId);
void deleteDocument(String databaseId, String documentId);
Long getCount(String databaseId);
/** The codec used by CouchbaseLiteWrapper. */
static MessageCodec<Object> getCodec() {
return CouchbaseLiteWrapperCodec.INSTANCE;
}
/** Sets up an instance of `CouchbaseLiteWrapper` to handle messages through the `binaryMessenger`. */
static void setup(BinaryMessenger binaryMessenger, CouchbaseLiteWrapper api) {
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.CouchbaseLiteWrapper.couchbaseLiteInit", getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
String output = api.couchbaseLiteInit();
wrapped.put("result", output);
}
catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.CouchbaseLiteWrapper.getDatabasePath", getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
ArrayList<Object> args = (ArrayList<Object>)message;
String idArg = (String)args.get(0);
if (idArg == null) {
throw new NullPointerException("idArg unexpectedly null.");
}
String output = api.getDatabasePath(idArg);
wrapped.put("result", output);
}
catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.CouchbaseLiteWrapper.openDatabase", getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
ArrayList<Object> args = (ArrayList<Object>)message;
String idArg = (String)args.get(0);
if (idArg == null) {
throw new NullPointerException("idArg unexpectedly null.");
}
api.openDatabase(idArg);
wrapped.put("result", null);
}
catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.CouchbaseLiteWrapper.closeDatabase", getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
ArrayList<Object> args = (ArrayList<Object>)message;
String idArg = (String)args.get(0);
if (idArg == null) {
throw new NullPointerException("idArg unexpectedly null.");
}
api.closeDatabase(idArg);
wrapped.put("result", null);
}
catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.CouchbaseLiteWrapper.executeQuery", getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
ArrayList<Object> args = (ArrayList<Object>)message;
List<Object> queryArg = (List<Object>)args.get(0);
if (queryArg == null) {
throw new NullPointerException("queryArg unexpectedly null.");
}
String output = api.executeQuery(queryArg);
wrapped.put("result", output);
}
catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.CouchbaseLiteWrapper.resultSetAllResults", getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
ArrayList<Object> args = (ArrayList<Object>)message;
String resultSetIdArg = (String)args.get(0);
if (resultSetIdArg == null) {
throw new NullPointerException("resultSetIdArg unexpectedly null.");
}
List<Object> output = api.resultSetAllResults(resultSetIdArg);
wrapped.put("result", output);
}
catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.CouchbaseLiteWrapper.resultSetNext", getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
ArrayList<Object> args = (ArrayList<Object>)message;
String resultSetIdArg = (String)args.get(0);
if (resultSetIdArg == null) {
throw new NullPointerException("resultSetIdArg unexpectedly null.");
}
Map<String, Object> output = api.resultSetNext(resultSetIdArg);
wrapped.put("result", output);
}
catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.CouchbaseLiteWrapper.saveDocument", getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
ArrayList<Object> args = (ArrayList<Object>)message;
String databaseIdArg = (String)args.get(0);
if (databaseIdArg == null) {
throw new NullPointerException("databaseIdArg unexpectedly null.");
}
String documentIdArg = (String)args.get(1);
if (documentIdArg == null) {
throw new NullPointerException("documentIdArg unexpectedly null.");
}
Map<String, Object> documentArg = (Map<String, Object>)args.get(2);
if (documentArg == null) {
throw new NullPointerException("documentArg unexpectedly null.");
}
api.saveDocument(databaseIdArg, documentIdArg, documentArg);
wrapped.put("result", null);
}
catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.CouchbaseLiteWrapper.getDocument", getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
ArrayList<Object> args = (ArrayList<Object>)message;
String databaseIdArg = (String)args.get(0);
if (databaseIdArg == null) {
throw new NullPointerException("databaseIdArg unexpectedly null.");
}
String documentIdArg = (String)args.get(1);
if (documentIdArg == null) {
throw new NullPointerException("documentIdArg unexpectedly null.");
}
Map<String, Object> output = api.getDocument(databaseIdArg, documentIdArg);
wrapped.put("result", output);
}
catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.CouchbaseLiteWrapper.deleteDatabase", getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
ArrayList<Object> args = (ArrayList<Object>)message;
String databaseIdArg = (String)args.get(0);
if (databaseIdArg == null) {
throw new NullPointerException("databaseIdArg unexpectedly null.");
}
api.deleteDatabase(databaseIdArg);
wrapped.put("result", null);
}
catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.CouchbaseLiteWrapper.deleteDocument", getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
ArrayList<Object> args = (ArrayList<Object>)message;
String databaseIdArg = (String)args.get(0);
if (databaseIdArg == null) {
throw new NullPointerException("databaseIdArg unexpectedly null.");
}
String documentIdArg = (String)args.get(1);
if (documentIdArg == null) {
throw new NullPointerException("documentIdArg unexpectedly null.");
}
api.deleteDocument(databaseIdArg, documentIdArg);
wrapped.put("result", null);
}
catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(binaryMessenger, "dev.flutter.pigeon.CouchbaseLiteWrapper.getCount", getCodec());
if (api != null) {
channel.setMessageHandler((message, reply) -> {
Map<String, Object> wrapped = new HashMap<>();
try {
ArrayList<Object> args = (ArrayList<Object>)message;
String databaseIdArg = (String)args.get(0);
if (databaseIdArg == null) {
throw new NullPointerException("databaseIdArg unexpectedly null.");
}
Long output = api.getCount(databaseIdArg);
wrapped.put("result", output);
}
catch (Error | RuntimeException exception) {
wrapped.put("error", wrapError(exception));
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
}
}
private static Map<String, Object> wrapError(Throwable exception) {
Map<String, Object> errorMap = new HashMap<>();
errorMap.put("message", exception.toString());
errorMap.put("code", exception.getClass().getSimpleName());
errorMap.put("details", "Cause: " + exception.getCause() + ", Stacktrace: " + Log.getStackTraceString(exception));
return errorMap;
}
}
|
9237b7ccc9002c91b95787f6b7c732f8a7e8e4d3 | 730 | java | Java | Talleres/Taller_Herencia/Proyecto1/src/main/MainLista.java | alejo780/Repositorio-Github | d83ecee14fc98707c6470c8d6839f933118a22ea | [
"Apache-2.0"
] | null | null | null | Talleres/Taller_Herencia/Proyecto1/src/main/MainLista.java | alejo780/Repositorio-Github | d83ecee14fc98707c6470c8d6839f933118a22ea | [
"Apache-2.0"
] | null | null | null | Talleres/Taller_Herencia/Proyecto1/src/main/MainLista.java | alejo780/Repositorio-Github | d83ecee14fc98707c6470c8d6839f933118a22ea | [
"Apache-2.0"
] | null | null | null | 28.076923 | 127 | 0.636986 | 998,175 | package main;
import clases.ListaMultimedia;
import clases.Formato;
import clases.Pelicula;
public class MainLista {
/**
*
* @param args
*/
public static void main(String[] args) {
ListaMultimedia lista = new ListaMultimedia(10);
Pelicula pelicula;
int posicion;
lista.add (new Pelicula ("Regreso al futuro", " Robert Zemeckis", Formato.wav, 197, "Michael J. Fox", "Lea Thompson"));
lista.add (new Pelicula ("Titanic", "James Cameronr", Formato.avi, 356, "Leonardo DiCaprio", "Kate Winslet"));
lista.add (new Pelicula ("Rapidos y Furiosos 8", "F. Gary Gray", Formato.avi, 168, "Vin Diesel", null));
System.out.println(lista.toString());
}
}
|
9237b893ee3348aae3df5379857007e3e2626823 | 482 | java | Java | neo4j/src/test/java/com/buschmais/xo/neo4j/test/implementedby/composite/RelationIncrementValueMethod.java | SMB-TEC/extended-objects | a78de53a2b0bbf7d512a19f896956bb36cf99000 | [
"Apache-2.0"
] | 1 | 2015-08-24T09:34:03.000Z | 2015-08-24T09:34:03.000Z | neo4j/src/test/java/com/buschmais/xo/neo4j/test/implementedby/composite/RelationIncrementValueMethod.java | SMB-TEC/extended-objects | a78de53a2b0bbf7d512a19f896956bb36cf99000 | [
"Apache-2.0"
] | null | null | null | neo4j/src/test/java/com/buschmais/xo/neo4j/test/implementedby/composite/RelationIncrementValueMethod.java | SMB-TEC/extended-objects | a78de53a2b0bbf7d512a19f896956bb36cf99000 | [
"Apache-2.0"
] | null | null | null | 26.777778 | 80 | 0.707469 | 998,176 | package com.buschmais.xo.neo4j.test.implementedby.composite;
import com.buschmais.xo.api.proxy.ProxyMethod;
import org.neo4j.graphdb.Relationship;
public class RelationIncrementValueMethod implements ProxyMethod<Relationship> {
@Override
public Object invoke(Relationship entity, Object instance, Object[] args) {
A2B a2b = A2B.class.cast(instance);
int value = a2b.getValue();
value++;
a2b.setValue(value);
return value;
}
}
|
9237b8ded3269b0be091a1bda78a97fab644b2d2 | 5,816 | java | Java | tests/jre/src/test/java/org/treblereel/gwt/xml/mapper/client/tests/pmml/model/AnovaRow.java | hasys/mapper-xml | d72cd9bb91060f85f4d6040b119fc4c98e88b189 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | tests/jre/src/test/java/org/treblereel/gwt/xml/mapper/client/tests/pmml/model/AnovaRow.java | hasys/mapper-xml | d72cd9bb91060f85f4d6040b119fc4c98e88b189 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | tests/jre/src/test/java/org/treblereel/gwt/xml/mapper/client/tests/pmml/model/AnovaRow.java | hasys/mapper-xml | d72cd9bb91060f85f4d6040b119fc4c98e88b189 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | 28.650246 | 110 | 0.66403 | 998,177 | /*
* Copyright © 2021 Treblereel
*
* 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.treblereel.gwt.xml.mapper.client.tests.pmml.model;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import jsinterop.annotations.JsType;
/**
* Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{http://www.dmg.org/PMML-4_4}Extension" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* <attribute name="type" use="required">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="Model"/>
* <enumeration value="Error"/>
* <enumeration value="Total"/>
* </restriction>
* </simpleType>
* </attribute>
* <attribute name="sumOfSquares" use="required" type="{http://www.dmg.org/PMML-4_4}NUMBER" />
* <attribute name="degreesOfFreedom" use="required" type="{http://www.dmg.org/PMML-4_4}NUMBER" />
* <attribute name="meanOfSquares" type="{http://www.dmg.org/PMML-4_4}NUMBER" />
* <attribute name="fValue" type="{http://www.dmg.org/PMML-4_4}NUMBER" />
* <attribute name="pValue" type="{http://www.dmg.org/PMML-4_4}PROB-NUMBER" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(
name = "",
propOrder = {"extension"})
@XmlRootElement(name = "AnovaRow")
@JsType
public class AnovaRow {
@XmlElement(name = "Extension")
protected List<Extension> extension;
@XmlAttribute(name = "type", required = true)
protected String type;
@XmlAttribute(name = "sumOfSquares", required = true)
protected double sumOfSquares;
@XmlAttribute(name = "degreesOfFreedom", required = true)
protected double degreesOfFreedom;
@XmlAttribute(name = "meanOfSquares")
protected Double meanOfSquares;
@XmlAttribute(name = "fValue")
protected Double fValue;
@XmlAttribute(name = "pValue")
protected Double pValue;
/**
* Gets the value of the extension 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 extension property.
*
* <p>For example, to add a new item, do as follows:
*
* <pre>
* getExtension().add(newItem);
* </pre>
*
* <p>Objects of the following type(s) are allowed in the list {@link Extension }
*/
public List<Extension> getExtension() {
if (extension == null) {
extension = new ArrayList<Extension>();
}
return this.extension;
}
/**
* Gets the value of the type property.
*
* @return possible object is {@link String }
*/
public String getType() {
return type;
}
/**
* Sets the value of the type property.
*
* @param value allowed object is {@link String }
*/
public void setType(String value) {
this.type = value;
}
/** Gets the value of the sumOfSquares property. */
public double getSumOfSquares() {
return sumOfSquares;
}
/** Sets the value of the sumOfSquares property. */
public void setSumOfSquares(double value) {
this.sumOfSquares = value;
}
/** Gets the value of the degreesOfFreedom property. */
public double getDegreesOfFreedom() {
return degreesOfFreedom;
}
/** Sets the value of the degreesOfFreedom property. */
public void setDegreesOfFreedom(double value) {
this.degreesOfFreedom = value;
}
/**
* Gets the value of the meanOfSquares property.
*
* @return possible object is {@link Double }
*/
public Double getMeanOfSquares() {
return meanOfSquares;
}
/**
* Sets the value of the meanOfSquares property.
*
* @param value allowed object is {@link Double }
*/
public void setMeanOfSquares(Double value) {
this.meanOfSquares = value;
}
/**
* Gets the value of the fValue property.
*
* @return possible object is {@link Double }
*/
public Double getFValue() {
return fValue;
}
/**
* Sets the value of the fValue property.
*
* @param value allowed object is {@link Double }
*/
public void setFValue(Double value) {
this.fValue = value;
}
/**
* Gets the value of the pValue property.
*
* @return possible object is {@link Double }
*/
public Double getPValue() {
return pValue;
}
/**
* Sets the value of the pValue property.
*
* @param value allowed object is {@link Double }
*/
public void setPValue(Double value) {
this.pValue = value;
}
}
|
9237ba1e790b2b7c8520a35e6771f7fd3f6a40d6 | 2,242 | java | Java | src/elevator/Elevator.java | nirlo/Elevators | cd32900d51c4b744dcfbc7f5c826e6ff5067c0d9 | [
"MIT"
] | null | null | null | src/elevator/Elevator.java | nirlo/Elevators | cd32900d51c4b744dcfbc7f5c826e6ff5067c0d9 | [
"MIT"
] | null | null | null | src/elevator/Elevator.java | nirlo/Elevators | cd32900d51c4b744dcfbc7f5c826e6ff5067c0d9 | [
"MIT"
] | null | null | null | 23.354167 | 90 | 0.640946 | 998,178 | package elevator;
import simulator.Observer;
/**
* <p>
* {@link Elevator} guideline to be used.
* these methods represent possible methods for {@link Elevator}
* </p>
*
* @author Shahriar (Shawn) Emami
* @version Jan 30, 2018
*/
public interface Elevator{
/**
* get current capacity of the elevator not the maximum capacity.
* @return integer for total capacity currently in the {@link Elevator}
*/
int getCapacity();
/**
* check if capacity has reached its maximum
* @return if {@link Elevator} is full
*/
boolean isFull();
/**
* check if capacity is zero
* @return if {@link Elevator} is empty
*/
boolean isEmpty();
/**
* check if elevator is in {@link MovingState#Idle}
* @return true if current elevator state is {@link MovingState#Idle}
*/
boolean isIdle();
/**
* get current {@link MovingState} of the {@link Elevator}
* @return current {@link MovingState}
*/
MovingState getState();
/**
* return total amount of power consumed to this point
* @return power consumed
*/
double getPowerConsumed();
/**
* move {@link Elevator} to a specific floor
* @param floor - target floor
*/
void moveTo( final int floor);
/**
* get current floor of {@link Elevator} at this point
* @return current floor
*/
int getFloor();
/**
* Unique integer that identifies this {@link Elevator} object
* @return unique identifier integer
*/
int id();
/**
* add number of persons to {@link Elevator}
* @param persons - number of passengers getting on at current floor
*/
void addPersons( final int persons);
/**
* represent the request made by one passenger inside of an {@link Elevator} object
* @param floor - target floor
*/
void requestStop( final int floor);
/**
* represent the request made by multiple passenger inside of an {@link Elevator} object
* @param floors - target floors
*/
void requestStops( final int...floors);
/**
* add an {@link Observer} to this {@link Elevator}
* @param observer - add to this {@link Elevator}, cannot be null
*/
void addObservers(Observer observer);
void setState(MovingState state);
}
|
9237ba61b19c20c4e696c86593e6841e258ea742 | 1,648 | java | Java | service/src/test/java/com/epam/repair/service/AddressServiceTest.java | Java-Arctic-Ratel/repair-service | 69cebef1c843163faaecc9fb095c6b1a22624ea9 | [
"Apache-2.0"
] | null | null | null | service/src/test/java/com/epam/repair/service/AddressServiceTest.java | Java-Arctic-Ratel/repair-service | 69cebef1c843163faaecc9fb095c6b1a22624ea9 | [
"Apache-2.0"
] | 15 | 2019-10-24T11:55:46.000Z | 2019-12-16T14:16:38.000Z | service/src/test/java/com/epam/repair/service/AddressServiceTest.java | Java-Arctic-Ratel/repair-service | 69cebef1c843163faaecc9fb095c6b1a22624ea9 | [
"Apache-2.0"
] | null | null | null | 31.692308 | 103 | 0.739684 | 998,179 | package com.epam.repair.service;
import com.epam.repair.dao.AddressDao;
import com.epam.repair.model.Address;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@ExtendWith(SpringExtension.class)
public class AddressServiceTest {
private static final Integer ADDRESS_ID_1 = 1;
private static final Integer ADDRESS_ID_2 = 2;
private Integer PAGE_0 = 0;
private Integer SIZE_2 = 2;
@InjectMocks
private AddressServiceImpl addressService;
@Mock
private AddressDao addressDao;
@Test
public void findAll() {
Mockito.when(addressDao.findAll()).thenReturn(Arrays.asList(createAddressForTest(ADDRESS_ID_1),
createAddressForTest(ADDRESS_ID_2)));
Page<Address> addresses = addressService.findAll(PageRequest.of(PAGE_0, SIZE_2));
assertNotNull(addresses);
assertTrue(addresses.getContent().size() > 0);
Mockito.verify(addressDao).findAll();
}
private Address createAddressForTest(int addressId) {
Address address = new Address();
address.setAddressId(addressId);
address.setHouseNumber("" + addressId);
address.setApartmentNumber("" + addressId);
return address;
}
} |
9237bb38ea33c69c03505a5fcfba5b7715fd39d3 | 1,060 | java | Java | DataStructure/DisjointSET2/WeightedQuickUniosCompress.java | SFARL/DataStructuresAndAlgorithms | b9fca27178c84e5e1663888f25c733f2698070eb | [
"Apache-2.0"
] | null | null | null | DataStructure/DisjointSET2/WeightedQuickUniosCompress.java | SFARL/DataStructuresAndAlgorithms | b9fca27178c84e5e1663888f25c733f2698070eb | [
"Apache-2.0"
] | null | null | null | DataStructure/DisjointSET2/WeightedQuickUniosCompress.java | SFARL/DataStructuresAndAlgorithms | b9fca27178c84e5e1663888f25c733f2698070eb | [
"Apache-2.0"
] | null | null | null | 21.632653 | 64 | 0.437736 | 998,180 | package DisjointSET2;
public class WeightedQuickUniosCompress implements DisjointSets{
private int[] parent;
private int[] size;
public WeightedQuickUniosCompress(int N) {
parent = new int[N];
size = new int[N];
for (int i = 0; i < N; i++) {
parent[i] = -1;
size[i] = 1;
}
}
private int find(int p) {
int q = p;
while (parent[p] >= 0) {
p = parent[p];
}
// The magic of compression is here.
while (parent[q] >= 0) {
int temp = parent[q];
parent[q] = p;
q = temp;
}
return p;
}
public void connect(int p, int q) {
int i = find(p);
int j = find(q);
if (i == j) return;
if (size[i] < size[j]) {
parent[i] = j;
size[j] += size[i];
} else {
parent[j] = i;
size[i] += size[j];
}
}
public boolean isConnected(int p, int q) {
return find(p) == find(q);
}
}
|
9237bb4bff09839e9537d3e3c2e79967bfed5dbe | 2,694 | java | Java | sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/EdgeNGramTokenizerConverter.java | wereHuang/azure-sdk-for-java | a08a57b060a025a8f455c5cfb5171fc52a3aeba4 | [
"MIT"
] | 1 | 2021-09-15T16:36:28.000Z | 2021-09-15T16:36:28.000Z | sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/EdgeNGramTokenizerConverter.java | wereHuang/azure-sdk-for-java | a08a57b060a025a8f455c5cfb5171fc52a3aeba4 | [
"MIT"
] | null | null | null | sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/EdgeNGramTokenizerConverter.java | wereHuang/azure-sdk-for-java | a08a57b060a025a8f455c5cfb5171fc52a3aeba4 | [
"MIT"
] | null | null | null | 38.485714 | 123 | 0.702301 | 998,181 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.search.documents.implementation.converters;
import com.azure.search.documents.indexes.models.EdgeNGramTokenizer;
import com.azure.search.documents.indexes.models.TokenCharacterKind;
import java.util.List;
import java.util.stream.Collectors;
/**
* A converter between {@link com.azure.search.documents.indexes.implementation.models.EdgeNGramTokenizer} and
* {@link EdgeNGramTokenizer}.
*/
public final class EdgeNGramTokenizerConverter {
/**
* Maps from {@link com.azure.search.documents.indexes.implementation.models.EdgeNGramTokenizer} to
* {@link EdgeNGramTokenizer}.
*/
public static EdgeNGramTokenizer map(com.azure.search.documents.indexes.implementation.models.EdgeNGramTokenizer obj) {
if (obj == null) {
return null;
}
EdgeNGramTokenizer edgeNGramTokenizer = new EdgeNGramTokenizer(obj.getName());
Integer maxGram = obj.getMaxGram();
edgeNGramTokenizer.setMaxGram(maxGram);
if (obj.getTokenChars() != null) {
List<TokenCharacterKind> tokenChars =
obj.getTokenChars().stream().map(TokenCharacterKindConverter::map).collect(Collectors.toList());
edgeNGramTokenizer.setTokenChars(tokenChars);
}
Integer minGram = obj.getMinGram();
edgeNGramTokenizer.setMinGram(minGram);
return edgeNGramTokenizer;
}
/**
* Maps from {@link EdgeNGramTokenizer} to
* {@link com.azure.search.documents.indexes.implementation.models.EdgeNGramTokenizer}.
*/
public static com.azure.search.documents.indexes.implementation.models.EdgeNGramTokenizer map(EdgeNGramTokenizer obj) {
if (obj == null) {
return null;
}
com.azure.search.documents.indexes.implementation.models.EdgeNGramTokenizer edgeNGramTokenizer =
new com.azure.search.documents.indexes.implementation.models.EdgeNGramTokenizer(obj.getName());
Integer maxGram = obj.getMaxGram();
edgeNGramTokenizer.setMaxGram(maxGram);
if (obj.getTokenChars() != null) {
List<com.azure.search.documents.indexes.implementation.models.TokenCharacterKind> tokenChars =
obj.getTokenChars().stream().map(TokenCharacterKindConverter::map).collect(Collectors.toList());
edgeNGramTokenizer.setTokenChars(tokenChars);
}
Integer minGram = obj.getMinGram();
edgeNGramTokenizer.setMinGram(minGram);
edgeNGramTokenizer.validate();
return edgeNGramTokenizer;
}
private EdgeNGramTokenizerConverter() {
}
}
|
9237bb560bf3f7164ec0cf2c7ec85bbbdf4b5284 | 7,582 | java | Java | fhir/com.b2international.snowowl.fhir.rest.tests/src/com/b2international/snowowl/fhir/tests/serialization/domain/ValueSetSerializationTest.java | eranhash/snow-owl | bee466023647e4512e96269f0a380fa1ff3a785a | [
"Apache-2.0"
] | 2 | 2020-02-13T15:51:26.000Z | 2021-09-14T00:44:27.000Z | fhir/com.b2international.snowowl.fhir.rest.tests/src/com/b2international/snowowl/fhir/tests/serialization/domain/ValueSetSerializationTest.java | eranhash/snow-owl | bee466023647e4512e96269f0a380fa1ff3a785a | [
"Apache-2.0"
] | 1 | 2020-07-27T14:41:03.000Z | 2020-07-27T14:41:03.000Z | fhir/com.b2international.snowowl.fhir.rest.tests/src/com/b2international/snowowl/fhir/tests/serialization/domain/ValueSetSerializationTest.java | eranhash/snow-owl | bee466023647e4512e96269f0a380fa1ff3a785a | [
"Apache-2.0"
] | null | null | null | 32.401709 | 91 | 0.735558 | 998,182 | /*
* Copyright 2011-2018 B2i Healthcare Pte Ltd, http://b2i.sg
*
* 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.b2international.snowowl.fhir.tests.serialization.domain;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.junit.Test;
import com.b2international.snowowl.fhir.core.FhirConstants;
import com.b2international.snowowl.fhir.core.codesystems.PublicationStatus;
import com.b2international.snowowl.fhir.core.model.ContactDetail;
import com.b2international.snowowl.fhir.core.model.Designation;
import com.b2international.snowowl.fhir.core.model.Extension;
import com.b2international.snowowl.fhir.core.model.IntegerExtension;
import com.b2international.snowowl.fhir.core.model.dt.ContactPoint;
import com.b2international.snowowl.fhir.core.model.dt.Identifier;
import com.b2international.snowowl.fhir.core.model.dt.Uri;
import com.b2international.snowowl.fhir.core.model.valueset.ValueSet;
import com.b2international.snowowl.fhir.core.model.valueset.expansion.Contains;
import com.b2international.snowowl.fhir.core.model.valueset.expansion.DateTimeParameter;
import com.b2international.snowowl.fhir.core.model.valueset.expansion.Expansion;
import com.b2international.snowowl.fhir.core.model.valueset.expansion.StringParameter;
import com.b2international.snowowl.fhir.core.model.valueset.expansion.UriParameter;
import com.b2international.snowowl.fhir.tests.FhirTest;
import io.restassured.path.json.JsonPath;
/**
* Test for checking the valueset serialization
* @since 6.3
*/
public class ValueSetSerializationTest extends FhirTest {
@Test
public void extensionTest() throws Exception {
Extension<Integer> integerExtension = new IntegerExtension("testUri", 1);
String expectedJson = "{\"url\":\"testUri\","
+ "\"valueInteger\":1}";
assertEquals(expectedJson, objectMapper.writeValueAsString(integerExtension));
}
@Test
public void stringParameterTest() throws Exception {
StringParameter parameter = StringParameter.builder()
.name("paramName")
.value("paramValue")
.build();
JsonPath jsonPath = getJsonPath(parameter);
assertThat(jsonPath.getString("name"), equalTo("paramName"));
assertThat(jsonPath.get("valueString"), equalTo("paramValue"));
}
@Test
public void uriParameterTest() throws Exception {
UriParameter parameter = UriParameter.builder()
.name("paramName")
.value(new Uri("paramValue"))
.build();
JsonPath jsonPath = getJsonPath(parameter);
assertThat(jsonPath.getString("name"), equalTo("paramName"));
assertThat(jsonPath.get("valueUri"), equalTo("paramValue"));
}
@Test
public void dateTimeParameterTest() throws Exception {
Date date = new SimpleDateFormat(FhirConstants.DATE_TIME_FORMAT).parse(TEST_DATE_STRING);
DateTimeParameter parameter = DateTimeParameter.builder()
.name("paramName")
.value(date)
.build();
JsonPath jsonPath = getJsonPath(parameter);
assertThat(jsonPath.getString("name"), equalTo("paramName"));
assertThat(jsonPath.get("valueDateTime"), equalTo(TEST_DATE_STRING));
}
@Test
public void expansionTest() throws Exception {
UriParameter stringParameter = UriParameter.builder()
.name("paramName")
.value(new Uri("paramValue"))
.build();
UriParameter uriParameter = UriParameter.builder()
.name("uriParamName")
.value(new Uri("uriParamValue"))
.build();
Expansion expansion = Expansion.builder()
.identifier("identifier")
.timestamp(TEST_DATE_STRING)
.total(200)
.addParameter(stringParameter)
.addParameter(uriParameter)
.build();
JsonPath jsonPath = getJsonPath(expansion);
assertThat(jsonPath.getString("identifier"), equalTo("identifier"));
assertThat(jsonPath.get("parameter.name"), hasItem("uriParamName"));
assertThat(jsonPath.get("parameter.name"), hasItem("paramName"));
}
@Test
public void containsTest() throws Exception {
Contains contains = Contains.builder()
.system("systemUri")
.isAbstract(true)
.inactive(false)
.version("20140131")
.code("Code")
.display("displayValue")
.addDesignation(Designation.builder()
.language("en-us")
.value("pt")
.build())
.addContains(Contains.builder().build())
.build();
JsonPath jsonPath = getJsonPath(contains);
assertThat(jsonPath.getString("system"), equalTo("systemUri"));
assertThat(jsonPath.getBoolean("abstract"), equalTo(true));
assertThat(jsonPath.getBoolean("inactive"), equalTo(false));
assertThat(jsonPath.getString("version"), equalTo("20140131"));
assertThat(jsonPath.getString("code"), equalTo("Code"));
assertThat(jsonPath.getString("display"), equalTo("displayValue"));
assertThat(jsonPath.getString("designation"), notNullValue());
assertThat(jsonPath.getString("contains"), notNullValue());
}
@Test
public void valueSetTest() throws Exception {
UriParameter stringParameter = UriParameter.builder()
.name("paramName")
.value(new Uri("paramValue"))
.build();
UriParameter uriParameter = UriParameter.builder()
.name("uriParamName")
.value(new Uri("uriParamValue"))
.build();
Contains contains = Contains.builder()
.system("systemUri")
.isAbstract(true)
.inactive(false)
.version("20140131")
.code("Code")
.display("displayValue")
.addDesignation(Designation.builder()
.language("en-us")
.value("pt")
.build())
.addContains(Contains.builder().build())
.build();
Expansion expansion = Expansion.builder()
.identifier("identifier")
.timestamp(TEST_DATE_STRING)
.total(200)
.addParameter(stringParameter)
.addParameter(uriParameter)
.addContains(contains)
.build();
ValueSet valueSet = ValueSet.builder("-1")
.url("http://who.org")
.identifier(Identifier.builder()
.build())
.version("20130131")
.name("refsetName")
.title("refsetTitle")
.status(PublicationStatus.ACTIVE)
.date(TEST_DATE_STRING)
.publisher("b2i")
.addContact(ContactDetail.builder()
.addContactPoint(ContactPoint.builder()
.id("contactPointId")
.build())
.build())
.description("descriptionString")
//.addUseContext(usageContext)
//.jurisdiction(jurisdiction)
.expansion(expansion)
.build();
applyFilter(valueSet);
JsonPath jsonPath = getJsonPath(valueSet);
assertThat(jsonPath.getString("url"), equalTo("http://who.org"));
assertThat(jsonPath.getString("version"), equalTo("20130131"));
assertThat(jsonPath.getString("name"), equalTo("refsetName"));
assertThat(jsonPath.getString("description"), equalTo("descriptionString"));
assertThat(jsonPath.getString("title"), equalTo("refsetTitle"));
assertThat(jsonPath.get("expansion.parameter.name"), hasItem("paramName"));
assertThat(jsonPath.get("expansion.contains.system"), hasItem("systemUri"));
}
}
|
9237bbe3e8afbfb5a333a2cca717698e4cfd5b3d | 2,375 | java | Java | backend/src/test/java/de/learnlib/alex/learning/entities/learnlibproxies/eqproxies/MealyRandomWordsEQOracleProxyTest.java | LearnLib/alex | 1d204d31a7992edb9a27567ac8ae5ea21bf054a3 | [
"Apache-2.0"
] | 29 | 2016-10-15T21:22:11.000Z | 2022-03-28T08:30:46.000Z | backend/src/test/java/de/learnlib/alex/learning/entities/learnlibproxies/eqproxies/MealyRandomWordsEQOracleProxyTest.java | LearnLib/alex | 1d204d31a7992edb9a27567ac8ae5ea21bf054a3 | [
"Apache-2.0"
] | 104 | 2016-10-15T21:27:09.000Z | 2022-03-04T06:46:28.000Z | backend/src/test/java/de/learnlib/alex/learning/entities/learnlibproxies/eqproxies/MealyRandomWordsEQOracleProxyTest.java | LearnLib/alex | 1d204d31a7992edb9a27567ac8ae5ea21bf054a3 | [
"Apache-2.0"
] | 8 | 2017-10-16T12:53:16.000Z | 2021-09-26T08:31:14.000Z | 32.986111 | 87 | 0.728 | 998,183 | /*
* Copyright 2015 - 2021 TU Dortmund
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.learnlib.alex.learning.entities.learnlibproxies.eqproxies;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class MealyRandomWordsEQOracleProxyTest {
public static final int MAX_LENGTH = 10;
public static final int MAX_NO_OF_TESTS = 10;
public static final int SEED = 42;
private MealyRandomWordsEQOracleProxy eqOracle;
@BeforeEach
public void setUp() {
eqOracle = new MealyRandomWordsEQOracleProxy();
eqOracle.setMinLength(1);
eqOracle.setMaxLength(MAX_LENGTH);
eqOracle.setMaxNoOfTests(MAX_NO_OF_TESTS);
eqOracle.setSeed(SEED);
}
@Test
public void ensureThatIfTheParametersAreValidNoExceptionWillBeThrown() {
eqOracle.checkParameters(); // nothing should happen
}
@Test
public void ensureThatAnExceptionIsThrownIfMinLengthIsGreaterThanMaxLength() {
eqOracle.setMinLength(MAX_LENGTH);
eqOracle.setMaxLength(1);
assertThrows(IllegalArgumentException.class, () -> eqOracle.checkParameters());
}
@Test
public void ensureThatAnExceptionIsThrownIfMinLengthIsNegative() {
eqOracle.setMinLength(-1);
assertThrows(IllegalArgumentException.class, () -> eqOracle.checkParameters());
}
@Test
public void ensureThatAnExceptionIsThrownIfMaxLengthIsNegative() {
eqOracle.setMaxLength(-1);
assertThrows(IllegalArgumentException.class, () -> eqOracle.checkParameters());
}
@Test
public void ensureThatAnExceptionIsThrownIfNoAmountOfTestIsGiven() {
eqOracle.setMaxNoOfTests(0);
assertThrows(IllegalArgumentException.class, () -> eqOracle.checkParameters());
}
}
|
9237bc49d5b8d5f246fde143654ea87480265c8c | 4,389 | java | Java | service/src/java/org/apache/hive/service/cli/OperationStatus.java | sho25/hive | 7a6a045c2a487bd200aeaded38497c843ec6a83c | [
"Apache-2.0"
] | null | null | null | service/src/java/org/apache/hive/service/cli/OperationStatus.java | sho25/hive | 7a6a045c2a487bd200aeaded38497c843ec6a83c | [
"Apache-2.0"
] | 3 | 2020-05-15T22:28:40.000Z | 2022-01-27T16:24:32.000Z | service/src/java/org/apache/hive/service/cli/OperationStatus.java | sho25/hive | 7a6a045c2a487bd200aeaded38497c843ec6a83c | [
"Apache-2.0"
] | null | null | null | 17.697581 | 813 | 0.815676 | 998,184 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * 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. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|hive
operator|.
name|service
operator|.
name|cli
package|;
end_package
begin_comment
comment|/** * OperationStatus * */
end_comment
begin_class
specifier|public
class|class
name|OperationStatus
block|{
specifier|private
specifier|final
name|OperationState
name|state
decl_stmt|;
specifier|private
specifier|final
name|String
name|taskStatus
decl_stmt|;
specifier|private
specifier|final
name|long
name|operationStarted
decl_stmt|;
specifier|private
specifier|final
name|long
name|operationCompleted
decl_stmt|;
specifier|private
specifier|final
name|Boolean
name|hasResultSet
decl_stmt|;
specifier|private
specifier|final
name|HiveSQLException
name|operationException
decl_stmt|;
specifier|private
name|JobProgressUpdate
name|jobProgressUpdate
decl_stmt|;
specifier|private
name|long
name|numModifiedRows
decl_stmt|;
specifier|public
name|OperationStatus
parameter_list|(
name|OperationState
name|state
parameter_list|,
name|String
name|taskStatus
parameter_list|,
name|long
name|operationStarted
parameter_list|,
name|long
name|operationCompleted
parameter_list|,
name|Boolean
name|hasResultSet
parameter_list|,
name|HiveSQLException
name|operationException
parameter_list|)
block|{
name|this
operator|.
name|state
operator|=
name|state
expr_stmt|;
name|this
operator|.
name|taskStatus
operator|=
name|taskStatus
expr_stmt|;
name|this
operator|.
name|operationStarted
operator|=
name|operationStarted
expr_stmt|;
name|this
operator|.
name|operationCompleted
operator|=
name|operationCompleted
expr_stmt|;
name|this
operator|.
name|hasResultSet
operator|=
name|hasResultSet
expr_stmt|;
name|this
operator|.
name|operationException
operator|=
name|operationException
expr_stmt|;
block|}
specifier|public
name|OperationState
name|getState
parameter_list|()
block|{
return|return
name|state
return|;
block|}
specifier|public
name|String
name|getTaskStatus
parameter_list|()
block|{
return|return
name|taskStatus
return|;
block|}
specifier|public
name|long
name|getOperationStarted
parameter_list|()
block|{
return|return
name|operationStarted
return|;
block|}
specifier|public
name|long
name|getOperationCompleted
parameter_list|()
block|{
return|return
name|operationCompleted
return|;
block|}
specifier|public
name|boolean
name|getHasResultSet
parameter_list|()
block|{
return|return
name|hasResultSet
operator|==
literal|null
condition|?
literal|false
else|:
name|hasResultSet
return|;
block|}
specifier|public
name|HiveSQLException
name|getOperationException
parameter_list|()
block|{
return|return
name|operationException
return|;
block|}
name|void
name|setJobProgressUpdate
parameter_list|(
name|JobProgressUpdate
name|jobProgressUpdate
parameter_list|)
block|{
name|this
operator|.
name|jobProgressUpdate
operator|=
name|jobProgressUpdate
expr_stmt|;
block|}
specifier|public
name|JobProgressUpdate
name|jobProgressUpdate
parameter_list|()
block|{
return|return
name|jobProgressUpdate
return|;
block|}
specifier|public
name|long
name|getNumModifiedRows
parameter_list|()
block|{
return|return
name|numModifiedRows
return|;
block|}
name|void
name|setNumModifiedRows
parameter_list|(
name|long
name|numRows
parameter_list|)
block|{
name|this
operator|.
name|numModifiedRows
operator|=
name|numRows
expr_stmt|;
block|}
specifier|public
name|boolean
name|isHasResultSetIsSet
parameter_list|()
block|{
return|return
name|hasResultSet
operator|!=
literal|null
return|;
block|}
block|}
end_class
end_unit
|
9237bdeeccf480a19a83c8544dd1239aee6101c7 | 549 | java | Java | src/test/java/com/medkhelifi/tutorials/todolist/services/MyUserDetailsServiceTest.java | medkhelifi/todolist | 05fa7eff09720e6160db2bb1bee30e26e1e5adac | [
"MIT"
] | null | null | null | src/test/java/com/medkhelifi/tutorials/todolist/services/MyUserDetailsServiceTest.java | medkhelifi/todolist | 05fa7eff09720e6160db2bb1bee30e26e1e5adac | [
"MIT"
] | null | null | null | src/test/java/com/medkhelifi/tutorials/todolist/services/MyUserDetailsServiceTest.java | medkhelifi/todolist | 05fa7eff09720e6160db2bb1bee30e26e1e5adac | [
"MIT"
] | null | null | null | 26.142857 | 71 | 0.790528 | 998,185 | package com.medkhelifi.tutorials.todolist.services;
import com.medkhelifi.tutorials.todolist.models.dao.IUserDao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.*;
public class MyUserDetailsServiceTest {
@Test
public void loadUserByUsername() {
}
@Test
public void setUserDao() {
}
} |
9237bf86ac25461c798494479492ef1faa594b26 | 720 | java | Java | src/main/java/org/kpax/foom/user/domain/internal/SelectJavaBeanFieldsStep.java | ecovaci/foom | 085fd6c14f97d4ff7f258ac3e602265115c54a53 | [
"MIT"
] | 1 | 2019-12-07T06:01:21.000Z | 2019-12-07T06:01:21.000Z | src/main/java/org/kpax/foom/user/domain/internal/SelectJavaBeanFieldsStep.java | ecovaci/foom | 085fd6c14f97d4ff7f258ac3e602265115c54a53 | [
"MIT"
] | 1 | 2021-06-03T09:38:23.000Z | 2021-09-07T15:55:28.000Z | src/main/java/org/kpax/foom/user/domain/internal/SelectJavaBeanFieldsStep.java | ecovaci/foom | 085fd6c14f97d4ff7f258ac3e602265115c54a53 | [
"MIT"
] | null | null | null | 24.827586 | 86 | 0.741667 | 998,186 | package org.kpax.foom.user.domain.internal;
import org.apache.commons.lang3.Validate;
import org.kpax.foom.domain.AbstractStep;
import org.kpax.foom.domain.StepContext;
import org.kpax.foom.domain.exception.ValidationException;
/**
* @author Eugen Covaci {@literal eugen.covaci.q@gmail.com}
* Created on 9/23/2019
*/
public class SelectJavaBeanFieldsStep extends AbstractStep {
public SelectJavaBeanFieldsStep(StepContext workflow) throws ValidationException {
super(workflow);
}
@Override
public void execute() {
}
@Override
protected void validate(StepContext context) throws ValidationException {
Validate.isTrue(context.getParameters().containsKey(""));
}
}
|
9237bf9e7eafab75d71d42ceb3d293514fa7732c | 2,531 | java | Java | app/src/main/java/com/example/taoguo/cloudreadertest/utils/CommonUtils.java | TaoMonkey/CloudReaderTest | ffa4ce7dc5bffa32bf6896186b5e21db41a84555 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/taoguo/cloudreadertest/utils/CommonUtils.java | TaoMonkey/CloudReaderTest | ffa4ce7dc5bffa32bf6896186b5e21db41a84555 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/taoguo/cloudreadertest/utils/CommonUtils.java | TaoMonkey/CloudReaderTest | ffa4ce7dc5bffa32bf6896186b5e21db41a84555 | [
"Apache-2.0"
] | null | null | null | 25.059406 | 94 | 0.64599 | 998,187 | package com.example.taoguo.cloudreadertest.utils;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.WindowManager;
import com.example.taoguo.cloudreadertest.app.CloudReaderApplication;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
/**
* Created by taoguo on 2017/5/18.
*/
public class CommonUtils {
/**
* 随机颜色
*/
public static int randomColor() {
Random random = new Random();
int red = random.nextInt(150) + 50;//50-199
int green = random.nextInt(150) + 50;//50-199
int blue = random.nextInt(150) + 50;//50-199
return Color.rgb(red, green, blue);
}
/**
* 得到年月日的"日"
*/
private String getDate() {
Date date = new Date();
SimpleDateFormat dateFm = new SimpleDateFormat("dd");
return dateFm.format(date);
}
/**
* 获取屏幕px
*
* @param context
* @return 分辨率
*/
static public int getScreenWidthPixels(Context context) {
DisplayMetrics dm = new DisplayMetrics();
((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay()
.getMetrics(dm);
return dm.widthPixels;
}
// public static void RunOnUiThread(Runnable r) {
// CloudReaderApplication.getInstance().getMainLooper().post(r);
// }
public static Drawable getDrawable(int resid) {
return getResoure().getDrawable(resid);
}
public static int getColor(int resid) {
return getResoure().getColor(resid);
}
public static Resources getResoure() {
return CloudReaderApplication.getInstance().getResources();
}
public static String[] getStringArray(int resid) {
return getResoure().getStringArray(resid);
}
public static String getString(int resid) {
return getResoure().getString(resid);
}
public static float getDimens(int resId) {
return getResoure().getDimension(resId);
}
public static void removeSelfFromParent(View child) {
if (child != null) {
ViewParent parent = child.getParent();
if (parent instanceof ViewGroup) {
ViewGroup group = (ViewGroup) parent;
group.removeView(child);
}
}
}
} |
9237bffbcedc782cc5c568e0321040ffac4a2900 | 1,244 | java | Java | src/main/java/com/coffeebeans/springnativeawslambda/SpringNativeAwsLambdaApplication.java | rajashekars/spring-native-aws-lambda | 1b4b024a6bc2c984c6244124c1e5450f75486211 | [
"Apache-2.0"
] | 6 | 2021-06-03T03:18:34.000Z | 2022-03-29T17:40:35.000Z | src/main/java/com/coffeebeans/springnativeawslambda/SpringNativeAwsLambdaApplication.java | rajashekars/spring-native-aws-lambda | 1b4b024a6bc2c984c6244124c1e5450f75486211 | [
"Apache-2.0"
] | 4 | 2021-08-14T03:52:16.000Z | 2022-03-11T00:13:37.000Z | src/main/java/com/coffeebeans/springnativeawslambda/SpringNativeAwsLambdaApplication.java | rajashekars/spring-native-aws-lambda | 1b4b024a6bc2c984c6244124c1e5450f75486211 | [
"Apache-2.0"
] | 3 | 2021-10-12T06:36:14.000Z | 2022-01-27T12:57:12.000Z | 44.428571 | 115 | 0.84164 | 998,188 | package com.coffeebeans.springnativeawslambda;
import com.coffeebeans.springnativeawslambda.functions.ExampleFunction;
import com.coffeebeans.springnativeawslambda.model.Request;
import com.coffeebeans.springnativeawslambda.model.Response;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.cloud.function.context.FunctionRegistration;
import org.springframework.cloud.function.context.FunctionalSpringApplication;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.nativex.hint.SerializationHint;
@SerializationHint(types = {Request.class, Response.class})
@SpringBootConfiguration
public class SpringNativeAwsLambdaApplication implements ApplicationContextInitializer<GenericApplicationContext> {
public static void main(final String[] args) {
FunctionalSpringApplication.run(SpringNativeAwsLambdaApplication.class, args);
}
@Override
public void initialize(final GenericApplicationContext context) {
context.registerBean("exampleFunction",
FunctionRegistration.class,
() -> new FunctionRegistration<>(new ExampleFunction()).type(ExampleFunction.class));
}
}
|
9237c057f87746c68c3f9c9223ca3ce1fa2bd557 | 2,404 | java | Java | androidclass/src/main/java/com/same/androidclass/view/activity/ExamDetailActivity.java | alicance/MyScse-Client | 230dcdd417ca1b9b034d8c7d95ef193a446999e9 | [
"Apache-2.0"
] | 10 | 2016-05-27T03:32:23.000Z | 2018-07-12T15:52:27.000Z | androidclass/src/main/java/com/same/androidclass/view/activity/ExamDetailActivity.java | alicfeng/sise | 230dcdd417ca1b9b034d8c7d95ef193a446999e9 | [
"Apache-2.0"
] | 1 | 2016-05-29T13:55:15.000Z | 2016-10-24T11:39:20.000Z | androidclass/src/main/java/com/same/androidclass/view/activity/ExamDetailActivity.java | alicfeng/sise | 230dcdd417ca1b9b034d8c7d95ef193a446999e9 | [
"Apache-2.0"
] | 2 | 2016-05-28T02:38:22.000Z | 2018-01-14T08:28:57.000Z | 32.486486 | 98 | 0.731697 | 998,189 | package com.same.androidclass.view.activity;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import com.atermenji.android.iconicdroid.IconicFontDrawable;
import com.atermenji.android.iconicdroid.icon.EntypoIcon;
import com.atermenji.android.iconicdroid.icon.FontAwesomeIcon;
import com.same.androidclass.R;
import com.same.androidclass.bean.Exam;
import com.same.androidclass.presenter.ExamDetailPresenter;
import com.same.androidclass.util.Colors;
import com.same.androidclass.util.DataUtil;
import com.same.androidclass.view.adapter.ExamDetailAdapter;
import com.same.androidclass.view.view.ExamDetailView;
import java.util.List;
/**
* 考试具体详细界面
* Created by alic on 16-5-13.
*/
public class ExamDetailActivity extends Activity implements ExamDetailView, View.OnClickListener {
private View backIcon;
private TextView toolbarName;
private ListView listView;
private ExamDetailAdapter adapter;
private Exam exam;
private ExamDetailPresenter presenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exam_detail);
initView();
}
public void initView(){
presenter = new ExamDetailPresenter(this,this);
presenter.doGetExam();
//处理返回icon
backIcon = findViewById(R.id.exam_detail_back_icon);
IconicFontDrawable back = new IconicFontDrawable(this, EntypoIcon.CHEVRON_THIN_LEFT);
back.setIconColor(Colors.color_pure_white);
backIcon.setBackground(back);
backIcon.setOnClickListener(this);
//顶部标题处理 课程名称
toolbarName = (TextView) findViewById(R.id.exam_detail_toolbar_name);
toolbarName.setText(DataUtil.subString(exam.getCourseName(),15,"..."));
//处理ListView
listView = (ListView) findViewById(R.id.exam_detail_listView);
adapter = new ExamDetailAdapter(this,exam);
listView.setAdapter(adapter);
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
@Override
public void onClick(View v) {
onBackPressed();
}
@Override
public void getIntentExam() {
exam = (Exam) getIntent().getSerializableExtra("exam");
}
}
|
9237c11177ba9452bdf5be6419850fcaf50352a8 | 691 | java | Java | smack-extensions/src/main/java/org/jivesoftware/smackx/jingle/Role.java | danielhams/Smack | 9d626bf787dc3e0e0a4399cef429285b22744d73 | [
"Apache-2.0"
] | 2,380 | 2015-01-01T16:37:15.000Z | 2022-03-29T15:08:37.000Z | smack-extensions/src/main/java/org/jivesoftware/smackx/jingle/Role.java | danielhams/Smack | 9d626bf787dc3e0e0a4399cef429285b22744d73 | [
"Apache-2.0"
] | 312 | 2015-01-03T23:39:29.000Z | 2022-03-26T11:40:07.000Z | smack-extensions/src/main/java/org/jivesoftware/smackx/jingle/Role.java | danielhams/Smack | 9d626bf787dc3e0e0a4399cef429285b22744d73 | [
"Apache-2.0"
] | 987 | 2015-01-02T10:25:46.000Z | 2022-03-23T18:37:27.000Z | 30.043478 | 75 | 0.730825 | 998,190 | /**
*
* Copyright 2017 Paul Schaub
*
* 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.jivesoftware.smackx.jingle;
public enum Role {
initiator,
responder,
}
|
9237c130d58239f3535b52e33e6e887e3fcdac24 | 956 | java | Java | bigstoreproject/src/test/java/org/regeneration/bigstoreproject/StoreTest.java | it1439/Java4Web-Skg2018 | d5745e3b3fe01b6fef3350a5e97cc130dfb428f1 | [
"Apache-2.0"
] | null | null | null | bigstoreproject/src/test/java/org/regeneration/bigstoreproject/StoreTest.java | it1439/Java4Web-Skg2018 | d5745e3b3fe01b6fef3350a5e97cc130dfb428f1 | [
"Apache-2.0"
] | 5 | 2018-11-02T08:53:25.000Z | 2018-11-05T12:49:38.000Z | bigstoreproject/src/test/java/org/regeneration/bigstoreproject/StoreTest.java | it1439/Java4Web-Skg2018 | d5745e3b3fe01b6fef3350a5e97cc130dfb428f1 | [
"Apache-2.0"
] | 24 | 2018-11-02T09:58:25.000Z | 2018-11-22T13:20:51.000Z | 27.314286 | 83 | 0.723849 | 998,191 | package org.regeneration.bigstoreproject;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import static org.junit.Assert.*;
public class StoreTest {
private ApplicationContext context;
@Before
public void setup() {
context = new ClassPathXmlApplicationContext(Constant.APP_CONFIG_LOCATION);
}
@Test
public void test_candy_store() {
Store candyStore = context.getBean("candyStore", Store.class);
Store candy2Store = context.getBean("candyStore", Store.class);
assertEquals(candyStore, candy2Store);
}
@Test
public void test_flower_store() {
Store flowerStore = context.getBean("flowerStore" , Store.class);
Store flower2Store = context.getBean("flowerStore" , Store.class);
assertNotEquals(flowerStore, flower2Store);
}
} |
9237c1601c4a4d472923980015f8c65b4e7cc00e | 2,348 | java | Java | EcMainModule/src/msf/ecmm/emctrl/restpojo/ConfigAuditFromEm.java | multi-service-fabric/element-controller | e1491c4e6df88606e908a1563a70a16e3ec53758 | [
"Apache-2.0"
] | 1 | 2018-03-19T03:45:59.000Z | 2018-03-19T03:45:59.000Z | EcMainModule/src/msf/ecmm/emctrl/restpojo/ConfigAuditFromEm.java | multi-service-fabric/element-controller | e1491c4e6df88606e908a1563a70a16e3ec53758 | [
"Apache-2.0"
] | null | null | null | EcMainModule/src/msf/ecmm/emctrl/restpojo/ConfigAuditFromEm.java | multi-service-fabric/element-controller | e1491c4e6df88606e908a1563a70a16e3ec53758 | [
"Apache-2.0"
] | 1 | 2020-04-02T01:18:04.000Z | 2020-04-02T01:18:04.000Z | 21.153153 | 119 | 0.624787 | 998,192 | /*
* Copyright(c) 2019 Nippon Telegraph and Telephone Corporation
*/
package msf.ecmm.emctrl.restpojo;
import msf.ecmm.emctrl.restpojo.parts.DiffFromEm;
import msf.ecmm.emctrl.restpojo.parts.LatestEmConfigFromEm;
import msf.ecmm.emctrl.restpojo.parts.NeConfigFromEm;
/**
* Getting Config-Audit.
*/
public class ConfigAuditFromEm extends AbstractResponse {
/** Host name. */
private String hostname;
/** Config information on server in EM. */
private LatestEmConfigFromEm latestEmConfig;
/** Current config information received from server. */
private NeConfigFromEm neConfig;
/** Difference information. */
private DiffFromEm diff;
/**
* Getting host name.
*
* @return host name
*/
public String getHostname() {
return hostname;
}
/**
* Setting host name.
*
* @param hostname
* host name
*/
public void setHostname(String hostname) {
this.hostname = hostname;
}
/**
* Getting Config information.
*
* @return Config information
*/
public LatestEmConfigFromEm getLatestEmConfig() {
return latestEmConfig;
}
/**
* Setting Config information..
*
* @param latestEmConfig
* Config information
*/
public void setLatestEmConfig(LatestEmConfigFromEm latestEmConfig) {
this.latestEmConfig = latestEmConfig;
}
/**
* Getting current Config information.
*
* @return current Config information
*/
public NeConfigFromEm getNeConfig() {
return neConfig;
}
/**
* GSetting current Config information.
*
* @param neConfig
* current Config information
*/
public void setNeConfig(NeConfigFromEm neConfig) {
this.neConfig = neConfig;
}
/**
* Getting difference information.
*
* @return difference information
*/
public DiffFromEm getDiff() {
return diff;
}
/**
* Setting difference information.
*
* @param diff
* difference information
*/
public void setDiff(DiffFromEm diff) {
this.diff = diff;
}
@Override
public String toString() {
return "ConfigAuditFromEm [hostname=" + hostname + ", latestEmConfig=" + latestEmConfig + ", neConfig=" + neConfig
+ ", diff=" + diff + "]";
}
}
|
9237c31e70f2515eee907d35d8b88ff7260ae2ff | 1,818 | java | Java | iris-impl/src/main/java/org/deri/iris/builtins/date/TimeLessBuiltin.java | distributed-iris-reasoner/distributed-iris-reasoner | 17305f93e7b79411bf978f053fb4a488c08f91f2 | [
"MIT"
] | 1 | 2015-05-02T19:07:57.000Z | 2015-05-02T19:07:57.000Z | iris-impl/src/main/java/org/deri/iris/builtins/date/TimeLessBuiltin.java | distributed-iris-reasoner/distributed-iris-reasoner | 17305f93e7b79411bf978f053fb4a488c08f91f2 | [
"MIT"
] | null | null | null | iris-impl/src/main/java/org/deri/iris/builtins/date/TimeLessBuiltin.java | distributed-iris-reasoner/distributed-iris-reasoner | 17305f93e7b79411bf978f053fb4a488c08f91f2 | [
"MIT"
] | null | null | null | 31.894737 | 74 | 0.741474 | 998,193 | /*
* Integrated Rule Inference System (IRIS):
* An extensible rule inference system for datalog with extensions.
*
* Copyright (C) 2009 Semantic Technology Institute (STI) Innsbruck,
* University of Innsbruck, Technikerstrasse 21a, 6020 Innsbruck, Austria.
*
* This library 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 2.1 of the License, or (at your option) any later version.
*
* This library 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 this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.deri.iris.builtins.date;
import static org.deri.iris.factory.Factory.BASIC;
import org.deri.iris.api.basics.IPredicate;
import org.deri.iris.api.terms.ITerm;
import org.deri.iris.api.terms.concrete.ITime;
import org.deri.iris.builtins.LessBuiltin;
/**
* <p>
* Represents the RIF built-in predicate pred:time-less-than.
* </p>
*/
public class TimeLessBuiltin extends LessBuiltin {
/** The predicate defining this built-in. */
private static final IPredicate PREDICATE = BASIC.createPredicate(
"TIME_LESS", 2);
public TimeLessBuiltin(ITerm... terms) {
super(PREDICATE, terms);
}
@Override
protected boolean computeResult(ITerm[] terms) {
if (terms[0] instanceof ITime && terms[1] instanceof ITime) {
return super.computeResult(terms);
}
return false;
}
}
|
9237c374c67f1acaf2dbb91f276840cfbad56ebf | 1,248 | java | Java | platform-db-sql/src/main/java/com/softicar/platform/db/sql/selects/SqlSelect0_7.java | softicar/platform | d4cf99f3e3537272af23bf60f6b088891bd271ff | [
"MIT"
] | 1 | 2021-11-25T09:58:31.000Z | 2021-11-25T09:58:31.000Z | platform-db-sql/src/main/java/com/softicar/platform/db/sql/selects/SqlSelect0_7.java | softicar/platform | d4cf99f3e3537272af23bf60f6b088891bd271ff | [
"MIT"
] | 22 | 2021-11-10T13:59:22.000Z | 2022-03-04T16:38:33.000Z | platform-db-sql/src/main/java/com/softicar/platform/db/sql/selects/SqlSelect0_7.java | softicar/platform | d4cf99f3e3537272af23bf60f6b088891bd271ff | [
"MIT"
] | null | null | null | 31.2 | 185 | 0.637019 | 998,194 | package com.softicar.platform.db.sql.selects;
import com.softicar.platform.db.sql.expressions.ISqlExpression;
import com.softicar.platform.db.sql.expressions.ISqlExpression0;
public final class SqlSelect0_7<V0, V1, V2, V3, V4, V5, V6> extends SqlSelectBase7<V0, V1, V2, V3, V4, V5, V6> implements ISqlSelectExtension<SqlSelect0_7<V0, V1, V2, V3, V4, V5, V6>> {
protected SqlSelect0_7(SqlSelectBase6<V0, V1, V2, V3, V4, V5> other, ISqlExpression<V6> expression) {
super(other, expression);
}
@Override
public SqlSelect0_7<V0, V1, V2, V3, V4, V5, V6> getThis() {
return this;
}
// -------------------------------- select -------------------------------- //
public SelectChooser0 select() {
return new SelectChooser0();
}
public <V> SqlSelect0_8<V0, V1, V2, V3, V4, V5, V6, V> select(ISqlExpression0<V> expression) {
return select().x(expression);
}
// -------------------------------- select chooser -------------------------------- //
public final class SelectChooser0 extends SelectChooserBase {
<V> SqlSelect0_8<V0, V1, V2, V3, V4, V5, V6, V> x(ISqlExpression0<V> expression) { return addExpression(new SqlSelect0_8<>(SqlSelect0_7.this, expression), expression); }
SelectChooser0() { /* non-public */ }
}
}
|
9237c5f4d7505be79dca28ecb76178fc2141ca3c | 6,074 | java | Java | jmeter/src/main/java/io/github/tcdl/msb/jmeter/sampler/MsbRequesterSampler.java | jabengozartc/msb-java | cd40a4048d96b2779bfd3972d7267909b607802c | [
"MIT"
] | null | null | null | jmeter/src/main/java/io/github/tcdl/msb/jmeter/sampler/MsbRequesterSampler.java | jabengozartc/msb-java | cd40a4048d96b2779bfd3972d7267909b607802c | [
"MIT"
] | null | null | null | jmeter/src/main/java/io/github/tcdl/msb/jmeter/sampler/MsbRequesterSampler.java | jabengozartc/msb-java | cd40a4048d96b2779bfd3972d7267909b607802c | [
"MIT"
] | null | null | null | 41.319728 | 134 | 0.687027 | 998,195 | package io.github.tcdl.msb.jmeter.sampler;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import com.typesafe.config.ConfigValueFactory;
import io.github.tcdl.msb.api.MessageTemplate;
import io.github.tcdl.msb.api.MsbContext;
import io.github.tcdl.msb.api.MsbContextBuilder;
import io.github.tcdl.msb.api.RequestOptions;
import io.github.tcdl.msb.support.Utils;
import org.apache.commons.lang3.StringUtils;
import org.apache.jmeter.samplers.AbstractSampler;
import org.apache.jmeter.samplers.Entry;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class MsbRequesterSampler extends AbstractSampler {
private static final Logger LOG = LoggingManager.getLoggerForClass();
private static AtomicInteger classCount = new AtomicInteger(0);
private String MSB_BROKER_CONFIG_ROOT = "msbConfig.brokerConfig";
private RequesterConfig currentRequesterConfig;
private MsbContext msbContext;
private ObjectMapper objectMapper = new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.setSerializationInclusion(JsonInclude.Include.NON_NULL);
public MsbRequesterSampler() {
classCount.incrementAndGet();
trace("MsbRequesterSampler()");
}
public void init() {
// do nothing
}
private void initMsb(RequesterConfig requesterConfig) {
Config msbConfig = ConfigFactory.load()
.withValue(MSB_BROKER_CONFIG_ROOT + ".host", ConfigValueFactory.fromAnyRef(requesterConfig.getHost()))
.withValue(MSB_BROKER_CONFIG_ROOT + ".port", ConfigValueFactory.fromAnyRef(requesterConfig.getPort()))
.withValue(MSB_BROKER_CONFIG_ROOT + ".virtualHost", ConfigValueFactory.fromAnyRef(requesterConfig.getVirtualHost()))
.withValue(MSB_BROKER_CONFIG_ROOT + ".username", ConfigValueFactory.fromAnyRef(requesterConfig.getUserName()))
.withValue(MSB_BROKER_CONFIG_ROOT + ".password", ConfigValueFactory.fromAnyRef(requesterConfig.getPassword()));
msbContext = new MsbContextBuilder()
.withConfig(msbConfig)
.enableShutdownHook(true)
.build();
}
public SampleResult sample(Entry e) {
trace("sample()");
RequesterConfig requesterConfig = (RequesterConfig)getProperty(RequesterConfig.TEST_ELEMENT_CONFIG).getObjectValue();
if (msbContext == null || !requesterConfig.equals(currentRequesterConfig)) {
currentRequesterConfig = requesterConfig;
initMsb(requesterConfig);
}
String namespace = requesterConfig.getNamespace();
RequestOptions requestOptions = new RequestOptions.Builder()
.withMessageTemplate(new MessageTemplate())
.withResponseTimeout(requesterConfig.getTimeout())
.withForwardNamespace(requesterConfig.getForwardNamespace())
.withWaitForResponses(requesterConfig.getWaitForResponses() ? requesterConfig.getNumberOfResponses() : 0)
.build();
String payloadJson = StringUtils.isNotEmpty(requesterConfig.getRequestPayload()) ? requesterConfig.getRequestPayload() : "{}";
JsonNode payload = Utils.fromJson(payloadJson, JsonNode.class, objectMapper);
final CountDownLatch waitForResponse = new CountDownLatch(requesterConfig.getNumberOfResponses());
final ArrayNode responses = objectMapper.createArrayNode();
SampleResult res = new SampleResult();
res.setSampleLabel(this.getName());
res.sampleStart();
msbContext
.getObjectFactory()
.createRequester(namespace, requestOptions, JsonNode.class)
.onResponse((response, messageContext) -> {
waitForResponse.countDown();
responses.add(response);
})
.publish(payload);
if (requesterConfig.getWaitForResponses()) {
try {
waitForResponse.await(2 * requesterConfig.getTimeout(), TimeUnit.MILLISECONDS);
} catch (InterruptedException ie) {
res.setResponseMessage(ie.getMessage());
}
}
res.sampleEnd();
int numberOfReceivedResponses = requesterConfig.getNumberOfResponses() - (int) waitForResponse.getCount();
trace("Received " + numberOfReceivedResponses + " responses from " + requesterConfig.getNumberOfResponses());
boolean isResultOk = !requesterConfig.getWaitForResponses() || waitForResponse.getCount() == 0;
if (isResultOk) {
String responsesAsJson = responses.toString();
trace("Responses: " + responsesAsJson);
res.setSuccessful(true);
res.setResponseCodeOK();
res.setResponseMessageOK();
res.setDataType(SampleResult.TEXT);
res.setResponseData(responsesAsJson, null);
} else {
res.setSuccessful(false);
res.setResponseCode("500");
res.setResponseMessage("No response(s)");
}
return res;
}
private void trace(String message) {
LOG.info(Thread.currentThread().getName() + " (" + classCount.get() + ") " + this.getName() + " " + message);
}
@Override
protected void finalize() throws Throwable {
if (msbContext != null) {
msbContext.shutdown();
}
}
} |
9237c688e60401066cb4bfd137c8f6b06127b27a | 6,662 | java | Java | java/Session2/web/src/main/java/devCamp/WebApp/services/IncidentServiceImpl.java | sriramdasbalaji/citypower | ce2febb768b3f5cb97356c9e0940742b46f55ec5 | [
"MIT"
] | 5 | 2017-05-16T23:10:40.000Z | 2020-06-01T13:59:48.000Z | java/Session2/web/src/main/java/devCamp/WebApp/services/IncidentServiceImpl.java | sriramdasbalaji/citypower | ce2febb768b3f5cb97356c9e0940742b46f55ec5 | [
"MIT"
] | 1 | 2021-02-24T02:17:26.000Z | 2021-02-24T02:17:26.000Z | java/Session2/web/src/main/java/devCamp/WebApp/services/IncidentServiceImpl.java | sriramdasbalaji/citypower | ce2febb768b3f5cb97356c9e0940742b46f55ec5 | [
"MIT"
] | 5 | 2017-11-22T22:37:57.000Z | 2021-01-12T09:12:27.000Z | 40.13253 | 113 | 0.774842 | 998,196 | package devCamp.WebApp.services;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.hateoas.PagedResources;
import org.springframework.hateoas.Resources;
import org.springframework.hateoas.hal.Jackson2HalModule;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import devCamp.WebApp.models.IncidentBean;
import devCamp.WebApp.properties.ApplicationProperties;
@Service
public class IncidentServiceImpl implements IncidentService {
private static final Logger LOG = LoggerFactory.getLogger(IncidentServiceImpl.class);
@Autowired
private ApplicationProperties applicationProperties;
@Autowired
private RestTemplate restTemplate;
@Override
public List<IncidentBean> getAllIncidents() {
LOG.info("Performing get {} web service", applicationProperties.getIncidentApiUrl() +"/incidents");
final String restUri = applicationProperties.getIncidentApiUrl() +"/incidents";
ResponseEntity<Resources<IncidentBean>> response = restTemplate.exchange(restUri, HttpMethod.GET, null,
new ParameterizedTypeReference<Resources<IncidentBean>>() {});
// LOG.info("Total Incidents {}", response.getBody().size());
Resources<IncidentBean> beanResources = response.getBody();
Collection<IncidentBean> beanCol = beanResources.getContent();
ArrayList<IncidentBean> beanList= new ArrayList<IncidentBean>(beanCol);
return beanList;
}
@Override
@JsonSerialize(using = Jackson2HalModule.HalResourcesSerializer.class)
@JsonDeserialize(using = Jackson2HalModule.HalResourcesDeserializer.class)
public PagedIncidents getIncidentsPaged(int pagenum,int pagesize) {
LOG.info("Performing get {} web service", applicationProperties.getIncidentApiUrl() +"/incidents");
final String restUri = applicationProperties.getIncidentApiUrl() +"/incidents?page="+pagenum+"&size="+pagesize;
ResponseEntity<PagedResources<IncidentBean>> response = restTemplate.exchange(restUri, HttpMethod.GET, null,
new ParameterizedTypeReference<PagedResources<IncidentBean>>() {});
// LOG.info("Total Incidents {}", response.getBody().size());
PagedResources<IncidentBean> beanResources = response.getBody();
PagedIncidents incidents = new PagedIncidents(beanResources,pagenum);
return incidents;
}
@Override
public IncidentBean createIncident(IncidentBean incident) {
LOG.info("Creating incident");
if (incident.getCreated() == null) {
incident.setCreated(getCurrentDate());
incident.setLastModified(getCurrentDate());
}
final String restUri = applicationProperties.getIncidentApiUrl() +"/incidents";
IncidentBean createdBean = restTemplate.postForObject(restUri, incident, IncidentBean.class);
LOG.info("Done creating incident");
return createdBean;
}
@Override
public IncidentBean updateIncident(IncidentBean newIncident) {
LOG.info("Updating incident");
newIncident.setLastModified(getCurrentDate());
final String restUri = applicationProperties.getIncidentApiUrl() +"/incidents/"+newIncident.getId();
IncidentBean createdBean = restTemplate.patchForObject(restUri, newIncident, IncidentBean.class);
LOG.info("Done updating incident");
return createdBean;
}
@Override
public IncidentBean getById(String incidentId) {
LOG.info("Getting incident by ID {}", incidentId);
final String restUri = applicationProperties.getIncidentApiUrl() +"/incidents/"+incidentId;
IncidentBean result = restTemplate.getForObject(restUri, IncidentBean.class);
return result;
}
@Override
public CompletableFuture<List<IncidentBean>> getAllIncidentsAsync() {
CompletableFuture<List<IncidentBean>> cf = new CompletableFuture<>();
CompletableFuture.runAsync(() -> {
LOG.info("Performing get {} web service", applicationProperties.getIncidentApiUrl() +"/incidents");
final String restUri = applicationProperties.getIncidentApiUrl() +"/incidents";
ResponseEntity<Resources<IncidentBean>> response = restTemplate.exchange(restUri, HttpMethod.GET, null,
new ParameterizedTypeReference<Resources<IncidentBean>>() {});
// LOG.info("Total Incidents {}", response.getBody().size());
Resources<IncidentBean> beanResources = response.getBody();
Collection<IncidentBean> beanCol = beanResources.getContent();
ArrayList<IncidentBean> beanList= new ArrayList<IncidentBean>(beanCol);
cf.complete( beanList );
LOG.info("Done getting incidents");
});
return cf;
}
@Override
public CompletableFuture<IncidentBean> createIncidentAsync(IncidentBean incident) {
CompletableFuture<IncidentBean> cf = new CompletableFuture<>();
CompletableFuture.runAsync(() -> {
LOG.info("Creating incident");
final String restUri = applicationProperties.getIncidentApiUrl() +"/incidents";
IncidentBean createdBean = restTemplate.postForObject(restUri, incident, IncidentBean.class);
cf.complete(createdBean);
LOG.info("Done creating incident");
});
return cf;
}
@Override
public CompletableFuture<IncidentBean> updateIncidentAsync(IncidentBean newIncident) {
CompletableFuture<IncidentBean> cf = new CompletableFuture<>();
CompletableFuture.runAsync(() -> {
LOG.info("Updating incident");
//Add update logic here
cf.complete(null); //change null to data that this method will return after update
LOG.info("Done updating incident");
});
return cf;
}
@Override
public CompletableFuture<IncidentBean> getByIdAsync(String incidentId) {
CompletableFuture<IncidentBean> cf = new CompletableFuture<>();
CompletableFuture.runAsync(() -> {
LOG.info("Getting incident by ID {}", incidentId);
final String restUri = applicationProperties.getIncidentApiUrl() +"/incidents";
IncidentBean result = restTemplate.getForObject(restUri, IncidentBean.class);
cf.complete(result);
LOG.info("Done getting incident by ID");
});
return cf;
}
@Override
public void clearCache() {
}
private String getCurrentDate() {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
Date parsedDate = new Date();
String formattedDate = formatter.format(parsedDate);
return formattedDate;
}
}
|
9237c74004d690a73b3c0855e08f4ad94307b040 | 1,629 | java | Java | src/huoShan/AnZhuo/JiBen/rg_TuPianAnNiu.java | qqqkoko123/qianghongbao | e2c9e6fdb8a2b3eb19e4bc65b8b165480852ccc0 | [
"Apache-2.0"
] | 102 | 2020-11-17T08:55:14.000Z | 2022-03-30T09:13:49.000Z | src/huoShan/AnZhuo/JiBen/rg_TuPianAnNiu.java | qqqkoko123/qianghongbao | e2c9e6fdb8a2b3eb19e4bc65b8b165480852ccc0 | [
"Apache-2.0"
] | 21 | 2020-10-27T02:42:45.000Z | 2022-01-31T13:41:23.000Z | src/huoShan/AnZhuo/JiBen/rg_TuPianAnNiu.java | qqqkoko123/qianghongbao | e2c9e6fdb8a2b3eb19e4bc65b8b165480852ccc0 | [
"Apache-2.0"
] | 31 | 2020-10-27T02:43:20.000Z | 2022-02-22T01:49:26.000Z | 46.542857 | 138 | 0.755064 | 998,197 |
package huoShan.AnZhuo.JiBen;
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
public class rg_TuPianAnNiu extends rg_TuPianKuang {
public rg_TuPianAnNiu () { }
public rg_TuPianAnNiu (android.content.Context context, ImageButton view, Object objInitData) { super (context, view, objInitData); }
public rg_TuPianAnNiu (android.content.Context context, ImageButton view) { this (context, view, null); }
public ImageButton GetImageButton () { return (ImageButton)GetView (); }
public static rg_TuPianAnNiu sNewInstance (android.content.Context context) {
return sNewInstanceAndAttachView (context, new ImageButton (context), null);
}
public static rg_TuPianAnNiu sNewInstance (android.content.Context context, Object objInitData) {
return sNewInstanceAndAttachView (context, new ImageButton (context), objInitData);
}
public static rg_TuPianAnNiu sNewInstanceAndAttachView (android.content.Context context, ImageButton viewAttach) {
return sNewInstanceAndAttachView (context, viewAttach, null);
}
public static rg_TuPianAnNiu sNewInstanceAndAttachView (android.content.Context context, ImageButton viewAttach, Object objInitData) {
rg_TuPianAnNiu objControl = new rg_TuPianAnNiu (context, viewAttach, objInitData);
objControl.onInitControlContent (context, objInitData);
return objControl;
}
protected void OnInitView (android.content.Context context, Object objInitData) {
super.OnInitView (context, objInitData);
rg_ZhiChiChanJi1 (true);
}
}
|
9237c747786bfc67b7ace0a3a4957f0a483e6206 | 1,274 | java | Java | lang/java/integration-test/test-custom-conversions/src/main/java/org/apache/avro/codegentest/FixedSizeStringFactory.java | kchobantonov/avro | 5d2f01a1ea73ba45391fcfaf0f349b81ec577f51 | [
"Apache-2.0"
] | 1,960 | 2015-01-02T15:11:37.000Z | 2022-03-31T19:50:17.000Z | lang/java/integration-test/test-custom-conversions/src/main/java/org/apache/avro/codegentest/FixedSizeStringFactory.java | kchobantonov/avro | 5d2f01a1ea73ba45391fcfaf0f349b81ec577f51 | [
"Apache-2.0"
] | 934 | 2015-02-19T23:29:16.000Z | 2022-03-31T08:33:26.000Z | lang/java/integration-test/test-custom-conversions/src/main/java/org/apache/avro/codegentest/FixedSizeStringFactory.java | kchobantonov/avro | 5d2f01a1ea73ba45391fcfaf0f349b81ec577f51 | [
"Apache-2.0"
] | 1,381 | 2015-01-02T15:11:37.000Z | 2022-03-28T07:25:09.000Z | 32.666667 | 80 | 0.759812 | 998,198 | /*
* 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.avro.codegentest;
import org.apache.avro.LogicalType;
import org.apache.avro.LogicalTypes;
import org.apache.avro.Schema;
public class FixedSizeStringFactory implements LogicalTypes.LogicalTypeFactory {
public static final String NAME = "fixed-size-string";
@Override
public LogicalType fromSchema(Schema schema) {
return new FixedSizeStringLogicalType(schema);
}
@Override
public String getTypeName() {
return NAME;
}
}
|
9237c7bdfa0971774efd176d5a33e8d765729a04 | 6,943 | java | Java | src/com/landawn/abacus/android/ProgressBarTask.java | landawn/AbacusUtil | fbcc6bc8cf53247079b9d6ce5f667880f3eaeb4c | [
"Apache-2.0"
] | 87 | 2016-02-07T23:13:57.000Z | 2021-09-03T01:54:44.000Z | src/com/landawn/abacus/android/ProgressBarTask.java | lihy70/AbacusUtil | 16f18daffbe4a047e2ebb5a0efe05bd189bdb90f | [
"Apache-2.0"
] | 28 | 2017-01-12T22:02:54.000Z | 2022-01-23T02:57:11.000Z | src/com/landawn/abacus/android/ProgressBarTask.java | lihy70/AbacusUtil | 16f18daffbe4a047e2ebb5a0efe05bd189bdb90f | [
"Apache-2.0"
] | 15 | 2016-09-02T23:10:42.000Z | 2021-12-04T13:30:22.000Z | 36.73545 | 141 | 0.642518 | 998,199 | /*
* Copyright (C) 2016 HaiYang Li
*
* 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.landawn.abacus.android;
import java.util.concurrent.Callable;
import com.landawn.abacus.android.util.Async.UIExecutor;
import com.landawn.abacus.android.util.ContinuableFuture;
import com.landawn.abacus.util.Multiset;
import android.app.Activity;
import android.app.Dialog;
import android.view.Gravity;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
/**
* Designed to show progress bar easily for network or other heavy operation:
* <pre>
* <code>
final ProgressBarTask progressBarTask = ProgressBarTask.display(this, 1000, 0xFFE0E0E0);
final LoginRequest request = ...;
AsyncExecutor.executeInParallel(() -> accountService.login(request))
.callbackOnUiThread((e, resp) -> {
displayProgressBarTask.finish();
if (resp != null && resp.getRespCode() == ResponseCode.OK) {
// TODO ...
} else {// TODO ...
}
});
* </code>
* </pre>
*
* @since 0.8
*
* @author haiyangl
*/
public class ProgressBarTask {
private static final Multiset<ViewGroup> activeProgressBarSet = new Multiset<>();
private static volatile int maxProgressBarTask = Integer.MAX_VALUE;
private static volatile int maxProgressBarTaskPerView = Integer.MAX_VALUE;
protected final ContinuableFuture<ProgressBar> future;
protected ProgressBar progressBar;
public ProgressBarTask(final ViewGroup root, final long delay, final int circleColor) {
future = UIExecutor.execute(new Callable<ProgressBar>() {
@Override
public ProgressBar call() {
synchronized (ProgressBarTask.this) {
return ProgressBarTask.this.progressBar = (future.isCancelled() || activeProgressBarTaskCount() >= maxProgressBarTask
|| activeProgressBarTaskCount(root) >= maxProgressBarTaskPerView) ? null : createProgressBar(root, circleColor);
}
}
}, delay);
}
public static void setMaxProgressBarTask(int maxProgressBarTask) {
ProgressBarTask.maxProgressBarTask = maxProgressBarTask;
}
public static void setMaxProgressBarTaskPerView(int maxProgressBarTaskPerView) {
ProgressBarTask.maxProgressBarTaskPerView = maxProgressBarTaskPerView;
}
public static ProgressBarTask display(final Activity activity) {
return display(activity, 0);
}
public static ProgressBarTask display(final Activity activity, final long delay) {
return display(activity, delay, Integer.MIN_VALUE);
}
public static ProgressBarTask display(final Activity activity, final long delay, final int circleColor) {
return display((ViewGroup) activity.getWindow().getDecorView(), delay, circleColor);
}
public static ProgressBarTask display(final Dialog dialog) {
return display(dialog, 0);
}
public static ProgressBarTask display(final Dialog dialog, final long delay) {
return display(dialog, delay, Integer.MIN_VALUE);
}
public static ProgressBarTask display(final Dialog dialog, final long delay, final int circleColor) {
return display((ViewGroup) dialog.getWindow().getDecorView(), delay, circleColor);
}
public static ProgressBarTask display(final ViewGroup root) {
return display(root, 0);
}
public static ProgressBarTask display(final ViewGroup root, final long delay) {
return display(root, delay, Integer.MIN_VALUE);
}
public static ProgressBarTask display(final ViewGroup root, final long delay, final int circleColor) {
return new ProgressBarTask(root, delay, circleColor);
}
static int activeProgressBarTaskCount() {
synchronized (activeProgressBarSet) {
return (int) activeProgressBarSet.sumOfOccurrences();
}
}
static int activeProgressBarTaskCount(Activity activity) {
synchronized (activeProgressBarSet) {
return activeProgressBarSet.get(activity.getWindow().getDecorView());
}
}
static int activeProgressBarTaskCount(Dialog dialog) {
synchronized (activeProgressBarSet) {
return activeProgressBarSet.get(dialog.getWindow().getDecorView());
}
}
static int activeProgressBarTaskCount(ViewGroup root) {
synchronized (activeProgressBarSet) {
return activeProgressBarSet.get(root);
}
}
public void finish() {
synchronized (this) {
try {
future.cancel(true);
} catch (Exception e) {
// ignore.
} finally {
if (progressBar != null) {
ViewParent parent = progressBar.getParent();
if (parent instanceof ViewGroup) {
final ViewGroup root = (ViewGroup) parent;
root.removeView(progressBar);
synchronized (activeProgressBarSet) {
activeProgressBarSet.remove(root);
}
}
}
}
}
}
protected ProgressBar createProgressBar(final ViewGroup root, final int circleColor) {
// Create layout params expecting to be added to a frame layout.
final FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(0, 0);
lp.width = lp.height = FrameLayout.LayoutParams.WRAP_CONTENT;
lp.gravity = Gravity.CENTER;
// Create a progress bar to be added to the window.
final ProgressBar progressBar = new ProgressBar(root.getContext());
progressBar.setIndeterminate(true);
progressBar.setLayoutParams(lp);
if (circleColor != Integer.MIN_VALUE) {
progressBar.getIndeterminateDrawable().setColorFilter(circleColor, android.graphics.PorterDuff.Mode.SRC_ATOP);
}
root.addView(progressBar);
synchronized (activeProgressBarSet) {
activeProgressBarSet.add(root);
}
return progressBar;
}
}
|
9237c81afbaa91a00b798db0ae553220558ff2f9 | 1,829 | java | Java | src/main/java/io/github/batetolast1/wedderforecast/dto/mapper/result/DailyResultMapper.java | batetolast1/wedder-forecast | eb37b5084bee86f8d9202879dc9970c3101cf0b5 | [
"MIT"
] | null | null | null | src/main/java/io/github/batetolast1/wedderforecast/dto/mapper/result/DailyResultMapper.java | batetolast1/wedder-forecast | eb37b5084bee86f8d9202879dc9970c3101cf0b5 | [
"MIT"
] | null | null | null | src/main/java/io/github/batetolast1/wedderforecast/dto/mapper/result/DailyResultMapper.java | batetolast1/wedder-forecast | eb37b5084bee86f8d9202879dc9970c3101cf0b5 | [
"MIT"
] | null | null | null | 46.897436 | 147 | 0.778021 | 998,200 | package io.github.batetolast1.wedderforecast.dto.mapper.result;
import io.github.batetolast1.wedderforecast.dto.mapper.location.LocationMapper;
import io.github.batetolast1.wedderforecast.dto.mapper.weather.DailyWeatherMapper;
import io.github.batetolast1.wedderforecast.dto.mapper.weather.PredictedDailyWeatherMapper;
import io.github.batetolast1.wedderforecast.dto.model.result.DailyResultDto;
import io.github.batetolast1.wedderforecast.model.results.DailyResult;
import io.github.batetolast1.wedderforecast.model.weather.DailyWeather;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.Comparator;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class DailyResultMapper {
private final LocationMapper locationMapper;
private final DailyWeatherMapper dailyWeatherMapper;
private final PredictedDailyWeatherMapper predictedDailyWeatherMapper;
public DailyResultDto toDailyResultDto(DailyResult dailyResult) {
DailyResultDto dailyResultDto = new DailyResultDto();
dailyResultDto.setId(dailyResult.getId());
dailyResultDto.setLocalDateTime(dailyResult.getLocalDateTime());
dailyResultDto.setLocationDto(locationMapper.toLocationDto(dailyResult.getLocation()));
dailyResultDto.setDailyWeatherDtos(
dailyResult.getDailyWeathers()
.stream()
.sorted(Comparator.comparing(DailyWeather::getLocalDateTime).reversed())
.map(dailyWeatherMapper::toDailyWeatherDto)
.collect(Collectors.toList()));
dailyResultDto.setPredictedDailyWeatherDto(predictedDailyWeatherMapper.toPredictedDailyWeatherDto(dailyResult.getPredictedDailyWeather()));
return dailyResultDto;
}
}
|
9237c846d7adf111134c5b6584985fc7c1a2a60e | 1,180 | java | Java | chess/src/test/java/ru/job4j/AppTest.java | Mrdomax/job4j | f38fe2a022a87293083d5c34edbc23f677657cb2 | [
"Apache-2.0"
] | 1 | 2019-03-24T23:10:43.000Z | 2019-03-24T23:10:43.000Z | chess/src/test/java/ru/job4j/AppTest.java | Mrdomax/job4j | f38fe2a022a87293083d5c34edbc23f677657cb2 | [
"Apache-2.0"
] | null | null | null | chess/src/test/java/ru/job4j/AppTest.java | Mrdomax/job4j | f38fe2a022a87293083d5c34edbc23f677657cb2 | [
"Apache-2.0"
] | null | null | null | 23.137255 | 48 | 0.7 | 998,201 | package ru.job4j;
import javafx.scene.Group;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Before;
import ru.job4j.chess.Chess;
import ru.job4j.chess.Logic;
import ru.job4j.chess.figures.Cell;
import ru.job4j.chess.figures.Figure;
import ru.job4j.chess.figures.black.BishopBlack;
import ru.job4j.chess.figures.black.PawnBlack;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase {
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest(String testName) {
super(testName);
}
/**
* @return the suite of tests being tested
*/
public static Test suite() {
return new TestSuite(AppTest.class);
}
/**
* Rigourous Test :-)
*/
public void testApp() {
assertTrue(true);
}
}
|
9237c97aa6715a5cc8e52838951f909a96fc678b | 4,111 | java | Java | openshift-tasks/src/main/java/com/openshift/service/DemoResource.java | bkugler-xv/rh-app-dev-hw | a60bfbecb25002fa45b8668429a9feec00701923 | [
"Unlicense"
] | null | null | null | openshift-tasks/src/main/java/com/openshift/service/DemoResource.java | bkugler-xv/rh-app-dev-hw | a60bfbecb25002fa45b8668429a9feec00701923 | [
"Unlicense"
] | null | null | null | openshift-tasks/src/main/java/com/openshift/service/DemoResource.java | bkugler-xv/rh-app-dev-hw | a60bfbecb25002fa45b8668429a9feec00701923 | [
"Unlicense"
] | null | null | null | 36.705357 | 124 | 0.654099 | 998,202 | package com.openshift.service;
import com.openshift.helpers.Load;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.SecurityContext;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A JAX-RS resource for exposing REST endpoints for Task manipulation
*/
@Path("demo")
public class DemoResource {
// application instance health
// 1 is healthy
private static Integer health = 1;
@GET
@Path("load/{seconds}")
@Produces({"application/json"})
public String generateLoad(@Context SecurityContext context, @PathParam("seconds") int seconds) {
Load cpuLoad = new Load();
cpuLoad.generateLoad(seconds * 1000);
String response = new String("Load being generated for " + seconds + " seconds.");
Logger log = Logger.getLogger(DemoResource.class.getName());
log.log(Level.INFO, "INFO: Requested to generate load for " + seconds + " seconds.");
return "{\"response\":\"" + response + "\"}";
}
@GET
@Path("log/info")
@Produces({"application/json"})
public String logInfo(@Context SecurityContext context) {
Logger log = Logger.getLogger(DemoResource.class.getName());
log.log(Level.INFO, "INFO: OpenShift 3 is an excellent platform for JEE development.");
return new String("{\"response\":\"An informational message was recorded internally.\"}");
}
@GET
@Path("log/warning")
@Produces({"application/json"})
public String logWarning(@Context SecurityContext context) {
Logger log = Logger.getLogger(DemoResource.class.getName());
log.log(Level.WARNING, "WARN: Flying a kite in a thunderstorm should not be attempted.");
return new String("{\"response\":\"A warning message was recorded internally.\"}");
}
@GET
@Path("log/error/")
@Produces({"application/json"})
public String logSevere(@Context SecurityContext context) {
Logger log = Logger.getLogger(DemoResource.class.getName());
log.log(Level.SEVERE, "ERROR: Something pretty bad has happened and should probably be addressed sooner or later.");
return new String("{\"response\":\"An internal error has occured!\"}");
}
// this endpoint will toggle the health of this instance
@GET
@Path("togglehealth/")
@Produces({"application/json"})
public String togglehealth(@Context SecurityContext context) {
// check if currently healthy, otherwise "become" healthy
if (health == 1) {
// become unhealthy
health = 0;
Logger log = Logger.getLogger(DemoResource.class.getName());
log.log(Level.SEVERE, "ERROR: I'm not feeling so well.");
return new String("{\"response\":\"The app is starting to look a little ill...\"}");
} else {
// become healthy
health = 1;
Logger log = Logger.getLogger(DemoResource.class.getName());
log.log(Level.INFO, "INFO: I feel much better.");
return new String("{\"response\":\"The app is starting to look great!\"}");
}
}
@GET
@Path("killswitch/")
@Produces({"application/json"})
public void killSwitch(@Context SecurityContext context) throws IOException {
Logger log = Logger.getLogger(DemoResource.class.getName());
log.log(Level.SEVERE, "ERROR: Going down NOW!");
Runtime.getRuntime().halt(255);
}
@GET
@Path("healthcheck/")
@Produces({"application/json"})
public Response checkHealth(@Context SecurityContext context) throws IOException {
String response = new String("{\"response\":\"Health Status: " + health + "\", \"health\": " + health + "}");
// if health is 1, return 200, otherwise 500
if (health == 1) {
return Response.status(Response.Status.OK).entity(response).build();
} else {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(response).build();
}
}
}
|
9237cacd122f32bfd8b4e97666ae29cba6adcfad | 9,204 | java | Java | src/test/java/ru/uglic/votelemo/data/TestData.java | uglic/votelemo | 28851de6ceab7794b026e26180aec44ab5fc6ee5 | [
"MIT"
] | 2 | 2019-08-18T10:30:14.000Z | 2019-08-27T21:08:37.000Z | src/test/java/ru/uglic/votelemo/data/TestData.java | uglic/votelemo | 28851de6ceab7794b026e26180aec44ab5fc6ee5 | [
"MIT"
] | 1 | 2022-01-21T23:28:18.000Z | 2022-01-21T23:28:18.000Z | src/test/java/ru/uglic/votelemo/data/TestData.java | uglic/votelemo | 28851de6ceab7794b026e26180aec44ab5fc6ee5 | [
"MIT"
] | null | null | null | 59.766234 | 150 | 0.753042 | 998,203 | package ru.uglic.votelemo.data;
import org.springframework.security.crypto.password.PasswordEncoder;
import ru.uglic.votelemo.dto.out.DishWithPricesDto;
import ru.uglic.votelemo.dto.out.VoteStatDto;
import ru.uglic.votelemo.model.*;
import ru.uglic.votelemo.security.AuthUtil;
import java.math.BigDecimal;
import java.time.LocalDate;
import static ru.uglic.votelemo.data.Util.*;
public class TestData {
private static final PasswordEncoder passwordEncoder = AuthUtil.getInstance().getPasswordEncoder();
private static final int SEQ_START = 10_000;
public static final int NEXT_CREATE_ID = 10_056;
public static final int NOT_EXISTED_ENTITY_ID = SEQ_START + 12345;
public static final int DISH_ID_FREE = 10_022;
public static final int RESTAURANT_ID_FREE = 10_027;
public static final int USER_ID_FREE = 10_028;
//-- users
public static final int USER_1_ID = 10_000;
public static final int ADMIN_1_ID = 10_001;
public static final int VOTE_BIG_USER_ID_0 = 10_035;
public static final int VOTE_BIG_USER_ID_1 = 10_036;
public static final int VOTE_BIG_USER_ID_2 = 10_037;
public static final int VOTE_BIG_USER_ID_3 = 10_038;
public static final int VOTE_BIG_USER_ID_4 = 10_039;
public static final int VOTE_BIG_USER_ID_5 = 10_040;
public static final int VOTE_BIG_USER_ID_6 = 10_041;
public static final int VOTE_BIG_USER_ID_7 = 10_042;
public static final int VOTE_BIG_USER_ID_8 = 10_043;
public static final int VOTE_BIG_USER_ID_9 = 10_044;
//-- dishes
public static final int DISH_ID_1 = 10_002;
public static final int DISH_ID_2 = 10_003;
public static final int DISH_ID_3 = 10_004;
//-- restaurants
public static final int RESTAURANT_ID_1 = 10_005;
public static final int RESTAURANT_ID_2 = 10_006;
public static final int RESTAURANT_ID_3 = 10_007;
//-- menus
public static final int MENU_ID_1 = 10_008;
public static final int MENU_ID_2 = 10_009;
public static final int MENU_ID_3 = 10_010;
//-- menu items
public static final int MENU_1_DISH_ID_1 = 10_011;
public static final int MENU_1_DISH_ID_2 = 10_012;
public static final int MENU_1_DISH_ID_3 = 10_013;
public static final int MENU_2_DISH_ID_1 = 10_014;
public static final int MENU_2_DISH_ID_2 = 10_015;
public static final int MENU_2_DISH_ID_3 = 10_016;
public static final int MENU_3_DISH_ID_1 = 10_017;
public static final int MENU_3_DISH_ID_2 = 10_018;
public static final int MENU_3_DISH_ID_3 = 10_019;
//-- votes
public static final int VOTE_USER_ID_1 = 10_020;
public static final int VOTE_ADMIN_ID_1 = 10_021;
public static final int VOTE_USER_ID_2 = 10_029;
public static final int VOTE_USER_ID_3 = 10_030;
public static final int VOTE_USER_ID_4 = 10_031;
public static final int VOTE_BIG_ID_0 = 10_045;
public static final int VOTE_BIG_ID_1 = 10_046;
public static final int VOTE_BIG_ID_2 = 10_047;
public static final int VOTE_BIG_ID_3 = 10_048;
public static final int VOTE_BIG_ID_4 = 10_049;
public static final int VOTE_BIG_ID_5 = 10_050;
public static final int VOTE_BIG_ID_6 = 10_051;
public static final int VOTE_BIG_ID_7 = 10_052;
public static final int VOTE_BIG_ID_8 = 10_053;
public static final int VOTE_BIG_ID_9 = 10_054;
public static final int VOTE_BIG_ID_ADMIN = 10_055;
//-- vote results
public static final int VOTE_RESULT_ID_1 = 10_032;
public static final int VOTE_RESULT_ID_2 = 10_033;
public static final int VOTE_RESULT_ID_3 = 10_034;
public static final String USER_1_RAW_PASSWORD = "password";
public static final String ADMIN_RAW_PASSWORD = "adssword";
public static final User USER_1 = newUser(USER_1_ID, "user", passwordEncoder.encode(USER_1_RAW_PASSWORD), false, false);
public static final User ADMIN = newUser(ADMIN_1_ID, "adin", passwordEncoder.encode(ADMIN_RAW_PASSWORD), true, false);
public static final User USER_FREE = newUser(USER_ID_FREE, "user_free", passwordEncoder.encode("empty"), false, false);
public static final User USER_BIG_0 = newUser(VOTE_BIG_USER_ID_0, "user0", "{bcrypt}errorneous", false, false);
public static final User USER_BIG_1 = newUser(VOTE_BIG_USER_ID_1, "user1", "{bcrypt}errorneous", false, false);
public static final User USER_BIG_2 = newUser(VOTE_BIG_USER_ID_2, "user2", "{bcrypt}errorneous", false, false);
public static final User USER_BIG_3 = newUser(VOTE_BIG_USER_ID_3, "user3", "{bcrypt}errorneous", false, false);
public static final User USER_BIG_4 = newUser(VOTE_BIG_USER_ID_4, "user4", "{bcrypt}errorneous", false, false);
public static final User USER_BIG_5 = newUser(VOTE_BIG_USER_ID_5, "user5", "{bcrypt}errorneous", false, false);
public static final User USER_BIG_6 = newUser(VOTE_BIG_USER_ID_6, "user6", "{bcrypt}errorneous", false, false);
public static final User USER_BIG_7 = newUser(VOTE_BIG_USER_ID_7, "user7", "{bcrypt}errorneous", false, false);
public static final User USER_BIG_8 = newUser(VOTE_BIG_USER_ID_8, "user8", "{bcrypt}errorneous", false, false);
public static final User USER_BIG_9 = newUser(VOTE_BIG_USER_ID_9, "user9", "{bcrypt}errorneous", false, true);
public static final Dish DISH_1 = newDish(DISH_ID_1, "First item");
public static final Dish DISH_2 = newDish(DISH_ID_2, "Second item");
public static final Dish DISH_3 = newDish(DISH_ID_3, "Third item");
public static final Restaurant RESTAURANT_1 = newRestaurant(RESTAURANT_ID_1, "First restaurant", 1);
public static final Restaurant RESTAURANT_2 = newRestaurant(RESTAURANT_ID_2, "Second restaurant", 2);
public static final Restaurant RESTAURANT_3 = newRestaurant(RESTAURANT_ID_3, "Third restaurant", 3);
public static final Restaurant RESTAURANT_FREE = newRestaurant(RESTAURANT_ID_FREE, "W-th ресторан", 6);
public static final Menu MENU_1 = newMenu(MENU_ID_1, LocalDate.of(2019, 7, 1), RESTAURANT_1, null);
public static final Menu MENU_2 = newMenu(MENU_ID_2, LocalDate.of(2019, 7, 1), RESTAURANT_2, null);
public static final Menu MENU_3 = newMenu(MENU_ID_3, LocalDate.of(2019, 7, 1), RESTAURANT_3, null);
static {
MENU_1.addMenuItem(newMenuItem(MENU_1_DISH_ID_1, MENU_1, DISH_1, new BigDecimal("1.20")));
MENU_1.addMenuItem(newMenuItem(MENU_1_DISH_ID_2, MENU_1, DISH_2, new BigDecimal("2.51")));
MENU_1.addMenuItem(newMenuItem(MENU_1_DISH_ID_3, MENU_1, DISH_3, new BigDecimal("3.63")));
MENU_2.addMenuItem(newMenuItem(MENU_2_DISH_ID_1, MENU_2, DISH_1, new BigDecimal("4.91")));
MENU_2.addMenuItem(newMenuItem(MENU_2_DISH_ID_2, MENU_2, DISH_2, new BigDecimal("5.46")));
MENU_2.addMenuItem(newMenuItem(MENU_2_DISH_ID_3, MENU_2, DISH_3, new BigDecimal("6.23")));
MENU_3.addMenuItem(newMenuItem(MENU_3_DISH_ID_1, MENU_3, DISH_1, new BigDecimal("7.43")));
MENU_3.addMenuItem(newMenuItem(MENU_3_DISH_ID_2, MENU_3, DISH_2, new BigDecimal("8.35")));
MENU_3.addMenuItem(newMenuItem(MENU_3_DISH_ID_3, MENU_3, DISH_3, new BigDecimal("9.67")));
}
public static final Vote VOTE_USER_1 = newVote(VOTE_USER_ID_1, LocalDate.of(2019, 7, 1), USER_1, RESTAURANT_1);
public static final Vote VOTE_ADMIN_1 = newVote(VOTE_ADMIN_ID_1, LocalDate.of(2019, 7, 1), USER_1, RESTAURANT_2);
public static final Vote VOTE_USER_2 = newVote(VOTE_USER_ID_2, LocalDate.of(2019, 7, 2), USER_1, RESTAURANT_1);
public static final Vote VOTE_USER_3 = newVote(VOTE_USER_ID_3, LocalDate.of(2019, 7, 3), USER_1, RESTAURANT_2);
public static final Vote VOTE_USER_4 = newVote(VOTE_USER_ID_4, LocalDate.of(2019, 7, 4), USER_1, RESTAURANT_3);
public static final Vote VOTE_BIG_ADMIN_2 = newVote(VOTE_BIG_ID_ADMIN, LocalDate.of(2019, 8, 1), ADMIN, RESTAURANT_1);
public static final VoteResult VOTE_RESULT_1 = newVoteResult(VOTE_RESULT_ID_1, LocalDate.of(2019, 7, 10), RESTAURANT_1, RESTAURANT_2, null);
public static final VoteResult VOTE_RESULT_2 = newVoteResult(VOTE_RESULT_ID_2, LocalDate.of(2019, 7, 11), null, RESTAURANT_1, null);
public static final VoteResult VOTE_RESULT_3 = newVoteResult(VOTE_RESULT_ID_3, LocalDate.of(2019, 7, 12), RESTAURANT_3, null, null);
// --- DTO's
public static final DishWithPricesDto DISH_WITH_PRICE_1 = new DishWithPricesDto(DISH_1.getName(), new BigDecimal("1.20"), new BigDecimal("7.43"));
public static final DishWithPricesDto DISH_WITH_PRICE_2 = new DishWithPricesDto(DISH_2.getName(), new BigDecimal("2.51"), new BigDecimal("8.35"));
public static final DishWithPricesDto DISH_WITH_PRICE_3 = new DishWithPricesDto(DISH_3.getName(), new BigDecimal("3.63"), new BigDecimal("9.67"));
public static final VoteStatDto VOTE_STAT_DATE_1_1 = new VoteStatDto(VOTE_USER_1.getDate(), VOTE_USER_1.getRestaurant(), 1);
public static final VoteStatDto VOTE_STAT_BIG_1 = new VoteStatDto(VOTE_BIG_ADMIN_2.getDate(), RESTAURANT_1, 5);
public static final VoteStatDto VOTE_STAT_BIG_2 = new VoteStatDto(VOTE_BIG_ADMIN_2.getDate(), RESTAURANT_2, 3);
public static final VoteStatDto VOTE_STAT_BIG_3 = new VoteStatDto(VOTE_BIG_ADMIN_2.getDate(), RESTAURANT_3, 1);
}
|
9237cc7215908c80ea466a7b7ae2af2bb91e4a56 | 1,048 | java | Java | src/main/java/com/clubobsidian/wrappy/UnknownFileTypeException.java | ClubObsidian/wrappy | bac7122891d4eb01f14204a9f9b77bb14f337ba2 | [
"ECL-2.0",
"Apache-2.0"
] | 3 | 2018-09-07T10:03:13.000Z | 2021-08-29T01:15:09.000Z | src/main/java/com/clubobsidian/wrappy/UnknownFileTypeException.java | ClubObsidian/wrappy | bac7122891d4eb01f14204a9f9b77bb14f337ba2 | [
"ECL-2.0",
"Apache-2.0"
] | 44 | 2018-09-15T00:04:40.000Z | 2022-03-14T02:21:44.000Z | src/main/java/com/clubobsidian/wrappy/UnknownFileTypeException.java | ClubObsidian/wrappy | bac7122891d4eb01f14204a9f9b77bb14f337ba2 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2018-11-25T06:30:25.000Z | 2020-03-21T19:30:35.000Z | 30.823529 | 78 | 0.726145 | 998,204 | /*
* Copyright 2021 Club Obsidian and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.clubobsidian.wrappy;
import java.io.File;
public class UnknownFileTypeException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 5825723878989203063L;
public UnknownFileTypeException(File file) {
this(file.getName());
}
public UnknownFileTypeException(String fileName) {
super("Unknown file type for configuration file " + fileName);
}
} |
9237ccb289f01b3dc60c0a34cff559e3c6abe2c4 | 166 | java | Java | src/rosetta/MDC_DIM_MILLI_EQUIV_PER_LB_PER_MIN.java | EDS-APHP/LightICE | 04d1c27bccd5c64df46d8182b8f4490b98540b3e | [
"BSD-2-Clause"
] | 4 | 2018-05-09T21:11:30.000Z | 2018-06-19T11:38:29.000Z | src/rosetta/MDC_DIM_MILLI_EQUIV_PER_LB_PER_MIN.java | Dubrzr/LightICE | 04d1c27bccd5c64df46d8182b8f4490b98540b3e | [
"BSD-2-Clause"
] | 8 | 2018-05-09T19:00:17.000Z | 2018-05-27T12:49:34.000Z | src/rosetta/MDC_DIM_MILLI_EQUIV_PER_LB_PER_MIN.java | Dubrzr/LightICE | 04d1c27bccd5c64df46d8182b8f4490b98540b3e | [
"BSD-2-Clause"
] | 2 | 2018-05-17T09:55:34.000Z | 2020-03-23T07:21:01.000Z | 18.444444 | 76 | 0.728916 | 998,205 | package rosetta;
public class MDC_DIM_MILLI_EQUIV_PER_LB_PER_MIN {
public static final String VALUE = "MDC_DIM_MILLI_EQUIV_PER_LB_PER_MIN";
}
|
9237cf2495a220ff7b0c1cc39398fe4e0e0d0e6d | 1,355 | java | Java | systemtests/src/main/java/org/bf2/admin/kafka/systemtest/listeners/TestCallbackListener.java | MikeEdgar/kafka-admin-api | 8d183d35bf91f48e212dd5a70a5ab78cd1e12281 | [
"Apache-2.0"
] | 1 | 2022-03-12T19:55:08.000Z | 2022-03-12T19:55:08.000Z | systemtests/src/main/java/org/bf2/admin/kafka/systemtest/listeners/TestCallbackListener.java | MikeEdgar/kafka-admin-api | 8d183d35bf91f48e212dd5a70a5ab78cd1e12281 | [
"Apache-2.0"
] | 8 | 2022-03-01T23:39:10.000Z | 2022-03-25T16:12:56.000Z | systemtests/src/main/java/org/bf2/admin/kafka/systemtest/listeners/TestCallbackListener.java | MikeEdgar/kafka-admin-api | 8d183d35bf91f48e212dd5a70a5ab78cd1e12281 | [
"Apache-2.0"
] | 6 | 2022-02-25T14:08:27.000Z | 2022-03-23T11:43:28.000Z | 43.709677 | 121 | 0.77786 | 998,206 | package org.bf2.admin.kafka.systemtest.listeners;
import org.bf2.admin.kafka.systemtest.utils.TestUtils;
import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
public class TestCallbackListener implements BeforeAllCallback, BeforeEachCallback, AfterAllCallback, AfterEachCallback {
@Override
public void beforeAll(ExtensionContext extensionContext) throws Exception {
TestUtils.logWithSeparator("-> Running test class: %s", extensionContext.getRequiredTestClass().getName());
}
@Override
public void beforeEach(ExtensionContext extensionContext) throws Exception {
TestUtils.logWithSeparator("-> Running test method: %s", extensionContext.getDisplayName());
}
@Override
public void afterAll(ExtensionContext extensionContext) throws Exception {
TestUtils.logWithSeparator("-> End of test class: %s", extensionContext.getRequiredTestClass().getName());
}
@Override
public void afterEach(ExtensionContext extensionContext) throws Exception {
TestUtils.logWithSeparator("-> End of test method: %s", extensionContext.getDisplayName());
}
}
|
9237d055d7891c907e1a9eb58bd17c0b259b755c | 280 | java | Java | src/main/java/com/example/demo/design/structural/adapter/twoway/TargetRealize.java | CounterattackOfAcmen/design-pattern | 2079a4e7ccbb2dd8b52220d756693f5a76c859c4 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/example/demo/design/structural/adapter/twoway/TargetRealize.java | CounterattackOfAcmen/design-pattern | 2079a4e7ccbb2dd8b52220d756693f5a76c859c4 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/example/demo/design/structural/adapter/twoway/TargetRealize.java | CounterattackOfAcmen/design-pattern | 2079a4e7ccbb2dd8b52220d756693f5a76c859c4 | [
"Apache-2.0"
] | null | null | null | 20 | 58 | 0.703571 | 998,207 | package com.example.demo.design.structural.adapter.twoway;
import com.example.demo.design.structural.adapter.ITarget;
/**
* @author zhang
*/
public class TargetRealize implements ITarget {
@Override
public void request() {
System.out.println("目标方法。");
}
}
|
9237d06b600c146d5577860441c9f9167086765a | 2,223 | java | Java | sequence-core/src/main/java/com/power4j/kit/seq/persistent/SeqSynchronizer.java | lishangbu/sequence | 28054611442ca6514faa98b2501e23ebd930f85e | [
"Apache-2.0"
] | 6 | 2020-07-08T01:17:17.000Z | 2021-11-26T02:44:55.000Z | sequence-core/src/main/java/com/power4j/kit/seq/persistent/SeqSynchronizer.java | power4j/sequence | 28054611442ca6514faa98b2501e23ebd930f85e | [
"Apache-2.0"
] | 65 | 2020-07-29T08:52:33.000Z | 2022-03-29T00:14:55.000Z | sequence-core/src/main/java/com/power4j/kit/seq/persistent/SeqSynchronizer.java | lishangbu/sequence | 28054611442ca6514faa98b2501e23ebd930f85e | [
"Apache-2.0"
] | 2 | 2020-07-29T08:50:03.000Z | 2021-02-15T03:04:11.000Z | 19.883929 | 88 | 0.658734 | 998,208 | /*
* Copyright 2020 ChenJun (lyhxr@example.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.power4j.kit.seq.persistent;
import java.util.Optional;
/**
* Seq记录同步接口 <br/>
* <ul>
* <li>Seq记录唯一性 = 名称 + 分区</li>
* <li>此接口的所有方法除非特别说明,默认必须提供线程安全保障</li>
* </ul>
*
* @author CJ (lyhxr@example.com)
* @date 2020/7/1
* @since 1.0
*/
public interface SeqSynchronizer {
/**
* 创建序号记录,如已经存在则忽略
* @param name 名称
* @param partition 分区
* @param nextValue 初始值
* @return true 表示创建成功,false 表示记录已经存在
*/
boolean tryCreate(String name, String partition, long nextValue);
/**
* 尝试更新记录
* <p>
* <b>此接口为可选实现接口</b>
* </p>
* @param name
* @param partition
* @param nextValueOld
* @param nextValueNew
* @return true 表示更新成功
* @throws UnsupportedOperationException 不支持此方法
*/
boolean tryUpdate(String name, String partition, long nextValueOld, long nextValueNew);
/**
* 尝试加法操作
* @param name
* @param partition
* @param delta 加数
* @param maxReTry 最大重试次数,小于0表示无限制. 0 表示重试零次(总共执行1次) 1 表示重试一次(总共执行2次)。此参数跟具体的实现层有关。
* @return 返回执行加法操作执行结果
*/
AddState tryAddAndGet(String name, String partition, int delta, int maxReTry);
/**
* 查询当前值
* @param name
* @param partition
* @return 返回null表示记录不存在
*/
Optional<Long> getNextValue(String name, String partition);
/**
* 执行初始化.
* <p>
* <b>无线程线程安全保障,但是可以多次执行</b>
* </p>
* 。
*/
void init();
/**
* 关闭,执行资源清理.
* <p>
* <b>无线程线程安全保障,但是可以多次执行</b>
* </p>
* 。
*/
default void shutdown() {
// do nothing
}
/**
* 查询语句总共执行的次数
* @return
*/
default long getQueryCounter() {
return 0L;
}
/**
* 更新语句总共执行的次数
* @return
*/
default long getUpdateCounter() {
return 0L;
}
}
|
9237d0ab52885715fe27f92dcbbdb9faf09d58e1 | 3,682 | java | Java | src/main/java/com/example/webclientdemo/GithubClient.java | Shamture/spring-webclient-demo | 5c1146f37465ca423d96e37e0fa67ff42dcf8465 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/example/webclientdemo/GithubClient.java | Shamture/spring-webclient-demo | 5c1146f37465ca423d96e37e0fa67ff42dcf8465 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/example/webclientdemo/GithubClient.java | Shamture/spring-webclient-demo | 5c1146f37465ca423d96e37e0fa67ff42dcf8465 | [
"Apache-2.0"
] | null | null | null | 40.021739 | 107 | 0.655622 | 998,209 | package com.example.webclientdemo;
import com.example.webclientdemo.config.AppProperties;
import com.example.webclientdemo.payload.RepoRequest;
import com.example.webclientdemo.payload.GithubRepo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import org.springframework.web.reactive.function.client.ExchangeFilterFunctions;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/**
* Created by rajeevkumarsingh on 10/11/17.
*/
@Service
public class GithubClient {
private static final String GITHUB_V3_MIME_TYPE = "application/vnd.github.v3+json";
private static final String GITHUB_API_BASE_URL = "https://api.github.com";
private static final String USER_AGENT = "Spring 5 WebClient";
private static final Logger logger = LoggerFactory.getLogger(GithubClient.class);
private final WebClient webClient;
@Autowired
public GithubClient(AppProperties appProperties) {
this.webClient = WebClient.builder()
.baseUrl(GITHUB_API_BASE_URL)
.defaultHeader(HttpHeaders.CONTENT_TYPE, GITHUB_V3_MIME_TYPE)
.defaultHeader(HttpHeaders.USER_AGENT, USER_AGENT)
.filter(ExchangeFilterFunctions
.basicAuthentication(appProperties.getGithub().getUsername(),
appProperties.getGithub().getToken()))
.filter(logRequest())
.build();
}
public Flux<GithubRepo> listGithubRepositories() {
return webClient.get()
.uri("/user/repos?sort={sortField}&direction={sortDirection}",
"updated", "desc")
.exchange()
.flatMapMany(clientResponse -> clientResponse.bodyToFlux(GithubRepo.class));
}
public Mono<GithubRepo> createGithubRepository(RepoRequest createRepoRequest) {
return webClient.post()
.uri("/user/repos")
.body(Mono.just(createRepoRequest), RepoRequest.class)
.retrieve()
.bodyToMono(GithubRepo.class);
}
public Mono<GithubRepo> getGithubRepository(String owner, String repo) {
return webClient.get()
.uri("/repos/{owner}/{repo}", owner, repo)
.retrieve()
.bodyToMono(GithubRepo.class);
}
public Mono<GithubRepo> editGithubRepository(String owner, String repo, RepoRequest editRepoRequest) {
return webClient.patch()
.uri("/repos/{owner}/{repo}", owner, repo)
.body(BodyInserters.fromObject(editRepoRequest))
.retrieve()
.bodyToMono(GithubRepo.class);
}
public Mono<Void> deleteGithubRepository(String owner, String repo) {
return webClient.delete()
.uri("/repos/{owner}/{repo}", owner, repo)
.retrieve()
.bodyToMono(Void.class);
}
private ExchangeFilterFunction logRequest() {
return (clientRequest, next) -> {
logger.info("Request: {} {}", clientRequest.method(), clientRequest.url());
clientRequest.headers()
.forEach((name, values) -> values.forEach(value -> logger.info("{}={}", name, value)));
return next.exchange(clientRequest);
};
}
}
|
9237d0ee5b1eb58f2069f18f1170370f27f002ae | 2,112 | java | Java | classpath-0.98/gnu/java/awt/font/autofit/LatinAxis.java | nmldiegues/jvm-stm | d422d78ba8efc99409ecb49efdb4edf4884658df | [
"Apache-2.0"
] | 2 | 2015-09-08T15:40:04.000Z | 2017-02-09T15:19:33.000Z | classpath-0.98/gnu/java/awt/font/autofit/LatinAxis.java | nmldiegues/jvm-stm | d422d78ba8efc99409ecb49efdb4edf4884658df | [
"Apache-2.0"
] | null | null | null | classpath-0.98/gnu/java/awt/font/autofit/LatinAxis.java | nmldiegues/jvm-stm | d422d78ba8efc99409ecb49efdb4edf4884658df | [
"Apache-2.0"
] | null | null | null | 33.52381 | 75 | 0.774621 | 998,210 | /* LatinAxis.java -- Axis specific data
Copyright (C) 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath 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, or (at your option)
any later version.
GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.java.awt.font.autofit;
/**
* Some axis specific data.
*/
class LatinAxis
{
int scale;
int delta;
int widthCount;
Width[] widths;
int edgeDistanceTreshold;
LatinBlue[] blues;
int blueCount;
int orgDelta;
int orgScale;
LatinAxis()
{
widths = new Width[Latin.MAX_WIDTHS];
blues = new LatinBlue[Latin.BLUE_MAX];
}
}
|
9237d30d51717c5c84100c0b9631d71a403cdb4b | 12,306 | java | Java | src/chapter3/section2/Exercise6.java | bkarjoo/algorithms-sedgewick-wayne | abb0004384493aaa17a1eaa26ba1923dac638b1c | [
"MIT"
] | 1,781 | 2017-01-14T16:08:52.000Z | 2022-03-31T14:50:39.000Z | src/chapter3/section2/Exercise6.java | bkarjoo/algorithms-sedgewick-wayne | abb0004384493aaa17a1eaa26ba1923dac638b1c | [
"MIT"
] | 220 | 2017-12-17T18:28:13.000Z | 2022-03-28T12:30:05.000Z | src/chapter3/section2/Exercise6.java | bkarjoo/algorithms-sedgewick-wayne | abb0004384493aaa17a1eaa26ba1923dac638b1c | [
"MIT"
] | 641 | 2017-10-10T17:50:06.000Z | 2022-03-31T06:49:32.000Z | 28.031891 | 94 | 0.483341 | 998,211 | package chapter3.section2;
import edu.princeton.cs.algs4.Queue;
import edu.princeton.cs.algs4.StdOut;
import java.util.NoSuchElementException;
/**
* Created by Rene Argento on 09/05/17.
*/
public class Exercise6 {
private class BinarySearchTree<Key extends Comparable<Key>, Value>{
private class Node {
private Key key;
private Value value;
private Node left;
private Node right;
private int size; //# of nodes in subtree rooted here
private int height; //height of the subtree rooted here
public Node(Key key, Value value, int size) {
this.key = key;
this.value = value;
this.size = size;
}
}
private Node root;
public int size() {
return size(root);
}
private int size(Node node) {
if (node == null) {
return 0;
}
return node.size;
}
public int heightRecursive() {
if (root == null) {
return -1;
}
return heightRecursive(root, -1);
}
private int heightRecursive(Node node, int currentHeight) {
if (node == null) {
return currentHeight;
}
int height = currentHeight;
int leftHeight = heightRecursive(node.left, currentHeight + 1);
if (leftHeight > height) {
height = leftHeight;
}
int rightHeight = heightRecursive(node.right, currentHeight + 1);
if (rightHeight > height) {
height = rightHeight;
}
return height;
}
public int heightConstant() {
return heightConstant(root);
}
private int heightConstant(Node node) {
if (node == null) {
return -1;
}
return node.height;
}
public Value get(Key key) {
return get(root, key);
}
private Value get(Node node, Key key) {
if (node == null) {
return null;
}
int compare = key.compareTo(node.key);
if (compare < 0) {
return get(node.left, key);
} else if (compare > 0) {
return get(node.right, key);
} else {
return node.value;
}
}
public void put(Key key, Value value) {
root = put(root, key, value);
}
private Node put(Node node, Key key, Value value) {
if (node == null) {
return new Node(key, value, 1);
}
int compare = key.compareTo(node.key);
if (compare < 0) {
node.left = put(node.left, key, value);
} else if (compare > 0) {
node.right = put(node.right, key, value);
} else {
node.value = value;
}
node.size = size(node.left) + 1 + size(node.right);
node.height = Math.max(heightConstant(node.left), heightConstant(node.right)) + 1;
return node;
}
public Key min() {
if (root == null) {
throw new NoSuchElementException("Empty binary search tree");
}
return min(root).key;
}
private Node min(Node node) {
if (node.left == null) {
return node;
}
return min(node.left);
}
public Key max() {
if (root == null) {
throw new NoSuchElementException("Empty binary search tree");
}
return max(root).key;
}
private Node max(Node node) {
if (node.right == null) {
return node;
}
return max(node.right);
}
public Key floor(Key key) {
Node node = floor(root, key);
if (node == null) {
return null;
}
return node.key;
}
private Node floor(Node node, Key key) {
if (node == null) {
return null;
}
int compare = key.compareTo(node.key);
if (compare == 0) {
return node;
} else if (compare < 0) {
return floor(node.left, key);
} else {
Node rightNode = floor(node.right, key);
if (rightNode != null) {
return rightNode;
} else {
return node;
}
}
}
public Key ceiling(Key key) {
Node node = ceiling(root, key);
if (node == null) {
return null;
}
return node.key;
}
private Node ceiling(Node node, Key key) {
if (node == null) {
return null;
}
int compare = key.compareTo(node.key);
if (compare == 0) {
return node;
} else if (compare > 0) {
return ceiling(node.right, key);
} else {
Node leftNode = ceiling(node.left, key);
if (leftNode != null) {
return leftNode;
} else {
return node;
}
}
}
public Key select(int index) {
if (index >= size()) {
throw new IllegalArgumentException("Index is higher than tree size");
}
return select(root, index).key;
}
private Node select(Node node, int index) {
int leftSubtreeSize = size(node.left);
if (leftSubtreeSize == index) {
return node;
} else if (leftSubtreeSize > index) {
return select(node.left, index);
} else {
return select(node.right, index - leftSubtreeSize - 1);
}
}
public int rank(Key key) {
return rank(root, key);
}
private int rank(Node node, Key key) {
if (node == null) {
return 0;
}
//Returns the number of keys less than node.key in the subtree rooted at node
int compare = key.compareTo(node.key);
if (compare < 0) {
return rank(node.left, key);
} else if (compare > 0) {
return size(node.left) + 1 + rank(node.right, key);
} else {
return size(node.left);
}
}
public void deleteMin() {
root = deleteMin(root);
}
private Node deleteMin(Node node) {
if (node == null) {
return null;
}
if (node.left == null) {
return node.right;
}
node.left = deleteMin(node.left);
node.size = size(node.left) + 1 + size(node.right);
node.height = Math.max(heightConstant(node.left), heightConstant(node.right)) + 1;
return node;
}
public void deleteMax() {
root = deleteMax(root);
}
private Node deleteMax(Node node) {
if (node == null) {
return null;
}
if (node.right == null) {
return node.left;
}
node.right = deleteMax(node.right);
node.size = size(node.left) + 1 + size(node.right);
node.height = Math.max(heightConstant(node.left), heightConstant(node.right)) + 1;
return node;
}
public void delete(Key key) {
root = delete(root, key);
}
private Node delete(Node node, Key key) {
if (node == null) {
return null;
}
int compare = key.compareTo(node.key);
if (compare < 0) {
node.left = delete(node.left, key);
} else if (compare > 0) {
node.right = delete(node.right, key);
} else {
if (node.left == null) {
return node.right;
} else if (node.right == null) {
return node.left;
} else {
Node aux = node;
node = min(aux.right);
node.right = deleteMin(aux.right);
node.left = aux.left;
}
}
node.size = size(node.left) + 1 + size(node.right);
node.height = Math.max(heightConstant(node.left), heightConstant(node.right)) + 1;
return node;
}
public Iterable<Key> keys() {
return keys(min(), max());
}
public Iterable<Key> keys(Key low, Key high) {
Queue<Key> queue = new Queue<>();
keys(root, queue, low, high);
return queue;
}
private void keys(Node node, Queue<Key> queue, Key low, Key high) {
if (node == null) {
return;
}
int compareLow = low.compareTo(node.key);
int compareHigh = high.compareTo(node.key);
if (compareLow < 0) {
keys(node.left, queue, low, high);
}
if (compareLow <= 0 && compareHigh >= 0) {
queue.enqueue(node.key);
}
if (compareHigh > 0) {
keys(node.right, queue, low, high);
}
}
}
public static void main(String[] args) {
Exercise6 exercise6 = new Exercise6();
exercise6.testRecursiveHeightMethod();
exercise6.testNonRecursiveHeightMethod();
}
private void testRecursiveHeightMethod() {
BinarySearchTree<Integer, Integer> binarySearchTree = new BinarySearchTree<>();
StdOut.println("Recursive height method tests");
StdOut.println("Height 1: " + binarySearchTree.heightRecursive() + " Expected: -1");
binarySearchTree.put(0, 0);
binarySearchTree.put(1, 1);
binarySearchTree.put(2, 2);
binarySearchTree.put(3, 3);
StdOut.println("Height 2: " + binarySearchTree.heightRecursive() + " Expected: 3");
binarySearchTree.put(-1, -1);
binarySearchTree.put(-2, -2);
StdOut.println("Height 3: " + binarySearchTree.heightRecursive() + " Expected: 3");
binarySearchTree.put(-10, -10);
binarySearchTree.put(-7, -7);
StdOut.println("Height 4: " + binarySearchTree.heightRecursive() + " Expected: 4");
binarySearchTree.delete(-7);
StdOut.println("Height 5: " + binarySearchTree.heightRecursive() + " Expected: 3");
binarySearchTree.deleteMin();
binarySearchTree.deleteMax();
StdOut.println("Height 6: " + binarySearchTree.heightRecursive() + " Expected: 2");
}
private void testNonRecursiveHeightMethod() {
BinarySearchTree<Integer, Integer> binarySearchTree = new BinarySearchTree<>();
StdOut.println("\nAdded-field height method tests");
StdOut.println("Height 1: " + binarySearchTree.heightConstant() + " Expected: -1");
binarySearchTree.put(0, 0);
binarySearchTree.put(1, 1);
binarySearchTree.put(2, 2);
binarySearchTree.put(3, 3);
StdOut.println("Height 2: " + binarySearchTree.heightConstant() + " Expected: 3");
binarySearchTree.put(-1, -1);
binarySearchTree.put(-2, -2);
StdOut.println("Height 3: " + binarySearchTree.heightConstant() + " Expected: 3");
binarySearchTree.put(-10, -10);
binarySearchTree.put(-7, -7);
StdOut.println("Height 4: " + binarySearchTree.heightConstant() + " Expected: 4");
binarySearchTree.delete(-7);
StdOut.println("Height 5: " + binarySearchTree.heightConstant() + " Expected: 3");
binarySearchTree.deleteMin();
binarySearchTree.deleteMax();
StdOut.println("Height 6: " + binarySearchTree.heightConstant() + " Expected: 2");
}
}
|
9237d3ffff96f58d268dda394e1e55d9bee34a9d | 670 | java | Java | src/main/java/io/demo/credit/DigitalCreditApplication.java | keithpuzey/Digital-Credit | 0dd9c15ac67a778298ed7014dc9762f7653a1bb7 | [
"MIT"
] | null | null | null | src/main/java/io/demo/credit/DigitalCreditApplication.java | keithpuzey/Digital-Credit | 0dd9c15ac67a778298ed7014dc9762f7653a1bb7 | [
"MIT"
] | null | null | null | src/main/java/io/demo/credit/DigitalCreditApplication.java | keithpuzey/Digital-Credit | 0dd9c15ac67a778298ed7014dc9762f7653a1bb7 | [
"MIT"
] | 1 | 2020-03-06T19:45:17.000Z | 2020-03-06T19:45:17.000Z | 31.904762 | 85 | 0.850746 | 998,212 | package io.demo.credit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@SpringBootApplication
public class DigitalCreditApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(DigitalCreditApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(DigitalCreditApplication.class, args);
}
}
|
9237d42e99416b349349be4d352a5d5c86de182c | 6,820 | java | Java | x-pack/plugin/spatial/src/main/java/org/elasticsearch/xpack/spatial/search/aggregations/bucket/geogrid/AbstractGeoHashGridTiler.java | diwasjoshi/elasticsearch | 58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f | [
"Apache-2.0"
] | null | null | null | x-pack/plugin/spatial/src/main/java/org/elasticsearch/xpack/spatial/search/aggregations/bucket/geogrid/AbstractGeoHashGridTiler.java | diwasjoshi/elasticsearch | 58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f | [
"Apache-2.0"
] | null | null | null | x-pack/plugin/spatial/src/main/java/org/elasticsearch/xpack/spatial/search/aggregations/bucket/geogrid/AbstractGeoHashGridTiler.java | diwasjoshi/elasticsearch | 58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f | [
"Apache-2.0"
] | null | null | null | 44.285714 | 138 | 0.640029 | 998,213 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.spatial.search.aggregations.bucket.geogrid;
import org.elasticsearch.geometry.utils.Geohash;
import org.elasticsearch.xpack.spatial.index.fielddata.GeoRelation;
import org.elasticsearch.xpack.spatial.index.fielddata.GeoShapeValues;
import java.io.IOException;
/**
* Implements most of the logic for the GeoHash aggregation.
*/
abstract class AbstractGeoHashGridTiler extends GeoGridTiler {
AbstractGeoHashGridTiler(int precision) {
super(precision);
}
/** check if the provided hash is in the solution space of this tiler */
protected abstract boolean validHash(String hash);
@Override
public long encode(double x, double y) {
return Geohash.longEncode(x, y, precision);
}
@Override
public int setValues(GeoShapeCellValues values, GeoShapeValues.GeoShapeValue geoValue) throws IOException {
if (precision == 0) {
return 1;
}
GeoShapeValues.BoundingBox bounds = geoValue.boundingBox();
assert bounds.minX() <= bounds.maxX();
// When the shape represents a point, we compute the hash directly as we do it for GeoPoint
if (bounds.minX() == bounds.maxX() && bounds.minY() == bounds.maxY()) {
return setValue(values, geoValue, bounds);
}
// TODO: optimize for when a shape fits in a single tile an
// for when brute-force is expected to be faster than rasterization, which
// is when the number of tiles expected is less than the precision
return setValuesByRasterization("", values, 0, geoValue);
}
protected int setValuesByBruteForceScan(
GeoShapeCellValues values,
GeoShapeValues.GeoShapeValue geoValue,
GeoShapeValues.BoundingBox bounds
) throws IOException {
// TODO: This way to discover cells inside of a bounding box seems not to work as expected. I can
// see that eventually we will be visiting twice the same cell which should not happen.
int idx = 0;
String min = Geohash.stringEncode(bounds.minX(), bounds.minY(), precision);
String max = Geohash.stringEncode(bounds.maxX(), bounds.maxY(), precision);
String minNeighborBelow = Geohash.getNeighbor(min, precision, 0, -1);
double minY = Geohash.decodeLatitude((minNeighborBelow == null) ? min : minNeighborBelow);
double minX = Geohash.decodeLongitude(min);
double maxY = Geohash.decodeLatitude(max);
double maxX = Geohash.decodeLongitude(max);
for (double i = minX; i <= maxX; i += Geohash.lonWidthInDegrees(precision)) {
for (double j = minY; j <= maxY; j += Geohash.latHeightInDegrees(precision)) {
String hash = Geohash.stringEncode(i, j, precision);
GeoRelation relation = relateTile(geoValue, hash);
if (relation != GeoRelation.QUERY_DISJOINT) {
values.resizeCell(idx + 1);
values.add(idx++, encode(i, j));
}
}
}
return idx;
}
/**
* Sets a singular doc-value for the {@link GeoShapeValues.GeoShapeValue}.
*/
protected int setValue(GeoShapeCellValues docValues, GeoShapeValues.GeoShapeValue geoValue, GeoShapeValues.BoundingBox bounds)
throws IOException {
String hash = Geohash.stringEncode(bounds.minX(), bounds.minY(), precision);
if (relateTile(geoValue, hash) != GeoRelation.QUERY_DISJOINT) {
docValues.resizeCell(1);
docValues.add(0, Geohash.longEncode(hash));
return 1;
}
return 0;
}
private GeoRelation relateTile(GeoShapeValues.GeoShapeValue geoValue, String hash) throws IOException {
return validHash(hash) ? geoValue.relate(Geohash.toBoundingBox(hash)) : GeoRelation.QUERY_DISJOINT;
}
protected int setValuesByRasterization(String hash, GeoShapeCellValues values, int valuesIndex, GeoShapeValues.GeoShapeValue geoValue)
throws IOException {
String[] hashes = Geohash.getSubGeohashes(hash);
for (int i = 0; i < hashes.length; i++) {
GeoRelation relation = relateTile(geoValue, hashes[i]);
if (relation == GeoRelation.QUERY_CROSSES) {
if (hashes[i].length() == precision) {
values.resizeCell(valuesIndex + 1);
values.add(valuesIndex++, Geohash.longEncode(hashes[i]));
} else {
valuesIndex = setValuesByRasterization(hashes[i], values, valuesIndex, geoValue);
}
} else if (relation == GeoRelation.QUERY_INSIDE) {
if (hashes[i].length() == precision) {
values.resizeCell(valuesIndex + 1);
values.add(valuesIndex++, Geohash.longEncode(hashes[i]));
} else {
int numTilesAtPrecision = getNumTilesAtPrecision(precision, hash.length());
values.resizeCell(getNewSize(valuesIndex, numTilesAtPrecision + 1));
valuesIndex = setValuesForFullyContainedTile(hashes[i], values, valuesIndex, precision);
}
}
}
return valuesIndex;
}
private int getNewSize(int valuesIndex, int increment) {
long newSize = (long) valuesIndex + increment;
if (newSize > Integer.MAX_VALUE) {
throw new IllegalArgumentException("Tile aggregation array overflow");
}
return (int) newSize;
}
private int getNumTilesAtPrecision(int finalPrecision, int currentPrecision) {
final long numTilesAtPrecision = Math.min((long) Math.pow(32, finalPrecision - currentPrecision) + 1, getMaxCells());
if (numTilesAtPrecision > Integer.MAX_VALUE) {
throw new IllegalArgumentException("Tile aggregation array overflow");
}
return (int) numTilesAtPrecision;
}
protected int setValuesForFullyContainedTile(String hash, GeoShapeCellValues values, int valuesIndex, int targetPrecision) {
String[] hashes = Geohash.getSubGeohashes(hash);
for (int i = 0; i < hashes.length; i++) {
if (validHash(hashes[i])) {
if (hashes[i].length() == targetPrecision) {
values.add(valuesIndex++, Geohash.longEncode(hashes[i]));
} else {
valuesIndex = setValuesForFullyContainedTile(hashes[i], values, valuesIndex, targetPrecision);
}
}
}
return valuesIndex;
}
}
|
9237d5140a9eb707e31e9a8e99855565153d022f | 333 | java | Java | org/apache/fop/fo/ValidationException.java | JaneMandy/CS | 4a95148cbeb3804b9c50da003d1a7cb12254cb58 | [
"Apache-2.0"
] | 1 | 2022-02-24T01:32:41.000Z | 2022-02-24T01:32:41.000Z | org/apache/fop/fo/ValidationException.java | JaneMandy/CS | 4a95148cbeb3804b9c50da003d1a7cb12254cb58 | [
"Apache-2.0"
] | null | null | null | org/apache/fop/fo/ValidationException.java | JaneMandy/CS | 4a95148cbeb3804b9c50da003d1a7cb12254cb58 | [
"Apache-2.0"
] | null | null | null | 22.2 | 64 | 0.741742 | 998,214 | package org.apache.fop.fo;
import org.apache.fop.apps.FOPException;
import org.xml.sax.Locator;
public class ValidationException extends FOPException {
public ValidationException(String message) {
super(message);
}
public ValidationException(String message, Locator locator) {
super(message, locator);
}
}
|
9237d574d4eaf72672afa764849ad732f09a5651 | 393 | java | Java | yxhshop-user-api/src/main/java/com/rkele/yxhshop/user/fallback/DictionaryApiFallback.java | keybersan/yxhshop | d03eda8dd588a9c186da84074eb160e0d86d9ce0 | [
"MIT"
] | 2 | 2020-05-16T05:57:25.000Z | 2020-06-18T12:56:25.000Z | yxhshop-user-api/src/main/java/com/rkele/yxhshop/user/fallback/DictionaryApiFallback.java | keybersan/yxhshop | d03eda8dd588a9c186da84074eb160e0d86d9ce0 | [
"MIT"
] | null | null | null | yxhshop-user-api/src/main/java/com/rkele/yxhshop/user/fallback/DictionaryApiFallback.java | keybersan/yxhshop | d03eda8dd588a9c186da84074eb160e0d86d9ce0 | [
"MIT"
] | 1 | 2021-03-30T02:34:42.000Z | 2021-03-30T02:34:42.000Z | 28.071429 | 94 | 0.811705 | 998,215 | package com.rkele.yxhshop.user.fallback;
import com.rkele.yxhshop.user.api.DictionaryApi;
import com.rkele.yxhshop.user.po.Dictionary;
import org.springframework.stereotype.Component;
import com.rkele.yxhshop.common.fallback.ApiFallback;
/**
* Created by keybersan on 2020/2/9.
*/
@Component
public class DictionaryApiFallback extends ApiFallback<Dictionary> implements DictionaryApi {
}
|
9237d69b7d8cb82d000d2df23c5e5ed895ca7cbd | 701 | java | Java | Atlas/core/src/main/java/net/avicus/atlas/module/gadget/map/MapTokenModule.java | jasoryeh/AvicusNetwork | a552beff1fc9c9b87477fae84cb52b8d79c10121 | [
"MIT"
] | 1 | 2019-07-09T13:00:38.000Z | 2019-07-09T13:00:38.000Z | Atlas/core/src/main/java/net/avicus/atlas/module/gadget/map/MapTokenModule.java | jasoryeh/AvicusNetwork | a552beff1fc9c9b87477fae84cb52b8d79c10121 | [
"MIT"
] | null | null | null | Atlas/core/src/main/java/net/avicus/atlas/module/gadget/map/MapTokenModule.java | jasoryeh/AvicusNetwork | a552beff1fc9c9b87477fae84cb52b8d79c10121 | [
"MIT"
] | 1 | 2020-01-18T16:50:21.000Z | 2020-01-18T16:50:21.000Z | 26.961538 | 61 | 0.741797 | 998,216 | package net.avicus.atlas.module.gadget.map;
import net.avicus.atlas.event.match.MatchCompleteEvent;
import net.avicus.atlas.module.Module;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.AsyncPlayerChatEvent;
public class MapTokenModule implements Module {
private MapTokenManager mapTokenManager;
public MapTokenModule() {
// Initialize Map tokens
this.mapTokenManager = MapTokenManager.getInstance();
}
@EventHandler
public void chatIn(AsyncPlayerChatEvent e) {
this.mapTokenManager.chatIn(e);
}
@EventHandler
public void matchComplete(MatchCompleteEvent e) {
this.mapTokenManager.onMatchComplete(e);
}
}
|
9237d899ab031a44a12228390f6849f1800ce56c | 3,452 | java | Java | src/main/java/org/springframework/data/redis/core/TimeoutUtils.java | upthewaterspout/spring-data-redis | a944aa2d1bd3551cf2146cdf4e03ed10c1f112a3 | [
"Apache-2.0"
] | 1,455 | 2015-01-01T05:14:04.000Z | 2022-03-30T07:10:42.000Z | src/main/java/org/springframework/data/redis/core/TimeoutUtils.java | upthewaterspout/spring-data-redis | a944aa2d1bd3551cf2146cdf4e03ed10c1f112a3 | [
"Apache-2.0"
] | 642 | 2015-01-19T13:47:02.000Z | 2022-03-31T09:18:11.000Z | src/main/java/org/springframework/data/redis/core/TimeoutUtils.java | upthewaterspout/spring-data-redis | a944aa2d1bd3551cf2146cdf4e03ed10c1f112a3 | [
"Apache-2.0"
] | 1,070 | 2015-01-05T14:05:10.000Z | 2022-03-31T09:21:27.000Z | 30.821429 | 116 | 0.719003 | 998,217 | /*
* Copyright 2013-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.redis.core;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
/**
* Helper class featuring methods for calculating Redis timeouts
*
* @author Jennifer Hickey
* @author Mark Paluch
* @author Christoph Strobl
*/
public abstract class TimeoutUtils {
/**
* Check if a given Duration can be represented in {@code sec} or requires {@code msec} representation.
*
* @param duration the actual {@link Duration} to inspect. Never {@literal null}.
* @return {@literal true} if the {@link Duration} contains millisecond information.
* @since 2.1
*/
public static boolean hasMillis(Duration duration) {
return duration.toMillis() % 1000 != 0;
}
/**
* Converts the given timeout to seconds.
* <p>
* Since a 0 timeout blocks some Redis ops indefinitely, this method will return 1 if the original value is greater
* than 0 but is truncated to 0 on conversion.
*
* @param duration The duration to convert
* @return The converted timeout
* @since 2.3
*/
public static long toSeconds(Duration duration) {
return roundUpIfNecessary(duration.toMillis(), duration.getSeconds());
}
/**
* Converts the given timeout to seconds.
* <p>
* Since a 0 timeout blocks some Redis ops indefinitely, this method will return 1 if the original value is greater
* than 0 but is truncated to 0 on conversion.
*
* @param timeout The timeout to convert
* @param unit The timeout's unit
* @return The converted timeout
*/
public static long toSeconds(long timeout, TimeUnit unit) {
return roundUpIfNecessary(timeout, unit.toSeconds(timeout));
}
/**
* Converts the given timeout to seconds with a fraction of seconds.
*
* @param timeout The timeout to convert
* @param unit The timeout's unit
* @return The converted timeout
* @since 2.6
*/
public static double toDoubleSeconds(long timeout, TimeUnit unit) {
switch (unit) {
case MILLISECONDS:
case MICROSECONDS:
case NANOSECONDS:
return unit.toMillis(timeout) / 1000d;
default:
return unit.toSeconds(timeout);
}
}
/**
* Converts the given timeout to milliseconds.
* <p>
* Since a 0 timeout blocks some Redis ops indefinitely, this method will return 1 if the original value is greater
* than 0 but is truncated to 0 on conversion.
*
* @param timeout The timeout to convert
* @param unit The timeout's unit
* @return The converted timeout
*/
public static long toMillis(long timeout, TimeUnit unit) {
return roundUpIfNecessary(timeout, unit.toMillis(timeout));
}
private static long roundUpIfNecessary(long timeout, long convertedTimeout) {
// A 0 timeout blocks some Redis ops indefinitely, round up if that's
// not the intention
if (timeout > 0 && convertedTimeout == 0) {
return 1;
}
return convertedTimeout;
}
}
|
9237da2aa6368177b8eba0c33b4cc43f2398cf13 | 382 | java | Java | config-client/src/main/java/javamentor/examples/springcloudconfigclient/SpringcloudconfigClientApplication.java | SZD-48/javamentor-spring-cloud | 72cfdee891ddbed4267fe03936dae3d65666201b | [
"BSD-2-Clause"
] | null | null | null | config-client/src/main/java/javamentor/examples/springcloudconfigclient/SpringcloudconfigClientApplication.java | SZD-48/javamentor-spring-cloud | 72cfdee891ddbed4267fe03936dae3d65666201b | [
"BSD-2-Clause"
] | null | null | null | config-client/src/main/java/javamentor/examples/springcloudconfigclient/SpringcloudconfigClientApplication.java | SZD-48/javamentor-spring-cloud | 72cfdee891ddbed4267fe03936dae3d65666201b | [
"BSD-2-Clause"
] | null | null | null | 27.285714 | 78 | 0.82199 | 998,218 | package javamentor.examples.springcloudconfigclient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringcloudconfigClientApplication {
public static void main(String[] args) {
SpringApplication.run(SpringcloudconfigClientApplication.class, args);
}
}
|
9237da96982d334efde0707347f717695b40f0b7 | 3,031 | java | Java | xdlx-core/src/main/java/com/rainerschuster/dlx/MinMaxDancingLinks.java | rainerschuster/xdlx | 9ea237c8dc3c20154249fbfb09955f3242d86301 | [
"Apache-2.0"
] | null | null | null | xdlx-core/src/main/java/com/rainerschuster/dlx/MinMaxDancingLinks.java | rainerschuster/xdlx | 9ea237c8dc3c20154249fbfb09955f3242d86301 | [
"Apache-2.0"
] | null | null | null | xdlx-core/src/main/java/com/rainerschuster/dlx/MinMaxDancingLinks.java | rainerschuster/xdlx | 9ea237c8dc3c20154249fbfb09955f3242d86301 | [
"Apache-2.0"
] | null | null | null | 30.616162 | 92 | 0.558232 | 998,219 | /*
* Copyright 2015 Rainer Schuster
*
* 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.rainerschuster.dlx;
import java.math.BigInteger;
/**
* Generalized version of {@link DancingLinks} with "minimum" and "maximum" constraints.
*/
public class MinMaxDancingLinks<C, V extends Value<C>> extends DancingLinks<C, V> {
public MinMaxDancingLinks(DancingLinksData<C, V> dlData) {
super(dlData);
}
// @Override
public void cover(final MaxColumn<C, V> c) {
// TODO updates k
// super.cover(c);
final Node<C, V> currentNode = c.getHead().getDown();
c.getChoice().add(currentNode);
if (c.getChoice().size() >= c.getMax()) {
super.cover(c);
} else {
// block this row only
blockRow(currentNode, BigInteger.ZERO);
}
}
// @Override
public void uncover(final MaxColumn<C, V> c) {
// super.uncover(c);
final Node<C, V> currentNode = c.getHead().getDown();
if (c.getChoice().size() >= c.getMax()) {
// TODO all except those in choice!
// super.uncover(c);
for (Node<C, V> rr = c.getHead().getUp(); rr != c.getHead(); rr = rr.getUp()) {
if (rr == currentNode || !c.getChoice().contains(rr)) {
unblockRow(rr);
}
}
// unblockColumn(c);
} else {
unblockRow(currentNode);
}
c.getChoice().remove(currentNode);
}
// @Override
public void cover(final MinColumn<C, V> c) {
// TODO updates k
// super.cover(c);
final Node<C, V> currentNode = c.getHead().getDown();
c.getChoice().add(currentNode);
if (c.getChoice().size() >= c.getMin()) {
blockColumn(c);
}
// block this row only
blockRow(currentNode, BigInteger.ZERO);
}
// @Override
public void uncover(final MinColumn<C, V> c) {
// super.uncover(c);
final Node<C, V> currentNode = c.getHead().getDown();
unblockRow(currentNode);
c.getChoice().remove(currentNode);
if (c.getChoice().size() < c.getMin()) {
unblockColumn(c);
}
}
// @Override
// public void cover(final Column<C, V> c) {
// super.cover(c);
// }
//
// @Override
// public void uncover(final Column<C, V> c) {
// super.uncover(c);
// }
}
|
9237da97c91a6d99d96d4ab20bdb7f33a941f7bd | 1,681 | java | Java | src/main/java/com/eternity/common/message/Message.java | sonjayatandon/eternity-common | c2947b2ad2b7333252370ea3684046d6a7ab03ba | [
"MIT"
] | null | null | null | src/main/java/com/eternity/common/message/Message.java | sonjayatandon/eternity-common | c2947b2ad2b7333252370ea3684046d6a7ab03ba | [
"MIT"
] | null | null | null | src/main/java/com/eternity/common/message/Message.java | sonjayatandon/eternity-common | c2947b2ad2b7333252370ea3684046d6a7ab03ba | [
"MIT"
] | null | null | null | 33.62 | 107 | 0.754313 | 998,220 | package com.eternity.common.message;
/*
The MIT License (MIT)
Copyright (c) 2011 Sonjaya Tandon
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 java.util.Map;
/**
*
* This class represents a JSON message of the format:
*
* {"commandName":"activateUser", "paramMap": { "param1":"param1 value", "param2":"param2 value", ... } }
*
*/
public class Message {
public MessageNames commandName;
public Map<ParameterNames, String> paramMap;
// if there is a post request, we store the posted data here
public String jsonData;
@Override
public String toString() {
return "Message [commandName=" + commandName + ", paramMap=" + paramMap + ", jsonData=" + jsonData + "]";
}
}
|
9237daa9702f34ed32852906287f6af0c71b2da5 | 2,741 | java | Java | tl/src/main/java/com/github/badoualy/telegram/tl/api/request/TLRequestInvokeAfterMsgs.java | FullStackD3vs/kotlogram | e3c26c69c2896b6bf3fce539ba0c46debc884e0f | [
"MIT"
] | 240 | 2016-01-04T11:23:29.000Z | 2022-03-04T20:22:30.000Z | tl/src/main/java/com/github/badoualy/telegram/tl/api/request/TLRequestInvokeAfterMsgs.java | FullStackD3vs/kotlogram | e3c26c69c2896b6bf3fce539ba0c46debc884e0f | [
"MIT"
] | 57 | 2016-01-28T10:57:25.000Z | 2021-03-02T21:32:57.000Z | tl/src/main/java/com/github/badoualy/telegram/tl/api/request/TLRequestInvokeAfterMsgs.java | FullStackD3vs/kotlogram | e3c26c69c2896b6bf3fce539ba0c46debc884e0f | [
"MIT"
] | 103 | 2016-01-29T20:20:17.000Z | 2022-03-28T18:48:51.000Z | 29.526882 | 95 | 0.719592 | 998,221 | package com.github.badoualy.telegram.tl.api.request;
import com.github.badoualy.telegram.tl.TLContext;
import com.github.badoualy.telegram.tl.core.TLLongVector;
import com.github.badoualy.telegram.tl.core.TLMethod;
import com.github.badoualy.telegram.tl.core.TLObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import static com.github.badoualy.telegram.tl.StreamUtils.readTLLongVector;
import static com.github.badoualy.telegram.tl.StreamUtils.readTLMethod;
import static com.github.badoualy.telegram.tl.StreamUtils.writeTLMethod;
import static com.github.badoualy.telegram.tl.StreamUtils.writeTLVector;
import static com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_CONSTRUCTOR_ID;
/**
* @author Yannick Badoual kenaa@example.com
* @see <a href="http://github.com/badoualy/kotlogram">http://github.com/badoualy/kotlogram</a>
*/
public class TLRequestInvokeAfterMsgs<T extends TLObject> extends TLMethod<T> {
public static final int CONSTRUCTOR_ID = 0x3dc4b4f0;
protected TLLongVector msgIds;
protected TLMethod<T> query;
private final String _constructor = "invokeAfterMsgs#3dc4b4f0";
public TLRequestInvokeAfterMsgs() {
}
public TLRequestInvokeAfterMsgs(TLLongVector msgIds, TLMethod<T> query) {
this.msgIds = msgIds;
this.query = query;
}
@Override
@SuppressWarnings({"unchecked", "SimplifiableConditionalExpression"})
public T deserializeResponse(InputStream stream, TLContext context) throws IOException {
return query.deserializeResponse(stream, context);
}
@Override
public void serializeBody(OutputStream stream) throws IOException {
writeTLVector(msgIds, stream);
writeTLMethod(query, stream);
}
@Override
@SuppressWarnings({"unchecked", "SimplifiableConditionalExpression"})
public void deserializeBody(InputStream stream, TLContext context) throws IOException {
msgIds = readTLLongVector(stream, context);
query = readTLMethod(stream, context);
}
@Override
public int computeSerializedSize() {
int size = SIZE_CONSTRUCTOR_ID;
size += msgIds.computeSerializedSize();
size += query.computeSerializedSize();
return size;
}
@Override
public String toString() {
return _constructor;
}
@Override
public int getConstructorId() {
return CONSTRUCTOR_ID;
}
public TLLongVector getMsgIds() {
return msgIds;
}
public void setMsgIds(TLLongVector msgIds) {
this.msgIds = msgIds;
}
public TLMethod<T> getQuery() {
return query;
}
public void setQuery(TLMethod<T> query) {
this.query = query;
}
}
|
9237db5059344d2c404fc6759d53d953b94980c5 | 1,208 | java | Java | modules/math/src/main/java/com/opengamma/strata/math/impl/function/special/HermitePolynomialFunction.java | LALAYANG/Strata | 7a3f9613913b383446d862c4606b5fbf59aaa213 | [
"Apache-2.0"
] | 696 | 2015-07-15T12:09:50.000Z | 2022-03-27T15:05:05.000Z | modules/math/src/main/java/com/opengamma/strata/math/impl/function/special/HermitePolynomialFunction.java | LALAYANG/Strata | 7a3f9613913b383446d862c4606b5fbf59aaa213 | [
"Apache-2.0"
] | 562 | 2015-07-17T11:31:08.000Z | 2022-03-29T16:15:39.000Z | modules/math/src/main/java/com/opengamma/strata/math/impl/function/special/HermitePolynomialFunction.java | LALAYANG/Strata | 7a3f9613913b383446d862c4606b5fbf59aaa213 | [
"Apache-2.0"
] | 315 | 2015-07-18T20:53:45.000Z | 2022-03-06T02:04:13.000Z | 27.454545 | 93 | 0.660596 | 998,222 | /*
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.strata.math.impl.function.special;
import com.opengamma.strata.collect.ArgChecker;
import com.opengamma.strata.collect.tuple.Pair;
import com.opengamma.strata.math.impl.function.DoubleFunction1D;
/**
*
*/
public class HermitePolynomialFunction extends OrthogonalPolynomialFunctionGenerator {
private static final DoubleFunction1D TWO_X = x -> 2 * x;
@Override
public DoubleFunction1D[] getPolynomials(int n) {
ArgChecker.isTrue(n >= 0);
DoubleFunction1D[] polynomials = new DoubleFunction1D[n + 1];
for (int i = 0; i <= n; i++) {
if (i == 0) {
polynomials[i] = getOne();
} else if (i == 1) {
polynomials[i] = TWO_X;
} else {
polynomials[i] = polynomials[i - 1]
.multiply(2)
.multiply(getX())
.subtract(polynomials[i - 2].multiply(2 * i - 2));
}
}
return polynomials;
}
@Override
public Pair<DoubleFunction1D, DoubleFunction1D>[] getPolynomialsAndFirstDerivative(int n) {
throw new UnsupportedOperationException();
}
}
|
9237dba5f4a7534b6d2ce0c8494c41737a2dd90c | 993 | java | Java | Dataset/Leetcode/test/102/193.java | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/test/102/193.java | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/test/102/193.java | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | 22.568182 | 57 | 0.398792 | 998,223 | class Solution {
public List<List<Integer>> XXX(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if(root == null) {
return result;
}
LinkedList<TreeNode> record = new LinkedList<>();
record.add(root);
record.add(null);
List<Integer> temp = new ArrayList<>();
while(true) {
TreeNode node = record.removeFirst();
if(node != null) {
temp.add(node.val);
if(node.left != null) {
record.add(node.left);
}
if(node.right != null) {
record.add(node.right);
}
} else {
result.add(temp);
temp = new ArrayList<>();
if(record.size() == 0) {
break;
}
record.add(null);
}
}
return result;
}
}
|
9237dbd5aaf9778402b5de65dbabeb8995bb1a31 | 373 | java | Java | framework/Music.java | milam/AndroidFramework | 55a1291ef6ecde83768d7e977bb5f8e2df8a7ad8 | [
"Unlicense"
] | 1 | 2016-11-10T18:32:08.000Z | 2016-11-10T18:32:08.000Z | framework/Music.java | milam/AndroidFramework | 55a1291ef6ecde83768d7e977bb5f8e2df8a7ad8 | [
"Unlicense"
] | null | null | null | framework/Music.java | milam/AndroidFramework | 55a1291ef6ecde83768d7e977bb5f8e2df8a7ad8 | [
"Unlicense"
] | null | null | null | 15.541667 | 44 | 0.670241 | 998,224 | package com.mdobbins.framework;
public interface Music {
public void play();
public void stop();
public void pause();
public void setLooping(boolean looping);
public void setVolume(float volume);
public boolean isPlaying();
public boolean isStopped();
public boolean isLooping();
public void dispose();
void seekBegin();
}
|
9237dd06980761b619bbe809b6870c55c125d7e5 | 3,236 | java | Java | order-impl/src/main/java/com/knoldus/lagom/sample/restaurant/order/impl/OrderEventProcessor.java | knoldus/lagom-on-k8s | 343263cc2e9df056b22a30d9334bef218d27fb91 | [
"Apache-2.0"
] | 5 | 2018-10-22T07:38:53.000Z | 2020-05-30T19:13:58.000Z | order-impl/src/main/java/com/knoldus/lagom/sample/restaurant/order/impl/OrderEventProcessor.java | knoldus/lagom-on-k8s | 343263cc2e9df056b22a30d9334bef218d27fb91 | [
"Apache-2.0"
] | null | null | null | order-impl/src/main/java/com/knoldus/lagom/sample/restaurant/order/impl/OrderEventProcessor.java | knoldus/lagom-on-k8s | 343263cc2e9df056b22a30d9334bef218d27fb91 | [
"Apache-2.0"
] | null | null | null | 39.463415 | 99 | 0.694685 | 998,225 | package com.knoldus.lagom.sample.restaurant.order.impl;
import akka.Done;
import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.PreparedStatement;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.inject.Inject;
import com.lightbend.lagom.javadsl.persistence.AggregateEventTag;
import com.lightbend.lagom.javadsl.persistence.ReadSideProcessor;
import com.lightbend.lagom.javadsl.persistence.cassandra.CassandraReadSide;
import com.lightbend.lagom.javadsl.persistence.cassandra.CassandraSession;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.pcollections.PSequence;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.stream.Collectors;
final class OrderEventProcessor extends ReadSideProcessor<OrderEvent> {
private static final Logger LOGGER = Logger.getLogger(OrderEventProcessor.class);
private final CassandraSession cassandraSession;
private final CassandraReadSide cassandraReadSide;
private final ObjectMapper objectMapper;
private PreparedStatement insertOrder;
@Inject
private OrderEventProcessor(final CassandraSession cassandraSession,
final CassandraReadSide cassandraReadSide,
final ObjectMapper objectMapper) {
this.cassandraSession = cassandraSession;
this.cassandraReadSide = cassandraReadSide;
this.objectMapper = objectMapper;
}
@Override
public ReadSideHandler<OrderEvent> buildHandler() {
return cassandraReadSide.<OrderEvent>builder("order_offset")
.setGlobalPrepare(this::createTable)
.setPrepare(tag -> prepareInsertItem())
.setEventHandler(OrderEvent.OrderPlaced.class, evt -> insertOrder(evt))
.build();
}
@Override
public PSequence<AggregateEventTag<OrderEvent>> aggregateTags() {
return OrderEvent.TAG.allTags();
}
private CompletionStage<Done> createTable() {
return cassandraSession.executeCreateTable(
"CREATE TABLE IF NOT EXISTS orders ("
+ "id text PRIMARY KEY,"
+ "items text"
+ ")");
}
private CompletionStage<Done> prepareInsertItem() {
return cassandraSession.prepare("INSERT INTO orders (id, items) VALUES (?, ?)")
.thenApply(preparedStatement -> {
insertOrder = preparedStatement;
return Done.getInstance();
});
}
private CompletionStage<List<BoundStatement>> insertOrder(OrderEvent.OrderPlaced orderPlaced) {
try {
return CassandraReadSide.completedStatement(insertOrder.bind(orderPlaced.getId(),
objectMapper.writeValueAsString(orderPlaced.getItems())));
} catch (Exception ex) {
LOGGER.error("Caught exception while placing order: " + orderPlaced.getId(), ex);
return CompletableFuture.completedFuture(Collections.emptyList());
}
}
}
|
9237dddf07a824f0907e53cc24dc6f2b24fc003c | 72 | java | Java | 1.JavaSyntax/src/com/javarush/task/pro/task17/task1706/Animal.java | ivaninkv/JavaRushTasks | 95053dea5d938a564e8c9b9824f41f6ebb58eed4 | [
"MIT"
] | null | null | null | 1.JavaSyntax/src/com/javarush/task/pro/task17/task1706/Animal.java | ivaninkv/JavaRushTasks | 95053dea5d938a564e8c9b9824f41f6ebb58eed4 | [
"MIT"
] | null | null | null | 1.JavaSyntax/src/com/javarush/task/pro/task17/task1706/Animal.java | ivaninkv/JavaRushTasks | 95053dea5d938a564e8c9b9824f41f6ebb58eed4 | [
"MIT"
] | null | null | null | 14.4 | 46 | 0.777778 | 998,226 | package com.javarush.task.pro.task17.task1706;
public class Animal {
}
|
9237dde382e6297e32a26c901eb8a5f7f0e71778 | 5,847 | java | Java | hyracks-fullstack/hyracks/hyracks-maven-plugins/license-automation-plugin/src/main/java/org/apache/hyracks/maven/license/freemarker/IndentDirective.java | simon-dew/asterixdb | 81c3249322957be261cd99bf7d6b464fcb4a3bbd | [
"Apache-2.0"
] | 200 | 2016-06-16T01:01:42.000Z | 2022-03-24T08:16:13.000Z | hyracks-fullstack/hyracks/hyracks-maven-plugins/license-automation-plugin/src/main/java/org/apache/hyracks/maven/license/freemarker/IndentDirective.java | simon-dew/asterixdb | 81c3249322957be261cd99bf7d6b464fcb4a3bbd | [
"Apache-2.0"
] | 3 | 2018-01-29T21:39:26.000Z | 2021-06-17T20:11:31.000Z | hyracks-fullstack/hyracks/hyracks-maven-plugins/license-automation-plugin/src/main/java/org/apache/hyracks/maven/license/freemarker/IndentDirective.java | prestoncarman/incubator-asterixdb | 013b4a431774b3b97275ad308dd3100dd1ab480e | [
"Apache-2.0"
] | 112 | 2016-06-12T21:51:05.000Z | 2022-02-05T17:16:33.000Z | 37.242038 | 115 | 0.626988 | 998,227 | /*
* 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.hyracks.maven.license.freemarker;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Arrays;
import java.util.Map;
import org.apache.commons.io.IOUtils;
import org.apache.hyracks.maven.license.LicenseUtil;
import freemarker.core.Environment;
import freemarker.template.TemplateBooleanModel;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateNumberModel;
public class IndentDirective implements TemplateDirectiveModel {
private static final String PARAM_NAME_SPACES = "spaces";
private static final String PARAM_NAME_UNPAD = "unpad";
private static final String PARAM_NAME_WRAP = "wrap";
private static final String PARAM_NAME_STRICT = "strict";
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
throws TemplateException, IOException {
int numSpaces = -1;
boolean unpad = false;
boolean wrap = false;
boolean strict = false;
for (Object o : params.entrySet()) {
Map.Entry ent = (Map.Entry) o;
String paramName = (String) ent.getKey();
TemplateModel paramValue = (TemplateModel) ent.getValue();
switch (paramName) {
case PARAM_NAME_SPACES:
numSpaces = getIntParam(paramName, paramValue);
break;
case PARAM_NAME_UNPAD:
unpad = getBooleanParam(paramName, paramValue);
break;
case PARAM_NAME_WRAP:
wrap = getBooleanParam(paramName, paramValue);
break;
case PARAM_NAME_STRICT:
strict = getBooleanParam(paramName, paramValue);
break;
default:
throw new TemplateModelException("Unsupported parameter: " + paramName);
}
}
if (numSpaces < 0) {
throw new TemplateModelException("The required \"" + PARAM_NAME_SPACES + "\" parameter is missing.");
}
if (body == null) {
throw new TemplateModelException("Indent requires a body");
} else {
// Executes the nested body (same as <#nested> in FTL). In this
// case we don't provide a special writer as the parameter:
StringWriter sw = new StringWriter();
body.render(sw);
String fixedup = LicenseUtil.process(sw.toString(), unpad, wrap, strict);
IOUtils.copy(new StringReader(fixedup), new IndentingWriter(env.getOut(), numSpaces));
}
}
private int getIntParam(String paramName, TemplateModel paramValue) throws TemplateModelException {
int spacesParam;
if (!(paramValue instanceof TemplateNumberModel)) {
throw paramException(paramName, "must be a number");
}
spacesParam = ((TemplateNumberModel) paramValue).getAsNumber().intValue();
if (spacesParam < 0) {
throw paramException(paramName, "can't be negative");
}
return spacesParam;
}
private boolean getBooleanParam(String paramName, TemplateModel paramValue) throws TemplateModelException {
if (!(paramValue instanceof TemplateBooleanModel)) {
throw paramException(paramName, "must be a boolean");
}
return ((TemplateBooleanModel) paramValue).getAsBoolean();
}
private TemplateModelException paramException(String paramName, String message) throws TemplateModelException {
return new TemplateModelException("The '" + paramName + "' parameter " + message);
}
private static class IndentingWriter extends Writer {
private final Writer out;
private final char[] padChars;
boolean needsToPad;
public IndentingWriter(Writer out, int numSpaces) {
this.out = out;
padChars = new char[numSpaces];
Arrays.fill(padChars, ' ');
needsToPad = true;
}
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
for (int i = off; i < len; i++) {
if (cbuf[i] == '\n') {
out.write(cbuf[i]);
needsToPad = true;
} else {
if (needsToPad) {
out.write(padChars);
needsToPad = false;
}
out.write(cbuf[i]);
}
}
}
@Override
public void flush() throws IOException {
out.flush();
}
@Override
public void close() throws IOException {
out.flush();
}
}
}
|
9237debf7e88552087f991d3d49a8f81f55dc00e | 235 | java | Java | src/test/java/com/ratz/springsecuritybasics/SpringSecurityBasicsApplicationTests.java | ratzPereira/spring-security-basics | 45ae1a449ee99485c59da99ea228135e92795313 | [
"MIT"
] | null | null | null | src/test/java/com/ratz/springsecuritybasics/SpringSecurityBasicsApplicationTests.java | ratzPereira/spring-security-basics | 45ae1a449ee99485c59da99ea228135e92795313 | [
"MIT"
] | null | null | null | src/test/java/com/ratz/springsecuritybasics/SpringSecurityBasicsApplicationTests.java | ratzPereira/spring-security-basics | 45ae1a449ee99485c59da99ea228135e92795313 | [
"MIT"
] | null | null | null | 16.785714 | 60 | 0.808511 | 998,228 | package com.ratz.springsecuritybasics;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SpringSecurityBasicsApplicationTests {
@Test
void contextLoads() {
}
}
|
9237dfc29ad6bf430bd2300c28ae4dc02ad15a7a | 7,904 | java | Java | src/main/java/com/blackducksoftware/integration/hub/alert/web/actions/LoginActions.java | junsulee/blackduck-alert | 9ffe1d11079dd0c20509023490c070731abe0b24 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/blackducksoftware/integration/hub/alert/web/actions/LoginActions.java | junsulee/blackduck-alert | 9ffe1d11079dd0c20509023490c070731abe0b24 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/blackducksoftware/integration/hub/alert/web/actions/LoginActions.java | junsulee/blackduck-alert | 9ffe1d11079dd0c20509023490c070731abe0b24 | [
"Apache-2.0"
] | null | null | null | 48.790123 | 221 | 0.730516 | 998,229 | /**
* hub-alert
*
* Copyright (C) 2018 Black Duck Software, Inc.
* http://www.blackducksoftware.com/
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.blackducksoftware.integration.hub.alert.web.actions;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import com.blackducksoftware.integration.exception.IntegrationException;
import com.blackducksoftware.integration.hub.alert.config.GlobalProperties;
import com.blackducksoftware.integration.hub.alert.exception.AlertFieldException;
import com.blackducksoftware.integration.hub.alert.web.model.LoginRestModel;
import com.blackducksoftware.integration.hub.api.generated.view.RoleAssignmentView;
import com.blackducksoftware.integration.hub.configuration.HubServerConfig;
import com.blackducksoftware.integration.hub.configuration.HubServerConfigBuilder;
import com.blackducksoftware.integration.hub.service.HubServicesFactory;
import com.blackducksoftware.integration.hub.service.UserGroupService;
import com.blackducksoftware.integration.log.IntLogger;
import com.blackducksoftware.integration.rest.connection.RestConnection;
import com.blackducksoftware.integration.validator.AbstractValidator;
import com.blackducksoftware.integration.validator.FieldEnum;
import com.blackducksoftware.integration.validator.ValidationResult;
import com.blackducksoftware.integration.validator.ValidationResults;
@Component
public class LoginActions {
final GlobalProperties globalProperties;
@Autowired
public LoginActions(final GlobalProperties globalProperties) {
this.globalProperties = globalProperties;
}
public boolean authenticateUser(final LoginRestModel loginRestModel, final IntLogger logger) throws IntegrationException {
final HubServerConfigBuilder serverConfigBuilder = new HubServerConfigBuilder();
serverConfigBuilder.setLogger(logger);
serverConfigBuilder.setHubUrl(globalProperties.getHubUrl());
serverConfigBuilder.setTimeout(HubServerConfigBuilder.DEFAULT_TIMEOUT_SECONDS);
if (globalProperties.getHubTrustCertificate() != null) {
serverConfigBuilder.setAlwaysTrustServerCertificate(globalProperties.getHubTrustCertificate());
}
serverConfigBuilder.setProxyHost(globalProperties.getHubProxyHost());
serverConfigBuilder.setProxyPort(globalProperties.getHubProxyPort());
serverConfigBuilder.setProxyUsername(globalProperties.getHubProxyUsername());
serverConfigBuilder.setProxyPassword(globalProperties.getHubProxyPassword());
serverConfigBuilder.setPassword(loginRestModel.getHubPassword());
serverConfigBuilder.setUsername(loginRestModel.getHubUsername());
try {
validateHubConfiguration(serverConfigBuilder);
try (final RestConnection restConnection = createRestConnection(serverConfigBuilder)) {
restConnection.connect();
logger.info("Connected");
final boolean isValidLoginUser = isUserRoleValid(loginRestModel.getHubUsername(), restConnection);
if (isValidLoginUser) {
final Authentication authentication = new UsernamePasswordAuthenticationToken(loginRestModel.getHubUsername(), loginRestModel.getHubPassword(), Arrays.asList(new SimpleGrantedAuthority("ROLE_ADMIN")));
SecurityContextHolder.getContext().setAuthentication(authentication);
return authentication.isAuthenticated();
}
} catch (final IOException ex) {
logger.error("Rest connection close failure", ex);
}
} catch (final AlertFieldException afex) {
logger.error("Error establishing connection", afex);
final Map<String, String> fieldErrorMap = afex.getFieldErrors();
fieldErrorMap.keySet().forEach(key -> {
final String value = fieldErrorMap.get(key);
logger.error(String.format("Field Error %s - %s", key, value));
});
logger.info("User not authenticated");
return false;
} catch (final IntegrationException ex) {
logger.error("Error establishing connection", ex);
logger.info("User not authenticated");
return false;
}
logger.info("User role not authenticated");
return false;
}
public boolean isUserRoleValid(final String userName, final RestConnection restConnection) {
final HubServicesFactory hubServicesFactory = new HubServicesFactory(restConnection);
final UserGroupService userGroupService = hubServicesFactory.createUserGroupService();
try {
final List<RoleAssignmentView> userRoles = userGroupService.getRolesForUser(userName);
for (final RoleAssignmentView roles : userRoles) {
if ("System Administrator".equalsIgnoreCase(roles.name)) {
return true;
}
}
} catch (final IntegrationException e) {
return false;
}
return false;
}
public void validateHubConfiguration(final HubServerConfigBuilder hubServerConfigBuilder) throws AlertFieldException {
final AbstractValidator validator = hubServerConfigBuilder.createValidator();
final ValidationResults results = validator.assertValid();
if (!results.getResultMap().isEmpty()) {
final Map<String, String> fieldErrors = new HashMap<>();
for (final Entry<FieldEnum, Set<ValidationResult>> result : results.getResultMap().entrySet()) {
final Set<ValidationResult> validationResult = result.getValue();
final List<String> errors = new ArrayList<>();
for (final ValidationResult currentValidationResult : validationResult) {
errors.add(currentValidationResult.getMessage());
}
final String key = result.getKey().getKey();
final String errorMessage = StringUtils.join(errors, " , ");
fieldErrors.put(key, errorMessage);
}
throw new AlertFieldException("There were issues with the configuration.", fieldErrors);
}
}
public RestConnection createRestConnection(final HubServerConfigBuilder hubServerConfigBuilder) throws IntegrationException {
final HubServerConfig hubServerConfig = hubServerConfigBuilder.build();
return hubServerConfig.createCredentialsRestConnection(hubServerConfigBuilder.getLogger());
}
}
|
9237dffafaf9081c2b1c1dcaa60a519a6c8d22bc | 2,819 | java | Java | src/org/siphon/visualbasic/VarDecl.java | igoreksiz/vba-interpreter | c00e8f18b84c33b33b258c7362eda76721402efb | [
"MIT"
] | 16 | 2017-12-12T04:21:22.000Z | 2021-12-16T15:02:54.000Z | src/org/siphon/visualbasic/VarDecl.java | igoreksiz/vba-interpreter | c00e8f18b84c33b33b258c7362eda76721402efb | [
"MIT"
] | 1 | 2019-11-11T11:07:38.000Z | 2019-11-12T05:47:35.000Z | src/org/siphon/visualbasic/VarDecl.java | igoreksiz/vba-interpreter | c00e8f18b84c33b33b258c7362eda76721402efb | [
"MIT"
] | 14 | 2018-09-23T01:55:12.000Z | 2021-09-30T02:00:23.000Z | 33.547619 | 81 | 0.681689 | 998,230 | /*******************************************************************************
* Copyright (C) 2017 Inshua<ychag@example.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
******************************************************************************/
package org.siphon.visualbasic;
import org.antlr.v4.runtime.ParserRuleContext;
import org.siphon.visualbasic.runtime.ModuleInstance;
import org.siphon.visualbasic.runtime.VbValue;
import org.siphon.visualbasic.runtime.VbVarType;
import org.siphon.visualbasic.runtime.VbVariable;
import vba.VbaParser.AmbiguousIdentifierContext;
public class VarDecl extends ModuleMemberDecl{
public VarDecl(Library library, ModuleDecl module) {
super(library, module);
}
public static final VarDecl AMBIGUOUS = new VarDecl(null, null);
public boolean isStatic;
public boolean withEvents;
public VbVarType varType;
public ParserRuleContext ast;
public boolean isImplicit; // 隐式声明的变量
public AmbiguousIdentifierContext ambiguousIdentifier(){
return ast.getChild(AmbiguousIdentifierContext.class, 0);
}
public MethodDecl methodDecl;
public boolean withNew; // vb 的对象即使声明为 new, 也只是在第一次使用时才真正 new
@Override
public String toString() {
String s = "";
if(visibility != Visibility.PRIVATE){
s += visibility.toString() + " ";
}
if(isStatic) s += "static ";
s += name + " ";
if(withEvents){
s += "WithEvents ";
}
if(withNew){
s += "New ";
}
assert (varType != null);
s += varType.toString();
return s;
}
public VbVariable createVar() {
if(!withNew)
return new VbVariable(this, varType.crateDefaultValue());
else
return new VbVariable(this, new VbValue(varType, ModuleInstance.WAIT_NEW));
}
}
|
9237e033ca1f0d802634104d38bb1cd6a2117cae | 2,373 | java | Java | jasperserver/jasperserver-api/engine/src/main/java/com/jaspersoft/jasperserver/api/engine/scheduling/service/TriggerTypeMismatchException.java | joshualucas84/jasper-soft-server | 6515c9e90a19535b2deba9264ed1ff9e77a2cc09 | [
"Apache-2.0"
] | 2 | 2021-02-25T16:35:45.000Z | 2021-07-07T05:11:55.000Z | jasperserver/jasperserver-api/engine/src/main/java/com/jaspersoft/jasperserver/api/engine/scheduling/service/TriggerTypeMismatchException.java | jlucas5190/jasper-soft-server | 6515c9e90a19535b2deba9264ed1ff9e77a2cc09 | [
"Apache-2.0"
] | null | null | null | jasperserver/jasperserver-api/engine/src/main/java/com/jaspersoft/jasperserver/api/engine/scheduling/service/TriggerTypeMismatchException.java | jlucas5190/jasper-soft-server | 6515c9e90a19535b2deba9264ed1ff9e77a2cc09 | [
"Apache-2.0"
] | 3 | 2018-11-14T07:01:06.000Z | 2021-07-07T05:12:03.000Z | 34.391304 | 144 | 0.713443 | 998,231 | /*
* Copyright (C) 2005 - 2014 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com.
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jaspersoft.jasperserver.api.engine.scheduling.service;
import com.jaspersoft.jasperserver.api.JSException;
import com.jaspersoft.jasperserver.api.JasperServerAPI;
/**
* Exception type used when a report job is not found for a specified ID.
*
* @author Ivan Chan
* @version $Id: TriggerTypeMismatchException.java 47331 2014-07-18 09:13:06Z kklein $
* @since 4.7
* @see com.jaspersoft.jasperserver.api.engine.scheduling.domain.ReportJob#getId()
*/
@JasperServerAPI
public class TriggerTypeMismatchException extends JSException {
private final long jobId;
public static enum TRIGGER_TYPE {
SIMPLE_TRIGGER,
CALENDAR_TRIGGER;
}
private TRIGGER_TYPE type = TRIGGER_TYPE.SIMPLE_TRIGGER;
/**
* Creates a report job not found exception.
*
* @param jobId the ID fow which finding a job failed
*/
public TriggerTypeMismatchException(long jobId, TRIGGER_TYPE type) {
super("jsexception.trigger.type.mismatch: expect " + (type == TRIGGER_TYPE.SIMPLE_TRIGGER? "simple trigger " : "calendar trigger ") +
"for report job ID " + + jobId + " [found " + (type != TRIGGER_TYPE.SIMPLE_TRIGGER? "simple trigger" : "calendar trigger") + "]"
, new Object[] {new Long(jobId), type});
this.jobId = jobId;
this.type = type;
}
/**
* Returns the ID for which a job was not found.
*
* @return the ID for which a job was not found
*/
public long getJobId() {
return jobId;
}
}
|
9237e07d17d0f0aff4b2477ff2a33de9abcb7f3a | 205,618 | java | Java | lib/mysql-connector-java-5.1.45/src/com/mysql/jdbc/MysqlIO.java | monicaespitiam/Curso-R | 8878a1d08ceb810369e44375eb33fa5ba5eb2240 | [
"MIT"
] | 121 | 2018-01-31T19:07:07.000Z | 2022-03-20T11:39:38.000Z | lib/mysql-connector-java-5.1.45/src/com/mysql/jdbc/MysqlIO.java | monicaespitiam/Curso-R | 8878a1d08ceb810369e44375eb33fa5ba5eb2240 | [
"MIT"
] | 1 | 2019-02-19T22:12:57.000Z | 2019-02-19T22:12:57.000Z | lib/mysql-connector-java-5.1.45/src/com/mysql/jdbc/MysqlIO.java | monicaespitiam/Curso-R | 8878a1d08ceb810369e44375eb33fa5ba5eb2240 | [
"MIT"
] | 392 | 2018-02-13T02:39:24.000Z | 2022-03-12T01:00:45.000Z | 40.7245 | 165 | 0.583417 | 998,232 | /*
Copyright (c) 2002, 2017, Oracle and/or its affiliates. All rights reserved.
The MySQL Connector/J is licensed under the terms of the GPLv2
<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most MySQL Connectors.
There are special exceptions to the terms and conditions of the GPLv2 as it is applied to
this software, see the FOSS License Exception
<http://www.mysql.com/about/legal/licensing/foss-exception.html>.
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; version 2
of the License.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this
program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth
Floor, Boston, MA 02110-1301 USA
*/
package com.mysql.jdbc;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.lang.ref.SoftReference;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.SocketException;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.zip.Deflater;
import com.mysql.jdbc.authentication.MysqlClearPasswordPlugin;
import com.mysql.jdbc.authentication.MysqlNativePasswordPlugin;
import com.mysql.jdbc.authentication.MysqlOldPasswordPlugin;
import com.mysql.jdbc.authentication.Sha256PasswordPlugin;
import com.mysql.jdbc.exceptions.MySQLStatementCancelledException;
import com.mysql.jdbc.exceptions.MySQLTimeoutException;
import com.mysql.jdbc.log.LogUtils;
import com.mysql.jdbc.profiler.ProfilerEvent;
import com.mysql.jdbc.profiler.ProfilerEventHandler;
import com.mysql.jdbc.util.ReadAheadInputStream;
import com.mysql.jdbc.util.ResultSetUtil;
/**
* This class is used by Connection for communicating with the MySQL server.
*/
public class MysqlIO {
private static final String CODE_PAGE_1252 = "Cp1252";
protected static final int NULL_LENGTH = ~0;
protected static final int COMP_HEADER_LENGTH = 3;
protected static final int MIN_COMPRESS_LEN = 50;
protected static final int HEADER_LENGTH = 4;
protected static final int AUTH_411_OVERHEAD = 33;
public static final int SEED_LENGTH = 20;
private static int maxBufferSize = 65535;
private static final String NONE = "none";
private static final int CLIENT_LONG_PASSWORD = 0x00000001; /* new more secure passwords */
private static final int CLIENT_FOUND_ROWS = 0x00000002;
private static final int CLIENT_LONG_FLAG = 0x00000004; /* Get all column flags */
protected static final int CLIENT_CONNECT_WITH_DB = 0x00000008;
private static final int CLIENT_COMPRESS = 0x00000020; /* Can use compression protcol */
private static final int CLIENT_LOCAL_FILES = 0x00000080; /* Can use LOAD DATA LOCAL */
private static final int CLIENT_PROTOCOL_41 = 0x00000200; // for > 4.1.1
private static final int CLIENT_INTERACTIVE = 0x00000400;
protected static final int CLIENT_SSL = 0x00000800;
private static final int CLIENT_TRANSACTIONS = 0x00002000; // Client knows about transactions
protected static final int CLIENT_RESERVED = 0x00004000; // for 4.1.0 only
protected static final int CLIENT_SECURE_CONNECTION = 0x00008000;
private static final int CLIENT_MULTI_STATEMENTS = 0x00010000; // Enable/disable multiquery support
private static final int CLIENT_MULTI_RESULTS = 0x00020000; // Enable/disable multi-results
private static final int CLIENT_PLUGIN_AUTH = 0x00080000;
private static final int CLIENT_CONNECT_ATTRS = 0x00100000;
private static final int CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA = 0x00200000;
private static final int CLIENT_CAN_HANDLE_EXPIRED_PASSWORD = 0x00400000;
private static final int CLIENT_SESSION_TRACK = 0x00800000;
private static final int CLIENT_DEPRECATE_EOF = 0x01000000;
private static final int SERVER_STATUS_IN_TRANS = 1;
private static final int SERVER_STATUS_AUTOCOMMIT = 2; // Server in auto_commit mode
static final int SERVER_MORE_RESULTS_EXISTS = 8; // Multi query - next query exists
private static final int SERVER_QUERY_NO_GOOD_INDEX_USED = 16;
private static final int SERVER_QUERY_NO_INDEX_USED = 32;
private static final int SERVER_QUERY_WAS_SLOW = 2048;
private static final int SERVER_STATUS_CURSOR_EXISTS = 64;
private static final String FALSE_SCRAMBLE = "xxxxxxxx";
protected static final int MAX_QUERY_SIZE_TO_LOG = 1024; // truncate logging of queries at 1K
protected static final int MAX_QUERY_SIZE_TO_EXPLAIN = 1024 * 1024; // don't explain queries above 1MB
protected static final int INITIAL_PACKET_SIZE = 1024;
/**
* We store the platform 'encoding' here, only used to avoid munging filenames for LOAD DATA LOCAL INFILE...
*/
private static String jvmPlatformCharset = null;
/**
* We need to have a 'marker' for all-zero datetimes so that ResultSet can decide what to do based on connection setting
*/
protected final static String ZERO_DATE_VALUE_MARKER = "0000-00-00";
protected final static String ZERO_DATETIME_VALUE_MARKER = "0000-00-00 00:00:00";
private static final String EXPLAINABLE_STATEMENT = "SELECT";
private static final String[] EXPLAINABLE_STATEMENT_EXTENSION = new String[] { "INSERT", "UPDATE", "REPLACE", "DELETE" };
static {
OutputStreamWriter outWriter = null;
//
// Use the I/O system to get the encoding (if possible), to avoid security restrictions on System.getProperty("file.encoding") in applets (why is that
// restricted?)
//
try {
outWriter = new OutputStreamWriter(new ByteArrayOutputStream());
jvmPlatformCharset = outWriter.getEncoding();
} finally {
try {
if (outWriter != null) {
outWriter.close();
}
} catch (IOException ioEx) {
// ignore
}
}
}
/** Max number of bytes to dump when tracing the protocol */
private final static int MAX_PACKET_DUMP_LENGTH = 1024;
private boolean packetSequenceReset = false;
protected int serverCharsetIndex;
//
// Use this when reading in rows to avoid thousands of new() calls, because the byte arrays just get copied out of the packet anyway
//
private Buffer reusablePacket = null;
private Buffer sendPacket = null;
private Buffer sharedSendPacket = null;
/** Data to the server */
protected BufferedOutputStream mysqlOutput = null;
protected MySQLConnection connection;
private Deflater deflater = null;
protected InputStream mysqlInput = null;
private LinkedList<StringBuilder> packetDebugRingBuffer = null;
private RowData streamingData = null;
/** The connection to the server */
public Socket mysqlConnection = null;
protected SocketFactory socketFactory = null;
//
// Packet used for 'LOAD DATA LOCAL INFILE'
//
// We use a SoftReference, so that we don't penalize intermittent use of this feature
//
private SoftReference<Buffer> loadFileBufRef;
//
// Used to send large packets to the server versions 4+
// We use a SoftReference, so that we don't penalize intermittent use of this feature
//
private SoftReference<Buffer> splitBufRef;
private SoftReference<Buffer> compressBufRef;
protected String host = null;
protected String seed;
private String serverVersion = null;
private String socketFactoryClassName = null;
private byte[] packetHeaderBuf = new byte[4];
private boolean colDecimalNeedsBump = false; // do we need to increment the colDecimal flag?
private boolean hadWarnings = false;
private boolean has41NewNewProt = false;
/** Does the server support long column info? */
private boolean hasLongColumnInfo = false;
private boolean isInteractiveClient = false;
private boolean logSlowQueries = false;
/**
* Does the character set of this connection match the character set of the
* platform
*/
private boolean platformDbCharsetMatches = true; // changed once we've connected.
private boolean profileSql = false;
private boolean queryBadIndexUsed = false;
private boolean queryNoIndexUsed = false;
private boolean serverQueryWasSlow = false;
/** Should we use 4.1 protocol extensions? */
private boolean use41Extensions = false;
private boolean useCompression = false;
private boolean useNewLargePackets = false;
private boolean useNewUpdateCounts = false; // should we use the new larger update counts?
private byte packetSequence = 0;
private byte compressedPacketSequence = 0;
private byte readPacketSequence = -1;
private boolean checkPacketSequence = false;
private byte protocolVersion = 0;
private int maxAllowedPacket = 1024 * 1024;
protected int maxThreeBytes = 255 * 255 * 255;
protected int port = 3306;
protected int serverCapabilities;
private int serverMajorVersion = 0;
private int serverMinorVersion = 0;
private int oldServerStatus = 0;
private int serverStatus = 0;
private int serverSubMinorVersion = 0;
private int warningCount = 0;
protected long clientParam = 0;
protected long lastPacketSentTimeMs = 0;
protected long lastPacketReceivedTimeMs = 0;
private boolean traceProtocol = false;
private boolean enablePacketDebug = false;
private boolean useConnectWithDb;
private boolean needToGrabQueryFromPacket;
private boolean autoGenerateTestcaseScript;
private long threadId;
private boolean useNanosForElapsedTime;
private long slowQueryThreshold;
private String queryTimingUnits;
private boolean useDirectRowUnpack = true;
private int useBufferRowSizeThreshold;
private int commandCount = 0;
private List<StatementInterceptorV2> statementInterceptors;
private ExceptionInterceptor exceptionInterceptor;
private int authPluginDataLength = 0;
/**
* Constructor: Connect to the MySQL server and setup a stream connection.
*
* @param host
* the hostname to connect to
* @param port
* the port number that the server is listening on
* @param props
* the Properties from DriverManager.getConnection()
* @param socketFactoryClassName
* the socket factory to use
* @param conn
* the Connection that is creating us
* @param socketTimeout
* the timeout to set for the socket (0 means no
* timeout)
*
* @throws IOException
* if an IOException occurs during connect.
* @throws SQLException
* if a database access error occurs.
*/
public MysqlIO(String host, int port, Properties props, String socketFactoryClassName, MySQLConnection conn, int socketTimeout,
int useBufferRowSizeThreshold) throws IOException, SQLException {
this.connection = conn;
if (this.connection.getEnablePacketDebug()) {
this.packetDebugRingBuffer = new LinkedList<StringBuilder>();
}
this.traceProtocol = this.connection.getTraceProtocol();
this.useAutoSlowLog = this.connection.getAutoSlowLog();
this.useBufferRowSizeThreshold = useBufferRowSizeThreshold;
this.useDirectRowUnpack = this.connection.getUseDirectRowUnpack();
this.logSlowQueries = this.connection.getLogSlowQueries();
this.reusablePacket = new Buffer(INITIAL_PACKET_SIZE);
this.sendPacket = new Buffer(INITIAL_PACKET_SIZE);
this.port = port;
this.host = host;
this.socketFactoryClassName = socketFactoryClassName;
this.socketFactory = createSocketFactory();
this.exceptionInterceptor = this.connection.getExceptionInterceptor();
try {
this.mysqlConnection = this.socketFactory.connect(this.host, this.port, props);
if (socketTimeout != 0) {
try {
this.mysqlConnection.setSoTimeout(socketTimeout);
} catch (Exception ex) {
/* Ignore if the platform does not support it */
}
}
this.mysqlConnection = this.socketFactory.beforeHandshake();
if (this.connection.getUseReadAheadInput()) {
this.mysqlInput = new ReadAheadInputStream(this.mysqlConnection.getInputStream(), 16384, this.connection.getTraceProtocol(),
this.connection.getLog());
} else if (this.connection.useUnbufferedInput()) {
this.mysqlInput = this.mysqlConnection.getInputStream();
} else {
this.mysqlInput = new BufferedInputStream(this.mysqlConnection.getInputStream(), 16384);
}
this.mysqlOutput = new BufferedOutputStream(this.mysqlConnection.getOutputStream(), 16384);
this.isInteractiveClient = this.connection.getInteractiveClient();
this.profileSql = this.connection.getProfileSql();
this.autoGenerateTestcaseScript = this.connection.getAutoGenerateTestcaseScript();
this.needToGrabQueryFromPacket = (this.profileSql || this.logSlowQueries || this.autoGenerateTestcaseScript);
if (this.connection.getUseNanosForElapsedTime() && TimeUtil.nanoTimeAvailable()) {
this.useNanosForElapsedTime = true;
this.queryTimingUnits = Messages.getString("Nanoseconds");
} else {
this.queryTimingUnits = Messages.getString("Milliseconds");
}
if (this.connection.getLogSlowQueries()) {
calculateSlowQueryThreshold();
}
} catch (IOException ioEx) {
throw SQLError.createCommunicationsException(this.connection, 0, 0, ioEx, getExceptionInterceptor());
}
}
/**
* Does the server send back extra column info?
*
* @return true if so
*/
public boolean hasLongColumnInfo() {
return this.hasLongColumnInfo;
}
protected boolean isDataAvailable() throws SQLException {
try {
return this.mysqlInput.available() > 0;
} catch (IOException ioEx) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs, ioEx,
getExceptionInterceptor());
}
}
/**
* @return Returns the lastPacketSentTimeMs.
*/
protected long getLastPacketSentTimeMs() {
return this.lastPacketSentTimeMs;
}
protected long getLastPacketReceivedTimeMs() {
return this.lastPacketReceivedTimeMs;
}
/**
* Build a result set. Delegates to buildResultSetWithRows() to build a
* JDBC-version-specific ResultSet, given rows as byte data, and field
* information.
*
* @param callingStatement
* @param columnCount
* the number of columns in the result set
* @param maxRows
* the maximum number of rows to read (-1 means all rows)
* @param resultSetType
* (TYPE_FORWARD_ONLY, TYPE_SCROLL_????)
* @param resultSetConcurrency
* the type of result set (CONCUR_UPDATABLE or
* READ_ONLY)
* @param streamResults
* should the result set be read all at once, or
* streamed?
* @param catalog
* the database name in use when the result set was created
* @param isBinaryEncoded
* is this result set in native encoding?
* @param unpackFieldInfo
* should we read MYSQL_FIELD info (if available)?
*
* @return a result set
*
* @throws SQLException
* if a database access error occurs
*/
protected ResultSetImpl getResultSet(StatementImpl callingStatement, long columnCount, int maxRows, int resultSetType, int resultSetConcurrency,
boolean streamResults, String catalog, boolean isBinaryEncoded, Field[] metadataFromCache) throws SQLException {
Buffer packet; // The packet from the server
Field[] fields = null;
// Read in the column information
if (metadataFromCache == null /* we want the metadata from the server */) {
fields = new Field[(int) columnCount];
for (int i = 0; i < columnCount; i++) {
Buffer fieldPacket = null;
fieldPacket = readPacket();
fields[i] = unpackField(fieldPacket, false);
}
} else {
for (int i = 0; i < columnCount; i++) {
skipPacket();
}
}
// There is no EOF packet after fields when CLIENT_DEPRECATE_EOF is set
if (!isEOFDeprecated() ||
// if we asked to use cursor then there should be an OK packet here
(this.connection.versionMeetsMinimum(5, 0, 2) && callingStatement != null && isBinaryEncoded && callingStatement.isCursorRequired())) {
packet = reuseAndReadPacket(this.reusablePacket);
readServerStatusForResultSets(packet);
}
//
// Handle cursor-based fetch first
//
if (this.connection.versionMeetsMinimum(5, 0, 2) && this.connection.getUseCursorFetch() && isBinaryEncoded && callingStatement != null
&& callingStatement.getFetchSize() != 0 && callingStatement.getResultSetType() == ResultSet.TYPE_FORWARD_ONLY) {
ServerPreparedStatement prepStmt = (com.mysql.jdbc.ServerPreparedStatement) callingStatement;
boolean usingCursor = true;
//
// Server versions 5.0.5 or newer will only open a cursor and set this flag if they can, otherwise they punt and go back to mysql_store_results()
// behavior
//
if (this.connection.versionMeetsMinimum(5, 0, 5)) {
usingCursor = (this.serverStatus & SERVER_STATUS_CURSOR_EXISTS) != 0;
}
if (usingCursor) {
RowData rows = new RowDataCursor(this, prepStmt, fields);
ResultSetImpl rs = buildResultSetWithRows(callingStatement, catalog, fields, rows, resultSetType, resultSetConcurrency, isBinaryEncoded);
if (usingCursor) {
rs.setFetchSize(callingStatement.getFetchSize());
}
return rs;
}
}
RowData rowData = null;
if (!streamResults) {
rowData = readSingleRowSet(columnCount, maxRows, resultSetConcurrency, isBinaryEncoded, (metadataFromCache == null) ? fields : metadataFromCache);
} else {
rowData = new RowDataDynamic(this, (int) columnCount, (metadataFromCache == null) ? fields : metadataFromCache, isBinaryEncoded);
this.streamingData = rowData;
}
ResultSetImpl rs = buildResultSetWithRows(callingStatement, catalog, (metadataFromCache == null) ? fields : metadataFromCache, rowData, resultSetType,
resultSetConcurrency, isBinaryEncoded);
return rs;
}
// We do this to break the chain between MysqlIO and Connection, so that we can have PhantomReferences on connections that let the driver clean up the
// socket connection without having to use finalize() somewhere (which although more straightforward, is horribly inefficient).
protected NetworkResources getNetworkResources() {
return new NetworkResources(this.mysqlConnection, this.mysqlInput, this.mysqlOutput);
}
/**
* Forcibly closes the underlying socket to MySQL.
*/
protected final void forceClose() {
try {
getNetworkResources().forceClose();
} finally {
this.mysqlConnection = null;
this.mysqlInput = null;
this.mysqlOutput = null;
}
}
/**
* Reads and discards a single MySQL packet from the input stream.
*
* @throws SQLException
* if the network fails while skipping the
* packet.
*/
protected final void skipPacket() throws SQLException {
try {
int lengthRead = readFully(this.mysqlInput, this.packetHeaderBuf, 0, 4);
if (lengthRead < 4) {
forceClose();
throw new IOException(Messages.getString("MysqlIO.1"));
}
int packetLength = (this.packetHeaderBuf[0] & 0xff) + ((this.packetHeaderBuf[1] & 0xff) << 8) + ((this.packetHeaderBuf[2] & 0xff) << 16);
if (this.traceProtocol) {
StringBuilder traceMessageBuf = new StringBuilder();
traceMessageBuf.append(Messages.getString("MysqlIO.2"));
traceMessageBuf.append(packetLength);
traceMessageBuf.append(Messages.getString("MysqlIO.3"));
traceMessageBuf.append(StringUtils.dumpAsHex(this.packetHeaderBuf, 4));
this.connection.getLog().logTrace(traceMessageBuf.toString());
}
byte multiPacketSeq = this.packetHeaderBuf[3];
if (!this.packetSequenceReset) {
if (this.enablePacketDebug && this.checkPacketSequence) {
checkPacketSequencing(multiPacketSeq);
}
} else {
this.packetSequenceReset = false;
}
this.readPacketSequence = multiPacketSeq;
skipFully(this.mysqlInput, packetLength);
} catch (IOException ioEx) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs, ioEx,
getExceptionInterceptor());
} catch (OutOfMemoryError oom) {
try {
this.connection.realClose(false, false, true, oom);
} catch (Exception ex) {
}
throw oom;
}
}
/**
* Read one packet from the MySQL server
*
* @return the packet from the server.
*
* @throws SQLException
* @throws CommunicationsException
*/
protected final Buffer readPacket() throws SQLException {
try {
int lengthRead = readFully(this.mysqlInput, this.packetHeaderBuf, 0, 4);
if (lengthRead < 4) {
forceClose();
throw new IOException(Messages.getString("MysqlIO.1"));
}
int packetLength = (this.packetHeaderBuf[0] & 0xff) + ((this.packetHeaderBuf[1] & 0xff) << 8) + ((this.packetHeaderBuf[2] & 0xff) << 16);
if (packetLength > this.maxAllowedPacket) {
throw new PacketTooBigException(packetLength, this.maxAllowedPacket);
}
if (this.traceProtocol) {
StringBuilder traceMessageBuf = new StringBuilder();
traceMessageBuf.append(Messages.getString("MysqlIO.2"));
traceMessageBuf.append(packetLength);
traceMessageBuf.append(Messages.getString("MysqlIO.3"));
traceMessageBuf.append(StringUtils.dumpAsHex(this.packetHeaderBuf, 4));
this.connection.getLog().logTrace(traceMessageBuf.toString());
}
byte multiPacketSeq = this.packetHeaderBuf[3];
if (!this.packetSequenceReset) {
if (this.enablePacketDebug && this.checkPacketSequence) {
checkPacketSequencing(multiPacketSeq);
}
} else {
this.packetSequenceReset = false;
}
this.readPacketSequence = multiPacketSeq;
// Read data
byte[] buffer = new byte[packetLength];
int numBytesRead = readFully(this.mysqlInput, buffer, 0, packetLength);
if (numBytesRead != packetLength) {
throw new IOException("Short read, expected " + packetLength + " bytes, only read " + numBytesRead);
}
Buffer packet = new Buffer(buffer);
if (this.traceProtocol) {
StringBuilder traceMessageBuf = new StringBuilder();
traceMessageBuf.append(Messages.getString("MysqlIO.4"));
traceMessageBuf.append(getPacketDumpToLog(packet, packetLength));
this.connection.getLog().logTrace(traceMessageBuf.toString());
}
if (this.enablePacketDebug) {
enqueuePacketForDebugging(false, false, 0, this.packetHeaderBuf, packet);
}
if (this.connection.getMaintainTimeStats()) {
this.lastPacketReceivedTimeMs = System.currentTimeMillis();
}
return packet;
} catch (IOException ioEx) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs, ioEx,
getExceptionInterceptor());
} catch (OutOfMemoryError oom) {
try {
this.connection.realClose(false, false, true, oom);
} catch (Exception ex) {
}
throw oom;
}
}
/**
* Unpacks the Field information from the given packet. Understands pre 4.1
* and post 4.1 server version field packet structures.
*
* @param packet
* the packet containing the field information
* @param extractDefaultValues
* should default values be extracted?
*
* @return the unpacked field
*
* @throws SQLException
*/
protected final Field unpackField(Buffer packet, boolean extractDefaultValues) throws SQLException {
if (this.use41Extensions) {
// we only store the position of the string and
// materialize only if needed...
if (this.has41NewNewProt) {
// Not used yet, 5.0?
int catalogNameStart = packet.getPosition() + 1;
int catalogNameLength = packet.fastSkipLenString();
catalogNameStart = adjustStartForFieldLength(catalogNameStart, catalogNameLength);
}
int databaseNameStart = packet.getPosition() + 1;
int databaseNameLength = packet.fastSkipLenString();
databaseNameStart = adjustStartForFieldLength(databaseNameStart, databaseNameLength);
int tableNameStart = packet.getPosition() + 1;
int tableNameLength = packet.fastSkipLenString();
tableNameStart = adjustStartForFieldLength(tableNameStart, tableNameLength);
// orgTableName is never used so skip
int originalTableNameStart = packet.getPosition() + 1;
int originalTableNameLength = packet.fastSkipLenString();
originalTableNameStart = adjustStartForFieldLength(originalTableNameStart, originalTableNameLength);
// we only store the position again...
int nameStart = packet.getPosition() + 1;
int nameLength = packet.fastSkipLenString();
nameStart = adjustStartForFieldLength(nameStart, nameLength);
// orgColName is not required so skip...
int originalColumnNameStart = packet.getPosition() + 1;
int originalColumnNameLength = packet.fastSkipLenString();
originalColumnNameStart = adjustStartForFieldLength(originalColumnNameStart, originalColumnNameLength);
packet.readByte();
short charSetNumber = (short) packet.readInt();
long colLength = 0;
if (this.has41NewNewProt) {
colLength = packet.readLong();
} else {
colLength = packet.readLongInt();
}
int colType = packet.readByte() & 0xff;
short colFlag = 0;
if (this.hasLongColumnInfo) {
colFlag = (short) packet.readInt();
} else {
colFlag = (short) (packet.readByte() & 0xff);
}
int colDecimals = packet.readByte() & 0xff;
int defaultValueStart = -1;
int defaultValueLength = -1;
if (extractDefaultValues) {
defaultValueStart = packet.getPosition() + 1;
defaultValueLength = packet.fastSkipLenString();
}
Field field = new Field(this.connection, packet.getByteBuffer(), databaseNameStart, databaseNameLength, tableNameStart, tableNameLength,
originalTableNameStart, originalTableNameLength, nameStart, nameLength, originalColumnNameStart, originalColumnNameLength, colLength,
colType, colFlag, colDecimals, defaultValueStart, defaultValueLength, charSetNumber);
return field;
}
int tableNameStart = packet.getPosition() + 1;
int tableNameLength = packet.fastSkipLenString();
tableNameStart = adjustStartForFieldLength(tableNameStart, tableNameLength);
int nameStart = packet.getPosition() + 1;
int nameLength = packet.fastSkipLenString();
nameStart = adjustStartForFieldLength(nameStart, nameLength);
int colLength = packet.readnBytes();
int colType = packet.readnBytes();
packet.readByte(); // We know it's currently 2
short colFlag = 0;
if (this.hasLongColumnInfo) {
colFlag = (short) (packet.readInt());
} else {
colFlag = (short) (packet.readByte() & 0xff);
}
int colDecimals = (packet.readByte() & 0xff);
if (this.colDecimalNeedsBump) {
colDecimals++;
}
Field field = new Field(this.connection, packet.getByteBuffer(), nameStart, nameLength, tableNameStart, tableNameLength, colLength, colType, colFlag,
colDecimals);
return field;
}
private int adjustStartForFieldLength(int nameStart, int nameLength) {
if (nameLength < 251) {
return nameStart;
}
if (nameLength >= 251 && nameLength < 65536) {
return nameStart + 2;
}
if (nameLength >= 65536 && nameLength < 16777216) {
return nameStart + 3;
}
return nameStart + 8;
}
protected boolean isSetNeededForAutoCommitMode(boolean autoCommitFlag) {
if (this.use41Extensions && this.connection.getElideSetAutoCommits()) {
boolean autoCommitModeOnServer = ((this.serverStatus & SERVER_STATUS_AUTOCOMMIT) != 0);
if (!autoCommitFlag && versionMeetsMinimum(5, 0, 0)) {
// Just to be safe, check if a transaction is in progress on the server....
// if so, then we must be in autoCommit == false
// therefore return the opposite of transaction status
return !inTransactionOnServer();
}
return autoCommitModeOnServer != autoCommitFlag;
}
return true;
}
protected boolean inTransactionOnServer() {
return (this.serverStatus & SERVER_STATUS_IN_TRANS) != 0;
}
/**
* Re-authenticates as the given user and password
*
* @param userName
* @param password
* @param database
*
* @throws SQLException
*/
protected void changeUser(String userName, String password, String database) throws SQLException {
this.packetSequence = -1;
this.compressedPacketSequence = -1;
int passwordLength = 16;
int userLength = (userName != null) ? userName.length() : 0;
int databaseLength = (database != null) ? database.length() : 0;
int packLength = ((userLength + passwordLength + databaseLength) * 3) + 7 + HEADER_LENGTH + AUTH_411_OVERHEAD;
if ((this.serverCapabilities & CLIENT_PLUGIN_AUTH) != 0) {
proceedHandshakeWithPluggableAuthentication(userName, password, database, null);
} else if ((this.serverCapabilities & CLIENT_SECURE_CONNECTION) != 0) {
Buffer changeUserPacket = new Buffer(packLength + 1);
changeUserPacket.writeByte((byte) MysqlDefs.COM_CHANGE_USER);
if (versionMeetsMinimum(4, 1, 1)) {
secureAuth411(changeUserPacket, packLength, userName, password, database, false);
} else {
secureAuth(changeUserPacket, packLength, userName, password, database, false);
}
} else {
// Passwords can be 16 chars long
Buffer packet = new Buffer(packLength);
packet.writeByte((byte) MysqlDefs.COM_CHANGE_USER);
// User/Password data
packet.writeString(userName);
if (this.protocolVersion > 9) {
packet.writeString(Util.newCrypt(password, this.seed, this.connection.getPasswordCharacterEncoding()));
} else {
packet.writeString(Util.oldCrypt(password, this.seed));
}
boolean localUseConnectWithDb = this.useConnectWithDb && (database != null && database.length() > 0);
if (localUseConnectWithDb) {
packet.writeString(database);
} else {
//Not needed, old server does not require \0
//packet.writeString("");
}
send(packet, packet.getPosition());
checkErrorPacket();
if (!localUseConnectWithDb) {
changeDatabaseTo(database);
}
}
}
/**
* Checks for errors in the reply packet, and if none, returns the reply
* packet, ready for reading
*
* @return a packet ready for reading.
*
* @throws SQLException
* is the packet is an error packet
*/
protected Buffer checkErrorPacket() throws SQLException {
return checkErrorPacket(-1);
}
/**
* Determines if the database charset is the same as the platform charset
*/
protected void checkForCharsetMismatch() {
if (this.connection.getUseUnicode() && (this.connection.getEncoding() != null)) {
String encodingToCheck = jvmPlatformCharset;
if (encodingToCheck == null) {
encodingToCheck = System.getProperty("file.encoding");
}
if (encodingToCheck == null) {
this.platformDbCharsetMatches = false;
} else {
this.platformDbCharsetMatches = encodingToCheck.equals(this.connection.getEncoding());
}
}
}
protected void clearInputStream() throws SQLException {
try {
int len;
// Due to a bug in some older Linux kernels (fixed after the patch "tcp: fix FIONREAD/SIOCINQ"), our SocketInputStream.available() may return 1 even
// if there is no data in the Stream, so, we need to check if InputStream.skip() actually skipped anything.
while ((len = this.mysqlInput.available()) > 0 && this.mysqlInput.skip(len) > 0) {
continue;
}
} catch (IOException ioEx) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs, ioEx,
getExceptionInterceptor());
}
}
protected void resetReadPacketSequence() {
this.readPacketSequence = 0;
}
protected void dumpPacketRingBuffer() throws SQLException {
if ((this.packetDebugRingBuffer != null) && this.connection.getEnablePacketDebug()) {
StringBuilder dumpBuffer = new StringBuilder();
dumpBuffer.append("Last " + this.packetDebugRingBuffer.size() + " packets received from server, from oldest->newest:\n");
dumpBuffer.append("\n");
for (Iterator<StringBuilder> ringBufIter = this.packetDebugRingBuffer.iterator(); ringBufIter.hasNext();) {
dumpBuffer.append(ringBufIter.next());
dumpBuffer.append("\n");
}
this.connection.getLog().logTrace(dumpBuffer.toString());
}
}
/**
* Runs an 'EXPLAIN' on the given query and dumps the results to the log
*
* @param querySQL
* @param truncatedQuery
*
* @throws SQLException
*/
protected void explainSlowQuery(byte[] querySQL, String truncatedQuery) throws SQLException {
if (StringUtils.startsWithIgnoreCaseAndWs(truncatedQuery, EXPLAINABLE_STATEMENT)
|| (versionMeetsMinimum(5, 6, 3) && StringUtils.startsWithIgnoreCaseAndWs(truncatedQuery, EXPLAINABLE_STATEMENT_EXTENSION) != -1)) {
PreparedStatement stmt = null;
java.sql.ResultSet rs = null;
try {
stmt = (PreparedStatement) this.connection.clientPrepareStatement("EXPLAIN ?");
stmt.setBytesNoEscapeNoQuotes(1, querySQL);
rs = stmt.executeQuery();
StringBuilder explainResults = new StringBuilder(Messages.getString("MysqlIO.8") + truncatedQuery + Messages.getString("MysqlIO.9"));
ResultSetUtil.appendResultSetSlashGStyle(explainResults, rs);
this.connection.getLog().logWarn(explainResults.toString());
} catch (SQLException sqlEx) {
} finally {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
}
}
}
static int getMaxBuf() {
return maxBufferSize;
}
/**
* Get the major version of the MySQL server we are talking to.
*/
final int getServerMajorVersion() {
return this.serverMajorVersion;
}
/**
* Get the minor version of the MySQL server we are talking to.
*/
final int getServerMinorVersion() {
return this.serverMinorVersion;
}
/**
* Get the sub-minor version of the MySQL server we are talking to.
*/
final int getServerSubMinorVersion() {
return this.serverSubMinorVersion;
}
/**
* Get the version string of the server we are talking to
*/
String getServerVersion() {
return this.serverVersion;
}
/**
* Initialize communications with the MySQL server. Handles logging on, and
* handling initial connection errors.
*
* @param user
* @param password
* @param database
*
* @throws SQLException
* @throws CommunicationsException
*/
void doHandshake(String user, String password, String database) throws SQLException {
// Read the first packet
this.checkPacketSequence = false;
this.readPacketSequence = 0;
Buffer buf = readPacket();
// Get the protocol version
this.protocolVersion = buf.readByte();
if (this.protocolVersion == -1) {
try {
this.mysqlConnection.close();
} catch (Exception e) {
// ignore
}
int errno = 2000;
errno = buf.readInt();
String serverErrorMessage = buf.readString("ASCII", getExceptionInterceptor());
StringBuilder errorBuf = new StringBuilder(Messages.getString("MysqlIO.10"));
errorBuf.append(serverErrorMessage);
errorBuf.append("\"");
String xOpen = SQLError.mysqlToSqlState(errno, this.connection.getUseSqlStateCodes());
throw SQLError.createSQLException(SQLError.get(xOpen) + ", " + errorBuf.toString(), xOpen, errno, getExceptionInterceptor());
}
this.serverVersion = buf.readString("ASCII", getExceptionInterceptor());
// Parse the server version into major/minor/subminor
int point = this.serverVersion.indexOf('.');
if (point != -1) {
try {
int n = Integer.parseInt(this.serverVersion.substring(0, point));
this.serverMajorVersion = n;
} catch (NumberFormatException NFE1) {
// ignore
}
String remaining = this.serverVersion.substring(point + 1, this.serverVersion.length());
point = remaining.indexOf('.');
if (point != -1) {
try {
int n = Integer.parseInt(remaining.substring(0, point));
this.serverMinorVersion = n;
} catch (NumberFormatException nfe) {
// ignore
}
remaining = remaining.substring(point + 1, remaining.length());
int pos = 0;
while (pos < remaining.length()) {
if ((remaining.charAt(pos) < '0') || (remaining.charAt(pos) > '9')) {
break;
}
pos++;
}
try {
int n = Integer.parseInt(remaining.substring(0, pos));
this.serverSubMinorVersion = n;
} catch (NumberFormatException nfe) {
// ignore
}
}
}
if (versionMeetsMinimum(4, 0, 8)) {
this.maxThreeBytes = (256 * 256 * 256) - 1;
this.useNewLargePackets = true;
} else {
this.maxThreeBytes = 255 * 255 * 255;
this.useNewLargePackets = false;
}
this.colDecimalNeedsBump = versionMeetsMinimum(3, 23, 0);
this.colDecimalNeedsBump = !versionMeetsMinimum(3, 23, 15); // guess? Not noted in changelog
this.useNewUpdateCounts = versionMeetsMinimum(3, 22, 5);
// read connection id
this.threadId = buf.readLong();
if (this.protocolVersion > 9) {
// read auth-plugin-data-part-1 (string[8])
this.seed = buf.readString("ASCII", getExceptionInterceptor(), 8);
// read filler ([00])
buf.readByte();
} else {
// read scramble (string[NUL])
this.seed = buf.readString("ASCII", getExceptionInterceptor());
}
this.serverCapabilities = 0;
// read capability flags (lower 2 bytes)
if (buf.getPosition() < buf.getBufLength()) {
this.serverCapabilities = buf.readInt();
}
if ((versionMeetsMinimum(4, 1, 1) || ((this.protocolVersion > 9) && (this.serverCapabilities & CLIENT_PROTOCOL_41) != 0))) {
/* New protocol with 16 bytes to describe server characteristics */
// read character set (1 byte)
this.serverCharsetIndex = buf.readByte() & 0xff;
// read status flags (2 bytes)
this.serverStatus = buf.readInt();
checkTransactionState(0);
// read capability flags (upper 2 bytes)
this.serverCapabilities |= buf.readInt() << 16;
if ((this.serverCapabilities & CLIENT_PLUGIN_AUTH) != 0) {
// read length of auth-plugin-data (1 byte)
this.authPluginDataLength = buf.readByte() & 0xff;
} else {
// read filler ([00])
buf.readByte();
}
// next 10 bytes are reserved (all [00])
buf.setPosition(buf.getPosition() + 10);
if ((this.serverCapabilities & CLIENT_SECURE_CONNECTION) != 0) {
String seedPart2;
StringBuilder newSeed;
// read string[$len] auth-plugin-data-part-2 ($len=MAX(13, length of auth-plugin-data - 8))
if (this.authPluginDataLength > 0) {
// TODO: disabled the following check for further clarification
// if (this.authPluginDataLength < 21) {
// forceClose();
// throw SQLError.createSQLException(Messages.getString("MysqlIO.103"),
// SQLError.SQL_STATE_UNABLE_TO_CONNECT_TO_DATASOURCE, getExceptionInterceptor());
// }
seedPart2 = buf.readString("ASCII", getExceptionInterceptor(), this.authPluginDataLength - 8);
newSeed = new StringBuilder(this.authPluginDataLength);
} else {
seedPart2 = buf.readString("ASCII", getExceptionInterceptor());
newSeed = new StringBuilder(SEED_LENGTH);
}
newSeed.append(this.seed);
newSeed.append(seedPart2);
this.seed = newSeed.toString();
}
}
if (((this.serverCapabilities & CLIENT_COMPRESS) != 0) && this.connection.getUseCompression()) {
this.clientParam |= CLIENT_COMPRESS;
}
this.useConnectWithDb = (database != null) && (database.length() > 0) && !this.connection.getCreateDatabaseIfNotExist();
if (this.useConnectWithDb) {
this.clientParam |= CLIENT_CONNECT_WITH_DB;
}
// Changing SSL defaults for 5.7+ server: useSSL=true, requireSSL=false, verifyServerCertificate=false
if (versionMeetsMinimum(5, 7, 0) && !this.connection.getUseSSL() && !this.connection.isUseSSLExplicit()) {
this.connection.setUseSSL(true);
this.connection.setVerifyServerCertificate(false);
this.connection.getLog().logWarn(Messages.getString("MysqlIO.SSLWarning"));
}
// check SSL availability
if (((this.serverCapabilities & CLIENT_SSL) == 0) && this.connection.getUseSSL()) {
if (this.connection.getRequireSSL()) {
this.connection.close();
forceClose();
throw SQLError.createSQLException(Messages.getString("MysqlIO.15"), SQLError.SQL_STATE_UNABLE_TO_CONNECT_TO_DATASOURCE,
getExceptionInterceptor());
}
this.connection.setUseSSL(false);
}
if ((this.serverCapabilities & CLIENT_LONG_FLAG) != 0) {
// We understand other column flags, as well
this.clientParam |= CLIENT_LONG_FLAG;
this.hasLongColumnInfo = true;
}
// return FOUND rows
if (!this.connection.getUseAffectedRows()) {
this.clientParam |= CLIENT_FOUND_ROWS;
}
if (this.connection.getAllowLoadLocalInfile()) {
this.clientParam |= CLIENT_LOCAL_FILES;
}
if (this.isInteractiveClient) {
this.clientParam |= CLIENT_INTERACTIVE;
}
if ((this.serverCapabilities & CLIENT_SESSION_TRACK) != 0) {
// TODO MYSQLCONNJ-437
// this.clientParam |= CLIENT_SESSION_TRACK;
}
if ((this.serverCapabilities & CLIENT_DEPRECATE_EOF) != 0) {
this.clientParam |= CLIENT_DEPRECATE_EOF;
}
//
// switch to pluggable authentication if available
//
if ((this.serverCapabilities & CLIENT_PLUGIN_AUTH) != 0) {
proceedHandshakeWithPluggableAuthentication(user, password, database, buf);
return;
}
// Authenticate
if (this.protocolVersion > 9) {
this.clientParam |= CLIENT_LONG_PASSWORD; // for long passwords
} else {
this.clientParam &= ~CLIENT_LONG_PASSWORD;
}
//
// 4.1 has some differences in the protocol
//
if ((versionMeetsMinimum(4, 1, 0) || ((this.protocolVersion > 9) && (this.serverCapabilities & CLIENT_RESERVED) != 0))) {
if ((versionMeetsMinimum(4, 1, 1) || ((this.protocolVersion > 9) && (this.serverCapabilities & CLIENT_PROTOCOL_41) != 0))) {
this.clientParam |= CLIENT_PROTOCOL_41;
this.has41NewNewProt = true;
// Need this to get server status values
this.clientParam |= CLIENT_TRANSACTIONS;
// We always allow multiple result sets
this.clientParam |= CLIENT_MULTI_RESULTS;
// We allow the user to configure whether
// or not they want to support multiple queries
// (by default, this is disabled).
if (this.connection.getAllowMultiQueries()) {
this.clientParam |= CLIENT_MULTI_STATEMENTS;
}
} else {
this.clientParam |= CLIENT_RESERVED;
this.has41NewNewProt = false;
}
this.use41Extensions = true;
}
int passwordLength = 16;
int userLength = (user != null) ? user.length() : 0;
int databaseLength = (database != null) ? database.length() : 0;
int packLength = ((userLength + passwordLength + databaseLength) * 3) + 7 + HEADER_LENGTH + AUTH_411_OVERHEAD;
Buffer packet = null;
if (!this.connection.getUseSSL()) {
if ((this.serverCapabilities & CLIENT_SECURE_CONNECTION) != 0) {
this.clientParam |= CLIENT_SECURE_CONNECTION;
if ((versionMeetsMinimum(4, 1, 1) || ((this.protocolVersion > 9) && (this.serverCapabilities & CLIENT_PROTOCOL_41) != 0))) {
secureAuth411(null, packLength, user, password, database, true);
} else {
secureAuth(null, packLength, user, password, database, true);
}
} else {
// Passwords can be 16 chars long
packet = new Buffer(packLength);
if ((this.clientParam & CLIENT_RESERVED) != 0) {
if ((versionMeetsMinimum(4, 1, 1) || ((this.protocolVersion > 9) && (this.serverCapabilities & CLIENT_PROTOCOL_41) != 0))) {
packet.writeLong(this.clientParam);
packet.writeLong(this.maxThreeBytes);
// charset, JDBC will connect as 'latin1', and use 'SET NAMES' to change to the desired charset after the connection is established.
packet.writeByte((byte) 8);
// Set of bytes reserved for future use.
packet.writeBytesNoNull(new byte[23]);
} else {
packet.writeLong(this.clientParam);
packet.writeLong(this.maxThreeBytes);
}
} else {
packet.writeInt((int) this.clientParam);
packet.writeLongInt(this.maxThreeBytes);
}
// User/Password data
packet.writeString(user, CODE_PAGE_1252, this.connection);
if (this.protocolVersion > 9) {
packet.writeString(Util.newCrypt(password, this.seed, this.connection.getPasswordCharacterEncoding()), CODE_PAGE_1252, this.connection);
} else {
packet.writeString(Util.oldCrypt(password, this.seed), CODE_PAGE_1252, this.connection);
}
if (this.useConnectWithDb) {
packet.writeString(database, CODE_PAGE_1252, this.connection);
}
send(packet, packet.getPosition());
}
} else {
negotiateSSLConnection(user, password, database, packLength);
if ((this.serverCapabilities & CLIENT_SECURE_CONNECTION) != 0) {
if (versionMeetsMinimum(4, 1, 1)) {
secureAuth411(null, packLength, user, password, database, true);
} else {
secureAuth411(null, packLength, user, password, database, true);
}
} else {
packet = new Buffer(packLength);
if (this.use41Extensions) {
packet.writeLong(this.clientParam);
packet.writeLong(this.maxThreeBytes);
} else {
packet.writeInt((int) this.clientParam);
packet.writeLongInt(this.maxThreeBytes);
}
// User/Password data
packet.writeString(user);
if (this.protocolVersion > 9) {
packet.writeString(Util.newCrypt(password, this.seed, this.connection.getPasswordCharacterEncoding()));
} else {
packet.writeString(Util.oldCrypt(password, this.seed));
}
if (((this.serverCapabilities & CLIENT_CONNECT_WITH_DB) != 0) && (database != null) && (database.length() > 0)) {
packet.writeString(database);
}
send(packet, packet.getPosition());
}
}
// Check for errors, not for 4.1.1 or newer, as the new auth protocol doesn't work that way (see secureAuth411() for more details...)
if (!(versionMeetsMinimum(4, 1, 1)) || !((this.protocolVersion > 9) && (this.serverCapabilities & CLIENT_PROTOCOL_41) != 0)) {
checkErrorPacket();
}
//
// Can't enable compression until after handshake
//
if (((this.serverCapabilities & CLIENT_COMPRESS) != 0) && this.connection.getUseCompression() && !(this.mysqlInput instanceof CompressedInputStream)) {
// The following matches with ZLIB's compress()
this.deflater = new Deflater();
this.useCompression = true;
this.mysqlInput = new CompressedInputStream(this.connection, this.mysqlInput);
}
if (!this.useConnectWithDb) {
changeDatabaseTo(database);
}
try {
this.mysqlConnection = this.socketFactory.afterHandshake();
} catch (IOException ioEx) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs, ioEx,
getExceptionInterceptor());
}
}
/**
* Contains instances of authentication plugins which implements {@link AuthenticationPlugin} interface. Key values are mysql
* protocol plugin names, for example "mysql_native_password" and
* "mysql_old_password" for built-in plugins.
*/
private Map<String, AuthenticationPlugin> authenticationPlugins = null;
/**
* Contains names of classes or mechanisms ("mysql_native_password"
* for example) of authentication plugins which must be disabled.
*/
private List<String> disabledAuthenticationPlugins = null;
/**
* Name of class for default authentication plugin in client
*/
private String clientDefaultAuthenticationPlugin = null;
/**
* Protocol name of default authentication plugin in client
*/
private String clientDefaultAuthenticationPluginName = null;
/**
* Protocol name of default authentication plugin in server
*/
private String serverDefaultAuthenticationPluginName = null;
/**
* Fill the {@link MysqlIO#authenticationPlugins} map.
* First this method fill the map with instances of {@link MysqlOldPasswordPlugin}, {@link MysqlNativePasswordPlugin}, {@link MysqlClearPasswordPlugin} and
* {@link Sha256PasswordPlugin}.
* Then it gets instances of plugins listed in "authenticationPlugins" connection property by
* {@link Util#loadExtensions(Connection, Properties, String, String, ExceptionInterceptor)} call and adds them to the map too.
*
* The key for the map entry is getted by {@link AuthenticationPlugin#getProtocolPluginName()}.
* Thus it is possible to replace built-in plugin with custom one, to do it custom plugin should return value
* "mysql_native_password", "mysql_old_password", "mysql_clear_password" or "sha256_password" from it's own getProtocolPluginName() method.
*
* All plugin instances in the map are initialized by {@link Extension#init(Connection, Properties)} call
* with this.connection and this.connection.getProperties() values.
*
* @throws SQLException
*/
private void loadAuthenticationPlugins() throws SQLException {
// default plugin
this.clientDefaultAuthenticationPlugin = this.connection.getDefaultAuthenticationPlugin();
if (this.clientDefaultAuthenticationPlugin == null || "".equals(this.clientDefaultAuthenticationPlugin.trim())) {
throw SQLError.createSQLException(
Messages.getString("Connection.BadDefaultAuthenticationPlugin", new Object[] { this.clientDefaultAuthenticationPlugin }),
getExceptionInterceptor());
}
// disabled plugins
String disabledPlugins = this.connection.getDisabledAuthenticationPlugins();
if (disabledPlugins != null && !"".equals(disabledPlugins)) {
this.disabledAuthenticationPlugins = new ArrayList<String>();
List<String> pluginsToDisable = StringUtils.split(disabledPlugins, ",", true);
Iterator<String> iter = pluginsToDisable.iterator();
while (iter.hasNext()) {
this.disabledAuthenticationPlugins.add(iter.next());
}
}
this.authenticationPlugins = new HashMap<String, AuthenticationPlugin>();
// embedded plugins
AuthenticationPlugin plugin = new MysqlOldPasswordPlugin();
plugin.init(this.connection, this.connection.getProperties());
boolean defaultIsFound = addAuthenticationPlugin(plugin);
plugin = new MysqlNativePasswordPlugin();
plugin.init(this.connection, this.connection.getProperties());
if (addAuthenticationPlugin(plugin)) {
defaultIsFound = true;
}
plugin = new MysqlClearPasswordPlugin();
plugin.init(this.connection, this.connection.getProperties());
if (addAuthenticationPlugin(plugin)) {
defaultIsFound = true;
}
plugin = new Sha256PasswordPlugin();
plugin.init(this.connection, this.connection.getProperties());
if (addAuthenticationPlugin(plugin)) {
defaultIsFound = true;
}
// plugins from authenticationPluginClasses connection parameter
String authenticationPluginClasses = this.connection.getAuthenticationPlugins();
if (authenticationPluginClasses != null && !"".equals(authenticationPluginClasses)) {
List<Extension> plugins = Util.loadExtensions(this.connection, this.connection.getProperties(), authenticationPluginClasses,
"Connection.BadAuthenticationPlugin", getExceptionInterceptor());
for (Extension object : plugins) {
plugin = (AuthenticationPlugin) object;
if (addAuthenticationPlugin(plugin)) {
defaultIsFound = true;
}
}
}
// check if default plugin is listed
if (!defaultIsFound) {
throw SQLError.createSQLException(
Messages.getString("Connection.DefaultAuthenticationPluginIsNotListed", new Object[] { this.clientDefaultAuthenticationPlugin }),
getExceptionInterceptor());
}
}
/**
* Add plugin to {@link MysqlIO#authenticationPlugins} if it is not disabled by
* "disabledAuthenticationPlugins" property, check is it a default plugin.
*
* @param plugin
* Instance of AuthenticationPlugin
* @return True if plugin is default, false if plugin is not default.
* @throws SQLException
* if plugin is default but disabled.
*/
private boolean addAuthenticationPlugin(AuthenticationPlugin plugin) throws SQLException {
boolean isDefault = false;
String pluginClassName = plugin.getClass().getName();
String pluginProtocolName = plugin.getProtocolPluginName();
boolean disabledByClassName = this.disabledAuthenticationPlugins != null && this.disabledAuthenticationPlugins.contains(pluginClassName);
boolean disabledByMechanism = this.disabledAuthenticationPlugins != null && this.disabledAuthenticationPlugins.contains(pluginProtocolName);
if (disabledByClassName || disabledByMechanism) {
// if disabled then check is it default
if (this.clientDefaultAuthenticationPlugin.equals(pluginClassName)) {
throw SQLError.createSQLException(Messages.getString("Connection.BadDisabledAuthenticationPlugin",
new Object[] { disabledByClassName ? pluginClassName : pluginProtocolName }), getExceptionInterceptor());
}
} else {
this.authenticationPlugins.put(pluginProtocolName, plugin);
if (this.clientDefaultAuthenticationPlugin.equals(pluginClassName)) {
this.clientDefaultAuthenticationPluginName = pluginProtocolName;
isDefault = true;
}
}
return isDefault;
}
/**
* Get authentication plugin instance from {@link MysqlIO#authenticationPlugins} map by
* pluginName key. If such plugin is found it's {@link AuthenticationPlugin#isReusable()} method
* is checked, when it's false this method returns a new instance of plugin
* and the same instance otherwise.
*
* If plugin is not found method returns null, in such case the subsequent behavior
* of handshake process depends on type of last packet received from server:
* if it was Auth Challenge Packet then handshake will proceed with default plugin,
* if it was Auth Method Switch Request Packet then handshake will be interrupted with exception.
*
* @param pluginName
* mysql protocol plugin names, for example "mysql_native_password" and "mysql_old_password" for built-in plugins
* @return null if plugin is not found or authentication plugin instance initialized with current connection properties
* @throws SQLException
*/
private AuthenticationPlugin getAuthenticationPlugin(String pluginName) throws SQLException {
AuthenticationPlugin plugin = this.authenticationPlugins.get(pluginName);
if (plugin != null && !plugin.isReusable()) {
try {
plugin = plugin.getClass().newInstance();
plugin.init(this.connection, this.connection.getProperties());
} catch (Throwable t) {
SQLException sqlEx = SQLError.createSQLException(
Messages.getString("Connection.BadAuthenticationPlugin", new Object[] { plugin.getClass().getName() }), getExceptionInterceptor());
sqlEx.initCause(t);
throw sqlEx;
}
}
return plugin;
}
/**
* Check if given plugin requires confidentiality, but connection is without SSL
*
* @param plugin
* @throws SQLException
*/
private void checkConfidentiality(AuthenticationPlugin plugin) throws SQLException {
if (plugin.requiresConfidentiality() && !isSSLEstablished()) {
throw SQLError.createSQLException(Messages.getString("Connection.AuthenticationPluginRequiresSSL", new Object[] { plugin.getProtocolPluginName() }),
getExceptionInterceptor());
}
}
/**
* Performs an authentication handshake to authorize connection to a
* given database as a given MySQL user. This can happen upon initial
* connection to the server, after receiving Auth Challenge Packet, or
* at any moment during the connection life-time via a Change User
* request.
*
* This method is aware of pluggable authentication and will use
* registered authentication plugins as requested by the server.
*
* @param user
* the MySQL user account to log into
* @param password
* authentication data for the user account (depends
* on authentication method used - can be empty)
* @param database
* database to connect to (can be empty)
* @param challenge
* the Auth Challenge Packet received from server if
* this method is used during the initial connection.
* Otherwise null.
*
* @throws SQLException
*/
private void proceedHandshakeWithPluggableAuthentication(String user, String password, String database, Buffer challenge) throws SQLException {
if (this.authenticationPlugins == null) {
loadAuthenticationPlugins();
}
boolean skipPassword = false;
int passwordLength = 16;
int userLength = (user != null) ? user.length() : 0;
int databaseLength = (database != null) ? database.length() : 0;
int packLength = ((userLength + passwordLength + databaseLength) * 3) + 7 + HEADER_LENGTH + AUTH_411_OVERHEAD;
AuthenticationPlugin plugin = null;
Buffer fromServer = null;
ArrayList<Buffer> toServer = new ArrayList<Buffer>();
boolean done = false;
Buffer last_sent = null;
boolean old_raw_challenge = false;
int counter = 100;
while (0 < counter--) {
if (!done) {
if (challenge != null) {
if (challenge.isOKPacket()) {
throw SQLError.createSQLException(
Messages.getString("Connection.UnexpectedAuthenticationApproval", new Object[] { plugin.getProtocolPluginName() }),
getExceptionInterceptor());
}
// read Auth Challenge Packet
this.clientParam |= CLIENT_PLUGIN_AUTH | CLIENT_LONG_PASSWORD | CLIENT_PROTOCOL_41 | CLIENT_TRANSACTIONS // Need this to get server status values
| CLIENT_MULTI_RESULTS // We always allow multiple result sets
| CLIENT_SECURE_CONNECTION; // protocol with pluggable authentication always support this
// We allow the user to configure whether or not they want to support multiple queries (by default, this is disabled).
if (this.connection.getAllowMultiQueries()) {
this.clientParam |= CLIENT_MULTI_STATEMENTS;
}
if (((this.serverCapabilities & CLIENT_CAN_HANDLE_EXPIRED_PASSWORD) != 0) && !this.connection.getDisconnectOnExpiredPasswords()) {
this.clientParam |= CLIENT_CAN_HANDLE_EXPIRED_PASSWORD;
}
if (((this.serverCapabilities & CLIENT_CONNECT_ATTRS) != 0) && !NONE.equals(this.connection.getConnectionAttributes())) {
this.clientParam |= CLIENT_CONNECT_ATTRS;
}
if ((this.serverCapabilities & CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA) != 0) {
this.clientParam |= CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA;
}
this.has41NewNewProt = true;
this.use41Extensions = true;
if (this.connection.getUseSSL()) {
negotiateSSLConnection(user, password, database, packLength);
}
String pluginName = null;
// Due to Bug#59453 the auth-plugin-name is missing the terminating NUL-char in versions prior to 5.5.10 and 5.6.2.
if ((this.serverCapabilities & CLIENT_PLUGIN_AUTH) != 0) {
if (!versionMeetsMinimum(5, 5, 10) || versionMeetsMinimum(5, 6, 0) && !versionMeetsMinimum(5, 6, 2)) {
pluginName = challenge.readString("ASCII", getExceptionInterceptor(), this.authPluginDataLength);
} else {
pluginName = challenge.readString("ASCII", getExceptionInterceptor());
}
}
plugin = getAuthenticationPlugin(pluginName);
if (plugin == null) {
/*
* Use default if there is no plugin for pluginName.
*/
plugin = getAuthenticationPlugin(this.clientDefaultAuthenticationPluginName);
} else if (pluginName.equals(Sha256PasswordPlugin.PLUGIN_NAME) && !isSSLEstablished() && this.connection.getServerRSAPublicKeyFile() == null
&& !this.connection.getAllowPublicKeyRetrieval()) {
/*
* Fall back to default if plugin is 'sha256_password' but required conditions for this to work aren't met. If default is other than
* 'sha256_password' this will result in an immediate authentication switch request, allowing for other plugins to authenticate
* successfully. If default is 'sha256_password' then the authentication will fail as expected. In both cases user's password won't be
* sent to avoid subjecting it to lesser security levels.
*/
plugin = getAuthenticationPlugin(this.clientDefaultAuthenticationPluginName);
skipPassword = !this.clientDefaultAuthenticationPluginName.equals(pluginName);
}
this.serverDefaultAuthenticationPluginName = plugin.getProtocolPluginName();
checkConfidentiality(plugin);
fromServer = new Buffer(StringUtils.getBytes(this.seed));
} else {
// no challenge so this is a changeUser call
plugin = getAuthenticationPlugin(this.serverDefaultAuthenticationPluginName == null ? this.clientDefaultAuthenticationPluginName
: this.serverDefaultAuthenticationPluginName);
checkConfidentiality(plugin);
// Servers not affected by Bug#70865 expect the Change User Request containing a correct answer
// to seed sent by the server during the initial handshake, thus we reuse it here.
// Servers affected by Bug#70865 will just ignore it and send the Auth Switch.
fromServer = new Buffer(StringUtils.getBytes(this.seed));
}
} else {
// read packet from server and check if it's an ERROR packet
challenge = checkErrorPacket();
old_raw_challenge = false;
this.packetSequence++;
this.compressedPacketSequence++;
if (plugin == null) {
// this shouldn't happen in normal handshake packets exchange,
// we do it just to ensure that we don't get NPE in other case
plugin = getAuthenticationPlugin(this.serverDefaultAuthenticationPluginName != null ? this.serverDefaultAuthenticationPluginName
: this.clientDefaultAuthenticationPluginName);
}
if (challenge.isOKPacket()) {
// get the server status from the challenge packet.
challenge.newReadLength(); // affected_rows
challenge.newReadLength(); // last_insert_id
this.oldServerStatus = this.serverStatus;
this.serverStatus = challenge.readInt();
// if OK packet then finish handshake
plugin.destroy();
break;
} else if (challenge.isAuthMethodSwitchRequestPacket()) {
skipPassword = false;
// read Auth Method Switch Request Packet
String pluginName = challenge.readString("ASCII", getExceptionInterceptor());
// get new plugin
if (!plugin.getProtocolPluginName().equals(pluginName)) {
plugin.destroy();
plugin = getAuthenticationPlugin(pluginName);
// if plugin is not found for pluginName throw exception
if (plugin == null) {
throw SQLError.createSQLException(Messages.getString("Connection.BadAuthenticationPlugin", new Object[] { pluginName }),
getExceptionInterceptor());
}
}
checkConfidentiality(plugin);
fromServer = new Buffer(StringUtils.getBytes(challenge.readString("ASCII", getExceptionInterceptor())));
} else {
// read raw packet
if (versionMeetsMinimum(5, 5, 16)) {
fromServer = new Buffer(challenge.getBytes(challenge.getPosition(), challenge.getBufLength() - challenge.getPosition()));
} else {
old_raw_challenge = true;
fromServer = new Buffer(challenge.getBytes(challenge.getPosition() - 1, challenge.getBufLength() - challenge.getPosition() + 1));
}
}
}
// call plugin
try {
plugin.setAuthenticationParameters(user, skipPassword ? null : password);
done = plugin.nextAuthenticationStep(fromServer, toServer);
} catch (SQLException e) {
throw SQLError.createSQLException(e.getMessage(), e.getSQLState(), e, getExceptionInterceptor());
}
// send response
if (toServer.size() > 0) {
if (challenge == null) {
String enc = getEncodingForHandshake();
// write COM_CHANGE_USER Packet
last_sent = new Buffer(packLength + 1);
last_sent.writeByte((byte) MysqlDefs.COM_CHANGE_USER);
// User/Password data
last_sent.writeString(user, enc, this.connection);
// 'auth-response-len' is limited to one Byte but, in case of success, COM_CHANGE_USER will be followed by an AuthSwitchRequest anyway
if (toServer.get(0).getBufLength() < 256) {
// non-mysql servers may use this information to authenticate without requiring another round-trip
last_sent.writeByte((byte) toServer.get(0).getBufLength());
last_sent.writeBytesNoNull(toServer.get(0).getByteBuffer(), 0, toServer.get(0).getBufLength());
} else {
last_sent.writeByte((byte) 0);
}
if (this.useConnectWithDb) {
last_sent.writeString(database, enc, this.connection);
} else {
/* For empty database */
last_sent.writeByte((byte) 0);
}
appendCharsetByteForHandshake(last_sent, enc);
// two (little-endian) bytes for charset in this packet
last_sent.writeByte((byte) 0);
// plugin name
if ((this.serverCapabilities & CLIENT_PLUGIN_AUTH) != 0) {
last_sent.writeString(plugin.getProtocolPluginName(), enc, this.connection);
}
// connection attributes
if ((this.clientParam & CLIENT_CONNECT_ATTRS) != 0) {
sendConnectionAttributes(last_sent, enc, this.connection);
last_sent.writeByte((byte) 0);
}
send(last_sent, last_sent.getPosition());
} else if (challenge.isAuthMethodSwitchRequestPacket()) {
// write Auth Method Switch Response Packet
last_sent = new Buffer(toServer.get(0).getBufLength() + HEADER_LENGTH);
last_sent.writeBytesNoNull(toServer.get(0).getByteBuffer(), 0, toServer.get(0).getBufLength());
send(last_sent, last_sent.getPosition());
} else if (challenge.isRawPacket() || old_raw_challenge) {
// write raw packet(s)
for (Buffer buffer : toServer) {
last_sent = new Buffer(buffer.getBufLength() + HEADER_LENGTH);
last_sent.writeBytesNoNull(buffer.getByteBuffer(), 0, toServer.get(0).getBufLength());
send(last_sent, last_sent.getPosition());
}
} else {
// write Auth Response Packet
String enc = getEncodingForHandshake();
last_sent = new Buffer(packLength);
last_sent.writeLong(this.clientParam);
last_sent.writeLong(this.maxThreeBytes);
appendCharsetByteForHandshake(last_sent, enc);
last_sent.writeBytesNoNull(new byte[23]); // Set of bytes reserved for future use.
// User/Password data
last_sent.writeString(user, enc, this.connection);
if ((this.serverCapabilities & CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA) != 0) {
// send lenenc-int length of auth-response and string[n] auth-response
last_sent.writeLenBytes(toServer.get(0).getBytes(toServer.get(0).getBufLength()));
} else {
// send 1 byte length of auth-response and string[n] auth-response
last_sent.writeByte((byte) toServer.get(0).getBufLength());
last_sent.writeBytesNoNull(toServer.get(0).getByteBuffer(), 0, toServer.get(0).getBufLength());
}
if (this.useConnectWithDb) {
last_sent.writeString(database, enc, this.connection);
} else {
/* For empty database */
last_sent.writeByte((byte) 0);
}
if ((this.serverCapabilities & CLIENT_PLUGIN_AUTH) != 0) {
last_sent.writeString(plugin.getProtocolPluginName(), enc, this.connection);
}
// connection attributes
if (((this.clientParam & CLIENT_CONNECT_ATTRS) != 0)) {
sendConnectionAttributes(last_sent, enc, this.connection);
}
send(last_sent, last_sent.getPosition());
}
}
}
if (counter == 0) {
throw SQLError.createSQLException(Messages.getString("CommunicationsException.TooManyAuthenticationPluginNegotiations"), getExceptionInterceptor());
}
//
// Can't enable compression until after handshake
//
if (((this.serverCapabilities & CLIENT_COMPRESS) != 0) && this.connection.getUseCompression() && !(this.mysqlInput instanceof CompressedInputStream)) {
// The following matches with ZLIB's compress()
this.deflater = new Deflater();
this.useCompression = true;
this.mysqlInput = new CompressedInputStream(this.connection, this.mysqlInput);
}
if (!this.useConnectWithDb) {
changeDatabaseTo(database);
}
try {
this.mysqlConnection = this.socketFactory.afterHandshake();
} catch (IOException ioEx) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs, ioEx,
getExceptionInterceptor());
}
}
private Properties getConnectionAttributesAsProperties(String atts) throws SQLException {
Properties props = new Properties();
if (atts != null) {
String[] pairs = atts.split(",");
for (String pair : pairs) {
int keyEnd = pair.indexOf(":");
if (keyEnd > 0 && (keyEnd + 1) < pair.length()) {
props.setProperty(pair.substring(0, keyEnd), pair.substring(keyEnd + 1));
}
}
}
// Leaving disabled until standard values are defined
// props.setProperty("_os", NonRegisteringDriver.OS);
// props.setProperty("_platform", NonRegisteringDriver.PLATFORM);
props.setProperty("_client_name", NonRegisteringDriver.NAME);
props.setProperty("_client_version", NonRegisteringDriver.VERSION);
props.setProperty("_runtime_vendor", NonRegisteringDriver.RUNTIME_VENDOR);
props.setProperty("_runtime_version", NonRegisteringDriver.RUNTIME_VERSION);
props.setProperty("_client_license", NonRegisteringDriver.LICENSE);
return props;
}
private void sendConnectionAttributes(Buffer buf, String enc, MySQLConnection conn) throws SQLException {
String atts = conn.getConnectionAttributes();
Buffer lb = new Buffer(100);
try {
Properties props = getConnectionAttributesAsProperties(atts);
for (Object key : props.keySet()) {
lb.writeLenString((String) key, enc, conn.getServerCharset(), null, conn.parserKnowsUnicode(), conn);
lb.writeLenString(props.getProperty((String) key), enc, conn.getServerCharset(), null, conn.parserKnowsUnicode(), conn);
}
} catch (UnsupportedEncodingException e) {
}
buf.writeByte((byte) (lb.getPosition() - 4));
buf.writeBytesNoNull(lb.getByteBuffer(), 4, lb.getBufLength() - 4);
}
private void changeDatabaseTo(String database) throws SQLException {
if (database == null || database.length() == 0) {
return;
}
try {
sendCommand(MysqlDefs.INIT_DB, database, null, false, null, 0);
} catch (Exception ex) {
if (this.connection.getCreateDatabaseIfNotExist()) {
sendCommand(MysqlDefs.QUERY, "CREATE DATABASE IF NOT EXISTS " + database, null, false, null, 0);
sendCommand(MysqlDefs.INIT_DB, database, null, false, null, 0);
} else {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs, ex,
getExceptionInterceptor());
}
}
}
/**
* Retrieve one row from the MySQL server. Note: this method is not
* thread-safe, but it is only called from methods that are guarded by
* synchronizing on this object.
*
* @param fields
* @param columnCount
* @param isBinaryEncoded
* @param resultSetConcurrency
* @param b
*
* @throws SQLException
*/
final ResultSetRow nextRow(Field[] fields, int columnCount, boolean isBinaryEncoded, int resultSetConcurrency, boolean useBufferRowIfPossible,
boolean useBufferRowExplicit, boolean canReuseRowPacketForBufferRow, Buffer existingRowPacket) throws SQLException {
if (this.useDirectRowUnpack && existingRowPacket == null && !isBinaryEncoded && !useBufferRowIfPossible && !useBufferRowExplicit) {
return nextRowFast(fields, columnCount, isBinaryEncoded, resultSetConcurrency, useBufferRowIfPossible, useBufferRowExplicit,
canReuseRowPacketForBufferRow);
}
Buffer rowPacket = null;
if (existingRowPacket == null) {
rowPacket = checkErrorPacket();
if (!useBufferRowExplicit && useBufferRowIfPossible) {
if (rowPacket.getBufLength() > this.useBufferRowSizeThreshold) {
useBufferRowExplicit = true;
}
}
} else {
// We attempted to do nextRowFast(), but the packet was a multipacket, so we couldn't unpack it directly
rowPacket = existingRowPacket;
checkErrorPacket(existingRowPacket);
}
if (!isBinaryEncoded) {
//
// Didn't read an error, so re-position to beginning of packet in order to read result set data
//
rowPacket.setPosition(rowPacket.getPosition() - 1);
if (!(!isEOFDeprecated() && rowPacket.isEOFPacket() || isEOFDeprecated() && rowPacket.isResultSetOKPacket())) {
if (resultSetConcurrency == ResultSet.CONCUR_UPDATABLE || (!useBufferRowIfPossible && !useBufferRowExplicit)) {
byte[][] rowData = new byte[columnCount][];
for (int i = 0; i < columnCount; i++) {
rowData[i] = rowPacket.readLenByteArray(0);
}
return new ByteArrayRow(rowData, getExceptionInterceptor());
}
if (!canReuseRowPacketForBufferRow) {
this.reusablePacket = new Buffer(rowPacket.getBufLength());
}
return new BufferRow(rowPacket, fields, false, getExceptionInterceptor());
}
readServerStatusForResultSets(rowPacket);
return null;
}
//
// Handle binary-encoded data for server-side PreparedStatements...
//
if (!(!isEOFDeprecated() && rowPacket.isEOFPacket() || isEOFDeprecated() && rowPacket.isResultSetOKPacket())) {
if (resultSetConcurrency == ResultSet.CONCUR_UPDATABLE || (!useBufferRowIfPossible && !useBufferRowExplicit)) {
return unpackBinaryResultSetRow(fields, rowPacket, resultSetConcurrency);
}
if (!canReuseRowPacketForBufferRow) {
this.reusablePacket = new Buffer(rowPacket.getBufLength());
}
return new BufferRow(rowPacket, fields, true, getExceptionInterceptor());
}
rowPacket.setPosition(rowPacket.getPosition() - 1);
readServerStatusForResultSets(rowPacket);
return null;
}
final ResultSetRow nextRowFast(Field[] fields, int columnCount, boolean isBinaryEncoded, int resultSetConcurrency, boolean useBufferRowIfPossible,
boolean useBufferRowExplicit, boolean canReuseRowPacket) throws SQLException {
try {
int lengthRead = readFully(this.mysqlInput, this.packetHeaderBuf, 0, 4);
if (lengthRead < 4) {
forceClose();
throw new RuntimeException(Messages.getString("MysqlIO.43"));
}
int packetLength = (this.packetHeaderBuf[0] & 0xff) + ((this.packetHeaderBuf[1] & 0xff) << 8) + ((this.packetHeaderBuf[2] & 0xff) << 16);
// Have we stumbled upon a multi-packet?
if (packetLength == this.maxThreeBytes) {
reuseAndReadPacket(this.reusablePacket, packetLength);
// Go back to "old" way which uses packets
return nextRow(fields, columnCount, isBinaryEncoded, resultSetConcurrency, useBufferRowIfPossible, useBufferRowExplicit, canReuseRowPacket,
this.reusablePacket);
}
// Does this go over the threshold where we should use a BufferRow?
if (packetLength > this.useBufferRowSizeThreshold) {
reuseAndReadPacket(this.reusablePacket, packetLength);
// Go back to "old" way which uses packets
return nextRow(fields, columnCount, isBinaryEncoded, resultSetConcurrency, true, true, false, this.reusablePacket);
}
int remaining = packetLength;
boolean firstTime = true;
byte[][] rowData = null;
for (int i = 0; i < columnCount; i++) {
int sw = this.mysqlInput.read() & 0xff;
remaining--;
if (firstTime) {
if (sw == Buffer.TYPE_ID_ERROR) {
// error packet - we assemble it whole for "fidelity" in case we ever need an entire packet in checkErrorPacket() but we could've gotten
// away with just writing the error code and message in it (for now).
Buffer errorPacket = new Buffer(packetLength + HEADER_LENGTH);
errorPacket.setPosition(0);
errorPacket.writeByte(this.packetHeaderBuf[0]);
errorPacket.writeByte(this.packetHeaderBuf[1]);
errorPacket.writeByte(this.packetHeaderBuf[2]);
errorPacket.writeByte((byte) 1);
errorPacket.writeByte((byte) sw);
readFully(this.mysqlInput, errorPacket.getByteBuffer(), 5, packetLength - 1);
errorPacket.setPosition(4);
checkErrorPacket(errorPacket);
}
if (sw == Buffer.TYPE_ID_EOF && packetLength < 16777215) {
// Both EOF and OK packets have the same 0xfe signature in result sets.
// OK packet length limit restricted to MAX_PACKET_LENGTH value (256L*256L*256L-1) as any length greater
// than this value will have first byte of OK packet to be 254 thus does not provide a means to identify
// if this is OK or EOF packet.
// Thus we need to check the packet length to distinguish between OK packet and ResultsetRow packet starting with 0xfe
if (this.use41Extensions) {
if (isEOFDeprecated()) {
// read OK packet
remaining -= skipLengthEncodedInteger(this.mysqlInput); // affected_rows
remaining -= skipLengthEncodedInteger(this.mysqlInput); // last_insert_id
this.oldServerStatus = this.serverStatus;
this.serverStatus = (this.mysqlInput.read() & 0xff) | ((this.mysqlInput.read() & 0xff) << 8);
checkTransactionState(this.oldServerStatus);
remaining -= 2;
this.warningCount = (this.mysqlInput.read() & 0xff) | ((this.mysqlInput.read() & 0xff) << 8);
remaining -= 2;
if (this.warningCount > 0) {
this.hadWarnings = true; // this is a 'latch', it's reset by sendCommand()
}
} else {
// read EOF packet
this.warningCount = (this.mysqlInput.read() & 0xff) | ((this.mysqlInput.read() & 0xff) << 8);
remaining -= 2;
if (this.warningCount > 0) {
this.hadWarnings = true; // this is a 'latch', it's reset by sendCommand()
}
this.oldServerStatus = this.serverStatus;
this.serverStatus = (this.mysqlInput.read() & 0xff) | ((this.mysqlInput.read() & 0xff) << 8);
checkTransactionState(this.oldServerStatus);
remaining -= 2;
}
setServerSlowQueryFlags();
if (remaining > 0) {
skipFully(this.mysqlInput, remaining);
}
}
return null; // last data packet
}
rowData = new byte[columnCount][];
firstTime = false;
}
int len = 0;
switch (sw) {
case 251:
len = NULL_LENGTH;
break;
case 252:
len = (this.mysqlInput.read() & 0xff) | ((this.mysqlInput.read() & 0xff) << 8);
remaining -= 2;
break;
case 253:
len = (this.mysqlInput.read() & 0xff) | ((this.mysqlInput.read() & 0xff) << 8) | ((this.mysqlInput.read() & 0xff) << 16);
remaining -= 3;
break;
case 254:
len = (int) ((this.mysqlInput.read() & 0xff) | ((long) (this.mysqlInput.read() & 0xff) << 8)
| ((long) (this.mysqlInput.read() & 0xff) << 16) | ((long) (this.mysqlInput.read() & 0xff) << 24)
| ((long) (this.mysqlInput.read() & 0xff) << 32) | ((long) (this.mysqlInput.read() & 0xff) << 40)
| ((long) (this.mysqlInput.read() & 0xff) << 48) | ((long) (this.mysqlInput.read() & 0xff) << 56));
remaining -= 8;
break;
default:
len = sw;
}
if (len == NULL_LENGTH) {
rowData[i] = null;
} else if (len == 0) {
rowData[i] = Constants.EMPTY_BYTE_ARRAY;
} else {
rowData[i] = new byte[len];
int bytesRead = readFully(this.mysqlInput, rowData[i], 0, len);
if (bytesRead != len) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs,
new IOException(Messages.getString("MysqlIO.43")), getExceptionInterceptor());
}
remaining -= bytesRead;
}
}
if (remaining > 0) {
skipFully(this.mysqlInput, remaining);
}
return new ByteArrayRow(rowData, getExceptionInterceptor());
} catch (IOException ioEx) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs, ioEx,
getExceptionInterceptor());
}
}
/**
* Log-off of the MySQL server and close the socket.
*
* @throws SQLException
*/
final void quit() throws SQLException {
try {
// we're not going to read the response, fixes BUG#56979 Improper connection closing logic leads to TIME_WAIT sockets on server
try {
if (!this.mysqlConnection.isClosed()) {
try {
this.mysqlConnection.shutdownInput();
} catch (UnsupportedOperationException ex) {
// ignore, some sockets do not support this method
}
}
} catch (IOException ioEx) {
this.connection.getLog().logWarn("Caught while disconnecting...", ioEx);
}
Buffer packet = new Buffer(6);
this.packetSequence = -1;
this.compressedPacketSequence = -1;
packet.writeByte((byte) MysqlDefs.QUIT);
send(packet, packet.getPosition());
} finally {
forceClose();
}
}
/**
* Returns the packet used for sending data (used by PreparedStatement)
* Guarded by external synchronization on a mutex.
*
* @return A packet to send data with
*/
Buffer getSharedSendPacket() {
if (this.sharedSendPacket == null) {
this.sharedSendPacket = new Buffer(INITIAL_PACKET_SIZE);
}
return this.sharedSendPacket;
}
void closeStreamer(RowData streamer) throws SQLException {
if (this.streamingData == null) {
throw SQLError.createSQLException(Messages.getString("MysqlIO.17") + streamer + Messages.getString("MysqlIO.18"), getExceptionInterceptor());
}
if (streamer != this.streamingData) {
throw SQLError.createSQLException(Messages.getString("MysqlIO.19") + streamer + Messages.getString("MysqlIO.20") + Messages.getString("MysqlIO.21")
+ Messages.getString("MysqlIO.22"), getExceptionInterceptor());
}
this.streamingData = null;
}
boolean tackOnMoreStreamingResults(ResultSetImpl addingTo) throws SQLException {
if ((this.serverStatus & SERVER_MORE_RESULTS_EXISTS) != 0) {
boolean moreRowSetsExist = true;
ResultSetImpl currentResultSet = addingTo;
boolean firstTime = true;
while (moreRowSetsExist) {
if (!firstTime && currentResultSet.reallyResult()) {
break;
}
firstTime = false;
Buffer fieldPacket = checkErrorPacket();
fieldPacket.setPosition(0);
java.sql.Statement owningStatement = addingTo.getStatement();
int maxRows = owningStatement.getMaxRows();
// fixme for catalog, isBinary
ResultSetImpl newResultSet = readResultsForQueryOrUpdate((StatementImpl) owningStatement, maxRows, owningStatement.getResultSetType(),
owningStatement.getResultSetConcurrency(), true, owningStatement.getConnection().getCatalog(), fieldPacket, addingTo.isBinaryEncoded,
-1L, null);
currentResultSet.setNextResultSet(newResultSet);
currentResultSet = newResultSet;
moreRowSetsExist = (this.serverStatus & MysqlIO.SERVER_MORE_RESULTS_EXISTS) != 0;
if (!currentResultSet.reallyResult() && !moreRowSetsExist) {
// special case, we can stop "streaming"
return false;
}
}
return true;
}
return false;
}
ResultSetImpl readAllResults(StatementImpl callingStatement, int maxRows, int resultSetType, int resultSetConcurrency, boolean streamResults,
String catalog, Buffer resultPacket, boolean isBinaryEncoded, long preSentColumnCount, Field[] metadataFromCache) throws SQLException {
resultPacket.setPosition(resultPacket.getPosition() - 1);
ResultSetImpl topLevelResultSet = readResultsForQueryOrUpdate(callingStatement, maxRows, resultSetType, resultSetConcurrency, streamResults, catalog,
resultPacket, isBinaryEncoded, preSentColumnCount, metadataFromCache);
ResultSetImpl currentResultSet = topLevelResultSet;
boolean checkForMoreResults = ((this.clientParam & CLIENT_MULTI_RESULTS) != 0);
boolean serverHasMoreResults = (this.serverStatus & SERVER_MORE_RESULTS_EXISTS) != 0;
//
// TODO: We need to support streaming of multiple result sets
//
if (serverHasMoreResults && streamResults) {
//clearInputStream();
//
//throw SQLError.createSQLException(Messages.getString("MysqlIO.23"),
//SQLError.SQL_STATE_DRIVER_NOT_CAPABLE);
if (topLevelResultSet.getUpdateCount() != -1) {
tackOnMoreStreamingResults(topLevelResultSet);
}
reclaimLargeReusablePacket();
return topLevelResultSet;
}
boolean moreRowSetsExist = checkForMoreResults & serverHasMoreResults;
while (moreRowSetsExist) {
Buffer fieldPacket = checkErrorPacket();
fieldPacket.setPosition(0);
ResultSetImpl newResultSet = readResultsForQueryOrUpdate(callingStatement, maxRows, resultSetType, resultSetConcurrency, streamResults, catalog,
fieldPacket, isBinaryEncoded, preSentColumnCount, metadataFromCache);
currentResultSet.setNextResultSet(newResultSet);
currentResultSet = newResultSet;
moreRowSetsExist = (this.serverStatus & SERVER_MORE_RESULTS_EXISTS) != 0;
}
if (!streamResults) {
clearInputStream();
}
reclaimLargeReusablePacket();
return topLevelResultSet;
}
/**
* Sets the buffer size to max-buf
*/
void resetMaxBuf() {
this.maxAllowedPacket = this.connection.getMaxAllowedPacket();
}
/**
* Send a command to the MySQL server If data is to be sent with command,
* it should be put in extraData.
*
* Raw packets can be sent by setting queryPacket to something other
* than null.
*
* @param command
* the MySQL protocol 'command' from MysqlDefs
* @param extraData
* any 'string' data for the command
* @param queryPacket
* a packet pre-loaded with data for the protocol (i.e.
* from a client-side prepared statement).
* @param skipCheck
* do not call checkErrorPacket() if true
* @param extraDataCharEncoding
* the character encoding of the extraData
* parameter.
*
* @return the response packet from the server
*
* @throws SQLException
* if an I/O error or SQL error occurs
*/
final Buffer sendCommand(int command, String extraData, Buffer queryPacket, boolean skipCheck, String extraDataCharEncoding, int timeoutMillis)
throws SQLException {
this.commandCount++;
//
// We cache these locally, per-command, as the checks for them are in very 'hot' sections of the I/O code and we save 10-15% in overall performance by
// doing this...
//
this.enablePacketDebug = this.connection.getEnablePacketDebug();
this.readPacketSequence = 0;
int oldTimeout = 0;
if (timeoutMillis != 0) {
try {
oldTimeout = this.mysqlConnection.getSoTimeout();
this.mysqlConnection.setSoTimeout(timeoutMillis);
} catch (SocketException e) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs, e,
getExceptionInterceptor());
}
}
try {
checkForOutstandingStreamingData();
// Clear serverStatus...this value is guarded by an external mutex, as you can only ever be processing one command at a time
this.oldServerStatus = this.serverStatus;
this.serverStatus = 0;
this.hadWarnings = false;
this.warningCount = 0;
this.queryNoIndexUsed = false;
this.queryBadIndexUsed = false;
this.serverQueryWasSlow = false;
//
// Compressed input stream needs cleared at beginning of each command execution...
//
if (this.useCompression) {
int bytesLeft = this.mysqlInput.available();
if (bytesLeft > 0) {
this.mysqlInput.skip(bytesLeft);
}
}
try {
clearInputStream();
//
// PreparedStatements construct their own packets, for efficiency's sake.
//
// If this is a generic query, we need to re-use the sending packet.
//
if (queryPacket == null) {
int packLength = HEADER_LENGTH + COMP_HEADER_LENGTH + 1 + ((extraData != null) ? extraData.length() : 0) + 2;
if (this.sendPacket == null) {
this.sendPacket = new Buffer(packLength);
}
this.packetSequence = -1;
this.compressedPacketSequence = -1;
this.readPacketSequence = 0;
this.checkPacketSequence = true;
this.sendPacket.clear();
this.sendPacket.writeByte((byte) command);
if ((command == MysqlDefs.INIT_DB) || (command == MysqlDefs.QUERY) || (command == MysqlDefs.COM_PREPARE)) {
if (extraDataCharEncoding == null) {
this.sendPacket.writeStringNoNull(extraData);
} else {
this.sendPacket.writeStringNoNull(extraData, extraDataCharEncoding, this.connection.getServerCharset(),
this.connection.parserKnowsUnicode(), this.connection);
}
}
send(this.sendPacket, this.sendPacket.getPosition());
} else {
this.packetSequence = -1;
this.compressedPacketSequence = -1;
send(queryPacket, queryPacket.getPosition()); // packet passed by PreparedStatement
}
} catch (SQLException sqlEx) {
// don't wrap SQLExceptions
throw sqlEx;
} catch (Exception ex) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs, ex,
getExceptionInterceptor());
}
Buffer returnPacket = null;
if (!skipCheck) {
if ((command == MysqlDefs.COM_EXECUTE) || (command == MysqlDefs.COM_RESET_STMT)) {
this.readPacketSequence = 0;
this.packetSequenceReset = true;
}
returnPacket = checkErrorPacket(command);
}
return returnPacket;
} catch (IOException ioEx) {
preserveOldTransactionState();
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs, ioEx,
getExceptionInterceptor());
} catch (SQLException e) {
preserveOldTransactionState();
throw e;
} finally {
if (timeoutMillis != 0) {
try {
this.mysqlConnection.setSoTimeout(oldTimeout);
} catch (SocketException e) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs, e,
getExceptionInterceptor());
}
}
}
}
private int statementExecutionDepth = 0;
private boolean useAutoSlowLog;
protected boolean shouldIntercept() {
return this.statementInterceptors != null;
}
/**
* Send a query stored in a packet directly to the server.
*
* @param callingStatement
* @param resultSetConcurrency
* @param characterEncoding
* @param queryPacket
* @param maxRows
* @param conn
* @param resultSetType
* @param resultSetConcurrency
* @param streamResults
* @param catalog
* @param unpackFieldInfo
* should we read MYSQL_FIELD info (if available)?
*
* @throws Exception
*/
final ResultSetInternalMethods sqlQueryDirect(StatementImpl callingStatement, String query, String characterEncoding, Buffer queryPacket, int maxRows,
int resultSetType, int resultSetConcurrency, boolean streamResults, String catalog, Field[] cachedMetadata) throws Exception {
this.statementExecutionDepth++;
try {
if (this.statementInterceptors != null) {
ResultSetInternalMethods interceptedResults = invokeStatementInterceptorsPre(query, callingStatement, false);
if (interceptedResults != null) {
return interceptedResults;
}
}
long queryStartTime = 0;
long queryEndTime = 0;
String statementComment = this.connection.getStatementComment();
if (this.connection.getIncludeThreadNamesAsStatementComment()) {
statementComment = (statementComment != null ? statementComment + ", " : "") + "java thread: " + Thread.currentThread().getName();
}
if (query != null) {
// We don't know exactly how many bytes we're going to get from the query. Since we're dealing with Unicode, the max is 2, so pad it
// (2 * query) + space for headers
int packLength = HEADER_LENGTH + 1 + (query.length() * 3) + 2;
byte[] commentAsBytes = null;
if (statementComment != null) {
commentAsBytes = StringUtils.getBytes(statementComment, null, characterEncoding, this.connection.getServerCharset(),
this.connection.parserKnowsUnicode(), getExceptionInterceptor());
packLength += commentAsBytes.length;
packLength += 6; // for /*[space] [space]*/
}
if (this.sendPacket == null) {
this.sendPacket = new Buffer(packLength);
} else {
this.sendPacket.clear();
}
this.sendPacket.writeByte((byte) MysqlDefs.QUERY);
if (commentAsBytes != null) {
this.sendPacket.writeBytesNoNull(Constants.SLASH_STAR_SPACE_AS_BYTES);
this.sendPacket.writeBytesNoNull(commentAsBytes);
this.sendPacket.writeBytesNoNull(Constants.SPACE_STAR_SLASH_SPACE_AS_BYTES);
}
if (characterEncoding != null) {
if (this.platformDbCharsetMatches) {
this.sendPacket.writeStringNoNull(query, characterEncoding, this.connection.getServerCharset(), this.connection.parserKnowsUnicode(),
this.connection);
} else {
if (StringUtils.startsWithIgnoreCaseAndWs(query, "LOAD DATA")) {
this.sendPacket.writeBytesNoNull(StringUtils.getBytes(query));
} else {
this.sendPacket.writeStringNoNull(query, characterEncoding, this.connection.getServerCharset(),
this.connection.parserKnowsUnicode(), this.connection);
}
}
} else {
this.sendPacket.writeStringNoNull(query);
}
queryPacket = this.sendPacket;
}
byte[] queryBuf = null;
int oldPacketPosition = 0;
if (this.needToGrabQueryFromPacket) {
queryBuf = queryPacket.getByteBuffer();
// save the packet position
oldPacketPosition = queryPacket.getPosition();
queryStartTime = getCurrentTimeNanosOrMillis();
}
if (this.autoGenerateTestcaseScript) {
String testcaseQuery = null;
if (query != null) {
if (statementComment != null) {
testcaseQuery = "/* " + statementComment + " */ " + query;
} else {
testcaseQuery = query;
}
} else {
testcaseQuery = StringUtils.toString(queryBuf, 5, (oldPacketPosition - 5));
}
StringBuilder debugBuf = new StringBuilder(testcaseQuery.length() + 32);
this.connection.generateConnectionCommentBlock(debugBuf);
debugBuf.append(testcaseQuery);
debugBuf.append(';');
this.connection.dumpTestcaseQuery(debugBuf.toString());
}
// Send query command and sql query string
Buffer resultPacket = sendCommand(MysqlDefs.QUERY, null, queryPacket, false, null, 0);
long fetchBeginTime = 0;
long fetchEndTime = 0;
String profileQueryToLog = null;
boolean queryWasSlow = false;
if (this.profileSql || this.logSlowQueries) {
queryEndTime = getCurrentTimeNanosOrMillis();
boolean shouldExtractQuery = false;
if (this.profileSql) {
shouldExtractQuery = true;
} else if (this.logSlowQueries) {
long queryTime = queryEndTime - queryStartTime;
boolean logSlow = false;
if (!this.useAutoSlowLog) {
logSlow = queryTime > this.connection.getSlowQueryThresholdMillis();
} else {
logSlow = this.connection.isAbonormallyLongQuery(queryTime);
this.connection.reportQueryTime(queryTime);
}
if (logSlow) {
shouldExtractQuery = true;
queryWasSlow = true;
}
}
if (shouldExtractQuery) {
// Extract the actual query from the network packet
boolean truncated = false;
int extractPosition = oldPacketPosition;
if (oldPacketPosition > this.connection.getMaxQuerySizeToLog()) {
extractPosition = this.connection.getMaxQuerySizeToLog() + 5;
truncated = true;
}
profileQueryToLog = StringUtils.toString(queryBuf, 5, (extractPosition - 5));
if (truncated) {
profileQueryToLog += Messages.getString("MysqlIO.25");
}
}
fetchBeginTime = queryEndTime;
}
ResultSetInternalMethods rs = readAllResults(callingStatement, maxRows, resultSetType, resultSetConcurrency, streamResults, catalog, resultPacket,
false, -1L, cachedMetadata);
if (queryWasSlow && !this.serverQueryWasSlow /* don't log slow queries twice */) {
StringBuilder mesgBuf = new StringBuilder(48 + profileQueryToLog.length());
mesgBuf.append(Messages.getString("MysqlIO.SlowQuery",
new Object[] { String.valueOf(this.useAutoSlowLog ? " 95% of all queries " : this.slowQueryThreshold), this.queryTimingUnits,
Long.valueOf(queryEndTime - queryStartTime) }));
mesgBuf.append(profileQueryToLog);
ProfilerEventHandler eventSink = ProfilerEventHandlerFactory.getInstance(this.connection);
eventSink.consumeEvent(new ProfilerEvent(ProfilerEvent.TYPE_SLOW_QUERY, "", catalog, this.connection.getId(),
(callingStatement != null) ? callingStatement.getId() : 999, ((ResultSetImpl) rs).resultId, System.currentTimeMillis(),
(int) (queryEndTime - queryStartTime), this.queryTimingUnits, null, LogUtils.findCallingClassAndMethod(new Throwable()),
mesgBuf.toString()));
if (this.connection.getExplainSlowQueries()) {
if (oldPacketPosition < MAX_QUERY_SIZE_TO_EXPLAIN) {
explainSlowQuery(queryPacket.getBytes(5, (oldPacketPosition - 5)), profileQueryToLog);
} else {
this.connection.getLog().logWarn(Messages.getString("MysqlIO.28") + MAX_QUERY_SIZE_TO_EXPLAIN + Messages.getString("MysqlIO.29"));
}
}
}
if (this.logSlowQueries) {
ProfilerEventHandler eventSink = ProfilerEventHandlerFactory.getInstance(this.connection);
if (this.queryBadIndexUsed && this.profileSql) {
eventSink.consumeEvent(new ProfilerEvent(ProfilerEvent.TYPE_SLOW_QUERY, "", catalog, this.connection.getId(),
(callingStatement != null) ? callingStatement.getId() : 999, ((ResultSetImpl) rs).resultId, System.currentTimeMillis(),
(queryEndTime - queryStartTime), this.queryTimingUnits, null, LogUtils.findCallingClassAndMethod(new Throwable()),
Messages.getString("MysqlIO.33") + profileQueryToLog));
}
if (this.queryNoIndexUsed && this.profileSql) {
eventSink.consumeEvent(new ProfilerEvent(ProfilerEvent.TYPE_SLOW_QUERY, "", catalog, this.connection.getId(),
(callingStatement != null) ? callingStatement.getId() : 999, ((ResultSetImpl) rs).resultId, System.currentTimeMillis(),
(queryEndTime - queryStartTime), this.queryTimingUnits, null, LogUtils.findCallingClassAndMethod(new Throwable()),
Messages.getString("MysqlIO.35") + profileQueryToLog));
}
if (this.serverQueryWasSlow && this.profileSql) {
eventSink.consumeEvent(new ProfilerEvent(ProfilerEvent.TYPE_SLOW_QUERY, "", catalog, this.connection.getId(),
(callingStatement != null) ? callingStatement.getId() : 999, ((ResultSetImpl) rs).resultId, System.currentTimeMillis(),
(queryEndTime - queryStartTime), this.queryTimingUnits, null, LogUtils.findCallingClassAndMethod(new Throwable()),
Messages.getString("MysqlIO.ServerSlowQuery") + profileQueryToLog));
}
}
if (this.profileSql) {
fetchEndTime = getCurrentTimeNanosOrMillis();
ProfilerEventHandler eventSink = ProfilerEventHandlerFactory.getInstance(this.connection);
eventSink.consumeEvent(new ProfilerEvent(ProfilerEvent.TYPE_QUERY, "", catalog, this.connection.getId(),
(callingStatement != null) ? callingStatement.getId() : 999, ((ResultSetImpl) rs).resultId, System.currentTimeMillis(),
(queryEndTime - queryStartTime), this.queryTimingUnits, null, LogUtils.findCallingClassAndMethod(new Throwable()), profileQueryToLog));
eventSink.consumeEvent(new ProfilerEvent(ProfilerEvent.TYPE_FETCH, "", catalog, this.connection.getId(),
(callingStatement != null) ? callingStatement.getId() : 999, ((ResultSetImpl) rs).resultId, System.currentTimeMillis(),
(fetchEndTime - fetchBeginTime), this.queryTimingUnits, null, LogUtils.findCallingClassAndMethod(new Throwable()), null));
}
if (this.hadWarnings) {
scanForAndThrowDataTruncation();
}
if (this.statementInterceptors != null) {
ResultSetInternalMethods interceptedResults = invokeStatementInterceptorsPost(query, callingStatement, rs, false, null);
if (interceptedResults != null) {
rs = interceptedResults;
}
}
return rs;
} catch (SQLException sqlEx) {
if (this.statementInterceptors != null) {
invokeStatementInterceptorsPost(query, callingStatement, null, false, sqlEx); // we don't do anything with the result set in this case
}
if (callingStatement != null) {
synchronized (callingStatement.cancelTimeoutMutex) {
if (callingStatement.wasCancelled) {
SQLException cause = null;
if (callingStatement.wasCancelledByTimeout) {
cause = new MySQLTimeoutException();
} else {
cause = new MySQLStatementCancelledException();
}
callingStatement.resetCancelledState();
throw cause;
}
}
}
throw sqlEx;
} finally {
this.statementExecutionDepth--;
}
}
ResultSetInternalMethods invokeStatementInterceptorsPre(String sql, Statement interceptedStatement, boolean forceExecute) throws SQLException {
ResultSetInternalMethods previousResultSet = null;
for (int i = 0, s = this.statementInterceptors.size(); i < s; i++) {
StatementInterceptorV2 interceptor = this.statementInterceptors.get(i);
boolean executeTopLevelOnly = interceptor.executeTopLevelOnly();
boolean shouldExecute = (executeTopLevelOnly && (this.statementExecutionDepth == 1 || forceExecute)) || (!executeTopLevelOnly);
if (shouldExecute) {
String sqlToInterceptor = sql;
//if (interceptedStatement instanceof PreparedStatement) {
// sqlToInterceptor = ((PreparedStatement) interceptedStatement)
// .asSql();
//}
ResultSetInternalMethods interceptedResultSet = interceptor.preProcess(sqlToInterceptor, interceptedStatement, this.connection);
if (interceptedResultSet != null) {
previousResultSet = interceptedResultSet;
}
}
}
return previousResultSet;
}
ResultSetInternalMethods invokeStatementInterceptorsPost(String sql, Statement interceptedStatement, ResultSetInternalMethods originalResultSet,
boolean forceExecute, SQLException statementException) throws SQLException {
for (int i = 0, s = this.statementInterceptors.size(); i < s; i++) {
StatementInterceptorV2 interceptor = this.statementInterceptors.get(i);
boolean executeTopLevelOnly = interceptor.executeTopLevelOnly();
boolean shouldExecute = (executeTopLevelOnly && (this.statementExecutionDepth == 1 || forceExecute)) || (!executeTopLevelOnly);
if (shouldExecute) {
String sqlToInterceptor = sql;
ResultSetInternalMethods interceptedResultSet = interceptor.postProcess(sqlToInterceptor, interceptedStatement, originalResultSet,
this.connection, this.warningCount, this.queryNoIndexUsed, this.queryBadIndexUsed, statementException);
if (interceptedResultSet != null) {
originalResultSet = interceptedResultSet;
}
}
}
return originalResultSet;
}
private void calculateSlowQueryThreshold() {
this.slowQueryThreshold = this.connection.getSlowQueryThresholdMillis();
if (this.connection.getUseNanosForElapsedTime()) {
long nanosThreshold = this.connection.getSlowQueryThresholdNanos();
if (nanosThreshold != 0) {
this.slowQueryThreshold = nanosThreshold;
} else {
this.slowQueryThreshold *= 1000000; // 1 million millis in a nano
}
}
}
protected long getCurrentTimeNanosOrMillis() {
if (this.useNanosForElapsedTime) {
return TimeUtil.getCurrentTimeNanosOrMillis();
}
return System.currentTimeMillis();
}
/**
* Returns the host this IO is connected to
*/
String getHost() {
return this.host;
}
/**
* Is the version of the MySQL server we are connected to the given
* version?
*
* @param major
* the major version
* @param minor
* the minor version
* @param subminor
* the subminor version
*
* @return true if the version of the MySQL server we are connected is the
* given version
*/
boolean isVersion(int major, int minor, int subminor) {
return ((major == getServerMajorVersion()) && (minor == getServerMinorVersion()) && (subminor == getServerSubMinorVersion()));
}
/**
* Does the version of the MySQL server we are connected to meet the given
* minimums?
*
* @param major
* @param minor
* @param subminor
*/
boolean versionMeetsMinimum(int major, int minor, int subminor) {
if (getServerMajorVersion() >= major) {
if (getServerMajorVersion() == major) {
if (getServerMinorVersion() >= minor) {
if (getServerMinorVersion() == minor) {
return (getServerSubMinorVersion() >= subminor);
}
// newer than major.minor
return true;
}
// older than major.minor
return false;
}
// newer than major
return true;
}
return false;
}
/**
* Returns the hex dump of the given packet, truncated to
* MAX_PACKET_DUMP_LENGTH if packetLength exceeds that value.
*
* @param packetToDump
* the packet to dump in hex
* @param packetLength
* the number of bytes to dump
*
* @return the hex dump of the given packet
*/
private final static String getPacketDumpToLog(Buffer packetToDump, int packetLength) {
if (packetLength < MAX_PACKET_DUMP_LENGTH) {
return packetToDump.dump(packetLength);
}
StringBuilder packetDumpBuf = new StringBuilder(MAX_PACKET_DUMP_LENGTH * 4);
packetDumpBuf.append(packetToDump.dump(MAX_PACKET_DUMP_LENGTH));
packetDumpBuf.append(Messages.getString("MysqlIO.36"));
packetDumpBuf.append(MAX_PACKET_DUMP_LENGTH);
packetDumpBuf.append(Messages.getString("MysqlIO.37"));
return packetDumpBuf.toString();
}
private final int readFully(InputStream in, byte[] b, int off, int len) throws IOException {
if (len < 0) {
throw new IndexOutOfBoundsException();
}
int n = 0;
while (n < len) {
int count = in.read(b, off + n, len - n);
if (count < 0) {
throw new EOFException(Messages.getString("MysqlIO.EOF", new Object[] { Integer.valueOf(len), Integer.valueOf(n) }));
}
n += count;
}
return n;
}
private final long skipFully(InputStream in, long len) throws IOException {
if (len < 0) {
throw new IOException("Negative skip length not allowed");
}
long n = 0;
while (n < len) {
long count = in.skip(len - n);
if (count < 0) {
throw new EOFException(Messages.getString("MysqlIO.EOF", new Object[] { Long.valueOf(len), Long.valueOf(n) }));
}
n += count;
}
return n;
}
private final int skipLengthEncodedInteger(InputStream in) throws IOException {
int sw = in.read() & 0xff;
switch (sw) {
case 252:
return (int) skipFully(in, 2) + 1;
case 253:
return (int) skipFully(in, 3) + 1;
case 254:
return (int) skipFully(in, 8) + 1;
default:
return 1;
}
}
/**
* Reads one result set off of the wire, if the result is actually an
* update count, creates an update-count only result set.
*
* @param callingStatement
* @param maxRows
* the maximum rows to return in the result set.
* @param resultSetType
* scrollability
* @param resultSetConcurrency
* updatability
* @param streamResults
* should the driver leave the results on the wire,
* and read them only when needed?
* @param catalog
* the catalog in use
* @param resultPacket
* the first packet of information in the result set
* @param isBinaryEncoded
* is this result set from a prepared statement?
* @param preSentColumnCount
* do we already know the number of columns?
* @param unpackFieldInfo
* should we unpack the field information?
*
* @return a result set that either represents the rows, or an update count
*
* @throws SQLException
* if an error occurs while reading the rows
*/
protected final ResultSetImpl readResultsForQueryOrUpdate(StatementImpl callingStatement, int maxRows, int resultSetType, int resultSetConcurrency,
boolean streamResults, String catalog, Buffer resultPacket, boolean isBinaryEncoded, long preSentColumnCount, Field[] metadataFromCache)
throws SQLException {
long columnCount = resultPacket.readFieldLength();
if (columnCount == 0) {
return buildResultSetWithUpdates(callingStatement, resultPacket);
} else if (columnCount == Buffer.NULL_LENGTH) {
String charEncoding = null;
if (this.connection.getUseUnicode()) {
charEncoding = this.connection.getEncoding();
}
String fileName = null;
if (this.platformDbCharsetMatches) {
fileName = ((charEncoding != null) ? resultPacket.readString(charEncoding, getExceptionInterceptor()) : resultPacket.readString());
} else {
fileName = resultPacket.readString();
}
return sendFileToServer(callingStatement, fileName);
} else {
com.mysql.jdbc.ResultSetImpl results = getResultSet(callingStatement, columnCount, maxRows, resultSetType, resultSetConcurrency, streamResults,
catalog, isBinaryEncoded, metadataFromCache);
return results;
}
}
private int alignPacketSize(int a, int l) {
return ((((a) + (l)) - 1) & ~((l) - 1));
}
private com.mysql.jdbc.ResultSetImpl buildResultSetWithRows(StatementImpl callingStatement, String catalog, com.mysql.jdbc.Field[] fields, RowData rows,
int resultSetType, int resultSetConcurrency, boolean isBinaryEncoded) throws SQLException {
ResultSetImpl rs = null;
switch (resultSetConcurrency) {
case java.sql.ResultSet.CONCUR_READ_ONLY:
rs = com.mysql.jdbc.ResultSetImpl.getInstance(catalog, fields, rows, this.connection, callingStatement, false);
if (isBinaryEncoded) {
rs.setBinaryEncoded();
}
break;
case java.sql.ResultSet.CONCUR_UPDATABLE:
rs = com.mysql.jdbc.ResultSetImpl.getInstance(catalog, fields, rows, this.connection, callingStatement, true);
break;
default:
return com.mysql.jdbc.ResultSetImpl.getInstance(catalog, fields, rows, this.connection, callingStatement, false);
}
rs.setResultSetType(resultSetType);
rs.setResultSetConcurrency(resultSetConcurrency);
return rs;
}
private com.mysql.jdbc.ResultSetImpl buildResultSetWithUpdates(StatementImpl callingStatement, Buffer resultPacket) throws SQLException {
long updateCount = -1;
long updateID = -1;
String info = null;
try {
if (this.useNewUpdateCounts) {
updateCount = resultPacket.newReadLength();
updateID = resultPacket.newReadLength();
} else {
updateCount = resultPacket.readLength();
updateID = resultPacket.readLength();
}
if (this.use41Extensions) {
// oldStatus set in sendCommand()
this.serverStatus = resultPacket.readInt();
checkTransactionState(this.oldServerStatus);
this.warningCount = resultPacket.readInt();
if (this.warningCount > 0) {
this.hadWarnings = true; // this is a 'latch', it's reset by sendCommand()
}
resultPacket.readByte(); // advance pointer
setServerSlowQueryFlags();
}
if (this.connection.isReadInfoMsgEnabled()) {
info = resultPacket.readString(this.connection.getErrorMessageEncoding(), getExceptionInterceptor());
}
} catch (Exception ex) {
SQLException sqlEx = SQLError.createSQLException(SQLError.get(SQLError.SQL_STATE_GENERAL_ERROR), SQLError.SQL_STATE_GENERAL_ERROR, -1,
getExceptionInterceptor());
sqlEx.initCause(ex);
throw sqlEx;
}
ResultSetInternalMethods updateRs = com.mysql.jdbc.ResultSetImpl.getInstance(updateCount, updateID, this.connection, callingStatement);
if (info != null) {
((com.mysql.jdbc.ResultSetImpl) updateRs).setServerInfo(info);
}
return (com.mysql.jdbc.ResultSetImpl) updateRs;
}
private void setServerSlowQueryFlags() {
this.queryBadIndexUsed = (this.serverStatus & SERVER_QUERY_NO_GOOD_INDEX_USED) != 0;
this.queryNoIndexUsed = (this.serverStatus & SERVER_QUERY_NO_INDEX_USED) != 0;
this.serverQueryWasSlow = (this.serverStatus & SERVER_QUERY_WAS_SLOW) != 0;
}
private void checkForOutstandingStreamingData() throws SQLException {
if (this.streamingData != null) {
boolean shouldClobber = this.connection.getClobberStreamingResults();
if (!shouldClobber) {
throw SQLError.createSQLException(Messages.getString("MysqlIO.39") + this.streamingData + Messages.getString("MysqlIO.40")
+ Messages.getString("MysqlIO.41") + Messages.getString("MysqlIO.42"), getExceptionInterceptor());
}
// Close the result set
this.streamingData.getOwner().realClose(false);
// clear any pending data....
clearInputStream();
}
}
/**
* @param packet
* original uncompressed MySQL packet
* @param offset
* begin of MySQL packet header
* @param packetLen
* real length of packet
* @return compressed packet with header
* @throws SQLException
*/
private Buffer compressPacket(Buffer packet, int offset, int packetLen) throws SQLException {
// uncompressed payload by default
int compressedLength = packetLen;
int uncompressedLength = 0;
byte[] compressedBytes = null;
int offsetWrite = offset;
if (packetLen < MIN_COMPRESS_LEN) {
compressedBytes = packet.getByteBuffer();
} else {
byte[] bytesToCompress = packet.getByteBuffer();
compressedBytes = new byte[bytesToCompress.length * 2];
if (this.deflater == null) {
this.deflater = new Deflater();
}
this.deflater.reset();
this.deflater.setInput(bytesToCompress, offset, packetLen);
this.deflater.finish();
compressedLength = this.deflater.deflate(compressedBytes);
if (compressedLength > packetLen) {
// if compressed data is greater then uncompressed then send uncompressed
compressedBytes = packet.getByteBuffer();
compressedLength = packetLen;
} else {
uncompressedLength = packetLen;
offsetWrite = 0;
}
}
Buffer compressedPacket = new Buffer(HEADER_LENGTH + COMP_HEADER_LENGTH + compressedLength);
compressedPacket.setPosition(0);
compressedPacket.writeLongInt(compressedLength);
compressedPacket.writeByte(this.compressedPacketSequence);
compressedPacket.writeLongInt(uncompressedLength);
compressedPacket.writeBytesNoNull(compressedBytes, offsetWrite, compressedLength);
return compressedPacket;
}
private final void readServerStatusForResultSets(Buffer rowPacket) throws SQLException {
if (this.use41Extensions) {
rowPacket.readByte(); // skips the 'last packet' flag
if (isEOFDeprecated()) {
// read OK packet
rowPacket.newReadLength(); // affected_rows
rowPacket.newReadLength(); // last_insert_id
this.oldServerStatus = this.serverStatus;
this.serverStatus = rowPacket.readInt();
checkTransactionState(this.oldServerStatus);
this.warningCount = rowPacket.readInt();
if (this.warningCount > 0) {
this.hadWarnings = true; // this is a 'latch', it's reset by sendCommand()
}
rowPacket.readByte(); // advance pointer
if (this.connection.isReadInfoMsgEnabled()) {
rowPacket.readString(this.connection.getErrorMessageEncoding(), getExceptionInterceptor()); // info
}
} else {
// read EOF packet
this.warningCount = rowPacket.readInt();
if (this.warningCount > 0) {
this.hadWarnings = true; // this is a 'latch', it's reset by sendCommand()
}
this.oldServerStatus = this.serverStatus;
this.serverStatus = rowPacket.readInt();
checkTransactionState(this.oldServerStatus);
}
setServerSlowQueryFlags();
}
}
private SocketFactory createSocketFactory() throws SQLException {
try {
if (this.socketFactoryClassName == null) {
throw SQLError.createSQLException(Messages.getString("MysqlIO.75"), SQLError.SQL_STATE_UNABLE_TO_CONNECT_TO_DATASOURCE,
getExceptionInterceptor());
}
return (SocketFactory) (Class.forName(this.socketFactoryClassName).newInstance());
} catch (Exception ex) {
SQLException sqlEx = SQLError.createSQLException(Messages.getString("MysqlIO.76") + this.socketFactoryClassName + Messages.getString("MysqlIO.77"),
SQLError.SQL_STATE_UNABLE_TO_CONNECT_TO_DATASOURCE, getExceptionInterceptor());
sqlEx.initCause(ex);
throw sqlEx;
}
}
private void enqueuePacketForDebugging(boolean isPacketBeingSent, boolean isPacketReused, int sendLength, byte[] header, Buffer packet)
throws SQLException {
if ((this.packetDebugRingBuffer.size() + 1) > this.connection.getPacketDebugBufferSize()) {
this.packetDebugRingBuffer.removeFirst();
}
StringBuilder packetDump = null;
if (!isPacketBeingSent) {
int bytesToDump = Math.min(MAX_PACKET_DUMP_LENGTH, packet.getBufLength());
Buffer packetToDump = new Buffer(4 + bytesToDump);
packetToDump.setPosition(0);
packetToDump.writeBytesNoNull(header);
packetToDump.writeBytesNoNull(packet.getBytes(0, bytesToDump));
String packetPayload = packetToDump.dump(bytesToDump);
packetDump = new StringBuilder(96 + packetPayload.length());
packetDump.append("Server ");
packetDump.append(isPacketReused ? "(re-used) " : "(new) ");
packetDump.append(packet.toSuperString());
packetDump.append(" --------------------> Client\n");
packetDump.append("\nPacket payload:\n\n");
packetDump.append(packetPayload);
if (bytesToDump == MAX_PACKET_DUMP_LENGTH) {
packetDump.append("\nNote: Packet of " + packet.getBufLength() + " bytes truncated to " + MAX_PACKET_DUMP_LENGTH + " bytes.\n");
}
} else {
int bytesToDump = Math.min(MAX_PACKET_DUMP_LENGTH, sendLength);
String packetPayload = packet.dump(bytesToDump);
packetDump = new StringBuilder(64 + 4 + packetPayload.length());
packetDump.append("Client ");
packetDump.append(packet.toSuperString());
packetDump.append("--------------------> Server\n");
packetDump.append("\nPacket payload:\n\n");
packetDump.append(packetPayload);
if (bytesToDump == MAX_PACKET_DUMP_LENGTH) {
packetDump.append("\nNote: Packet of " + sendLength + " bytes truncated to " + MAX_PACKET_DUMP_LENGTH + " bytes.\n");
}
}
this.packetDebugRingBuffer.addLast(packetDump);
}
private RowData readSingleRowSet(long columnCount, int maxRows, int resultSetConcurrency, boolean isBinaryEncoded, Field[] fields) throws SQLException {
RowData rowData;
ArrayList<ResultSetRow> rows = new ArrayList<ResultSetRow>();
boolean useBufferRowExplicit = useBufferRowExplicit(fields);
// Now read the data
ResultSetRow row = nextRow(fields, (int) columnCount, isBinaryEncoded, resultSetConcurrency, false, useBufferRowExplicit, false, null);
int rowCount = 0;
if (row != null) {
rows.add(row);
rowCount = 1;
}
while (row != null) {
row = nextRow(fields, (int) columnCount, isBinaryEncoded, resultSetConcurrency, false, useBufferRowExplicit, false, null);
if (row != null) {
if ((maxRows == -1) || (rowCount < maxRows)) {
rows.add(row);
rowCount++;
}
}
}
rowData = new RowDataStatic(rows);
return rowData;
}
public static boolean useBufferRowExplicit(Field[] fields) {
if (fields == null) {
return false;
}
for (int i = 0; i < fields.length; i++) {
switch (fields[i].getSQLType()) {
case Types.BLOB:
case Types.CLOB:
case Types.LONGVARBINARY:
case Types.LONGVARCHAR:
return true;
}
}
return false;
}
/**
* Don't hold on to overly-large packets
*/
private void reclaimLargeReusablePacket() {
if ((this.reusablePacket != null) && (this.reusablePacket.getCapacity() > 1048576)) {
this.reusablePacket = new Buffer(INITIAL_PACKET_SIZE);
}
}
/**
* Re-use a packet to read from the MySQL server
*
* @param reuse
* @throws SQLException
*/
private final Buffer reuseAndReadPacket(Buffer reuse) throws SQLException {
return reuseAndReadPacket(reuse, -1);
}
private final Buffer reuseAndReadPacket(Buffer reuse, int existingPacketLength) throws SQLException {
try {
reuse.setWasMultiPacket(false);
int packetLength = 0;
if (existingPacketLength == -1) {
int lengthRead = readFully(this.mysqlInput, this.packetHeaderBuf, 0, 4);
if (lengthRead < 4) {
forceClose();
throw new IOException(Messages.getString("MysqlIO.43"));
}
packetLength = (this.packetHeaderBuf[0] & 0xff) + ((this.packetHeaderBuf[1] & 0xff) << 8) + ((this.packetHeaderBuf[2] & 0xff) << 16);
} else {
packetLength = existingPacketLength;
}
if (this.traceProtocol) {
StringBuilder traceMessageBuf = new StringBuilder();
traceMessageBuf.append(Messages.getString("MysqlIO.44"));
traceMessageBuf.append(packetLength);
traceMessageBuf.append(Messages.getString("MysqlIO.45"));
traceMessageBuf.append(StringUtils.dumpAsHex(this.packetHeaderBuf, 4));
this.connection.getLog().logTrace(traceMessageBuf.toString());
}
byte multiPacketSeq = this.packetHeaderBuf[3];
if (!this.packetSequenceReset) {
if (this.enablePacketDebug && this.checkPacketSequence) {
checkPacketSequencing(multiPacketSeq);
}
} else {
this.packetSequenceReset = false;
}
this.readPacketSequence = multiPacketSeq;
// Set the Buffer to it's original state
reuse.setPosition(0);
// Do we need to re-alloc the byte buffer?
//
// Note: We actually check the length of the buffer, rather than getBufLength(), because getBufLength() is not necesarily the actual length of the
// byte array used as the buffer
if (reuse.getByteBuffer().length <= packetLength) {
reuse.setByteBuffer(new byte[packetLength + 1]);
}
// Set the new length
reuse.setBufLength(packetLength);
// Read the data from the server
int numBytesRead = readFully(this.mysqlInput, reuse.getByteBuffer(), 0, packetLength);
if (numBytesRead != packetLength) {
throw new IOException("Short read, expected " + packetLength + " bytes, only read " + numBytesRead);
}
if (this.traceProtocol) {
StringBuilder traceMessageBuf = new StringBuilder();
traceMessageBuf.append(Messages.getString("MysqlIO.46"));
traceMessageBuf.append(getPacketDumpToLog(reuse, packetLength));
this.connection.getLog().logTrace(traceMessageBuf.toString());
}
if (this.enablePacketDebug) {
enqueuePacketForDebugging(false, true, 0, this.packetHeaderBuf, reuse);
}
boolean isMultiPacket = false;
if (packetLength == this.maxThreeBytes) {
reuse.setPosition(this.maxThreeBytes);
// it's multi-packet
isMultiPacket = true;
packetLength = readRemainingMultiPackets(reuse, multiPacketSeq);
}
if (!isMultiPacket) {
reuse.getByteBuffer()[packetLength] = 0; // Null-termination
}
if (this.connection.getMaintainTimeStats()) {
this.lastPacketReceivedTimeMs = System.currentTimeMillis();
}
return reuse;
} catch (IOException ioEx) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs, ioEx,
getExceptionInterceptor());
} catch (OutOfMemoryError oom) {
try {
// _Try_ this
clearInputStream();
} catch (Exception ex) {
}
try {
this.connection.realClose(false, false, true, oom);
} catch (Exception ex) {
}
throw oom;
}
}
private int readRemainingMultiPackets(Buffer reuse, byte multiPacketSeq) throws IOException, SQLException {
int packetLength = -1;
Buffer multiPacket = null;
do {
final int lengthRead = readFully(this.mysqlInput, this.packetHeaderBuf, 0, 4);
if (lengthRead < 4) {
forceClose();
throw new IOException(Messages.getString("MysqlIO.47"));
}
packetLength = (this.packetHeaderBuf[0] & 0xff) + ((this.packetHeaderBuf[1] & 0xff) << 8) + ((this.packetHeaderBuf[2] & 0xff) << 16);
if (multiPacket == null) {
multiPacket = new Buffer(packetLength);
}
if (!this.useNewLargePackets && (packetLength == 1)) {
clearInputStream();
break;
}
multiPacketSeq++;
if (multiPacketSeq != this.packetHeaderBuf[3]) {
throw new IOException(Messages.getString("MysqlIO.49"));
}
// Set the Buffer to it's original state
multiPacket.setPosition(0);
// Set the new length
multiPacket.setBufLength(packetLength);
// Read the data from the server
byte[] byteBuf = multiPacket.getByteBuffer();
int lengthToWrite = packetLength;
int bytesRead = readFully(this.mysqlInput, byteBuf, 0, packetLength);
if (bytesRead != lengthToWrite) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs,
SQLError.createSQLException(Messages.getString("MysqlIO.50") + lengthToWrite + Messages.getString("MysqlIO.51") + bytesRead + ".",
getExceptionInterceptor()),
getExceptionInterceptor());
}
reuse.writeBytesNoNull(byteBuf, 0, lengthToWrite);
} while (packetLength == this.maxThreeBytes);
reuse.setPosition(0);
reuse.setWasMultiPacket(true);
return packetLength;
}
/**
* @param multiPacketSeq
* @throws CommunicationsException
*/
private void checkPacketSequencing(byte multiPacketSeq) throws SQLException {
if ((multiPacketSeq == -128) && (this.readPacketSequence != 127)) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs,
new IOException("Packets out of order, expected packet # -128, but received packet # " + multiPacketSeq), getExceptionInterceptor());
}
if ((this.readPacketSequence == -1) && (multiPacketSeq != 0)) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs,
new IOException("Packets out of order, expected packet # -1, but received packet # " + multiPacketSeq), getExceptionInterceptor());
}
if ((multiPacketSeq != -128) && (this.readPacketSequence != -1) && (multiPacketSeq != (this.readPacketSequence + 1))) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs,
new IOException("Packets out of order, expected packet # " + (this.readPacketSequence + 1) + ", but received packet # " + multiPacketSeq),
getExceptionInterceptor());
}
}
void enableMultiQueries() throws SQLException {
Buffer buf = getSharedSendPacket();
buf.clear();
buf.writeByte((byte) MysqlDefs.COM_SET_OPTION);
buf.writeInt(0);
sendCommand(MysqlDefs.COM_SET_OPTION, null, buf, false, null, 0);
}
void disableMultiQueries() throws SQLException {
Buffer buf = getSharedSendPacket();
buf.clear();
buf.writeByte((byte) MysqlDefs.COM_SET_OPTION);
buf.writeInt(1);
sendCommand(MysqlDefs.COM_SET_OPTION, null, buf, false, null, 0);
}
/**
* @param packet
* @param packetLen
* length of header + payload
* @throws SQLException
*/
private final void send(Buffer packet, int packetLen) throws SQLException {
try {
if (this.maxAllowedPacket > 0 && packetLen > this.maxAllowedPacket) {
throw new PacketTooBigException(packetLen, this.maxAllowedPacket);
}
if ((this.serverMajorVersion >= 4) && (packetLen - HEADER_LENGTH >= this.maxThreeBytes
|| (this.useCompression && packetLen - HEADER_LENGTH >= this.maxThreeBytes - COMP_HEADER_LENGTH))) {
sendSplitPackets(packet, packetLen);
} else {
this.packetSequence++;
Buffer packetToSend = packet;
packetToSend.setPosition(0);
packetToSend.writeLongInt(packetLen - HEADER_LENGTH);
packetToSend.writeByte(this.packetSequence);
if (this.useCompression) {
this.compressedPacketSequence++;
int originalPacketLen = packetLen;
packetToSend = compressPacket(packetToSend, 0, packetLen);
packetLen = packetToSend.getPosition();
if (this.traceProtocol) {
StringBuilder traceMessageBuf = new StringBuilder();
traceMessageBuf.append(Messages.getString("MysqlIO.57"));
traceMessageBuf.append(getPacketDumpToLog(packetToSend, packetLen));
traceMessageBuf.append(Messages.getString("MysqlIO.58"));
traceMessageBuf.append(getPacketDumpToLog(packet, originalPacketLen));
this.connection.getLog().logTrace(traceMessageBuf.toString());
}
} else {
if (this.traceProtocol) {
StringBuilder traceMessageBuf = new StringBuilder();
traceMessageBuf.append(Messages.getString("MysqlIO.59"));
traceMessageBuf.append("host: '");
traceMessageBuf.append(this.host);
traceMessageBuf.append("' threadId: '");
traceMessageBuf.append(this.threadId);
traceMessageBuf.append("'\n");
traceMessageBuf.append(packetToSend.dump(packetLen));
this.connection.getLog().logTrace(traceMessageBuf.toString());
}
}
this.mysqlOutput.write(packetToSend.getByteBuffer(), 0, packetLen);
this.mysqlOutput.flush();
}
if (this.enablePacketDebug) {
enqueuePacketForDebugging(true, false, packetLen + 5, this.packetHeaderBuf, packet);
}
//
// Don't hold on to large packets
//
if (packet == this.sharedSendPacket) {
reclaimLargeSharedSendPacket();
}
if (this.connection.getMaintainTimeStats()) {
this.lastPacketSentTimeMs = System.currentTimeMillis();
}
} catch (IOException ioEx) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs, ioEx,
getExceptionInterceptor());
}
}
/**
* Reads and sends a file to the server for LOAD DATA LOCAL INFILE
*
* @param callingStatement
* @param fileName
* the file name to send.
*
* @throws SQLException
*/
private final ResultSetImpl sendFileToServer(StatementImpl callingStatement, String fileName) throws SQLException {
if (this.useCompression) {
this.compressedPacketSequence++;
}
Buffer filePacket = (this.loadFileBufRef == null) ? null : this.loadFileBufRef.get();
int bigPacketLength = Math.min(this.connection.getMaxAllowedPacket() - (HEADER_LENGTH * 3),
alignPacketSize(this.connection.getMaxAllowedPacket() - 16, 4096) - (HEADER_LENGTH * 3));
int oneMeg = 1024 * 1024;
int smallerPacketSizeAligned = Math.min(oneMeg - (HEADER_LENGTH * 3), alignPacketSize(oneMeg - 16, 4096) - (HEADER_LENGTH * 3));
int packetLength = Math.min(smallerPacketSizeAligned, bigPacketLength);
if (filePacket == null) {
try {
filePacket = new Buffer((packetLength + HEADER_LENGTH));
this.loadFileBufRef = new SoftReference<Buffer>(filePacket);
} catch (OutOfMemoryError oom) {
throw SQLError.createSQLException(
"Could not allocate packet of " + packetLength + " bytes required for LOAD DATA LOCAL INFILE operation."
+ " Try increasing max heap allocation for JVM or decreasing server variable 'max_allowed_packet'",
SQLError.SQL_STATE_MEMORY_ALLOCATION_FAILURE, getExceptionInterceptor());
}
}
filePacket.clear();
send(filePacket, 0);
byte[] fileBuf = new byte[packetLength];
BufferedInputStream fileIn = null;
try {
if (!this.connection.getAllowLoadLocalInfile()) {
throw SQLError.createSQLException(Messages.getString("MysqlIO.LoadDataLocalNotAllowed"), SQLError.SQL_STATE_GENERAL_ERROR,
getExceptionInterceptor());
}
InputStream hookedStream = null;
if (callingStatement != null) {
hookedStream = callingStatement.getLocalInfileInputStream();
}
if (hookedStream != null) {
fileIn = new BufferedInputStream(hookedStream);
} else if (!this.connection.getAllowUrlInLocalInfile()) {
fileIn = new BufferedInputStream(new FileInputStream(fileName));
} else {
// First look for ':'
if (fileName.indexOf(':') != -1) {
try {
URL urlFromFileName = new URL(fileName);
fileIn = new BufferedInputStream(urlFromFileName.openStream());
} catch (MalformedURLException badUrlEx) {
// we fall back to trying this as a file input stream
fileIn = new BufferedInputStream(new FileInputStream(fileName));
}
} else {
fileIn = new BufferedInputStream(new FileInputStream(fileName));
}
}
int bytesRead = 0;
while ((bytesRead = fileIn.read(fileBuf)) != -1) {
filePacket.clear();
filePacket.writeBytesNoNull(fileBuf, 0, bytesRead);
send(filePacket, filePacket.getPosition());
}
} catch (IOException ioEx) {
StringBuilder messageBuf = new StringBuilder(Messages.getString("MysqlIO.60"));
if (fileName != null && !this.connection.getParanoid()) {
messageBuf.append("'");
messageBuf.append(fileName);
messageBuf.append("'");
}
messageBuf.append(Messages.getString("MysqlIO.63"));
if (!this.connection.getParanoid()) {
messageBuf.append(Messages.getString("MysqlIO.64"));
messageBuf.append(Util.stackTraceToString(ioEx));
}
throw SQLError.createSQLException(messageBuf.toString(), SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
} finally {
if (fileIn != null) {
try {
fileIn.close();
} catch (Exception ex) {
SQLException sqlEx = SQLError.createSQLException(Messages.getString("MysqlIO.65"), SQLError.SQL_STATE_GENERAL_ERROR, ex,
getExceptionInterceptor());
throw sqlEx;
}
fileIn = null;
} else {
// file open failed, but server needs one packet
filePacket.clear();
send(filePacket, filePacket.getPosition());
checkErrorPacket(); // to clear response off of queue
}
}
// send empty packet to mark EOF
filePacket.clear();
send(filePacket, filePacket.getPosition());
Buffer resultPacket = checkErrorPacket();
return buildResultSetWithUpdates(callingStatement, resultPacket);
}
/**
* Checks for errors in the reply packet, and if none, returns the reply
* packet, ready for reading
*
* @param command
* the command being issued (if used)
*
* @throws SQLException
* if an error packet was received
* @throws CommunicationsException
*/
private Buffer checkErrorPacket(int command) throws SQLException {
//int statusCode = 0;
Buffer resultPacket = null;
this.serverStatus = 0;
try {
// Check return value, if we get a java.io.EOFException, the server has gone away. We'll pass it on up the exception chain and let someone higher up
// decide what to do (barf, reconnect, etc).
resultPacket = reuseAndReadPacket(this.reusablePacket);
} catch (SQLException sqlEx) {
// Don't wrap SQL Exceptions
throw sqlEx;
} catch (Exception fallThru) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs, fallThru,
getExceptionInterceptor());
}
checkErrorPacket(resultPacket);
return resultPacket;
}
private void checkErrorPacket(Buffer resultPacket) throws SQLException {
int statusCode = resultPacket.readByte();
// Error handling
if (statusCode == (byte) 0xff) {
String serverErrorMessage;
int errno = 2000;
if (this.protocolVersion > 9) {
errno = resultPacket.readInt();
String xOpen = null;
serverErrorMessage = resultPacket.readString(this.connection.getErrorMessageEncoding(), getExceptionInterceptor());
if (serverErrorMessage.charAt(0) == '#') {
// we have an SQLState
if (serverErrorMessage.length() > 6) {
xOpen = serverErrorMessage.substring(1, 6);
serverErrorMessage = serverErrorMessage.substring(6);
if (xOpen.equals("HY000")) {
xOpen = SQLError.mysqlToSqlState(errno, this.connection.getUseSqlStateCodes());
}
} else {
xOpen = SQLError.mysqlToSqlState(errno, this.connection.getUseSqlStateCodes());
}
} else {
xOpen = SQLError.mysqlToSqlState(errno, this.connection.getUseSqlStateCodes());
}
clearInputStream();
StringBuilder errorBuf = new StringBuilder();
String xOpenErrorMessage = SQLError.get(xOpen);
if (!this.connection.getUseOnlyServerErrorMessages()) {
if (xOpenErrorMessage != null) {
errorBuf.append(xOpenErrorMessage);
errorBuf.append(Messages.getString("MysqlIO.68"));
}
}
errorBuf.append(serverErrorMessage);
if (!this.connection.getUseOnlyServerErrorMessages()) {
if (xOpenErrorMessage != null) {
errorBuf.append("\"");
}
}
appendDeadlockStatusInformation(xOpen, errorBuf);
if (xOpen != null && xOpen.startsWith("22")) {
throw new MysqlDataTruncation(errorBuf.toString(), 0, true, false, 0, 0, errno);
}
throw SQLError.createSQLException(errorBuf.toString(), xOpen, errno, false, getExceptionInterceptor(), this.connection);
}
serverErrorMessage = resultPacket.readString(this.connection.getErrorMessageEncoding(), getExceptionInterceptor());
clearInputStream();
if (serverErrorMessage.indexOf(Messages.getString("MysqlIO.70")) != -1) {
throw SQLError.createSQLException(SQLError.get(SQLError.SQL_STATE_COLUMN_NOT_FOUND) + ", " + serverErrorMessage,
SQLError.SQL_STATE_COLUMN_NOT_FOUND, -1, false, getExceptionInterceptor(), this.connection);
}
StringBuilder errorBuf = new StringBuilder(Messages.getString("MysqlIO.72"));
errorBuf.append(serverErrorMessage);
errorBuf.append("\"");
throw SQLError.createSQLException(SQLError.get(SQLError.SQL_STATE_GENERAL_ERROR) + ", " + errorBuf.toString(), SQLError.SQL_STATE_GENERAL_ERROR, -1,
false, getExceptionInterceptor(), this.connection);
}
}
private void appendDeadlockStatusInformation(String xOpen, StringBuilder errorBuf) throws SQLException {
if (this.connection.getIncludeInnodbStatusInDeadlockExceptions() && xOpen != null && (xOpen.startsWith("40") || xOpen.startsWith("41"))
&& this.streamingData == null) {
ResultSet rs = null;
try {
rs = sqlQueryDirect(null, "SHOW ENGINE INNODB STATUS", this.connection.getEncoding(), null, -1, ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY, false, this.connection.getCatalog(), null);
if (rs.next()) {
errorBuf.append("\n\n");
errorBuf.append(rs.getString("Status"));
} else {
errorBuf.append("\n\n");
errorBuf.append(Messages.getString("MysqlIO.NoInnoDBStatusFound"));
}
} catch (Exception ex) {
errorBuf.append("\n\n");
errorBuf.append(Messages.getString("MysqlIO.InnoDBStatusFailed"));
errorBuf.append("\n\n");
errorBuf.append(Util.stackTraceToString(ex));
} finally {
if (rs != null) {
rs.close();
}
}
}
if (this.connection.getIncludeThreadDumpInDeadlockExceptions()) {
errorBuf.append("\n\n*** Java threads running at time of deadlock ***\n\n");
ThreadMXBean threadMBean = ManagementFactory.getThreadMXBean();
long[] threadIds = threadMBean.getAllThreadIds();
ThreadInfo[] threads = threadMBean.getThreadInfo(threadIds, Integer.MAX_VALUE);
List<ThreadInfo> activeThreads = new ArrayList<ThreadInfo>();
for (ThreadInfo info : threads) {
if (info != null) {
activeThreads.add(info);
}
}
for (ThreadInfo threadInfo : activeThreads) {
// "Thread-60" daemon prio=1 tid=0x093569c0 nid=0x1b99 in Object.wait()
errorBuf.append('"');
errorBuf.append(threadInfo.getThreadName());
errorBuf.append("\" tid=");
errorBuf.append(threadInfo.getThreadId());
errorBuf.append(" ");
errorBuf.append(threadInfo.getThreadState());
if (threadInfo.getLockName() != null) {
errorBuf.append(" on lock=" + threadInfo.getLockName());
}
if (threadInfo.isSuspended()) {
errorBuf.append(" (suspended)");
}
if (threadInfo.isInNative()) {
errorBuf.append(" (running in native)");
}
StackTraceElement[] stackTrace = threadInfo.getStackTrace();
if (stackTrace.length > 0) {
errorBuf.append(" in ");
errorBuf.append(stackTrace[0].getClassName());
errorBuf.append(".");
errorBuf.append(stackTrace[0].getMethodName());
errorBuf.append("()");
}
errorBuf.append("\n");
if (threadInfo.getLockOwnerName() != null) {
errorBuf.append("\t owned by " + threadInfo.getLockOwnerName() + " Id=" + threadInfo.getLockOwnerId());
errorBuf.append("\n");
}
for (int j = 0; j < stackTrace.length; j++) {
StackTraceElement ste = stackTrace[j];
errorBuf.append("\tat " + ste.toString());
errorBuf.append("\n");
}
}
}
}
/**
* Sends a large packet to the server as a series of smaller packets
*
* @param packet
*
* @throws SQLException
* @throws CommunicationsException
*/
private final void sendSplitPackets(Buffer packet, int packetLen) throws SQLException {
try {
Buffer packetToSend = (this.splitBufRef == null) ? null : this.splitBufRef.get();
Buffer toCompress = (!this.useCompression || this.compressBufRef == null) ? null : this.compressBufRef.get();
//
// Store this packet in a soft reference...It can be re-used if not GC'd (so clients that use it frequently won't have to re-alloc the 16M buffer),
// but we don't penalize infrequent users of large packets by keeping 16M allocated all of the time
//
if (packetToSend == null) {
packetToSend = new Buffer((this.maxThreeBytes + HEADER_LENGTH));
this.splitBufRef = new SoftReference<Buffer>(packetToSend);
}
if (this.useCompression) {
int cbuflen = packetLen + ((packetLen / this.maxThreeBytes) + 1) * HEADER_LENGTH;
if (toCompress == null) {
toCompress = new Buffer(cbuflen);
this.compressBufRef = new SoftReference<Buffer>(toCompress);
} else if (toCompress.getBufLength() < cbuflen) {
toCompress.setPosition(toCompress.getBufLength());
toCompress.ensureCapacity(cbuflen - toCompress.getBufLength());
}
}
int len = packetLen - HEADER_LENGTH; // payload length left
int splitSize = this.maxThreeBytes;
int originalPacketPos = HEADER_LENGTH;
byte[] origPacketBytes = packet.getByteBuffer();
int toCompressPosition = 0;
// split to MySQL packets
while (len >= 0) {
this.packetSequence++;
if (len < splitSize) {
splitSize = len;
}
packetToSend.setPosition(0);
packetToSend.writeLongInt(splitSize);
packetToSend.writeByte(this.packetSequence);
if (len > 0) {
System.arraycopy(origPacketBytes, originalPacketPos, packetToSend.getByteBuffer(), HEADER_LENGTH, splitSize);
}
if (this.useCompression) {
System.arraycopy(packetToSend.getByteBuffer(), 0, toCompress.getByteBuffer(), toCompressPosition, HEADER_LENGTH + splitSize);
toCompressPosition += HEADER_LENGTH + splitSize;
} else {
this.mysqlOutput.write(packetToSend.getByteBuffer(), 0, HEADER_LENGTH + splitSize);
this.mysqlOutput.flush();
}
originalPacketPos += splitSize;
len -= this.maxThreeBytes;
}
// split to compressed packets
if (this.useCompression) {
len = toCompressPosition;
toCompressPosition = 0;
splitSize = this.maxThreeBytes - COMP_HEADER_LENGTH;
while (len >= 0) {
this.compressedPacketSequence++;
if (len < splitSize) {
splitSize = len;
}
Buffer compressedPacketToSend = compressPacket(toCompress, toCompressPosition, splitSize);
packetLen = compressedPacketToSend.getPosition();
this.mysqlOutput.write(compressedPacketToSend.getByteBuffer(), 0, packetLen);
this.mysqlOutput.flush();
toCompressPosition += splitSize;
len -= (this.maxThreeBytes - COMP_HEADER_LENGTH);
}
}
} catch (IOException ioEx) {
throw SQLError.createCommunicationsException(this.connection, this.lastPacketSentTimeMs, this.lastPacketReceivedTimeMs, ioEx,
getExceptionInterceptor());
}
}
private void reclaimLargeSharedSendPacket() {
if ((this.sharedSendPacket != null) && (this.sharedSendPacket.getCapacity() > 1048576)) {
this.sharedSendPacket = new Buffer(INITIAL_PACKET_SIZE);
}
}
boolean hadWarnings() {
return this.hadWarnings;
}
void scanForAndThrowDataTruncation() throws SQLException {
if ((this.streamingData == null) && versionMeetsMinimum(4, 1, 0) && this.connection.getJdbcCompliantTruncation() && this.warningCount > 0) {
SQLError.convertShowWarningsToSQLWarnings(this.connection, this.warningCount, true);
}
}
/**
* Secure authentication for 4.1 and newer servers.
*
* @param packet
* @param packLength
* @param user
* @param password
* @param database
* @param writeClientParams
*
* @throws SQLException
*/
private void secureAuth(Buffer packet, int packLength, String user, String password, String database, boolean writeClientParams) throws SQLException {
// Passwords can be 16 chars long
if (packet == null) {
packet = new Buffer(packLength);
}
if (writeClientParams) {
if (this.use41Extensions) {
if (versionMeetsMinimum(4, 1, 1)) {
packet.writeLong(this.clientParam);
packet.writeLong(this.maxThreeBytes);
// charset, JDBC will connect as 'latin1', and use 'SET NAMES' to change to the desired charset after the connection is established.
packet.writeByte((byte) 8);
// Set of bytes reserved for future use.
packet.writeBytesNoNull(new byte[23]);
} else {
packet.writeLong(this.clientParam);
packet.writeLong(this.maxThreeBytes);
}
} else {
packet.writeInt((int) this.clientParam);
packet.writeLongInt(this.maxThreeBytes);
}
}
// User/Password data
packet.writeString(user, CODE_PAGE_1252, this.connection);
if (password.length() != 0) {
/* Prepare false scramble */
packet.writeString(FALSE_SCRAMBLE, CODE_PAGE_1252, this.connection);
} else {
/* For empty password */
packet.writeString("", CODE_PAGE_1252, this.connection);
}
if (this.useConnectWithDb) {
packet.writeString(database, CODE_PAGE_1252, this.connection);
}
send(packet, packet.getPosition());
//
// Don't continue stages if password is empty
//
if (password.length() > 0) {
Buffer b = readPacket();
b.setPosition(0);
byte[] replyAsBytes = b.getByteBuffer();
if ((replyAsBytes.length == 24) && (replyAsBytes[0] != 0)) {
// Old passwords will have '*' at the first byte of hash */
if (replyAsBytes[0] != '*') {
try {
/* Build full password hash as it is required to decode scramble */
byte[] buff = Security.passwordHashStage1(password);
/* Store copy as we'll need it later */
byte[] passwordHash = new byte[buff.length];
System.arraycopy(buff, 0, passwordHash, 0, buff.length);
/* Finally hash complete password using hash we got from server */
passwordHash = Security.passwordHashStage2(passwordHash, replyAsBytes);
byte[] packetDataAfterSalt = new byte[replyAsBytes.length - 4];
System.arraycopy(replyAsBytes, 4, packetDataAfterSalt, 0, replyAsBytes.length - 4);
byte[] mysqlScrambleBuff = new byte[SEED_LENGTH];
/* Decypt and store scramble 4 = hash for stage2 */
Security.xorString(packetDataAfterSalt, mysqlScrambleBuff, passwordHash, SEED_LENGTH);
/* Encode scramble with password. Recycle buffer */
Security.xorString(mysqlScrambleBuff, buff, buff, SEED_LENGTH);
Buffer packet2 = new Buffer(25);
packet2.writeBytesNoNull(buff);
this.packetSequence++;
send(packet2, 24);
} catch (NoSuchAlgorithmException nse) {
throw SQLError.createSQLException(Messages.getString("MysqlIO.91") + Messages.getString("MysqlIO.92"), SQLError.SQL_STATE_GENERAL_ERROR,
getExceptionInterceptor());
}
} else {
try {
/* Create password to decode scramble */
byte[] passwordHash = Security.createKeyFromOldPassword(password);
/* Decypt and store scramble 4 = hash for stage2 */
byte[] netReadPos4 = new byte[replyAsBytes.length - 4];
System.arraycopy(replyAsBytes, 4, netReadPos4, 0, replyAsBytes.length - 4);
byte[] mysqlScrambleBuff = new byte[SEED_LENGTH];
/* Decypt and store scramble 4 = hash for stage2 */
Security.xorString(netReadPos4, mysqlScrambleBuff, passwordHash, SEED_LENGTH);
/* Finally scramble decoded scramble with password */
String scrambledPassword = Util.scramble(StringUtils.toString(mysqlScrambleBuff), password);
Buffer packet2 = new Buffer(packLength);
packet2.writeString(scrambledPassword, CODE_PAGE_1252, this.connection);
this.packetSequence++;
send(packet2, 24);
} catch (NoSuchAlgorithmException nse) {
throw SQLError.createSQLException(Messages.getString("MysqlIO.91") + Messages.getString("MysqlIO.92"), SQLError.SQL_STATE_GENERAL_ERROR,
getExceptionInterceptor());
}
}
}
}
}
/**
* Secure authentication for 4.1.1 and newer servers.
*
* @param packet
* @param packLength
* @param user
* @param password
* @param database
* @param writeClientParams
*
* @throws SQLException
*/
void secureAuth411(Buffer packet, int packLength, String user, String password, String database, boolean writeClientParams) throws SQLException {
String enc = getEncodingForHandshake();
// SERVER: public_seed=create_random_string()
// send(public_seed)
//
// CLIENT: recv(public_seed)
// hash_stage1=sha1("password")
// hash_stage2=sha1(hash_stage1)
// reply=xor(hash_stage1, sha1(public_seed,hash_stage2)
//
// // this three steps are done in scramble()
//
// send(reply)
//
//
// SERVER: recv(reply)
// hash_stage1=xor(reply, sha1(public_seed,hash_stage2))
// candidate_hash2=sha1(hash_stage1)
// check(candidate_hash2==hash_stage2)
// Passwords can be 16 chars long
if (packet == null) {
packet = new Buffer(packLength);
}
if (writeClientParams) {
if (this.use41Extensions) {
if (versionMeetsMinimum(4, 1, 1)) {
packet.writeLong(this.clientParam);
packet.writeLong(this.maxThreeBytes);
appendCharsetByteForHandshake(packet, enc);
// Set of bytes reserved for future use.
packet.writeBytesNoNull(new byte[23]);
} else {
packet.writeLong(this.clientParam);
packet.writeLong(this.maxThreeBytes);
}
} else {
packet.writeInt((int) this.clientParam);
packet.writeLongInt(this.maxThreeBytes);
}
}
// User/Password data
if (user != null) {
packet.writeString(user, enc, this.connection);
}
if (password.length() != 0) {
packet.writeByte((byte) 0x14);
try {
packet.writeBytesNoNull(Security.scramble411(password, this.seed, this.connection.getPasswordCharacterEncoding()));
} catch (NoSuchAlgorithmException nse) {
throw SQLError.createSQLException(Messages.getString("MysqlIO.91") + Messages.getString("MysqlIO.92"), SQLError.SQL_STATE_GENERAL_ERROR,
getExceptionInterceptor());
} catch (UnsupportedEncodingException e) {
throw SQLError.createSQLException(Messages.getString("MysqlIO.91") + Messages.getString("MysqlIO.92"), SQLError.SQL_STATE_GENERAL_ERROR,
getExceptionInterceptor());
}
} else {
/* For empty password */
packet.writeByte((byte) 0);
}
if (this.useConnectWithDb) {
packet.writeString(database, enc, this.connection);
} else {
/* For empty database */
packet.writeByte((byte) 0);
}
// connection attributes
if ((this.serverCapabilities & CLIENT_CONNECT_ATTRS) != 0) {
sendConnectionAttributes(packet, enc, this.connection);
}
send(packet, packet.getPosition());
byte savePacketSequence = this.packetSequence++;
Buffer reply = checkErrorPacket();
if (reply.isAuthMethodSwitchRequestPacket()) {
/*
* By sending this very specific reply server asks us to send scrambled password in old format. The reply contains scramble_323.
*/
this.packetSequence = ++savePacketSequence;
packet.clear();
String seed323 = this.seed.substring(0, 8);
packet.writeString(Util.newCrypt(password, seed323, this.connection.getPasswordCharacterEncoding()));
send(packet, packet.getPosition());
/* Read what server thinks about out new auth message report */
checkErrorPacket();
}
}
/**
* Un-packs binary-encoded result set data for one row
*
* @param fields
* @param binaryData
* @param resultSetConcurrency
*
* @return byte[][]
*
* @throws SQLException
*/
private final ResultSetRow unpackBinaryResultSetRow(Field[] fields, Buffer binaryData, int resultSetConcurrency) throws SQLException {
int numFields = fields.length;
byte[][] unpackedRowData = new byte[numFields][];
//
// Unpack the null bitmask, first
//
int nullCount = (numFields + 9) / 8;
int nullMaskPos = binaryData.getPosition();
binaryData.setPosition(nullMaskPos + nullCount);
int bit = 4; // first two bits are reserved for future use
//
// TODO: Benchmark if moving check for updatable result sets out of loop is worthwhile?
//
for (int i = 0; i < numFields; i++) {
if ((binaryData.readByte(nullMaskPos) & bit) != 0) {
unpackedRowData[i] = null;
} else {
if (resultSetConcurrency != ResultSet.CONCUR_UPDATABLE) {
extractNativeEncodedColumn(binaryData, fields, i, unpackedRowData);
} else {
unpackNativeEncodedColumn(binaryData, fields, i, unpackedRowData);
}
}
if (((bit <<= 1) & 255) == 0) {
bit = 1; /* To next byte */
nullMaskPos++;
}
}
return new ByteArrayRow(unpackedRowData, getExceptionInterceptor());
}
private final void extractNativeEncodedColumn(Buffer binaryData, Field[] fields, int columnIndex, byte[][] unpackedRowData) throws SQLException {
Field curField = fields[columnIndex];
switch (curField.getMysqlType()) {
case MysqlDefs.FIELD_TYPE_NULL:
break; // for dummy binds
case MysqlDefs.FIELD_TYPE_TINY:
unpackedRowData[columnIndex] = new byte[] { binaryData.readByte() };
break;
case MysqlDefs.FIELD_TYPE_SHORT:
case MysqlDefs.FIELD_TYPE_YEAR:
unpackedRowData[columnIndex] = binaryData.getBytes(2);
break;
case MysqlDefs.FIELD_TYPE_LONG:
case MysqlDefs.FIELD_TYPE_INT24:
unpackedRowData[columnIndex] = binaryData.getBytes(4);
break;
case MysqlDefs.FIELD_TYPE_LONGLONG:
unpackedRowData[columnIndex] = binaryData.getBytes(8);
break;
case MysqlDefs.FIELD_TYPE_FLOAT:
unpackedRowData[columnIndex] = binaryData.getBytes(4);
break;
case MysqlDefs.FIELD_TYPE_DOUBLE:
unpackedRowData[columnIndex] = binaryData.getBytes(8);
break;
case MysqlDefs.FIELD_TYPE_TIME:
int length = (int) binaryData.readFieldLength();
unpackedRowData[columnIndex] = binaryData.getBytes(length);
break;
case MysqlDefs.FIELD_TYPE_DATE:
length = (int) binaryData.readFieldLength();
unpackedRowData[columnIndex] = binaryData.getBytes(length);
break;
case MysqlDefs.FIELD_TYPE_DATETIME:
case MysqlDefs.FIELD_TYPE_TIMESTAMP:
length = (int) binaryData.readFieldLength();
unpackedRowData[columnIndex] = binaryData.getBytes(length);
break;
case MysqlDefs.FIELD_TYPE_TINY_BLOB:
case MysqlDefs.FIELD_TYPE_MEDIUM_BLOB:
case MysqlDefs.FIELD_TYPE_LONG_BLOB:
case MysqlDefs.FIELD_TYPE_BLOB:
case MysqlDefs.FIELD_TYPE_VAR_STRING:
case MysqlDefs.FIELD_TYPE_VARCHAR:
case MysqlDefs.FIELD_TYPE_STRING:
case MysqlDefs.FIELD_TYPE_DECIMAL:
case MysqlDefs.FIELD_TYPE_NEW_DECIMAL:
case MysqlDefs.FIELD_TYPE_GEOMETRY:
case MysqlDefs.FIELD_TYPE_BIT:
case MysqlDefs.FIELD_TYPE_JSON:
unpackedRowData[columnIndex] = binaryData.readLenByteArray(0);
break;
default:
throw SQLError.createSQLException(
Messages.getString("MysqlIO.97") + curField.getMysqlType() + Messages.getString("MysqlIO.98") + columnIndex
+ Messages.getString("MysqlIO.99") + fields.length + Messages.getString("MysqlIO.100"),
SQLError.SQL_STATE_GENERAL_ERROR, getExceptionInterceptor());
}
}
private final void unpackNativeEncodedColumn(Buffer binaryData, Field[] fields, int columnIndex, byte[][] unpackedRowData) throws SQLException {
Field curField = fields[columnIndex];
switch (curField.getMysqlType()) {
case MysqlDefs.FIELD_TYPE_NULL:
break; // for dummy binds
case MysqlDefs.FIELD_TYPE_TINY:
byte tinyVal = binaryData.readByte();
if (!curField.isUnsigned()) {
unpackedRowData[columnIndex] = StringUtils.getBytes(String.valueOf(tinyVal));
} else {
short unsignedTinyVal = (short) (tinyVal & 0xff);
unpackedRowData[columnIndex] = StringUtils.getBytes(String.valueOf(unsignedTinyVal));
}
break;
case MysqlDefs.FIELD_TYPE_SHORT:
case MysqlDefs.FIELD_TYPE_YEAR:
short shortVal = (short) binaryData.readInt();
if (!curField.isUnsigned()) {
unpackedRowData[columnIndex] = StringUtils.getBytes(String.valueOf(shortVal));
} else {
int unsignedShortVal = shortVal & 0xffff;
unpackedRowData[columnIndex] = StringUtils.getBytes(String.valueOf(unsignedShortVal));
}
break;
case MysqlDefs.FIELD_TYPE_LONG:
case MysqlDefs.FIELD_TYPE_INT24:
int intVal = (int) binaryData.readLong();
if (!curField.isUnsigned()) {
unpackedRowData[columnIndex] = StringUtils.getBytes(String.valueOf(intVal));
} else {
long longVal = intVal & 0xffffffffL;
unpackedRowData[columnIndex] = StringUtils.getBytes(String.valueOf(longVal));
}
break;
case MysqlDefs.FIELD_TYPE_LONGLONG:
long longVal = binaryData.readLongLong();
if (!curField.isUnsigned()) {
unpackedRowData[columnIndex] = StringUtils.getBytes(String.valueOf(longVal));
} else {
BigInteger asBigInteger = ResultSetImpl.convertLongToUlong(longVal);
unpackedRowData[columnIndex] = StringUtils.getBytes(asBigInteger.toString());
}
break;
case MysqlDefs.FIELD_TYPE_FLOAT:
float floatVal = Float.intBitsToFloat(binaryData.readIntAsLong());
unpackedRowData[columnIndex] = StringUtils.getBytes(String.valueOf(floatVal));
break;
case MysqlDefs.FIELD_TYPE_DOUBLE:
double doubleVal = Double.longBitsToDouble(binaryData.readLongLong());
unpackedRowData[columnIndex] = StringUtils.getBytes(String.valueOf(doubleVal));
break;
case MysqlDefs.FIELD_TYPE_TIME:
int length = (int) binaryData.readFieldLength();
int hour = 0;
int minute = 0;
int seconds = 0;
if (length != 0) {
binaryData.readByte(); // skip tm->neg
binaryData.readLong(); // skip daysPart
hour = binaryData.readByte();
minute = binaryData.readByte();
seconds = binaryData.readByte();
if (length > 8) {
binaryData.readLong(); // ignore 'secondsPart'
}
}
byte[] timeAsBytes = new byte[8];
timeAsBytes[0] = (byte) Character.forDigit(hour / 10, 10);
timeAsBytes[1] = (byte) Character.forDigit(hour % 10, 10);
timeAsBytes[2] = (byte) ':';
timeAsBytes[3] = (byte) Character.forDigit(minute / 10, 10);
timeAsBytes[4] = (byte) Character.forDigit(minute % 10, 10);
timeAsBytes[5] = (byte) ':';
timeAsBytes[6] = (byte) Character.forDigit(seconds / 10, 10);
timeAsBytes[7] = (byte) Character.forDigit(seconds % 10, 10);
unpackedRowData[columnIndex] = timeAsBytes;
break;
case MysqlDefs.FIELD_TYPE_DATE:
length = (int) binaryData.readFieldLength();
int year = 0;
int month = 0;
int day = 0;
hour = 0;
minute = 0;
seconds = 0;
if (length != 0) {
year = binaryData.readInt();
month = binaryData.readByte();
day = binaryData.readByte();
}
if ((year == 0) && (month == 0) && (day == 0)) {
if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL.equals(this.connection.getZeroDateTimeBehavior())) {
unpackedRowData[columnIndex] = null;
break;
} else if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_EXCEPTION.equals(this.connection.getZeroDateTimeBehavior())) {
throw SQLError.createSQLException("Value '0000-00-00' can not be represented as java.sql.Date", SQLError.SQL_STATE_ILLEGAL_ARGUMENT,
getExceptionInterceptor());
}
year = 1;
month = 1;
day = 1;
}
byte[] dateAsBytes = new byte[10];
dateAsBytes[0] = (byte) Character.forDigit(year / 1000, 10);
int after1000 = year % 1000;
dateAsBytes[1] = (byte) Character.forDigit(after1000 / 100, 10);
int after100 = after1000 % 100;
dateAsBytes[2] = (byte) Character.forDigit(after100 / 10, 10);
dateAsBytes[3] = (byte) Character.forDigit(after100 % 10, 10);
dateAsBytes[4] = (byte) '-';
dateAsBytes[5] = (byte) Character.forDigit(month / 10, 10);
dateAsBytes[6] = (byte) Character.forDigit(month % 10, 10);
dateAsBytes[7] = (byte) '-';
dateAsBytes[8] = (byte) Character.forDigit(day / 10, 10);
dateAsBytes[9] = (byte) Character.forDigit(day % 10, 10);
unpackedRowData[columnIndex] = dateAsBytes;
break;
case MysqlDefs.FIELD_TYPE_DATETIME:
case MysqlDefs.FIELD_TYPE_TIMESTAMP:
length = (int) binaryData.readFieldLength();
year = 0;
month = 0;
day = 0;
hour = 0;
minute = 0;
seconds = 0;
int nanos = 0;
if (length != 0) {
year = binaryData.readInt();
month = binaryData.readByte();
day = binaryData.readByte();
if (length > 4) {
hour = binaryData.readByte();
minute = binaryData.readByte();
seconds = binaryData.readByte();
}
//if (length > 7) {
// nanos = (int)binaryData.readLong();
//}
}
if ((year == 0) && (month == 0) && (day == 0)) {
if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL.equals(this.connection.getZeroDateTimeBehavior())) {
unpackedRowData[columnIndex] = null;
break;
} else if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_EXCEPTION.equals(this.connection.getZeroDateTimeBehavior())) {
throw SQLError.createSQLException("Value '0000-00-00' can not be represented as java.sql.Timestamp",
SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
}
year = 1;
month = 1;
day = 1;
}
int stringLength = 19;
byte[] nanosAsBytes = StringUtils.getBytes(Integer.toString(nanos));
stringLength += (1 + nanosAsBytes.length); // '.' + # of digits
byte[] datetimeAsBytes = new byte[stringLength];
datetimeAsBytes[0] = (byte) Character.forDigit(year / 1000, 10);
after1000 = year % 1000;
datetimeAsBytes[1] = (byte) Character.forDigit(after1000 / 100, 10);
after100 = after1000 % 100;
datetimeAsBytes[2] = (byte) Character.forDigit(after100 / 10, 10);
datetimeAsBytes[3] = (byte) Character.forDigit(after100 % 10, 10);
datetimeAsBytes[4] = (byte) '-';
datetimeAsBytes[5] = (byte) Character.forDigit(month / 10, 10);
datetimeAsBytes[6] = (byte) Character.forDigit(month % 10, 10);
datetimeAsBytes[7] = (byte) '-';
datetimeAsBytes[8] = (byte) Character.forDigit(day / 10, 10);
datetimeAsBytes[9] = (byte) Character.forDigit(day % 10, 10);
datetimeAsBytes[10] = (byte) ' ';
datetimeAsBytes[11] = (byte) Character.forDigit(hour / 10, 10);
datetimeAsBytes[12] = (byte) Character.forDigit(hour % 10, 10);
datetimeAsBytes[13] = (byte) ':';
datetimeAsBytes[14] = (byte) Character.forDigit(minute / 10, 10);
datetimeAsBytes[15] = (byte) Character.forDigit(minute % 10, 10);
datetimeAsBytes[16] = (byte) ':';
datetimeAsBytes[17] = (byte) Character.forDigit(seconds / 10, 10);
datetimeAsBytes[18] = (byte) Character.forDigit(seconds % 10, 10);
datetimeAsBytes[19] = (byte) '.';
final int nanosOffset = 20;
System.arraycopy(nanosAsBytes, 0, datetimeAsBytes, nanosOffset, nanosAsBytes.length);
unpackedRowData[columnIndex] = datetimeAsBytes;
break;
case MysqlDefs.FIELD_TYPE_TINY_BLOB:
case MysqlDefs.FIELD_TYPE_MEDIUM_BLOB:
case MysqlDefs.FIELD_TYPE_LONG_BLOB:
case MysqlDefs.FIELD_TYPE_BLOB:
case MysqlDefs.FIELD_TYPE_VAR_STRING:
case MysqlDefs.FIELD_TYPE_STRING:
case MysqlDefs.FIELD_TYPE_VARCHAR:
case MysqlDefs.FIELD_TYPE_DECIMAL:
case MysqlDefs.FIELD_TYPE_NEW_DECIMAL:
case MysqlDefs.FIELD_TYPE_BIT:
case MysqlDefs.FIELD_TYPE_JSON:
unpackedRowData[columnIndex] = binaryData.readLenByteArray(0);
break;
default:
throw SQLError.createSQLException(
Messages.getString("MysqlIO.97") + curField.getMysqlType() + Messages.getString("MysqlIO.98") + columnIndex
+ Messages.getString("MysqlIO.99") + fields.length + Messages.getString("MysqlIO.100"),
SQLError.SQL_STATE_GENERAL_ERROR, getExceptionInterceptor());
}
}
/**
* Negotiates the SSL communications channel used when connecting
* to a MySQL server that understands SSL.
*
* @param user
* @param password
* @param database
* @param packLength
* @throws SQLException
* @throws CommunicationsException
*/
private void negotiateSSLConnection(String user, String password, String database, int packLength) throws SQLException {
if (!ExportControlled.enabled()) {
throw new ConnectionFeatureNotAvailableException(this.connection, this.lastPacketSentTimeMs, null);
}
if ((this.serverCapabilities & CLIENT_SECURE_CONNECTION) != 0) {
this.clientParam |= CLIENT_SECURE_CONNECTION;
}
this.clientParam |= CLIENT_SSL;
Buffer packet = new Buffer(packLength);
if (this.use41Extensions) {
packet.writeLong(this.clientParam);
packet.writeLong(this.maxThreeBytes);
appendCharsetByteForHandshake(packet, getEncodingForHandshake());
packet.writeBytesNoNull(new byte[23]); // Set of bytes reserved for future use.
} else {
packet.writeInt((int) this.clientParam);
}
send(packet, packet.getPosition());
ExportControlled.transformSocketToSSLSocket(this);
}
public boolean isSSLEstablished() {
return ExportControlled.enabled() && ExportControlled.isSSLEstablished(this);
}
protected int getServerStatus() {
return this.serverStatus;
}
protected List<ResultSetRow> fetchRowsViaCursor(List<ResultSetRow> fetchedRows, long statementId, Field[] columnTypes, int fetchSize,
boolean useBufferRowExplicit) throws SQLException {
if (fetchedRows == null) {
fetchedRows = new ArrayList<ResultSetRow>(fetchSize);
} else {
fetchedRows.clear();
}
this.sharedSendPacket.clear();
this.sharedSendPacket.writeByte((byte) MysqlDefs.COM_FETCH);
this.sharedSendPacket.writeLong(statementId);
this.sharedSendPacket.writeLong(fetchSize);
sendCommand(MysqlDefs.COM_FETCH, null, this.sharedSendPacket, true, null, 0);
ResultSetRow row = null;
while ((row = nextRow(columnTypes, columnTypes.length, true, ResultSet.CONCUR_READ_ONLY, false, useBufferRowExplicit, false, null)) != null) {
fetchedRows.add(row);
}
return fetchedRows;
}
protected long getThreadId() {
return this.threadId;
}
protected boolean useNanosForElapsedTime() {
return this.useNanosForElapsedTime;
}
protected long getSlowQueryThreshold() {
return this.slowQueryThreshold;
}
protected String getQueryTimingUnits() {
return this.queryTimingUnits;
}
protected int getCommandCount() {
return this.commandCount;
}
private void checkTransactionState(int oldStatus) throws SQLException {
boolean previouslyInTrans = (oldStatus & SERVER_STATUS_IN_TRANS) != 0;
boolean currentlyInTrans = inTransactionOnServer();
if (previouslyInTrans && !currentlyInTrans) {
this.connection.transactionCompleted();
} else if (!previouslyInTrans && currentlyInTrans) {
this.connection.transactionBegun();
}
}
private void preserveOldTransactionState() {
this.serverStatus |= (this.oldServerStatus & SERVER_STATUS_IN_TRANS);
}
protected void setStatementInterceptors(List<StatementInterceptorV2> statementInterceptors) {
this.statementInterceptors = statementInterceptors.isEmpty() ? null : statementInterceptors;
}
protected ExceptionInterceptor getExceptionInterceptor() {
return this.exceptionInterceptor;
}
protected void setSocketTimeout(int milliseconds) throws SQLException {
try {
if (this.mysqlConnection != null) {
this.mysqlConnection.setSoTimeout(milliseconds);
}
} catch (SocketException e) {
SQLException sqlEx = SQLError.createSQLException("Invalid socket timeout value or state", SQLError.SQL_STATE_ILLEGAL_ARGUMENT,
getExceptionInterceptor());
sqlEx.initCause(e);
throw sqlEx;
}
}
protected void releaseResources() {
if (this.deflater != null) {
this.deflater.end();
this.deflater = null;
}
}
/**
* Get the Java encoding to be used for the handshake
* response. Defaults to UTF-8.
*/
String getEncodingForHandshake() {
String enc = this.connection.getEncoding();
if (enc == null) {
enc = "UTF-8";
}
return enc;
}
/**
* Append the MySQL collation index to the handshake packet. A
* single byte will be added to the packet corresponding to the
* collation index found for the requested Java encoding name.
*
* If the index is > 255 which may be valid at some point in
* the future, an exception will be thrown. At the time of this
* implementation the index cannot be > 255 and only the
* COM_CHANGE_USER rpc, not the handshake response, can handle a
* value > 255.
*
* @param packet
* to append to
* @param end
* The Java encoding name used to lookup the collation index
*/
private void appendCharsetByteForHandshake(Buffer packet, String enc) throws SQLException {
int charsetIndex = 0;
if (enc != null) {
charsetIndex = CharsetMapping.getCollationIndexForJavaEncoding(enc, this.connection);
}
if (charsetIndex == 0) {
charsetIndex = CharsetMapping.MYSQL_COLLATION_INDEX_utf8;
}
if (charsetIndex > 255) {
throw SQLError.createSQLException("Invalid character set index for encoding: " + enc, SQLError.SQL_STATE_ILLEGAL_ARGUMENT,
getExceptionInterceptor());
}
packet.writeByte((byte) charsetIndex);
}
public boolean isEOFDeprecated() {
return (this.clientParam & CLIENT_DEPRECATE_EOF) != 0;
}
}
|
9237e14be8caca2358eabf8dd94257fd46300b53 | 3,294 | java | Java | src/main/java/com/alipay/api/request/ZhimaCustomerEpCertificationQueryRequest.java | doveylovey/alipay-sdk-java | 89cf2e649d753cad5c95ef0d1256c3c8b6fac6ed | [
"Apache-2.0"
] | null | null | null | src/main/java/com/alipay/api/request/ZhimaCustomerEpCertificationQueryRequest.java | doveylovey/alipay-sdk-java | 89cf2e649d753cad5c95ef0d1256c3c8b6fac6ed | [
"Apache-2.0"
] | null | null | null | src/main/java/com/alipay/api/request/ZhimaCustomerEpCertificationQueryRequest.java | doveylovey/alipay-sdk-java | 89cf2e649d753cad5c95ef0d1256c3c8b6fac6ed | [
"Apache-2.0"
] | null | null | null | 23.361702 | 123 | 0.673345 | 998,233 | package com.alipay.api.request;
import com.alipay.api.domain.ZhimaCustomerEpCertificationQueryModel;
import java.util.Map;
import com.alipay.api.AlipayRequest;
import com.alipay.api.internal.util.AlipayHashMap;
import com.alipay.api.response.ZhimaCustomerEpCertificationQueryResponse;
import com.alipay.api.AlipayObject;
/**
* ALIPAY API: zhima.customer.ep.certification.query request
*
* @author auto create
* @since 1.0, 2020-07-10 10:18:04
*/
public class ZhimaCustomerEpCertificationQueryRequest implements AlipayRequest<ZhimaCustomerEpCertificationQueryResponse> {
private AlipayHashMap udfParams; // add user-defined text parameters
private String apiVersion = "1.0";
/**
* 企业认证查询服务
*/
private String bizContent;
public void setBizContent(String bizContent) {
this.bizContent = bizContent;
}
public String getBizContent() {
return this.bizContent;
}
private String terminalType;
private String terminalInfo;
private String prodCode;
private String notifyUrl;
private String returnUrl;
private boolean needEncrypt = false;
private AlipayObject bizModel = null;
public String getNotifyUrl() {
return this.notifyUrl;
}
public void setNotifyUrl(String notifyUrl) {
this.notifyUrl = notifyUrl;
}
public String getReturnUrl() {
return this.returnUrl;
}
public void setReturnUrl(String returnUrl) {
this.returnUrl = returnUrl;
}
public String getApiVersion() {
return this.apiVersion;
}
public void setApiVersion(String apiVersion) {
this.apiVersion = apiVersion;
}
public void setTerminalType(String terminalType) {
this.terminalType = terminalType;
}
public String getTerminalType() {
return this.terminalType;
}
public void setTerminalInfo(String terminalInfo) {
this.terminalInfo = terminalInfo;
}
public String getTerminalInfo() {
return this.terminalInfo;
}
public void setProdCode(String prodCode) {
this.prodCode = prodCode;
}
public String getProdCode() {
return this.prodCode;
}
public String getApiMethodName() {
return "zhima.customer.ep.certification.query";
}
public Map<String, String> getTextParams() {
AlipayHashMap txtParams = new AlipayHashMap();
txtParams.put("biz_content", this.bizContent);
if (udfParams != null) {
txtParams.putAll(this.udfParams);
}
return txtParams;
}
public void putOtherTextParam(String key, String value) {
if (this.udfParams == null) {
this.udfParams = new AlipayHashMap();
}
this.udfParams.put(key, value);
}
public Class<ZhimaCustomerEpCertificationQueryResponse> getResponseClass() {
return ZhimaCustomerEpCertificationQueryResponse.class;
}
public boolean isNeedEncrypt() {
return this.needEncrypt;
}
public void setNeedEncrypt(boolean needEncrypt) {
this.needEncrypt = needEncrypt;
}
public AlipayObject getBizModel() {
return this.bizModel;
}
public void setBizModel(AlipayObject bizModel) {
this.bizModel = bizModel;
}
}
|
9237e1aa0db1fb24ce7b8f7992f028afbb147f76 | 1,013 | java | Java | mywork-mgs/src/main/java/com/lanzhu/mywork/mgs/account/UserController.java | lanzhu259X/mywork | e37aa820d304a4a64d8294615178f1543c792873 | [
"Apache-2.0"
] | null | null | null | mywork-mgs/src/main/java/com/lanzhu/mywork/mgs/account/UserController.java | lanzhu259X/mywork | e37aa820d304a4a64d8294615178f1543c792873 | [
"Apache-2.0"
] | null | null | null | mywork-mgs/src/main/java/com/lanzhu/mywork/mgs/account/UserController.java | lanzhu259X/mywork | e37aa820d304a4a64d8294615178f1543c792873 | [
"Apache-2.0"
] | null | null | null | 30.69697 | 72 | 0.735439 | 998,234 | package com.lanzhu.mywork.mgs.account;
import com.lanzhu.mywork.mgs.account.vo.UserResult;
import com.lanzhu.mywork.mgs.base.BaseAction;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
@Log4j2
@RestController
@RequestMapping("/private/v1")
public class UserController extends BaseAction {
@GetMapping("/account/user/{userId}")
public UserResult getUserById(@PathVariable("userId") Long userId) {
log.info("get user by userId:{}", userId);
UserResult result = new UserResult();
result.setDisplayName("test");
result.setAvatarUrl("https://xxx.com/xxx.png");
result.setInviteCode("12345");
result.setUpdateTime(new Date());
result.setCreateTime(new Date());
return result;
}
}
|
9237e1ab982a5b5fc4c4f2e059ab322e4a643efd | 7,509 | java | Java | core/src/test/java/com/artos/tests/core/AbstractRaftTest.java | apmedvedev/artos-java | e51fcd41c7a29063e100bd5442541be2c3fee3f0 | [
"Apache-2.0"
] | null | null | null | core/src/test/java/com/artos/tests/core/AbstractRaftTest.java | apmedvedev/artos-java | e51fcd41c7a29063e100bd5442541be2c3fee3f0 | [
"Apache-2.0"
] | null | null | null | core/src/test/java/com/artos/tests/core/AbstractRaftTest.java | apmedvedev/artos-java | e51fcd41c7a29063e100bd5442541be2c3fee3f0 | [
"Apache-2.0"
] | null | null | null | 43.404624 | 148 | 0.717938 | 998,235 | package com.artos.tests.core;
import com.artos.api.core.server.conf.GroupConfiguration;
import com.artos.api.core.server.conf.MemoryLogStoreFactoryConfiguration;
import com.artos.api.core.server.conf.ServerChannelConfiguration;
import com.artos.api.core.server.conf.ServerChannelConfigurationBuilder;
import com.artos.api.core.server.conf.ServerChannelFactoryConfiguration;
import com.artos.api.core.server.conf.ServerChannelFactoryConfigurationBuilder;
import com.artos.api.core.server.conf.ServerConfiguration;
import com.artos.impl.core.message.AppendEntriesRequestBuilder;
import com.artos.impl.core.message.AppendEntriesResponse;
import com.artos.impl.core.message.AppendEntriesResponseBuilder;
import com.artos.impl.core.message.PublishRequestBuilder;
import com.artos.impl.core.server.impl.Context;
import com.artos.impl.core.server.impl.State;
import com.artos.spi.core.ILogStore;
import com.artos.spi.core.IMessageListenerFactory;
import com.artos.spi.core.IMessageSenderFactory;
import com.artos.spi.core.IStateMachine;
import com.artos.spi.core.LogEntry;
import com.artos.spi.core.LogValueType;
import com.artos.spi.core.ServerState;
import com.artos.tests.core.mocks.LogStoreMock;
import com.artos.tests.core.mocks.MessageListenerFactoryMock;
import com.artos.tests.core.mocks.MessageSenderFactoryMock;
import com.artos.tests.core.mocks.StateMachineMock;
import com.artos.tests.core.mocks.TestMessageListenerFactoryConfiguration;
import com.artos.tests.core.mocks.TestMessageSenderFactoryConfiguration;
import com.exametrika.common.compartment.ICompartment;
import com.exametrika.common.compartment.ICompartmentFactory.Parameters;
import com.exametrika.common.compartment.impl.CompartmentFactory;
import com.exametrika.common.utils.ByteArray;
import com.exametrika.common.utils.Times;
import org.junit.After;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public abstract class AbstractRaftTest {
protected Context context;
protected State state;
@After
public void tearDown() {
Times.clearTest();
if (context != null)
context.getCompartment().stop();
}
protected State createState(int serverCount) {
State state = new State();
List<ServerConfiguration> serverConfigurations = new ArrayList<>();
for (int i = 0; i < serverCount; i++)
serverConfigurations.add(new ServerConfiguration(UUID.randomUUID(), "testEndpoint-" + i));
GroupConfiguration groupConfiguration = new GroupConfiguration("test", UUID.randomUUID(), serverConfigurations, false);
state.setConfiguration(groupConfiguration);
ServerState serverState = new ServerState();
state.setServerState(serverState);
this.state = state;
return state;
}
protected Context createContext(GroupConfiguration groupConfiguration) {
IStateMachine stateMachine = new StateMachineMock();
stateMachine.beginTransaction(false).writeConfiguration(groupConfiguration);
IMessageListenerFactory messageListenerFactory = new MessageListenerFactoryMock();
IMessageSenderFactory messageSenderFactory = new MessageSenderFactoryMock();
ICompartment compartment = new CompartmentFactory().createCompartment(new Parameters());
compartment.start();
ServerChannelFactoryConfiguration serverChannelFactoryConfiguration =
new ServerChannelFactoryConfigurationBuilder().toConfiguration();
ServerChannelConfiguration serverChannelConfiguration = new ServerChannelConfigurationBuilder()
.setGroup(groupConfiguration)
.setServer(groupConfiguration.getServers().get(0))
.setLogStore(new MemoryLogStoreFactoryConfiguration(0))
.setMessageListener(new TestMessageListenerFactoryConfiguration())
.setMessageSender(new TestMessageSenderFactoryConfiguration())
.setStateTransferPortRangeStart(17000)
.setStateTransferPortRangeEnd(19000)
.setStateTransferUseCompression(true)
.setStateTransferMaxSize(1000)
.setStateTransferBindAddress("localhost")
.setWorkDir("").toConfiguration();
ILogStore logStore = new LogStoreMock(0);
ServerConfiguration configuration = groupConfiguration.getServers().get(0);
return new Context(configuration, groupConfiguration.getGroupId(), logStore,
stateMachine, serverChannelFactoryConfiguration, serverChannelConfiguration, messageListenerFactory, messageSenderFactory, compartment);
}
protected AppendEntriesRequestBuilder createAppendEntriesRequest() {
AppendEntriesRequestBuilder builder = new AppendEntriesRequestBuilder();
builder.setGroupId(context.getGroupId());
if (state.getConfiguration().getServers().size() > 1)
builder.setSource(state.getConfiguration().getServers().get(1).getId());
else
builder.setSource(UUID.randomUUID());
builder.setLogEntries(new ArrayList<>());
return builder;
}
protected AppendEntriesResponse createAppendEntriesResponse() {
AppendEntriesResponseBuilder builder = new AppendEntriesResponseBuilder();
builder.setGroupId(UUID.randomUUID());
builder.setSource(UUID.randomUUID());
return builder.toMessage();
}
protected PublishRequestBuilder createPublishRequest() {
PublishRequestBuilder request = new PublishRequestBuilder();
request.setGroupId(context.getGroupId());
request.setSource(UUID.randomUUID());
return request;
}
protected void addLogEntries(UUID clientId, long term, int count) {
for (int i = 0; i < count; i++)
context.getLogStore().append(new LogEntry(term, new ByteArray(new byte[0]), LogValueType.APPLICATION,
clientId, context.getLogStore().getEndIndex()));
}
protected List<LogEntry> createLogEntries(UUID clientId, long term, int start, int count) {
List<LogEntry> logEntries = new ArrayList<>();
for (int i = 0; i < count; i++)
logEntries.add(new LogEntry(term, new ByteArray(new byte[0]), LogValueType.APPLICATION, clientId, start + i));
return logEntries;
}
protected List<ByteArray> createLogEntries(int count, int size) {
List<ByteArray> list = new ArrayList<>();
for (int i = 0; i < count; i++)
list.add(new ByteArray(new byte[size]));
return list;
}
protected void checkLogEntries(List<LogEntry> logEntries, UUID clientId, long term, long startIndex, int count, boolean checkValue) {
assertThat(logEntries.size(), is(count));
for (int i = 0; i < count; i++) {
LogEntry entry = logEntries.get(i);
assertThat(entry.getValueType(), is(LogValueType.APPLICATION));
assertThat(entry.getClientId(), is(clientId));
assertThat(entry.getMessageId(), is(startIndex + i));
assertThat(entry.getTerm(), is(term));
if (checkValue)
assertThat(entry.getValue() != null, is(true));
}
}
protected ByteArray createBuffer(byte start, int size) {
byte[] buffer = new byte[size];
byte value = start;
for (int i = 0; i < size; i++) {
buffer[i] = value;
value++;
}
return new ByteArray(buffer);
}
}
|
9237e230530b0410cb56e9528d53e345858c251f | 592 | java | Java | src/main/java/net/hyjuki/smgen/base/utils/PageResult.java | wintop/Spring-mytabits-generator | 8797f207fbd9e1dd33072acb1816a10463c20779 | [
"MIT"
] | null | null | null | src/main/java/net/hyjuki/smgen/base/utils/PageResult.java | wintop/Spring-mytabits-generator | 8797f207fbd9e1dd33072acb1816a10463c20779 | [
"MIT"
] | null | null | null | src/main/java/net/hyjuki/smgen/base/utils/PageResult.java | wintop/Spring-mytabits-generator | 8797f207fbd9e1dd33072acb1816a10463c20779 | [
"MIT"
] | null | null | null | 17.939394 | 73 | 0.543919 | 998,236 | package net.hyjuki.smgen.base.utils;
public class PageResult<T> {
private T data;
private int total;
public PageResult(T data, int total) {
this.data = data;
this.total = total;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
@Override
public String toString() {
return "PageResult{" + "data=" + data + ", total=" + total + '}';
}
}
|
9237e38a16921bead23a1d59c603a8b84c118b3a | 1,726 | java | Java | src/test/java/seedu/travel/testutil/TypicalYearChart.java | chung-ming/main | 37175a6888efc20d844b5461fe4a0ae067f9906e | [
"MIT"
] | 2 | 2019-04-12T01:48:29.000Z | 2019-04-16T04:45:26.000Z | src/test/java/seedu/travel/testutil/TypicalYearChart.java | chung-ming/main | 37175a6888efc20d844b5461fe4a0ae067f9906e | [
"MIT"
] | 87 | 2019-04-03T08:24:29.000Z | 2019-07-26T07:19:16.000Z | src/test/java/seedu/travel/testutil/TypicalYearChart.java | chung-ming/main | 37175a6888efc20d844b5461fe4a0ae067f9906e | [
"MIT"
] | 5 | 2019-02-03T05:54:01.000Z | 2019-02-19T12:17:10.000Z | 29.758621 | 86 | 0.634994 | 998,237 | package seedu.travel.testutil;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import seedu.travel.model.ChartBook;
import seedu.travel.model.chart.YearChart;
/**
* A utility class containing a list of {@code YearChart} objects to be used in tests.
*/
public class TypicalYearChart {
public static final YearChart TWO_ZERO_ONE_ZERO = new YearChartBuilder()
.withYear("2010")
.withTotal("6")
.build();
public static final YearChart TWO_ZERO_ONE_ONE = new YearChartBuilder()
.withYear("2011")
.withTotal("7")
.build();
public static final YearChart TWO_ZERO_ONE_TWO = new YearChartBuilder()
.withYear("2012")
.withTotal("8")
.build();
public static final YearChart TWO_ZERO_ONE_THREE = new YearChartBuilder()
.withYear("2013")
.withTotal("9")
.build();
public static final YearChart TWO_ZERO_ONE_FOUR = new YearChartBuilder()
.withYear("2014")
.withTotal("10")
.build();
private TypicalYearChart() {} // prevents instantiation
/**
* Returns an {@code ChartBook} with all the typical year chart.
*/
public static ChartBook getTypicalChartBook() {
ChartBook chartBook = new ChartBook();
for (YearChart yearChart : getTypicalYearChart()) {
chartBook.addYearChart(yearChart);
}
return chartBook;
}
public static List<YearChart> getTypicalYearChart() {
return new ArrayList<>(Arrays.asList(TWO_ZERO_ONE_ZERO, TWO_ZERO_ONE_ONE,
TWO_ZERO_ONE_TWO, TWO_ZERO_ONE_THREE, TWO_ZERO_ONE_FOUR));
}
}
|
9237e3ae340eb98b6823bdcc8b9d2ed626a9827e | 4,633 | java | Java | src/main/java/com/google/webauthn/gaedemo/servlets/SaveCredential.java | agektmr/webauthndemo | d990db6e369e74fdd67048b277b7f5c1f8573dd8 | [
"Apache-2.0"
] | 303 | 2017-06-09T20:57:58.000Z | 2022-03-26T13:35:25.000Z | src/main/java/com/google/webauthn/gaedemo/servlets/SaveCredential.java | agektmr/webauthndemo | d990db6e369e74fdd67048b277b7f5c1f8573dd8 | [
"Apache-2.0"
] | 47 | 2017-10-02T05:39:00.000Z | 2022-02-02T17:27:10.000Z | src/main/java/com/google/webauthn/gaedemo/servlets/SaveCredential.java | agektmr/webauthndemo | d990db6e369e74fdd67048b277b7f5c1f8573dd8 | [
"Apache-2.0"
] | 103 | 2017-07-24T06:06:51.000Z | 2022-03-22T09:02:34.000Z | 38.932773 | 100 | 0.758904 | 998,238 | // Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.webauthn.gaedemo.servlets;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.webauthn.gaedemo.crypto.Crypto;
import com.google.webauthn.gaedemo.objects.AttestationData;
import com.google.webauthn.gaedemo.objects.AttestationObject;
import com.google.webauthn.gaedemo.objects.AuthenticatorAttestationResponse;
import com.google.webauthn.gaedemo.objects.AuthenticatorData;
import com.google.webauthn.gaedemo.objects.EccKey;
import com.google.webauthn.gaedemo.objects.FidoU2fAttestationStatement;
import com.google.webauthn.gaedemo.objects.PublicKeyCredential;
import com.google.webauthn.gaedemo.storage.Credential;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.interfaces.ECPublicKey;
import java.security.spec.ECGenParameterSpec;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
/**
* Servlet implementation class SaveCredential
*/
public class SaveCredential extends HttpServlet {
private static final long serialVersionUID = 1L;
private final UserService userService = UserServiceFactory.getUserService();
/**
* @see HttpServlet#HttpServlet()
*/
public SaveCredential() {
super();
}
static {
Security.addProvider(new BouncyCastleProvider());
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String currentUser = userService.getCurrentUser().getEmail();
String id = request.getParameter("id");
Random rand = new Random();
byte[] aaguid = new byte[16];
rand.nextBytes(aaguid);
byte[] x = new byte[5], y = new byte[5];
ECGenParameterSpec ecGenSpec = new ECGenParameterSpec("secp256r1");
KeyPairGenerator keyGen;
try {
keyGen = KeyPairGenerator.getInstance("ECDSA", "BC");
} catch (NoSuchAlgorithmException e) {
throw new ServletException(e);
} catch (NoSuchProviderException e) {
throw new ServletException(e);
}
try {
keyGen.initialize(ecGenSpec, new SecureRandom());
} catch (InvalidAlgorithmParameterException e) {
throw new ServletException(e);
}
KeyPair keyPair = keyGen.generateKeyPair();
PublicKey pub = keyPair.getPublic();
ECPublicKey publicKey = (ECPublicKey) pub;
x = publicKey.getW().getAffineX().toByteArray();
y = publicKey.getW().getAffineY().toByteArray();
EccKey ecc = new EccKey(x, y);
AttestationData attData = new AttestationData(aaguid, aaguid, ecc);
byte[] rpIdHash = Crypto
.sha256Digest(((request.isSecure() ? "https://" : "http://") + request.getHeader("Host"))
.getBytes(StandardCharsets.UTF_8));
AuthenticatorData authData = new AuthenticatorData(rpIdHash, (byte) (1 << 6), 0, attData, null);
FidoU2fAttestationStatement attStmt = new FidoU2fAttestationStatement();
AttestationObject attObj = new AttestationObject(authData, "fido-u2f", attStmt);
AuthenticatorAttestationResponse attRsp = new AuthenticatorAttestationResponse();
attRsp.decodedObject = attObj;
PublicKeyCredential pkc =
new PublicKeyCredential(id, "", id.getBytes(StandardCharsets.UTF_8), attRsp);
Credential credential = new Credential(pkc);
credential.save(currentUser);
response.setContentType("application/json");
response.getWriter().println(credential.toJson());
}
}
|
9237e3aed51119b1657486078a0279e578e303ea | 1,522 | java | Java | src/main/java/cn/lacknb/toolsspringbootautoconfigure/utils/MobileUtils.java | MrNiebit/little-tools | 63a0952550e3530e13f932f23a400c0dee53932f | [
"MIT"
] | null | null | null | src/main/java/cn/lacknb/toolsspringbootautoconfigure/utils/MobileUtils.java | MrNiebit/little-tools | 63a0952550e3530e13f932f23a400c0dee53932f | [
"MIT"
] | null | null | null | src/main/java/cn/lacknb/toolsspringbootautoconfigure/utils/MobileUtils.java | MrNiebit/little-tools | 63a0952550e3530e13f932f23a400c0dee53932f | [
"MIT"
] | null | null | null | 28.185185 | 69 | 0.630749 | 998,239 | package cn.lacknb.toolsspringbootautoconfigure.utils;
import cn.lacknb.toolsspringbootautoconfigure.entity.MobileInfo;
import me.ihxq.projects.pna.PhoneNumberInfo;
import me.ihxq.projects.pna.PhoneNumberLookup;
/**
* <h2> </h2>
*
* @author: gitsilence
* @description:
* @date: 2021/12/12 11:35 上午
**/
public class MobileUtils {
private static PhoneNumberLookup NUMBER_LOOKUP;
static {
NUMBER_LOOKUP = new PhoneNumberLookup();
}
public static MobileInfo getMobileInfo(String mobile) {
PhoneNumberInfo found = NUMBER_LOOKUP.lookup(mobile)
.orElse(null);
if (found == null) {
return null;
}
MobileInfo mobileInfo = new MobileInfo();
mobileInfo.setMobile(found.getNumber());
mobileInfo.setCity(found.getAttribution().getCity());
mobileInfo.setIsp(found.getIsp().getCnName());
mobileInfo.setZipCode(found.getAttribution().getZipCode());
mobileInfo.setAreaCode(found.getAttribution().getAreaCode());
mobileInfo.setProvince(found.getAttribution().getProvince());
return mobileInfo;
}
public static boolean isInvalidPhoneNumber(String phoneNumber) {
if (phoneNumber == null) {
return true;
} else {
int phoneNumberLength = phoneNumber.length();
if (phoneNumberLength >= 7 && phoneNumberLength <= 11) {
return false;
} else {
return true;
}
}
}
}
|
9237e4df08f74ea7450d90009ff12ca2f9044001 | 3,027 | java | Java | src/main/java/com/mrbysco/blockhistory/helper/LogHelper.java | Mrbysco/BlockHistory | 0fccfb8ba69cff21da4850c68122b20986363873 | [
"MIT"
] | null | null | null | src/main/java/com/mrbysco/blockhistory/helper/LogHelper.java | Mrbysco/BlockHistory | 0fccfb8ba69cff21da4850c68122b20986363873 | [
"MIT"
] | 1 | 2021-08-06T06:21:33.000Z | 2021-08-06T06:21:33.000Z | src/main/java/com/mrbysco/blockhistory/helper/LogHelper.java | Mrbysco/BlockHistory | 0fccfb8ba69cff21da4850c68122b20986363873 | [
"MIT"
] | 1 | 2021-11-18T20:52:07.000Z | 2021-11-18T20:52:07.000Z | 49.622951 | 250 | 0.689792 | 998,240 | package com.mrbysco.blockhistory.helper;
import com.mrbysco.blockhistory.BlockHistory;
import com.mrbysco.blockhistory.storage.ChangeAction;
import com.mrbysco.blockhistory.storage.ChangeStorage;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.TranslationTextComponent;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
public class LogHelper {
public static File logFile = new File(BlockHistory.personalFolder, "/log.txt");
public static void logHistoryToFile(List<ChangeStorage> storageList) {
try {
FileWriter fileWriter = new FileWriter(logFile,false);
for (ChangeStorage change : storageList) {
String changeTxt = getLogText(change).getContents();
fileWriter.write(changeTxt + "\n");
}
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static ITextComponent getLogText(ChangeStorage change) {
ChangeAction action = ChangeAction.getAction(change.change);
if(action == ChangeAction.INVENTORY_INSERTION || action == ChangeAction.INVENTORY_WITHDRAWAL) {
if(change.extraData != null && !change.extraData.isEmpty()) {
TranslationTextComponent startComponent = new TranslationTextComponent("At %s %s has ", change.date, change.username);
startComponent.withStyle(action.getColor());
StringTextComponent changeListComponent = new StringTextComponent(change.extraData);
changeListComponent.withStyle(TextFormatting.WHITE);
TranslationTextComponent changeComponent = new TranslationTextComponent(action.getNicerName(), changeListComponent);
changeComponent.withStyle(action.getColor());
TranslationTextComponent endComponent = new TranslationTextComponent(" the inventory of block [%s]", change.resourceLocation.toString());
endComponent.withStyle(action.getColor());
ITextComponent logComponent = startComponent.append(changeComponent).append(endComponent);
return logComponent;
} else {
TranslationTextComponent fallBackComponent = new TranslationTextComponent("At %s %s has %s the inventory of block [%s]", change.date, change.username, String.format(action.getNicerName(), "items"), change.resourceLocation.toString());
fallBackComponent.withStyle(action.getColor());
return fallBackComponent;
}
} else {
TranslationTextComponent logComponent = new TranslationTextComponent("At %s %s has %s a block [%s]", change.date, change.username, action.getNicerName(), change.resourceLocation.toString());
logComponent.withStyle(action.getColor());
return logComponent;
}
}
}
|
9237e6195dea3b694a769fe1aae379d0d4321fdd | 10,904 | java | Java | src/test/java/io/cryostat/net/web/http/api/v1/TargetSnapshotPostHandlerTest.java | jan-law/cryostat | 8347e65e09eb46db9624e4f9b31e27202c03604e | [
"UPL-1.0"
] | 70 | 2021-05-14T15:50:42.000Z | 2022-02-25T04:48:23.000Z | src/test/java/io/cryostat/net/web/http/api/v1/TargetSnapshotPostHandlerTest.java | jan-law/cryostat | 8347e65e09eb46db9624e4f9b31e27202c03604e | [
"UPL-1.0"
] | 285 | 2021-04-26T15:26:16.000Z | 2022-03-30T12:40:16.000Z | src/test/java/io/cryostat/net/web/http/api/v1/TargetSnapshotPostHandlerTest.java | jan-law/cryostat | 8347e65e09eb46db9624e4f9b31e27202c03604e | [
"UPL-1.0"
] | 10 | 2019-07-22T12:31:16.000Z | 2021-02-15T10:22:47.000Z | 48.678571 | 209 | 0.708731 | 998,241 | /*
* Copyright The Cryostat Authors
*
* The Universal Permissive License (UPL), Version 1.0
*
* Subject to the condition set forth below, permission is hereby granted to any
* person obtaining a copy of this software, associated documentation and/or data
* (collectively the "Software"), free of charge and under any and all copyright
* rights in the Software, and any and all patent rights owned or freely
* licensable by each licensor hereunder covering either (i) the unmodified
* Software as contributed to or provided by such licensor, or (ii) the Larger
* Works (as defined below), to deal in both
*
* (a) the Software, and
* (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
* one is included with the Software (each a "Larger Work" to which the Software
* is contributed by such licensors),
*
* without restriction, including without limitation the rights to copy, create
* derivative works of, display, perform, and distribute the Software and make,
* use, sell, offer for sale, import, export, have made, and have sold the
* Software and the Larger Work(s), and to sublicense the foregoing rights on
* either these or other terms.
*
* This license is subject to the following condition:
* The above copyright notice and either this complete permission notice or at
* a minimum a reference to the UPL must 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.cryostat.net.web.http.api.v1;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import io.cryostat.jmc.serialization.HyperlinkedSerializableRecordingDescriptor;
import io.cryostat.net.AuthManager;
import io.cryostat.net.ConnectionDescriptor;
import io.cryostat.net.security.ResourceAction;
import io.cryostat.recordings.RecordingTargetHelper;
import io.cryostat.recordings.RecordingTargetHelper.SnapshotCreationException;
import io.vertx.core.MultiMap;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.impl.HttpStatusException;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class TargetSnapshotPostHandlerTest {
TargetSnapshotPostHandler handler;
@Mock AuthManager auth;
@Mock RecordingTargetHelper recordingTargetHelper;
@BeforeEach
void setup() {
this.handler = new TargetSnapshotPostHandler(auth, recordingTargetHelper);
}
@Test
void shouldHaveExpectedRequiredPermissions() {
MatcherAssert.assertThat(
handler.resourceActions(),
Matchers.equalTo(
Set.of(ResourceAction.READ_TARGET, ResourceAction.UPDATE_RECORDING)));
}
@Test
void shouldCreateSnapshot() throws Exception {
Mockito.when(auth.validateHttpHeader(Mockito.any(), Mockito.any()))
.thenReturn(CompletableFuture.completedFuture(true));
RoutingContext ctx = Mockito.mock(RoutingContext.class);
HttpServerRequest req = Mockito.mock(HttpServerRequest.class);
Mockito.when(ctx.request()).thenReturn(req);
Mockito.when(req.headers()).thenReturn(MultiMap.caseInsensitiveMultiMap());
HttpServerResponse resp = Mockito.mock(HttpServerResponse.class);
Mockito.when(ctx.response()).thenReturn(resp);
Mockito.when(ctx.pathParam("targetId")).thenReturn("someHost");
HyperlinkedSerializableRecordingDescriptor snapshotDescriptor =
Mockito.mock(HyperlinkedSerializableRecordingDescriptor.class);
CompletableFuture<HyperlinkedSerializableRecordingDescriptor> future1 =
Mockito.mock(CompletableFuture.class);
Mockito.when(recordingTargetHelper.createSnapshot(Mockito.any(ConnectionDescriptor.class)))
.thenReturn(future1);
Mockito.when(future1.get()).thenReturn(snapshotDescriptor);
Mockito.when(snapshotDescriptor.getName()).thenReturn("snapshot-1");
CompletableFuture<Boolean> future2 = Mockito.mock(CompletableFuture.class);
Mockito.when(
recordingTargetHelper.verifySnapshot(
Mockito.any(ConnectionDescriptor.class), Mockito.eq("snapshot-1")))
.thenReturn(future2);
Mockito.when(future2.get()).thenReturn(true);
handler.handle(ctx);
Mockito.verify(resp).setStatusCode(200);
Mockito.verify(resp).end("snapshot-1");
}
@Test
void shouldHandleSnapshotCreationExceptionDuringCreation() throws Exception {
Mockito.when(auth.validateHttpHeader(Mockito.any(), Mockito.any()))
.thenReturn(CompletableFuture.completedFuture(true));
RoutingContext ctx = Mockito.mock(RoutingContext.class);
HttpServerRequest req = Mockito.mock(HttpServerRequest.class);
Mockito.when(ctx.request()).thenReturn(req);
Mockito.when(req.headers()).thenReturn(MultiMap.caseInsensitiveMultiMap());
HttpServerResponse resp = Mockito.mock(HttpServerResponse.class);
Mockito.when(ctx.response()).thenReturn(resp);
Mockito.when(ctx.pathParam("targetId")).thenReturn("someHost");
CompletableFuture<HyperlinkedSerializableRecordingDescriptor> future1 =
Mockito.mock(CompletableFuture.class);
Mockito.when(recordingTargetHelper.createSnapshot(Mockito.any(ConnectionDescriptor.class)))
.thenReturn(future1);
Mockito.when(future1.get())
.thenThrow(
new ExecutionException(
new SnapshotCreationException("some error message")));
HttpStatusException ex =
Assertions.assertThrows(HttpStatusException.class, () -> handler.handle(ctx));
MatcherAssert.assertThat(ex.getStatusCode(), Matchers.equalTo(500));
MatcherAssert.assertThat(ex.getPayload(), Matchers.equalTo("some error message"));
}
@Test
void shouldHandleSnapshotCreationExceptionDuringVerification() throws Exception {
Mockito.when(auth.validateHttpHeader(Mockito.any(), Mockito.any()))
.thenReturn(CompletableFuture.completedFuture(true));
RoutingContext ctx = Mockito.mock(RoutingContext.class);
HttpServerRequest req = Mockito.mock(HttpServerRequest.class);
Mockito.when(ctx.request()).thenReturn(req);
Mockito.when(req.headers()).thenReturn(MultiMap.caseInsensitiveMultiMap());
HttpServerResponse resp = Mockito.mock(HttpServerResponse.class);
Mockito.when(ctx.response()).thenReturn(resp);
Mockito.when(ctx.pathParam("targetId")).thenReturn("someHost");
HyperlinkedSerializableRecordingDescriptor snapshotDescriptor =
Mockito.mock(HyperlinkedSerializableRecordingDescriptor.class);
CompletableFuture<HyperlinkedSerializableRecordingDescriptor> future1 =
Mockito.mock(CompletableFuture.class);
Mockito.when(recordingTargetHelper.createSnapshot(Mockito.any(ConnectionDescriptor.class)))
.thenReturn(future1);
Mockito.when(future1.get()).thenReturn(snapshotDescriptor);
Mockito.when(snapshotDescriptor.getName()).thenReturn("snapshot-1");
CompletableFuture<Boolean> future2 = Mockito.mock(CompletableFuture.class);
Mockito.when(
recordingTargetHelper.verifySnapshot(
Mockito.any(ConnectionDescriptor.class), Mockito.eq("snapshot-1")))
.thenReturn(future2);
Mockito.when(future2.get())
.thenThrow(
new ExecutionException(
new SnapshotCreationException("some error message")));
HttpStatusException ex =
Assertions.assertThrows(HttpStatusException.class, () -> handler.handle(ctx));
MatcherAssert.assertThat(ex.getStatusCode(), Matchers.equalTo(500));
MatcherAssert.assertThat(ex.getPayload(), Matchers.equalTo("some error message"));
}
@Test
void shouldHandleFailedSnapshotVerification() throws Exception {
Mockito.when(auth.validateHttpHeader(Mockito.any(), Mockito.any()))
.thenReturn(CompletableFuture.completedFuture(true));
RoutingContext ctx = Mockito.mock(RoutingContext.class);
HttpServerRequest req = Mockito.mock(HttpServerRequest.class);
Mockito.when(ctx.request()).thenReturn(req);
Mockito.when(req.headers()).thenReturn(MultiMap.caseInsensitiveMultiMap());
HttpServerResponse resp = Mockito.mock(HttpServerResponse.class);
Mockito.when(ctx.response()).thenReturn(resp);
Mockito.when(ctx.pathParam("targetId")).thenReturn("someHost");
HyperlinkedSerializableRecordingDescriptor snapshotDescriptor =
Mockito.mock(HyperlinkedSerializableRecordingDescriptor.class);
CompletableFuture<HyperlinkedSerializableRecordingDescriptor> future1 =
Mockito.mock(CompletableFuture.class);
Mockito.when(recordingTargetHelper.createSnapshot(Mockito.any(ConnectionDescriptor.class)))
.thenReturn(future1);
Mockito.when(future1.get()).thenReturn(snapshotDescriptor);
Mockito.when(snapshotDescriptor.getName()).thenReturn("snapshot-1");
CompletableFuture<Boolean> future2 = Mockito.mock(CompletableFuture.class);
Mockito.when(
recordingTargetHelper.verifySnapshot(
Mockito.any(ConnectionDescriptor.class), Mockito.eq("snapshot-1")))
.thenReturn(future2);
Mockito.when(future2.get()).thenReturn(false);
handler.handle(ctx);
Mockito.verify(resp).setStatusCode(202);
Mockito.verify(resp)
.end(
"Snapshot snapshot-1 failed to create: The resultant recording was unreadable for some reason, likely due to a lack of Active, non-Snapshot source recordings to take event data from.");
}
}
|
9237e62c874c3693ac8b3b80d5d26ce62753a7e8 | 3,964 | java | Java | app/src/main/java/com/ibus/droidibus/ibus/systems/GlobalBroadcastSystem.java | tedsalmon/DroidIBus | ed0e21515164edf2bedb457fa5427ff0631afa7b | [
"MIT"
] | 15 | 2017-01-04T09:11:48.000Z | 2022-01-22T04:53:52.000Z | app/src/main/java/com/ibus/droidibus/ibus/systems/GlobalBroadcastSystem.java | t3ddftw/DroidIBus | ed0e21515164edf2bedb457fa5427ff0631afa7b | [
"MIT"
] | 41 | 2015-04-29T06:43:52.000Z | 2016-11-23T03:48:26.000Z | app/src/main/java/com/ibus/droidibus/ibus/systems/GlobalBroadcastSystem.java | t3ddftw/DroidIBus | ed0e21515164edf2bedb457fa5427ff0631afa7b | [
"MIT"
] | 5 | 2015-03-01T19:16:47.000Z | 2016-09-05T20:41:31.000Z | 38.115385 | 93 | 0.527245 | 998,242 | package com.ibus.droidibus.ibus.systems;
import java.util.ArrayList;
import com.ibus.droidibus.ibus.IBusSystem;
public class GlobalBroadcastSystem extends IBusSystem{
private static final byte IKE_SYSTEM = Devices.InstrumentClusterElectronics.toByte();
private static final byte GLOBAL_BROADCAST = Devices.GlobalBroadcast.toByte();
/**
* Messages from the IKE to the GlobalBroadcast
*/
class IKESystem extends IBusSystem{
private static final byte IGN_STATE = 0x11;
private static final byte OBC_UNITSET = 0x15;
private static final byte SPEED_RPM = 0x18;
private static final byte MILEAGE = 0x17;
private static final byte COOLANT_TEMP = 0x19;
public void mapReceived(ArrayList<Byte> msg){
currentMessage = msg;
switch(msg.get(3)){
case IGN_STATE:
int state = (msg.get(4) < 2) ? msg.get(4) : (0x02 & msg.get(4));
triggerCallback("onUpdateIgnitionSate", state);
break;
case OBC_UNITSET:
triggerCallback(
"onUpdateUnits",
String.format(
"%8s;%8s",
Integer.toBinaryString(msg.get(5) & 0xFF),
Integer.toBinaryString(msg.get(6) & 0xFF)
).replace(' ', '0')
);
break;
case SPEED_RPM:
triggerCallback("onUpdateSpeed", (int) msg.get(4));
triggerCallback("onUpdateRPM", (int) msg.get(5) * 100);
break;
case MILEAGE:
// Bytes 5-7 contain the Mileage in KMs
// Bytes 8 and 9 hold the inspection interval in KMs
// Byte 10 is the SIA Type (0x40 == Inspection)
// Byte 11 is the the days to inspection.
int mls = (msg.get(6) * 65536) + (msg.get(5) * 256) + msg.get(4);
int serviceInterval = (msg.get(7) + msg.get(8)) * 50;
int serviceIntervalType = msg.get(9);
int daysToInspection = msg.get(10);
triggerCallback("onUpdateMileage", mls);
triggerCallback("onUpdateServiceInterval", serviceInterval);
triggerCallback(
"onUpdateServiceIntervalType", serviceIntervalType
);
triggerCallback("onUpdateDaysToInspection", daysToInspection);
break;
case COOLANT_TEMP:
triggerCallback("onUpdateCoolantTemp", (int)msg.get(5));
break;
}
}
}
/**
* Messages from the LCM to the GlobalBroadcast
*/
class LightControlModuleSystem extends IBusSystem{
public void mapReceived(ArrayList<Byte> msg) {
currentMessage = msg;
// 0x5C is the light dimmer status. It appears FF = lights off and FE = lights on
if(currentMessage.get(3) == 0x5C){
int lightStatus = (currentMessage.get(4) == (byte) 0xFF) ? 0 : 1;
triggerCallback("onLightStatus", lightStatus);
}
}
}
/**
* Request mileage from the IKE
* IBUS Message: BF 03 80 16 2A
* @return byte[] Message for the IBus
*/
public byte[] getMileage(){
return new byte[]{
GLOBAL_BROADCAST, 0x03, IKE_SYSTEM, 0x16, 0x2A
};
}
public GlobalBroadcastSystem(){
IBusDestinationSystems.put(
Devices.InstrumentClusterElectronics.toByte(), new IKESystem()
);
IBusDestinationSystems.put(
Devices.LightControlModule.toByte(), new LightControlModuleSystem()
);
}
}
|
9237e665e0d59e58cddac5baca271123cde37ae8 | 349 | java | Java | moxy/src/test/resources/presenter/InjectViewStateForGenericPresenter.java | Neoksi/Moxy | 7e1cd88b6aa31071f2a17b5cfc5b42572db425e2 | [
"MIT"
] | 1,906 | 2016-02-12T15:01:54.000Z | 2022-03-27T06:07:58.000Z | moxy/src/test/resources/presenter/InjectViewStateForGenericPresenter.java | Neoksi/Moxy | 7e1cd88b6aa31071f2a17b5cfc5b42572db425e2 | [
"MIT"
] | 234 | 2016-02-27T09:52:10.000Z | 2022-03-15T05:20:39.000Z | moxy/src/test/resources/presenter/InjectViewStateForGenericPresenter.java | Neoksi/Moxy | 7e1cd88b6aa31071f2a17b5cfc5b42572db425e2 | [
"MIT"
] | 329 | 2016-02-13T21:25:53.000Z | 2022-01-11T12:09:54.000Z | 21.8125 | 100 | 0.787966 | 998,243 | package presenter;
import com.arellomobile.mvp.InjectViewState;
import com.arellomobile.mvp.MvpPresenter;
import com.arellomobile.mvp.view.CounterTestView;
/**
* Date: 15.03.2016
* Time: 13:32
*
* @author Savin Mikhail
*/
@InjectViewState
public class InjectViewStateForGenericPresenter<T extends CounterTestView> extends MvpPresenter<T> {
}
|
9237e6b4b9ec5f3c612c649b2f59f2d6a9c44d8d | 638 | java | Java | languages/util/core.text/source_gen/jetbrains/mps/lang/text/editor/Word_Editor.java | trespasserw/MPS | dbc5c76496e8ccef46dd420eefcd5089b1bc234b | [
"Apache-2.0"
] | null | null | null | languages/util/core.text/source_gen/jetbrains/mps/lang/text/editor/Word_Editor.java | trespasserw/MPS | dbc5c76496e8ccef46dd420eefcd5089b1bc234b | [
"Apache-2.0"
] | null | null | null | languages/util/core.text/source_gen/jetbrains/mps/lang/text/editor/Word_Editor.java | trespasserw/MPS | dbc5c76496e8ccef46dd420eefcd5089b1bc234b | [
"Apache-2.0"
] | null | null | null | 35.444444 | 82 | 0.811912 | 998,244 | package jetbrains.mps.lang.text.editor;
/*Generated by MPS */
import jetbrains.mps.nodeEditor.DefaultNodeEditor;
import jetbrains.mps.openapi.editor.cells.EditorCell;
import jetbrains.mps.openapi.editor.EditorContext;
import org.jetbrains.mps.openapi.model.SNode;
public class Word_Editor extends DefaultNodeEditor {
public EditorCell createEditorCell(EditorContext editorContext, SNode node) {
return new Word_EditorBuilder_a(editorContext, node).createCell();
}
public EditorCell createInspectedCell(EditorContext editorContext, SNode node) {
return new Word_InspectorBuilder_a(editorContext, node).createCell();
}
}
|
9237e7a44317594a25a92034aa85be8997d3a484 | 2,263 | java | Java | src/main/java/org/vaadin/spring/sample/security/ui/MainUI.java | GJRTimmer/Vaadin4Spring-MVP-Sample-SpringSecurity | 15f807d96189f445830d8d0bd07436053a83ff98 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/vaadin/spring/sample/security/ui/MainUI.java | GJRTimmer/Vaadin4Spring-MVP-Sample-SpringSecurity | 15f807d96189f445830d8d0bd07436053a83ff98 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/vaadin/spring/sample/security/ui/MainUI.java | GJRTimmer/Vaadin4Spring-MVP-Sample-SpringSecurity | 15f807d96189f445830d8d0bd07436053a83ff98 | [
"Apache-2.0"
] | 1 | 2018-08-27T20:03:46.000Z | 2018-08-27T20:03:46.000Z | 33.776119 | 164 | 0.726027 | 998,245 | package org.vaadin.spring.sample.security.ui;
import java.util.Locale;
import org.springframework.beans.factory.annotation.Autowired;
import org.vaadin.spring.annotation.VaadinUIScope;
import org.vaadin.spring.events.EventBus;
import org.vaadin.spring.navigator.SpringViewProvider;
import org.vaadin.spring.sample.security.ui.security.SecuredNavigator;
import org.vaadin.spring.sample.security.ui.security.SpringSecurityErrorHandler;
import org.vaadin.spring.security.VaadinSecurity;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.Title;
import com.vaadin.server.VaadinRequest;
import com.vaadin.ui.UI;
@VaadinUIScope
@Title("Vaadin4Spring Security Demo")
@Theme("valo")
@SuppressWarnings("serial")
public class MainUI extends UI {
@Autowired
SpringViewProvider springViewProvider;
@Autowired
EventBus eventBus;
@Autowired
VaadinSecurity security;
@Autowired
MainLayout mainLayout;
@Override
protected void init(VaadinRequest request) {
setLocale(new Locale.Builder().setLanguage("sr").setScript("Latn").setRegion("RS").build());
SecuredNavigator securedNavigator = new SecuredNavigator(MainUI.this, mainLayout, springViewProvider, security, eventBus);
securedNavigator.addViewChangeListener(mainLayout);
setContent(mainLayout);
setErrorHandler(new SpringSecurityErrorHandler());
/*
* Handling redirections
*/
// RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
// if (sessionStrategy.getAttribute(attrs, VaadinRedirectObject.REDIRECT_OBJECT_SESSION_ATTRIBUTE) != null) {
// VaadinRedirectObject redirectObject = (VaadinRedirectObject) sessionStrategy.getAttribute(attrs, VaadinRedirectObject.REDIRECT_OBJECT_SESSION_ATTRIBUTE);
// sessionStrategy.removeAttribute(attrs, VaadinRedirectObject.REDIRECT_OBJECT_SESSION_ATTRIBUTE);
//
// navigator.navigateTo(redirectObject.getRedirectViewToken());
//
// if (redirectObject.getErrorMessage() != null) {
// Notification.show("Error", redirectObject.getErrorMessage(), Type.ERROR_MESSAGE);
// }
//
// }
}
}
|
9237e896e1fcf8a231015f896164b475cc68947f | 1,835 | java | Java | src/main/java/com/hui/Math/MyAtoi.java | shenhaizhilong/algorithm | eae0c971ce29399d194051ee1328ecbca7dcd511 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/com/hui/Math/MyAtoi.java | shenhaizhilong/algorithm | eae0c971ce29399d194051ee1328ecbca7dcd511 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/com/hui/Math/MyAtoi.java | shenhaizhilong/algorithm | eae0c971ce29399d194051ee1328ecbca7dcd511 | [
"BSD-3-Clause"
] | null | null | null | 26.214286 | 64 | 0.426158 | 998,246 | package com.hui.Math;
/**
* @author: shenhaizhilong
* @date: 2018/7/1 14:01
*/
public class MyAtoi {
public static int myAtoi(String str) {
if(str.isEmpty())return 0;
// str = str.replaceAll("\\s","");
str = str.trim();
if(str.length() == 0)return 0;
int sign = 1;
if(str.matches("^(\\+||\\-)?[0-9]+.*?"))
{
System.out.println("str format: " + str);
char[] chars = str.toCharArray();
if(chars[0] == '-')
sign = -1;
int start=0;
if(chars[0] == '-' || chars[0] == '+')
start++;
return to_num(chars, start, sign);
}
return 0;
}
public static int to_num(char[] chars, int start, int sign)
{
long num = 0;
for (int i = start; i < chars.length; i++) {
if(chars[i] >='0' && chars[i] <='9')
{
num = num*10 + sign*(chars[i] - '0');
if(num > 0x7fffffff)
{
return Integer.MAX_VALUE;
}
if(num <0x80000000)
{
return Integer.MIN_VALUE;
}
}else {
break;
}
}
return (int)num;
}
public static void main(String[] args) {
System.out.println(myAtoi("words "));
System.out.println(myAtoi("032words "));
System.out.println(myAtoi("+-words "));
System.out.println(myAtoi("+words "));
System.out.println(myAtoi("+036555words"));
System.out.println(myAtoi("+- 0369words "));
System.out.println(myAtoi("-91283472332"));
System.out.println(myAtoi("+0 123"));
}
}
|
9237e962aefb627769c16ef7d5cc10b61bfafa63 | 419 | java | Java | src/main/java/com/github/datalking/jdbc/UncategorizedDataAccessException.java | uptonking/play-servlet-rest | 35e3f4900fae4690e397d915564d3ca034b26ebb | [
"MIT"
] | null | null | null | src/main/java/com/github/datalking/jdbc/UncategorizedDataAccessException.java | uptonking/play-servlet-rest | 35e3f4900fae4690e397d915564d3ca034b26ebb | [
"MIT"
] | 10 | 2020-02-28T01:26:13.000Z | 2020-12-06T10:15:02.000Z | src/main/java/com/github/datalking/jdbc/UncategorizedDataAccessException.java | uptonking/play-servlet-rest | 35e3f4900fae4690e397d915564d3ca034b26ebb | [
"MIT"
] | 1 | 2019-08-20T18:15:38.000Z | 2019-08-20T18:15:38.000Z | 22.052632 | 78 | 0.739857 | 998,247 | package com.github.datalking.jdbc;
import com.github.datalking.jdbc.dao.DataAccessException;
/**
* @author yaoo on 5/26/18
*/
public class UncategorizedDataAccessException extends DataAccessException {
public UncategorizedDataAccessException(String message) {
super(message);
}
public UncategorizedDataAccessException(String message, Throwable cause) {
super(message, cause);
}
}
|
9237e9a14ad5552de1913d06affe23c67ad07d59 | 584 | java | Java | src/main/java/com/lykke/tests/api/service/referral/model/referralhotel/ReferralHotelCreateResponse.java | LykkeBusiness/MAVN.Service.Tests | b59cee127fc29f03c5764456b2b77c5ef213663b | [
"MIT"
] | null | null | null | src/main/java/com/lykke/tests/api/service/referral/model/referralhotel/ReferralHotelCreateResponse.java | LykkeBusiness/MAVN.Service.Tests | b59cee127fc29f03c5764456b2b77c5ef213663b | [
"MIT"
] | 3 | 2020-03-25T18:49:57.000Z | 2020-03-25T19:02:56.000Z | src/main/java/com/lykke/tests/api/service/referral/model/referralhotel/ReferralHotelCreateResponse.java | LykkeBusiness/MAVN.Service.Tests | b59cee127fc29f03c5764456b2b77c5ef213663b | [
"MIT"
] | 3 | 2020-03-25T19:15:49.000Z | 2020-05-05T11:36:55.000Z | 32.444444 | 84 | 0.857877 | 998,248 | package com.lykke.tests.api.service.referral.model.referralhotel;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.PropertyNamingStrategy.UpperCamelCaseStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@JsonNaming(UpperCamelCaseStrategy.class)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ReferralHotelCreateResponse {
private ReferralHotelModel hotelReferral;
private ReferralHotelCreateErrorCode errorCode;
}
|
9237e9e5653b511de603ffbb6e6af56ade37326e | 166 | java | Java | ezyfox-database/src/main/java/com/tvd12/ezyfox/database/entity/EzyLongIdEntity.java | youngmonkeys/ezyfox | 9f5586c0aaf6101ffc488072f86dabb4ad9f5b08 | [
"Apache-2.0"
] | 16 | 2016-06-17T03:17:41.000Z | 2021-12-28T23:30:13.000Z | ezyfox-database/src/main/java/com/tvd12/ezyfox/database/entity/EzyLongIdEntity.java | gc-garcol/ezyfox | 288641d43aa24fce477399e3a2a0fbdd5e576cc6 | [
"Apache-2.0"
] | 9 | 2019-04-06T03:50:22.000Z | 2021-12-02T12:14:38.000Z | ezyfox-database/src/main/java/com/tvd12/ezyfox/database/entity/EzyLongIdEntity.java | youngmonkeys/ezyfox | 9f5586c0aaf6101ffc488072f86dabb4ad9f5b08 | [
"Apache-2.0"
] | 8 | 2016-06-08T15:51:28.000Z | 2021-08-15T14:34:50.000Z | 23.714286 | 74 | 0.825301 | 998,249 | package com.tvd12.ezyfox.database.entity;
import com.tvd12.ezyfox.util.EzyHasIdEntity;
public interface EzyLongIdEntity extends EzyHasIdEntity<Long>, EzyEntity {
}
|
9237e9f850cf2f1fc809f4d798737efd843bfc99 | 512 | java | Java | rpm-common/src/main/java/com/wwh/rpm/protocol/packet/transport/TransportPacket.java | wangwen135/rpm | 77307a462466e98c3e4065a659ce3b460e070015 | [
"Apache-2.0"
] | null | null | null | rpm-common/src/main/java/com/wwh/rpm/protocol/packet/transport/TransportPacket.java | wangwen135/rpm | 77307a462466e98c3e4065a659ce3b460e070015 | [
"Apache-2.0"
] | 1 | 2021-11-08T01:07:38.000Z | 2021-11-08T01:07:38.000Z | rpm-common/src/main/java/com/wwh/rpm/protocol/packet/transport/TransportPacket.java | wangwen135/rpm | 77307a462466e98c3e4065a659ce3b460e070015 | [
"Apache-2.0"
] | null | null | null | 19.692308 | 53 | 0.683594 | 998,250 | package com.wwh.rpm.protocol.packet.transport;
import com.wwh.rpm.protocol.ProtocolConstants;
import com.wwh.rpm.protocol.packet.AbstractPacket;
public class TransportPacket extends AbstractPacket {
private static final long serialVersionUID = 1L;
private byte[] data;
@Override
public byte getType() {
return ProtocolConstants.TYPE_TRANSPORT;
}
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
}
|
9237ea2fee614bdbdc7e6aeca4adb9a61529b746 | 426 | java | Java | spring-graphql/src/main/java/com/devopslam/graphql/config/ApplicationConfig.java | greenlucky/spring-tutorial | d62a130dc5dbe5f037068738987342a3d97f8a02 | [
"MIT"
] | null | null | null | spring-graphql/src/main/java/com/devopslam/graphql/config/ApplicationConfig.java | greenlucky/spring-tutorial | d62a130dc5dbe5f037068738987342a3d97f8a02 | [
"MIT"
] | null | null | null | spring-graphql/src/main/java/com/devopslam/graphql/config/ApplicationConfig.java | greenlucky/spring-tutorial | d62a130dc5dbe5f037068738987342a3d97f8a02 | [
"MIT"
] | null | null | null | 26.625 | 66 | 0.807512 | 998,251 | package com.devopslam.graphql.config;
;import com.devopslam.graphql.exceptions.CustomGraphQLErrorHandle;
import graphql.servlet.GraphQLErrorHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ApplicationConfig {
@Bean
public GraphQLErrorHandler errorHandler() {
return new CustomGraphQLErrorHandle();
}
}
|
9237eb30870aafeb5ed7693c1abde9eb78d8448c | 2,772 | java | Java | src/main/java/org/olat/instantMessaging/ui/component/UserAvatarCellRenderer.java | em3ndez/OpenOLAT | 80176e03805b823645eb2878d0d0725fa345f5c6 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/olat/instantMessaging/ui/component/UserAvatarCellRenderer.java | em3ndez/OpenOLAT | 80176e03805b823645eb2878d0d0725fa345f5c6 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/olat/instantMessaging/ui/component/UserAvatarCellRenderer.java | em3ndez/OpenOLAT | 80176e03805b823645eb2878d0d0725fa345f5c6 | [
"Apache-2.0"
] | null | null | null | 41.507463 | 174 | 0.738224 | 998,252 | /**
* <a href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at the
* <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a>
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Initial code contributed and copyrighted by<br>
* frentix GmbH, http://www.frentix.com
* <p>
*/
package org.olat.instantMessaging.ui.component;
import java.util.List;
import org.olat.core.dispatcher.impl.StaticMediaDispatcher;
import org.olat.core.gui.components.form.flexible.impl.elements.table.FlexiCellRenderer;
import org.olat.core.gui.components.form.flexible.impl.elements.table.FlexiTableComponent;
import org.olat.core.gui.render.Renderer;
import org.olat.core.gui.render.StringOutput;
import org.olat.core.gui.render.URLBuilder;
import org.olat.core.gui.translator.Translator;
import org.olat.instantMessaging.RosterEntry;
import org.olat.instantMessaging.model.RosterChannelInfos;
/**
*
* Initial date: 24 févr. 2022<br>
* @author srosse, ychag@example.com, http://www.frentix.com
*
*/
public class UserAvatarCellRenderer implements FlexiCellRenderer {
private final String avatarBaseURL;
private final String transparentGif;
public UserAvatarCellRenderer(String avatarBaseURL) {
this.avatarBaseURL = avatarBaseURL;
transparentGif = StaticMediaDispatcher.getStaticURI("images/transparent.gif");
}
@Override
public void render(Renderer renderer, StringOutput target, Object cellValue, int row, FlexiTableComponent source,
URLBuilder ubu, Translator translator) {
if(cellValue instanceof RosterChannelInfos) {
RosterChannelInfos infos = (RosterChannelInfos)cellValue;
List<RosterEntry> entries = infos.getNonVipEntries();
if(!entries.isEmpty()) {
RosterEntry entry = entries.get(0);
String name = entry.isAnonym() ? entry.getNickName() : entry.getFullName();
target.append("<span class=\"o_portrait\"><img src=\"").append(transparentGif).append("\"")
.append(" alt=\"").append(name).append("\" title=\"").append(name).append("\"")
.append(" class=\"o_portrait_avatar_small\"")
.append(" style=\"background-image: url('").append(avatarBaseURL).append("/").append(entry.getIdentityKey().toString()).append("/portrait_small.jpg')\" /></span>");
}
}
}
}
|
9237eba025d20d3513190e2c6ecf25201969daed | 2,501 | java | Java | src/server/world/entity/combat/Projectile.java | lare96/asteria-1.0 | fe65861fc5f912d09a8b366385062bbc27075e7a | [
"MIT"
] | null | null | null | src/server/world/entity/combat/Projectile.java | lare96/asteria-1.0 | fe65861fc5f912d09a8b366385062bbc27075e7a | [
"MIT"
] | null | null | null | src/server/world/entity/combat/Projectile.java | lare96/asteria-1.0 | fe65861fc5f912d09a8b366385062bbc27075e7a | [
"MIT"
] | 2 | 2019-07-23T00:53:04.000Z | 2020-01-10T23:40:38.000Z | 22.330357 | 84 | 0.576569 | 998,253 | package server.world.entity.combat;
/**
* A projectile used when doing things like firing arrows or casting spells.
*
* @author lare96
*/
public class Projectile {
/**
* The id of the projectile.
*/
private int id;
/**
* The height of the projectile.
*/
private int height;
/**
* The delay of the projectile.
*/
private int delay;
/**
* Create a new projectile.
*
* @param projectileId
* the projectile id.
* @param projectileHeight
* the projectile height.
* @param projectileDelay
* the projectile delay.
*/
public Projectile(int projectileId, int projectileHeight, int projectileDelay) {
this.setProjectileId(projectileId);
this.setProjectileHeight(projectileHeight);
this.setProjectileDelay(projectileDelay);
}
/**
* Create a new projectile.
*
* @param projectileId
* the projectile id.
* @param projectileHeight
* the projectile height.
*/
public Projectile(int projectileId, int projectileHeight) {
this.setProjectileId(projectileId);
this.setProjectileHeight(projectileHeight);
this.setProjectileDelay(0);
}
/**
* Create a new projectile.
*
* @param projectileId
* the projectile id.
*/
public Projectile(int projectileId) {
this.setProjectileId(projectileId);
this.setProjectileHeight(0);
this.setProjectileDelay(0);
}
/**
* @return the projectileId.
*/
public int getProjectileId() {
return id;
}
/**
* @param projectileId
* the projectileId to set.
*/
public void setProjectileId(int projectileId) {
this.id = projectileId;
}
/**
* @return the projectileHeight.
*/
public int getProjectileHeight() {
return height;
}
/**
* @param projectileHeight
* the projectileHeight to set.
*/
public void setProjectileHeight(int projectileHeight) {
this.height = projectileHeight;
}
/**
* @return the projectileDelay.
*/
public int getProjectileDelay() {
return delay;
}
/**
* @param projectileDelay
* the projectileDelay to set.
*/
public void setProjectileDelay(int projectileDelay) {
this.delay = projectileDelay;
}
}
|
9237ec90d318e700ef2ce71f0340061c9b3869f0 | 8,198 | java | Java | app/src/main/java/com/moblyo/market/MapsActivity.java | cumbari/LBA_Client_Android | 08b68fa8038776cd42b7edda4cb3713a35fee4e5 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/moblyo/market/MapsActivity.java | cumbari/LBA_Client_Android | 08b68fa8038776cd42b7edda4cb3713a35fee4e5 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/moblyo/market/MapsActivity.java | cumbari/LBA_Client_Android | 08b68fa8038776cd42b7edda4cb3713a35fee4e5 | [
"Apache-2.0"
] | null | null | null | 37.778802 | 179 | 0.626982 | 998,254 | package com.moblyo.market;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.gson.Gson;
import com.moblyo.market.model.FavouritesModel;
import com.moblyo.market.model.ListOfStores;
import com.moblyo.market.model.ResponseGetCoupons;
import com.moblyo.market.utils.SharedPrefKeys;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class MapsActivity extends BaseActivity
{
// the Google Map object
private GoogleMap mMap;
private String fromWhere;
private String filter;
public ResponseGetCoupons getCouponsData;
private ArrayList<ListOfStores> listOfStores ;
private TextView mapTypeHybrid,mapTypeSatellite,mapTypeNormal;
private String title,snippet;
private float lat,longitude;
private GoogleMap.OnMapClickListener clickListener=new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(final LatLng pos) {
}
};
private LatLng STARTING_MARKER_POSITION;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapType();
getDataFromBundle();
extractDataFromLocal();
setDataInList();
setUpMapIfNeeded();
}
private void setUpMapType() {
mapTypeHybrid= (TextView) findViewById(R.id.hybridmap);
typeFaceClass.setTypefaceNormal(mapTypeHybrid);
mapTypeSatellite= (TextView) findViewById(R.id.satellitemap);
typeFaceClass.setTypefaceNormal(mapTypeSatellite);
mapTypeNormal= (TextView) findViewById(R.id.normalmap);
typeFaceClass.setTypefaceNormal(mapTypeNormal);
mapTypeNormal.setSelected(true);
mapTypeNormal.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mapTypeNormal.setSelected(true);
mapTypeSatellite.setSelected(false);
mapTypeHybrid.setSelected(false);
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
});
mapTypeSatellite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mapTypeNormal.setSelected(false);
mapTypeSatellite.setSelected(true);
mapTypeHybrid.setSelected(false);
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
}
});
mapTypeHybrid.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mapTypeNormal.setSelected(false);
mapTypeSatellite.setSelected(false);
mapTypeHybrid.setSelected(true);
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
}
});
}
private void getDataFromBundle() {
fromWhere = getIntent().getStringExtra("fromWhere");
filter = getIntent().getStringExtra("filter");
lat= getIntent().getFloatExtra("latitude",0f);
longitude = getIntent().getFloatExtra("longitude",0f);
title= getIntent().getStringExtra("title");
snippet = getIntent().getStringExtra("snippet");
if(filter == null){
filter = "";
}
}
private void extractDataFromLocal() {
Gson gson = new Gson();
JSONObject onj = null;
String getCouponString = null;
if(fromWhere.equals(SharedPrefKeys.GET_COUPONS)){
getCouponString = sharedPreferenceUtil.getData(SharedPrefKeys.GET_COUPONS +
sharedPreferenceUtil.getData(SharedPrefKeys.LANGUAGE,"ENG") + filter, "");
}else if(fromWhere.equals(SharedPrefKeys.GET_CATEGORIES)){
getCouponString = sharedPreferenceUtil.getData(SharedPrefKeys.GET_CATEGORIES +
sharedPreferenceUtil.getData(SharedPrefKeys.LANGUAGE,"ENG") + filter, "");
} else if(fromWhere.equals(SharedPrefKeys.GET_BRANDEDCOUPONS)){
getCouponString = sharedPreferenceUtil.getData(SharedPrefKeys.GET_BRANDEDCOUPONS +
sharedPreferenceUtil.getData(SharedPrefKeys.LANGUAGE,"ENG") + filter, "");
}else if(fromWhere.equals(SharedPrefKeys.GET_FAVORITES))
{
listOfStores = new ArrayList<ListOfStores>();
if(sharedPreferenceUtil.getData(SharedPrefKeys.FAVOURITIES_ADDED,"").length()>0) {
try {
onj = new JSONObject(sharedPreferenceUtil.getData(SharedPrefKeys.FAVOURITIES_ADDED,""));
} catch (JSONException e) {
}
if(onj != null) {
FavouritesModel favouritesList = gson.fromJson(onj.toString(), FavouritesModel.class);
if(favouritesList != null && favouritesList.getCoupons() != null) {
for (int i = 0; i < favouritesList.getCoupons().size();i++)
{
listOfStores.add(favouritesList.getListOfStores().get(i));
}
}
}
}
}
if(getCouponString!=null)
{
try{
onj = new JSONObject(getCouponString);
}catch (JSONException e) {
}
if(onj != null) {
getCouponsData = gson.fromJson(onj.toString(), ResponseGetCoupons.class);
}
}
}
private void setDataInList()
{
if(getCouponsData != null){
listOfStores = getCouponsData.getListOfStores();
}
if(title!=null)
{
listOfStores= new ArrayList<ListOfStores>();
ListOfStores model=new ListOfStores();
model.setStoreName(title);
model.setStreet(snippet);
model.setLatitude(lat);
model.setLongitude(longitude);
listOfStores.add(model);
}
}
@Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
float latitude = sharedPreferenceUtil.getData(SharedPrefKeys.CURRENT_LATITUDE, 0f);
float longitude = sharedPreferenceUtil.getData(SharedPrefKeys.CURRENT_LONGITUDE, 0f);
STARTING_MARKER_POSITION=new LatLng(latitude,longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(STARTING_MARKER_POSITION, 14));
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
if(title!=null) {
mMap.addMarker(new MarkerOptions()
.position(STARTING_MARKER_POSITION)
.title("You are here!!")
.snippet(latitude + "," + longitude)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
}
if(listOfStores!=null) {
for (int i = 0; i < listOfStores.size(); i++) {
drawMarker(new LatLng(listOfStores.get(i).getLatitude(), listOfStores.get(i).getLongitude()), listOfStores.get(i).getStoreName(), listOfStores.get(i).getStreet());
}
}
mMap.setOnMapClickListener(clickListener);
}
private void drawMarker(LatLng point, String storeName, String street){
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(point);
markerOptions.draggable(false);
markerOptions.title(storeName);
markerOptions.snippet(street);
mMap.addMarker(markerOptions);
}
}
|
9237ecb985a1acc3f15c3146f2887f39a774bbaa | 12,259 | java | Java | grouper/src/grouper/edu/internet2/middleware/grouper/membership/MembershipPathNode.java | rb12345/grouper | 1df01636c6647d27e7ded7463498cc245f6b314f | [
"Apache-2.0"
] | 63 | 2015-02-02T17:24:08.000Z | 2022-02-18T07:20:13.000Z | grouper/src/grouper/edu/internet2/middleware/grouper/membership/MembershipPathNode.java | rb12345/grouper | 1df01636c6647d27e7ded7463498cc245f6b314f | [
"Apache-2.0"
] | 92 | 2015-01-21T14:40:00.000Z | 2022-02-10T23:56:03.000Z | grouper/src/grouper/edu/internet2/middleware/grouper/membership/MembershipPathNode.java | rb12345/grouper | 1df01636c6647d27e7ded7463498cc245f6b314f | [
"Apache-2.0"
] | 70 | 2015-03-23T08:50:33.000Z | 2022-03-18T07:00:57.000Z | 29.973105 | 195 | 0.668407 | 998,255 | /**
* Copyright 2014 Internet2
*
* 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 edu.internet2.middleware.grouper.membership;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import edu.internet2.middleware.grouper.Field;
import edu.internet2.middleware.grouper.Group;
import edu.internet2.middleware.grouper.Stem;
import edu.internet2.middleware.grouper.attr.AttributeDef;
import edu.internet2.middleware.grouper.misc.CompositeType;
/**
* membership path node including both end nodes
* @author mchyzer
*
*/
public class MembershipPathNode implements Comparable<MembershipPathNode> {
/**
* default constructor
*/
public MembershipPathNode() {
}
/**
* @see java.lang.Object#clone()
*/
@Override
protected Object clone() {
MembershipPathNode membershipPathNode = new MembershipPathNode();
membershipPathNode.setComposite(this.composite);
membershipPathNode.setCompositeType(this.compositeType);
membershipPathNode.setLeftCompositeFactor(this.leftCompositeFactor);
membershipPathNode.setMembershipOwnerType(this.membershipOwnerType);
membershipPathNode.setOwnerAttributeDef(this.ownerAttributeDef);
membershipPathNode.setOwnerGroup(this.ownerGroup);
membershipPathNode.setOwnerStem(this.ownerStem);
membershipPathNode.setRightCompositeFactor(this.rightCompositeFactor);
return membershipPathNode;
}
/**
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return new HashCodeBuilder().append(this.composite).append(this.compositeType).append(this.ownerAttributeDef)
.append(this.ownerGroup).append(this.ownerStem).append(this.membershipOwnerType).toHashCode();
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (!(obj instanceof MembershipPathNode)) {
return false;
}
MembershipPathNode that = (MembershipPathNode)obj;
return new EqualsBuilder().append(this.composite, that.composite)
.append(this.compositeType, that.compositeType).append(this.membershipOwnerType, that.membershipOwnerType)
.append(this.ownerAttributeDef, that.ownerAttributeDef).append(this.ownerGroup, that.ownerGroup)
.append(this.ownerStem, that.ownerStem).isEquals();
}
/**
* constructor for group path code
* @param field
* @param theOwnerGroup
*/
public MembershipPathNode(Field field, Group theOwnerGroup) {
if (field.isGroupListField()) {
this.setMembershipOwnerType(MembershipOwnerType.list);
} else if (field.isGroupAccessField()) {
this.setMembershipOwnerType(MembershipOwnerType.groupPrivilege);
} else {
throw new RuntimeException("Not expecting field type: " + field);
}
this.setOwnerGroup(theOwnerGroup);
}
/**
* construct a composite group node
* @param field
* @param ownerGroup
* @param compositeType
* @param theLeftCompositeFactor
* @param theRightCompositeFactor
* @param theOtherFactor
*/
public MembershipPathNode(Field field, Group ownerGroup,
CompositeType compositeType,
Group theLeftCompositeFactor, Group theRightCompositeFactor, Group theOtherFactor) {
this(field, ownerGroup);
this.composite = true;
this.compositeType = compositeType;
this.leftCompositeFactor = theLeftCompositeFactor;
this.rightCompositeFactor = theRightCompositeFactor;
this.otherFactor = theOtherFactor;
}
/**
* constructor for stem path code
* @param field
* @param theOwnerStem
*/
public MembershipPathNode(Field field, Stem theOwnerStem) {
if (field.isStemListField()) {
this.setMembershipOwnerType(MembershipOwnerType.stemPrivilege);
} else {
throw new RuntimeException("Not expecting field type: " + field);
}
this.setOwnerStem(theOwnerStem);
}
/**
* constructor for attributeDef path code
* @param field
* @param theOwnerAttributeDef
*/
public MembershipPathNode(Field field, AttributeDef theOwnerAttributeDef) {
if (field.isAttributeDefListField()) {
this.setMembershipOwnerType(MembershipOwnerType.attributeDefPrivilege);
} else {
throw new RuntimeException("Not expecting field type: " + field);
}
this.setOwnerAttributeDef(theOwnerAttributeDef);
}
/**
* @see Object#toString()
*/
@Override
public String toString() {
switch (this.membershipOwnerType) {
case list:
case groupPrivilege:
if (this.composite) {
switch (this.compositeType) {
case COMPLEMENT:
return this.ownerGroup.getName() + " (composite " + this.compositeType + " with " + this.leftCompositeFactor.getName() + " and not in " + this.rightCompositeFactor.getName() + ")";
case INTERSECTION:
return this.ownerGroup.getName() + " (composite " + this.compositeType + " of " + this.leftCompositeFactor.getName() + " and in " + this.rightCompositeFactor.getName() + ")";
case UNION:
return this.ownerGroup.getName() + " (composite " + this.compositeType + " of " + this.leftCompositeFactor.getName() + " or in " + this.rightCompositeFactor.getName() + ")";
default:
throw new RuntimeException("Not expecting compositeType: " + this.compositeType);
}
}
return this.ownerGroup.getName();
case stemPrivilege:
return this.ownerStem.getName();
case attributeDefPrivilege:
return this.ownerAttributeDef.getName();
default:
throw new RuntimeException("Not expecting owner type: " + this.membershipOwnerType);
}
}
/**
* if this is an attributeDef privilege, this is the owner attribute def
*/
private AttributeDef ownerAttributeDef;
/**
* if this is a list or group privilege, this is the owner group
*/
private Group ownerGroup;
/**
* if this is a stem privilege, this is the owner stem
*/
private Stem ownerStem;
/**
* type of composite, INTERSECTION, COMPLEMENT, UNION
*/
private CompositeType compositeType;
/**
* if composite, this is the right composite factor
* @return composite
*/
public CompositeType getCompositeType() {
return this.compositeType;
}
/**
* if composite, this is the right composite factor
* @param compositeType1
*/
public void setCompositeType(CompositeType compositeType1) {
this.compositeType = compositeType1;
}
/**
* if this is a composite group
*/
private boolean composite;
/**
* if composite, this is the right composite factor
*/
private Group leftCompositeFactor;
/**
* if composite, this is the right composite factor
*/
private Group rightCompositeFactor;
/**
* this is the factor not in the path
*/
private Group otherFactor;
/**
* this is the factor not in the path
* @return the otherFactor
*/
public Group getOtherFactor() {
return this.otherFactor;
}
/**
* this is the factor not in the path
* @param otherFactor1 the otherFactor to set
*/
public void setOtherFactor(Group otherFactor1) {
this.otherFactor = otherFactor1;
}
/**
* if this is a composite group
* @return composite
*/
public boolean isComposite() {
return this.composite;
}
/**
* if this is a composite group
* @param composite1
*/
public void setComposite(boolean composite1) {
this.composite = composite1;
}
/**
* if composite, this is the right composite factor
* @return factor
*/
public Group getLeftCompositeFactor() {
return this.leftCompositeFactor;
}
/**
* if composite, this is the right composite factor
* @param leftCompositeFactor1
*/
public void setLeftCompositeFactor(Group leftCompositeFactor1) {
this.leftCompositeFactor = leftCompositeFactor1;
}
/**
* if composite, this is the right composite factor
* @return right composite factor
*/
public Group getRightCompositeFactor() {
return this.rightCompositeFactor;
}
/**
* if composite, this is the right composite factor
* @param rightCompositeFactor1
*/
public void setRightCompositeFactor(Group rightCompositeFactor1) {
this.rightCompositeFactor = rightCompositeFactor1;
}
/**
* what type e.g. list, or stemPrivilege
*/
private MembershipOwnerType membershipOwnerType;
/**
* if this is an attributeDef privilege, this is the owner attribute def
* @return attribute def
*/
public AttributeDef getOwnerAttributeDef() {
return this.ownerAttributeDef;
}
/**
* if this is a list or group privilege, this is the owner group
* @return group
*/
public Group getOwnerGroup() {
return this.ownerGroup;
}
/**
* if this is a stem privilege, this is the owner stem
* @return owner stem
*/
public Stem getOwnerStem() {
return this.ownerStem;
}
/**
* if this is an attributeDef privilege, this is the owner attribute def
* @param ownerAttributeDef1
*/
public void setOwnerAttributeDef(AttributeDef ownerAttributeDef1) {
this.ownerAttributeDef = ownerAttributeDef1;
}
/**
* if this is a list or group privilege, this is the owner group
* @param ownerGroup1
*/
public void setOwnerGroup(Group ownerGroup1) {
this.ownerGroup = ownerGroup1;
}
/**
* if this is a stem privilege, this is the owner stem
* @param ownerStem1
*/
public void setOwnerStem(Stem ownerStem1) {
this.ownerStem = ownerStem1;
}
/**
* what type e.g. list, or stemPrivilege
* @return owner type
*/
public MembershipOwnerType getMembershipOwnerType() {
return this.membershipOwnerType;
}
/**
* what type e.g. list, or stemPrivilege
* @param membershipOwnerType1
*/
public void setMembershipOwnerType(MembershipOwnerType membershipOwnerType1) {
this.membershipOwnerType = membershipOwnerType1;
}
/**
* @see Comparable#compareTo(Object)
*/
@Override
public int compareTo(MembershipPathNode membershipPathNode) {
if (this.membershipOwnerType != membershipPathNode.membershipOwnerType) {
if (this.membershipOwnerType == null) {
return -1;
}
if (membershipPathNode.membershipOwnerType == null) {
return -1;
}
return this.membershipOwnerType.name().compareTo(membershipPathNode.membershipOwnerType.name());
}
switch(this.membershipOwnerType) {
case groupPrivilege:
case list:
if (this.ownerGroup == null && membershipPathNode.ownerGroup != null) {
return -1;
}
return this.ownerGroup.compareTo(membershipPathNode.ownerGroup);
case stemPrivilege:
if (this.ownerStem == null && membershipPathNode.ownerStem != null) {
return -1;
}
return this.ownerStem.compareTo(membershipPathNode.ownerStem);
case attributeDefPrivilege:
if (this.ownerAttributeDef == null && membershipPathNode.ownerAttributeDef != null) {
return -1;
}
return this.ownerAttributeDef.compareTo(membershipPathNode.ownerAttributeDef);
default:
throw new RuntimeException("Not expecting membershipOwnerType: " + this.membershipOwnerType);
}
}
}
|
9237ed04ecd23f6128af51f649defc5295e39ecf | 9,062 | java | Java | src/main/java/com/chrisrm/idea/ui/MTCheckBoxUI.java | meowding/material-theme-jetbrains | eb554c081a1669deac2a2103b87d8204dfbb3d0d | [
"MIT"
] | 2 | 2019-01-23T07:42:57.000Z | 2019-01-23T07:43:06.000Z | src/main/java/com/chrisrm/idea/ui/MTCheckBoxUI.java | meowding/material-theme-jetbrains | eb554c081a1669deac2a2103b87d8204dfbb3d0d | [
"MIT"
] | null | null | null | src/main/java/com/chrisrm/idea/ui/MTCheckBoxUI.java | meowding/material-theme-jetbrains | eb554c081a1669deac2a2103b87d8204dfbb3d0d | [
"MIT"
] | null | null | null | 37.292181 | 115 | 0.666188 | 998,256 | /*
* The MIT License (MIT)
*
* Copyright (c) 2018 Chris Magnussen and Elior Boukhobza
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*
*/
package com.chrisrm.idea.ui;
import com.chrisrm.idea.utils.MTUI;
import com.intellij.ide.ui.laf.darcula.ui.DarculaCheckBoxUI;
import com.intellij.openapi.ui.GraphicsConfig;
import com.intellij.util.ui.EmptyIcon;
import com.intellij.util.ui.JBInsets;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import sun.swing.SwingUtilities2;
import javax.swing.*;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicHTML;
import javax.swing.text.View;
import java.awt.*;
/**
* @author Konstantin Bulenkov
*/
@SuppressWarnings("IntegerDivisionInFloatingPointContext")
public final class MTCheckBoxUI extends DarculaCheckBoxUI {
private static final Icon DEFAULT_ICON = JBUI.scale(EmptyIcon.create(20)).asUIResource();
@SuppressWarnings({"MethodOverridesStaticMethodOfSuperclass",
"unused"})
public static ComponentUI createUI(final JComponent component) {
return new MTCheckBoxUI();
}
@Override
public void installUI(final JComponent c) {
super.installUI(c);
if (UIUtil.getParentOfType(CellRendererPane.class, c) != null) {
c.setBorder(null);
}
}
@Override
public void installDefaults(final AbstractButton b) {
super.installDefaults(b);
b.setIconTextGap(JBUI.scale(4));
}
@Override
public synchronized void paint(final Graphics g2d, final JComponent c) {
final Graphics2D g = (Graphics2D) g2d;
final JCheckBox checkBox = (JCheckBox) c;
final Dimension size = c.getSize();
final Font font = c.getFont();
g.setFont(font);
final FontMetrics fm = SwingUtilities2.getFontMetrics(c, g, font);
final Rectangle viewRect = new Rectangle(size);
final Rectangle iconRect = new Rectangle();
final Rectangle textRect = new Rectangle();
JBInsets.removeFrom(viewRect, c.getInsets());
final String text = SwingUtilities.layoutCompoundLabel(c, fm, checkBox.getText(), DEFAULT_ICON,
checkBox.getVerticalAlignment(), checkBox.getHorizontalAlignment(),
checkBox.getVerticalTextPosition(), checkBox.getHorizontalTextPosition(),
viewRect, iconRect, textRect, checkBox.getIconTextGap());
//background
if (c.isOpaque()) {
g.setColor(checkBox.getBackground());
g.fillRect(0, 0, size.width, size.height);
}
final boolean selected = checkBox.isSelected();
final boolean enabled = checkBox.isEnabled();
drawCheckIcon(c, g, checkBox, iconRect, selected, enabled);
drawText(c, g, checkBox, fm, textRect, text);
}
@Override
public Icon getDefaultIcon() {
return DEFAULT_ICON;
}
@SuppressWarnings({"MethodWithMoreThanThreeNegations",
"OverlyComplexMethod",
"OverlyLongMethod",
"FeatureEnvy"})
@Override
protected void drawCheckIcon(final JComponent c,
final Graphics2D g,
final AbstractButton b,
final Rectangle iconRect,
final boolean selected,
final boolean enabled) {
if (selected && b.getSelectedIcon() != null) {
b.getSelectedIcon().paintIcon(b, g, iconRect.x + JBUI.scale(4), iconRect.y + JBUI.scale(2));
} else if (!selected && b.getIcon() != null) {
b.getIcon().paintIcon(b, g, iconRect.x + JBUI.scale(4), iconRect.y + JBUI.scale(2));
} else {
final int off = JBUI.scale(3);
final int x = iconRect.x + off;
final int y = iconRect.y + off;
final int w = iconRect.width - 2 * off;
final int h = iconRect.height - 2 * off;
g.translate(x, y);
final Paint paint = UIUtil.getGradientPaint(w / 2, 0, b.getBackground().brighter(),
w / 2, h, b.getBackground());
g.setPaint(paint);
final int fillOffset = JBUI.scale(1);
g.fillRect(fillOffset, fillOffset, w - 2 * fillOffset, h - 2 * fillOffset);
//setup AA for lines
final GraphicsConfig config = new GraphicsConfig(g);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
final boolean armed = b.getModel().isArmed();
final int rad = JBUI.scale(2);
final boolean overrideBg = isIndeterminate(b);
if (c.hasFocus()) {
paintOvalRing(g, w, h);
g.setPaint(MTUI.CheckBox.getFocusedBackgroundColor1(armed, selected || overrideBg));
g.fillRoundRect(0, 0, w, h, rad, rad);
} else {
g.setPaint(MTUI.CheckBox.getBackgroundColor1(selected || overrideBg));
g.fillRoundRect(0, 0, w, h, rad, rad);
final Color borderColor;
if (!b.getModel().isSelected()) {
borderColor = MTUI.CheckBox.getBorderColor(enabled, selected || overrideBg);
} else if (isIndeterminate(b)) {
borderColor = MTUI.CheckBox.getBorderColorSelected(enabled, true);
} else {
borderColor = MTUI.CheckBox.getBorderColorSelected(enabled, selected || overrideBg);
}
g.setPaint(borderColor);
g.drawRoundRect(0, 0, w, h - 1, rad, rad);
if (!b.isEnabled()) {
g.setPaint(MTUI.CheckBox.getInactiveFillColor());
g.drawRoundRect(0, 0, w, h - 1, rad, rad);
}
}
if (isIndeterminate(b)) {
paintIndeterminateSign(g, enabled, w, h);
} else if (b.getModel().isSelected()) {
paintCheckSign(g, enabled, w);
}
g.translate(-x, -y);
config.restore();
}
}
private static void paintOvalRing(final Graphics2D g, final int w, final int h) {
g.setColor(UIManager.getColor("Focus.color"));
g.fillOval(-5, -5, w + 10, h + 10);
}
@Override
protected void drawText(final JComponent c,
final Graphics2D g,
final AbstractButton b,
final FontMetrics fm,
final Rectangle textRect,
final String text) {
//text
if (text != null) {
final View view = (View) c.getClientProperty(BasicHTML.propertyKey);
if (view != null) {
view.paint(g, textRect);
} else {
g.setColor(b.isEnabled() ? b.getForeground() : getDisabledTextColor());
SwingUtilities2.drawStringUnderlineCharAt(c, g, text,
b.getDisplayedMnemonicIndex(),
textRect.x,
textRect.y + fm.getAscent());
}
}
}
private static void paintIndeterminateSign(final Graphics2D g, final boolean enabled, final int w, final int h) {
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
g.setStroke(new BasicStroke(1 * JBUI.scale(2.0f), BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
final int off = JBUI.scale(4);
final int y1 = h / 2;
g.setColor(MTUI.CheckBox.getShadowColor(enabled));
final GraphicsConfig graphicsConfig = new GraphicsConfig(g).paintWithAlpha(0.8f);
g.drawLine(off, y1 + JBUI.scale(1), w - off + JBUI.scale(1), y1 + JBUI.scale(1));
graphicsConfig.restore();
g.setColor(MTUI.CheckBox.getCheckSignColor(enabled));
g.drawLine(off, y1, w - off + JBUI.scale(1), y1);
}
private static void paintCheckSign(final Graphics2D g, final boolean enabled, final int w) {
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
g.setStroke(new BasicStroke(1 * JBUI.scale(2.0f), BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g.setPaint(MTUI.CheckBox.getCheckSignColor(enabled));
final int x1 = JBUI.scale(3);
final int y1 = JBUI.scale(7);
final int x2 = JBUI.scale(7);
final int y2 = JBUI.scale(10);
final int x3 = w - JBUI.scale(2);
final int y3 = JBUI.scale(3);
g.drawLine(x1, y1, x2, y2);
g.drawLine(x2, y2, x3, y3);
g.setPaint(MTUI.CheckBox.getCheckSignColor(enabled));
}
}
|
9237ef8b2e049b7fbe176b65c9fd7dad7ec6860c | 5,660 | java | Java | src/main/java/com/xebia/incubator/xebium/VisualAnalyzer.java | rselie/Xebium | eb5892bafb28611f3df8ad29d2153ae99a0dfce4 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/xebia/incubator/xebium/VisualAnalyzer.java | rselie/Xebium | eb5892bafb28611f3df8ad29d2153ae99a0dfce4 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/xebia/incubator/xebium/VisualAnalyzer.java | rselie/Xebium | eb5892bafb28611f3df8ad29d2153ae99a0dfce4 | [
"Apache-2.0"
] | null | null | null | 36.516129 | 116 | 0.708127 | 998,257 | package com.xebia.incubator.xebium;
import java.io.IOException;
import java.io.StringWriter;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.openqa.selenium.Dimension;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
public class VisualAnalyzer {
private static final Logger LOG = LoggerFactory.getLogger(VisualAnalyzer.class);
private static final String DEFAULT_HOSTNAME = "nohost";
private static final String DEFAULT_PORT = "7000";
private static String hostname = DEFAULT_HOSTNAME;
private static String port = DEFAULT_PORT;
private static String project;
private static String suite;
private static int runId;
private String browserName = "chrome";
private static String platformName = "Windows7";
private static String resolution = "unkown x unknown";
private static String browserVersion = "45.0 (64-bit)";
/**
* Creates a new run on the VisualReview server with the given project name and suite name.
*
* @return the new run's RunID, which can be used to upload screenshots to
* @throws IOException
*/
public void createRun() throws IOException {
if (DEFAULT_HOSTNAME.equalsIgnoreCase(hostname)) {
LOG.info("The hostname is 'nohost' VisualAnalyzer acts if it is not configured and will ignore commands.");
return;
}
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://" + hostname + ":" + port + "/api/runs");
StringEntity input = new StringEntity("{\"projectName\":\"" + project + "\",\"suiteName\":\"" + suite + "\"}");
input.setContentType("application/json");
LOG.info("httpPost when creating run: " + "http://" + hostname + ":" + port + "/api/runs");
httpPost.setEntity(input);
CloseableHttpResponse response = httpclient.execute(httpPost);
try {
LOG.info("response from server when creating run: " + response.getStatusLine());
HttpEntity responseEntity = response.getEntity();
JsonFactory factory = new JsonFactory();
JsonParser parser = factory.createParser(response.getEntity().getContent());
if (parser.nextToken() != JsonToken.START_OBJECT) {
throw new IOException("Expected data to start with an Object");
}
while (parser.nextToken() != JsonToken.END_OBJECT) {
String fieldName = parser.getCurrentName();
parser.nextToken(); // moves to value
if (fieldName != null && fieldName.equals("id")) {
runId = Integer.parseInt(parser.getValueAsString());
}
}
EntityUtils.consume(responseEntity);
} finally {
response.close();
}
if (runId == 0) {
throw new RuntimeException("something went wrong while creating suite.. The runId was still zero");
}
}
public void takeAndSendScreenshot(String screenshotName, String output) throws IOException {
if (runId == 0) {
return;
}
byte[] screenshotData = Base64.decodeBase64(output);
JsonFactory factory = new JsonFactory();
StringWriter jsonString = new StringWriter();
JsonGenerator generator = factory.createGenerator(jsonString);
generator.writeStartObject();
generator.writeStringField("browser", browserName);
generator.writeStringField("platform", platformName);
generator.writeStringField("resolution", resolution);
generator.writeStringField("version", browserVersion);
generator.writeEndObject();
generator.flush();
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://" + hostname + ":" + port + "/api/runs/" + runId + "/screenshots");
HttpEntity input = MultipartEntityBuilder.create()
.addBinaryBody("file", screenshotData, ContentType.parse("image/png"), "file.png")
.addTextBody("screenshotName", screenshotName, ContentType.TEXT_PLAIN)
.addTextBody("properties", jsonString.toString(), ContentType.APPLICATION_JSON)
.addTextBody("meta", "{}", ContentType.APPLICATION_JSON)
.build();
httpPost.setEntity(input);
CloseableHttpResponse response = httpclient.execute(httpPost);
try {
LOG.info("response from server when uploading screenshot: " + response.getStatusLine());
} finally {
response.close();
}
}
public void setProject(String project) {
VisualAnalyzer.project = project;
}
public void setSuite(String suite) {
VisualAnalyzer.suite = suite;
}
public void setHost(String hostname) {
VisualAnalyzer.hostname = hostname;
}
public void setPort(String port) {
VisualAnalyzer.port = port;
}
public boolean isInitialized(String project, String suite) {
return VisualAnalyzer.runId != 0 && project.equals(VisualAnalyzer.project) && suite.equals(VisualAnalyzer.suite);
}
public void setBrowser(String browser) {
this.browserName = browser;
}
public void setSize(Dimension size) {
if (size != null) {
resolution = size.getHeight() + " x " + size.getWidth();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.