text
stringlengths 7
1.01M
|
|---|
package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import org.firstinspires.ftc.teamcode.MM_Classes.MM_IterativeOpMode;
@Disabled
@TeleOp(name = "Iterative Drive")
public class Iterative_BasicDrive extends MM_IterativeOpMode {
@Override
public void init() {
super.init();
}
Boolean safety = true;
@Override
public void loop(){
double scalar;
if (gamepad1.b) {
scalar = 1;
}
else{
scalar = .35;
}
double r = Math.hypot(gamepad1.left_stick_x, gamepad1.left_stick_y) * scalar;
double radians = Math.atan2(-gamepad1.left_stick_y, gamepad1.left_stick_x) - Math.PI / 4;
double turn = gamepad1.right_stick_x * scalar;
final double v1 = r * Math.cos(radians) - turn;
final double v2 = r * Math.sin(radians) + turn;
final double v3 = r * Math.sin(radians) - turn;
final double v4 = r * Math.cos(radians) + turn;
robot.motorPowers(v1, v2, v3, v4);
telemetry.addData("Steering","Mag: %.2f, Theta: %.1f deg", r, (radians*180)/Math.PI);
telemetry.addData("Motor Powers", "fl: %.3f, fr: %.3f, br: %.3f, bl: %.3f", v1,v2,v3,v4);
telemetry.addData("Scalar value", scalar);
}
}
|
/*
* Copyright 2011-present JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package org.intellij.jflex.psi;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
public interface JFlexMacroReference extends JFlexComposite {
@NotNull
PsiElement getId();
@NotNull
PsiReference getReference();
}
|
package org.ovirt.engine.ui.uicommonweb.models.hosts;
import java.io.Serializable;
public class HostDetailModel implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String address;
private String password;
private String glusterPeerAddress;
private String glusterPeerAddressSSHPublicKey;
private String sshPublicKey;
public HostDetailModel() {
}
public HostDetailModel(String address, String sshPublicKeyPem) {
setAddress(address);
setGlusterPeerAddress(address);
setSshPublicKey(sshPublicKeyPem);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getGlusterPeerAddress() {
return glusterPeerAddress;
}
public void setGlusterPeerAddress(String glusterPeerAddress) {
this.glusterPeerAddress = glusterPeerAddress;
}
public void setSshPublicKey(String sshPublicKey) {
this.sshPublicKey = sshPublicKey;
}
public String getSshPublicKey() {
return sshPublicKey;
}
public void setGlusterPeerAddressSSHPublicKey(String glusterPeerAddressSSHPublicKey) {
this.glusterPeerAddressSSHPublicKey = glusterPeerAddressSSHPublicKey;
}
public String getGlusterPeerAddressSSHPublicKey() {
return glusterPeerAddressSSHPublicKey;
}
}
|
package in.hasirudala.dwcc.server.service;
import in.hasirudala.dwcc.server.domain.ExpenseRecord;
import in.hasirudala.dwcc.server.repository.DwccRepository;
import in.hasirudala.dwcc.server.repository.ExpenseRecordRepository;
import in.hasirudala.dwcc.server.web.contract.ExpenseRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
@Service
public class ExpenseService {
private ExpenseRecordRepository recordRepository;
private DwccRepository dwccRepository;
private ExpenseEntryService entryService;
private ExpensePurchaseEntryService purchaseEntryService;
@Autowired
public ExpenseService(ExpenseRecordRepository recordRepository,
DwccRepository dwccRepository,
ExpenseEntryService entryService,
ExpensePurchaseEntryService purchaseEntryService) {
this.recordRepository = recordRepository;
this.dwccRepository = dwccRepository;
this.entryService = entryService;
this.purchaseEntryService = purchaseEntryService;
}
public Page<ExpenseRecord> getAllRecords(Pageable pageable) {
return recordRepository.findAll(pageable);
}
public ExpenseRecord createFromRequest(ExpenseRequest request) {
ExpenseRecord record = new ExpenseRecord();
record.assignUuid();
record.setDate(request.getDate());
record.setDwcc(dwccRepository.getOne(request.getDwccId()));
entryService.createAndAdd(record, request.getEntries());
purchaseEntryService.createAndAdd(record, request.getPurchaseEntries());
recordRepository.save(record);
return record;
}
public ExpenseRecord updateFromRequest(ExpenseRecord record, ExpenseRequest request) {
entryService.update(record, request.getEntries());
purchaseEntryService.update(record, request.getPurchaseEntries());
recordRepository.save(record);
return record;
}
}
|
package com.anysoftkeyboard.keyboards.views.preview;
import android.graphics.Point;
import com.anysoftkeyboard.keyboards.Keyboard;
public interface PositionCalculator {
Point calculatePositionForPreview(
Keyboard.Key key, PreviewPopupTheme theme, int[] windowOffset);
}
|
package io.jpom.controller.onekey.host;
import cn.hutool.core.text.StrSplitter;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.ssh.JschUtil;
import cn.jiangzeyin.common.JsonMessage;
import cn.jiangzeyin.common.validator.ValidatorItem;
import cn.jiangzeyin.common.validator.ValidatorRule;
import com.alibaba.fastjson.JSONArray;
import com.jcraft.jsch.Session;
import io.jpom.common.BaseServerController;
import io.jpom.common.interceptor.OptLog;
import io.jpom.model.BaseModel;
import io.jpom.model.data.NodeModel;
import io.jpom.model.data.PackageHostModel;
import io.jpom.model.log.UserOperateLogV1;
import io.jpom.plugin.ClassFeature;
import io.jpom.plugin.Feature;
import io.jpom.plugin.MethodFeature;
import io.jpom.service.zfpackage.host.HostService;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping(value = "onekey/host")
@Feature(cls = ClassFeature.ONEKEY_HOST)
public class HostController extends BaseServerController {
@Resource
private HostService hostService;
@RequestMapping(value = "list_data.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
@Feature(method = MethodFeature.LIST)
public JsonMessage<List<PackageHostModel>> listData() {
List<PackageHostModel> list = hostService.list();
if (list != null) {
// 读取节点信息
List<NodeModel> list1 = nodeService.list();
Map<String, NodeModel> map = new HashMap<>(10);
list1.forEach(nodeModel -> {
String sshId = nodeModel.getSshId();
if (StrUtil.isNotEmpty(sshId)) {
map.put(sshId, nodeModel);
}
});
list.forEach(PackageHostModel -> {
// 不返回密码
PackageHostModel.setPassword(null);
// PackageHostModel.setPrivateKey(null);
// 节点信息
BaseModel nodeModel = map.get(PackageHostModel.getId());
PackageHostModel.setNodeModel(nodeModel);
});
}
return new JsonMessage<>(200, "", list);
}
/**
* @param name
* @param host
* @param user
* @param password
* @param connectType
* @param privateKey
* @param port
* @param charset
* @param fileDirs
* @param id
* @param type {'add': 新增, 'edit': 修改}
* @return
*/
@RequestMapping(value = "save.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@OptLog(UserOperateLogV1.OptType.EditSsh)
@ResponseBody
@Feature(method = MethodFeature.EDIT)
public String save(@ValidatorItem(value = ValidatorRule.NOT_BLANK, msg = "主机名称不能为空") String name,
@ValidatorItem(value = ValidatorRule.NOT_BLANK, msg = "host不能为空") String host,
@ValidatorItem(value = ValidatorRule.NOT_BLANK, msg = "user不能为空") String user,
String password,
PackageHostModel.ConnectType connectType,
String privateKey,
@ValidatorItem(value = ValidatorRule.POSITIVE_INTEGER, msg = "port错误") int port,
String charset, String fileDirs,
String id, String type, String notAllowedCommand) {
// 优先判断参数 如果是 password 在修改时可以不填写
if (connectType == PackageHostModel.ConnectType.PASS && StrUtil.isEmpty(password) && "add".equals(type)) {
return JsonMessage.getString(405, "请填写登录密码");
}
if (connectType == PackageHostModel.ConnectType.PUBKEY && StrUtil.isEmpty(privateKey)) {
return JsonMessage.getString(405, "请填写证书内容");
}
PackageHostModel packageHostModel;
if ("edit".equals(type)) {
packageHostModel = hostService.getItem(id);
if (packageHostModel == null) {
return JsonMessage.getString(500, "不存在对应主机");
}
} else {
packageHostModel = new PackageHostModel();
}
// 目录
if (StrUtil.isEmpty(fileDirs)) {
packageHostModel.setFileDirs(null);
} else {
List<String> list = StrSplitter.splitTrim(fileDirs, StrUtil.LF, true);
packageHostModel.setFileDirs(list);
}
packageHostModel.setHost(host);
// 如果密码传递不为空就设置值 因为上面已经判断了只有修改的情况下 password 才可能为空
if (!StrUtil.isEmpty(password)) {
packageHostModel.setPassword(password);
}
packageHostModel.setPort(port);
packageHostModel.setUser(user);
packageHostModel.setName(name);
packageHostModel.setNotAllowedCommand(notAllowedCommand);
packageHostModel.setConnectType(connectType);
packageHostModel.setPrivateKey(privateKey);
try {
Charset.forName(charset);
packageHostModel.setCharset(charset);
} catch (Exception e) {
return JsonMessage.getString(405, "请填写正确的编码格式");
}
try {
Session session = HostService.getSession(packageHostModel);
JschUtil.close(session);
} catch (Exception e) {
return JsonMessage.getString(505, "主机连接失败:" + e.getMessage());
}
if ("add".equalsIgnoreCase(type)) {
hostService.addItem(packageHostModel);
} else {
hostService.updateItem(packageHostModel);
}
return JsonMessage.getString(200, "操作成功");
}
// @RequestMapping(value = "edit.html", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
// @Feature(method = MethodFeature.EDIT)
// public String edit(String id) {
// if (StrUtil.isNotEmpty(id)) {
// PackageHostModel PackageHostModel = sshService.getItem(id);
// if (PackageHostModel != null) {
// setAttribute("item", PackageHostModel);
// //
// String fileDirs = AgentWhitelist.convertToLine(PackageHostModel.getFileDirs());
// setAttribute("fileDirs", fileDirs);
// }
// }
// Collection<Charset> charsets = Charset.availableCharsets().values();
// Collection<Charset> collect = charsets.stream().filter(charset -> !StrUtil.startWithAny(charset.name(), "x", "w", "IBM")).collect(Collectors.toList());
// setAttribute("charsets", collect);
// //
// PackageHostModel.ConnectType[] values = PackageHostModel.ConnectType.values();
// setAttribute("connectTypes", values);
// return "node/ssh/edit";
// }
// @RequestMapping(value = "terminal.html", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
// @Feature(method = MethodFeature.TERMINAL)
// public String terminal(String id) {
// PackageHostModel PackageHostModel = sshService.getItem(id);
// setAttribute("item", PackageHostModel);
// return "node/ssh/terminal";
// }
/**
* 根据 nodeId 查询 SSH 列表
*
* @param nodeId
* @return
* @description for dev 3.x
* @author Hotstrip
*/
@RequestMapping(value = "list_by_node_id", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
@Feature(method = MethodFeature.LIST)
public String listByNodeId(String nodeId) {
JSONArray sshList = hostService.listSelect(nodeId);
return JsonMessage.getString(200, "success", sshList);
}
}
|
/*
* Copyright 2017-2019 EPAM Systems, Inc. (https://www.epam.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.epam.pipeline.entity.graph;
import com.epam.pipeline.entity.pipeline.PipelineTask;
import com.epam.pipeline.entity.pipeline.Tool;
import lombok.Data;
import java.util.HashSet;
import java.util.Set;
@Data
public class TaskNode {
private PipelineTask task;
private Set<Long> parents;
private Set<TaskNode> children;
private Set<String> inputs;
private Set<String> outputs;
private Tool tool;
public TaskNode() {
this.inputs = new HashSet<>();
this.outputs = new HashSet<>();
this.children = new HashSet<>();
this.parents = new HashSet<>();
}
public TaskNode(PipelineTask task) {
this();
this.task = task;
}
public void addParent(Long parent) {
this.parents.add(parent);
}
public void switchInputOutput() {
Set<String> tmp = this.outputs;
this.outputs = this.inputs;
this.inputs = tmp;
}
}
|
package com.google.firebase.udacity.daggerPosts.dagger.di.daggerViewModelHandling;
import androidx.lifecycle.ViewModel;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import dagger.MapKey;
/*
* to work with ViewModelFactory u need this scope class
* just don't care about the written copy/past it
* this is a solution for dagger/ViewModel problem
* */
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@MapKey
public @interface ViewModelKey {
Class<? extends ViewModel> value();
}
|
package org.arp.javautil.sql;
/*-
* #%L
* JavaUtil
* %%
* Copyright (C) 2012 - 2016 Emory University
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import com.mockrunner.mock.jdbc.JDBCMockObjectFactory;
import java.sql.SQLException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Tests whether {@link ConnectionSpec} returns correct database metadata for
* the MockRunner database driver.
*
* @author Andrew Post
*/
public class MockRunnerDatabaseMetaDataTest
extends AbstractDatabaseMetaDataTest {
private static JDBCMockObjectFactory JDBC_MOCK_OBJECT_FACTORY;
@BeforeClass
public static void setUpClass() throws InvalidConnectionSpecArguments {
JDBC_MOCK_OBJECT_FACTORY = new JDBCMockObjectFactory();
JDBC_MOCK_OBJECT_FACTORY.registerMockDriver();
createConnectionSpecInstance("", null, null);
}
@AfterClass
public static void tearDownClass() {
destroyConnectionSpecInstance();
JDBC_MOCK_OBJECT_FACTORY.restoreDrivers();
JDBC_MOCK_OBJECT_FACTORY = null;
}
@Test
public void testDatabaseProduct() throws SQLException {
assertDatabaseProduct(DatabaseProduct.OTHER);
}
@Test
public void testDatabaseVersion() throws SQLException {
assertDatabaseVersion(new DatabaseVersion(1, 0, "1.0"));
}
@Test
public void testDriver() throws SQLException {
assertDriver(Driver.OTHER);
}
@Test
public void testDriverVersion() throws SQLException {
assertDriverVersion(new DriverVersion(1, 0, "1.0"));
}
}
|
package org.apache.spark.sql.catalyst.expressions;
/**
* Replace all occurrences with string.
*/
public class StringReplace extends org.apache.spark.sql.catalyst.expressions.TernaryExpression implements org.apache.spark.sql.catalyst.expressions.ImplicitCastInputTypes, scala.Product, scala.Serializable {
static public abstract boolean canEqual (Object that) ;
static public abstract boolean equals (Object that) ;
static public abstract Object productElement (int n) ;
static public abstract int productArity () ;
static public scala.collection.Iterator<java.lang.Object> productIterator () { throw new RuntimeException(); }
static public java.lang.String productPrefix () { throw new RuntimeException(); }
static public org.apache.spark.sql.catalyst.trees.Origin origin () { throw new RuntimeException(); }
static public scala.collection.immutable.Set<org.apache.spark.sql.catalyst.trees.TreeNode<?>> containsChild () { throw new RuntimeException(); }
static public int hashCode () { throw new RuntimeException(); }
static public boolean fastEquals (org.apache.spark.sql.catalyst.trees.TreeNode<?> other) { throw new RuntimeException(); }
static public scala.Option<BaseType> find (scala.Function1<BaseType, java.lang.Object> f) { throw new RuntimeException(); }
static public void foreach (scala.Function1<BaseType, scala.runtime.BoxedUnit> f) { throw new RuntimeException(); }
static public void foreachUp (scala.Function1<BaseType, scala.runtime.BoxedUnit> f) { throw new RuntimeException(); }
static public <A extends java.lang.Object> scala.collection.Seq<A> map (scala.Function1<BaseType, A> f) { throw new RuntimeException(); }
static public <A extends java.lang.Object> scala.collection.Seq<A> flatMap (scala.Function1<BaseType, scala.collection.TraversableOnce<A>> f) { throw new RuntimeException(); }
static public <B extends java.lang.Object> scala.collection.Seq<B> collect (scala.PartialFunction<BaseType, B> pf) { throw new RuntimeException(); }
static public scala.collection.Seq<BaseType> collectLeaves () { throw new RuntimeException(); }
static public <B extends java.lang.Object> scala.Option<B> collectFirst (scala.PartialFunction<BaseType, B> pf) { throw new RuntimeException(); }
static protected <B extends java.lang.Object> java.lang.Object mapProductIterator (scala.Function1<java.lang.Object, B> f, scala.reflect.ClassTag<B> evidence$1) { throw new RuntimeException(); }
static public BaseType withNewChildren (scala.collection.Seq<BaseType> newChildren) { throw new RuntimeException(); }
static public BaseType transform (scala.PartialFunction<BaseType, BaseType> rule) { throw new RuntimeException(); }
static public BaseType transformDown (scala.PartialFunction<BaseType, BaseType> rule) { throw new RuntimeException(); }
static public BaseType transformUp (scala.PartialFunction<BaseType, BaseType> rule) { throw new RuntimeException(); }
static public BaseType mapChildren (scala.Function1<BaseType, BaseType> f) { throw new RuntimeException(); }
static protected scala.collection.Seq<java.lang.Object> otherCopyArgs () { throw new RuntimeException(); }
static public BaseType makeCopy (java.lang.Object[] newArgs) { throw new RuntimeException(); }
static public java.lang.String nodeName () { throw new RuntimeException(); }
static protected scala.collection.Iterator<java.lang.Object> stringArgs () { throw new RuntimeException(); }
static public java.lang.String argString () { throw new RuntimeException(); }
static public java.lang.String verboseStringWithSuffix () { throw new RuntimeException(); }
static public java.lang.String treeString () { throw new RuntimeException(); }
static public java.lang.String treeString (boolean verbose, boolean addSuffix) { throw new RuntimeException(); }
static public java.lang.String numberedTreeString () { throw new RuntimeException(); }
static public org.apache.spark.sql.catalyst.trees.TreeNode<?> apply (int number) { throw new RuntimeException(); }
static public BaseType p (int number) { throw new RuntimeException(); }
static protected scala.collection.Seq<org.apache.spark.sql.catalyst.trees.TreeNode<?>> innerChildren () { throw new RuntimeException(); }
static public scala.collection.mutable.StringBuilder generateTreeString (int depth, scala.collection.Seq<java.lang.Object> lastChildren, scala.collection.mutable.StringBuilder builder, boolean verbose, java.lang.String prefix, boolean addSuffix) { throw new RuntimeException(); }
static public java.lang.String asCode () { throw new RuntimeException(); }
static public java.lang.String toJSON () { throw new RuntimeException(); }
static public java.lang.String prettyJson () { throw new RuntimeException(); }
static protected scala.collection.immutable.List<scala.Tuple2<java.lang.String, org.json4s.JsonAST.JValue>> jsonFields () { throw new RuntimeException(); }
static public boolean treeString$default$2 () { throw new RuntimeException(); }
static public java.lang.String generateTreeString$default$5 () { throw new RuntimeException(); }
static public boolean generateTreeString$default$6 () { throw new RuntimeException(); }
static public boolean deterministic () { throw new RuntimeException(); }
static public org.apache.spark.sql.catalyst.expressions.AttributeSet references () { throw new RuntimeException(); }
static public org.apache.spark.sql.catalyst.expressions.codegen.ExprCode genCode (org.apache.spark.sql.catalyst.expressions.codegen.CodegenContext ctx) { throw new RuntimeException(); }
static public boolean resolved () { throw new RuntimeException(); }
static public boolean childrenResolved () { throw new RuntimeException(); }
static public org.apache.spark.sql.catalyst.expressions.Expression canonicalized () { throw new RuntimeException(); }
static public boolean semanticEquals (org.apache.spark.sql.catalyst.expressions.Expression other) { throw new RuntimeException(); }
static public int semanticHash () { throw new RuntimeException(); }
static protected scala.collection.Iterator<java.lang.Object> flatArguments () { throw new RuntimeException(); }
static public final java.lang.String verboseString () { throw new RuntimeException(); }
static public java.lang.String simpleString () { throw new RuntimeException(); }
static public java.lang.String toString () { throw new RuntimeException(); }
static public java.lang.String sql () { throw new RuntimeException(); }
static public org.apache.spark.sql.catalyst.InternalRow eval$default$1 () { throw new RuntimeException(); }
static public boolean foldable () { throw new RuntimeException(); }
static public boolean nullable () { throw new RuntimeException(); }
static public Object eval (org.apache.spark.sql.catalyst.InternalRow input) { throw new RuntimeException(); }
static protected org.apache.spark.sql.catalyst.expressions.codegen.ExprCode defineCodeGen (org.apache.spark.sql.catalyst.expressions.codegen.CodegenContext ctx, org.apache.spark.sql.catalyst.expressions.codegen.ExprCode ev, scala.Function3<java.lang.String, java.lang.String, java.lang.String, java.lang.String> f) { throw new RuntimeException(); }
static protected org.apache.spark.sql.catalyst.expressions.codegen.ExprCode nullSafeCodeGen (org.apache.spark.sql.catalyst.expressions.codegen.CodegenContext ctx, org.apache.spark.sql.catalyst.expressions.codegen.ExprCode ev, scala.Function3<java.lang.String, java.lang.String, java.lang.String, java.lang.String> f) { throw new RuntimeException(); }
static public org.apache.spark.sql.catalyst.analysis.TypeCheckResult checkInputDataTypes () { throw new RuntimeException(); }
public org.apache.spark.sql.catalyst.expressions.Expression srcExpr () { throw new RuntimeException(); }
public org.apache.spark.sql.catalyst.expressions.Expression searchExpr () { throw new RuntimeException(); }
public org.apache.spark.sql.catalyst.expressions.Expression replaceExpr () { throw new RuntimeException(); }
// not preceding
public StringReplace (org.apache.spark.sql.catalyst.expressions.Expression srcExpr, org.apache.spark.sql.catalyst.expressions.Expression searchExpr, org.apache.spark.sql.catalyst.expressions.Expression replaceExpr) { throw new RuntimeException(); }
public StringReplace (org.apache.spark.sql.catalyst.expressions.Expression srcExpr, org.apache.spark.sql.catalyst.expressions.Expression searchExpr) { throw new RuntimeException(); }
public Object nullSafeEval (Object srcEval, Object searchEval, Object replaceEval) { throw new RuntimeException(); }
public org.apache.spark.sql.catalyst.expressions.codegen.ExprCode doGenCode (org.apache.spark.sql.catalyst.expressions.codegen.CodegenContext ctx, org.apache.spark.sql.catalyst.expressions.codegen.ExprCode ev) { throw new RuntimeException(); }
public org.apache.spark.sql.types.DataType dataType () { throw new RuntimeException(); }
public scala.collection.Seq<org.apache.spark.sql.types.DataType> inputTypes () { throw new RuntimeException(); }
public scala.collection.Seq<org.apache.spark.sql.catalyst.expressions.Expression> children () { throw new RuntimeException(); }
public java.lang.String prettyName () { throw new RuntimeException(); }
}
|
package io.slingr.api.common;
import org.apache.log4j.Logger;
import org.glassfish.jersey.media.multipart.MultiPart;
import javax.ws.rs.client.WebTarget;
import java.io.InputStream;
/**
* Simple Rest client over a unique URI
*
* Created by lefunes on 21/03/16.
*/
public class SimpleRestClient extends RestClient {
private static final Logger logger = Logger.getLogger(SimpleRestClient.class);
public SimpleRestClient(String apiUri) throws RestException {
super(apiUri, isSecureConnection(apiUri));
}
public SimpleRestClient setHeader(String name, Object value) {
setupDefaultHeader(name, value);
return this;
}
public SimpleRestClient setParam(String name, String value) {
setupDefaultParam(name, value);
return this;
}
public SimpleRestClient path(String path) {
super.setPath(path);
return this;
}
public SimpleRestClient retries(Integer retries) {
this.setRetries(retries);
return this;
}
public SimpleRestClient connectionTimeout(Integer timeout) {
this.setConnectionTimeout(timeout);
return this;
}
public SimpleRestClient readTimeout(Integer timeout) {
this.setReadTimeout(timeout);
return this;
}
public SimpleRestClient silenceLogger() {
this.setSilenceLogger(true);
return this;
}
public SimpleRestClient disableConvertContentToString() {
this.setConvertContentToString(false);
return this;
}
public static SimpleRestClient uri(String apiUri){
return new SimpleRestClient(apiUri);
}
public Json get() throws RestException {
return super.get(null);
}
public Json get(String path) throws RestException {
WebTarget target = getApiTarget().path(path);
return super.get(target);
}
public Json get(String path, Json params) throws RestException {
WebTarget target = getApiTarget().path(path);
for (String key : params.keys()) {
target = target.queryParam(key, params.string(key));
}
return super.get(target);
}
public Json post() throws RestException {
return super.post(null);
}
public Json post(String path) throws RestException {
WebTarget target = getApiTarget().path(path);
return super.post(target);
}
public Json post(Json content) throws RestException {
return super.post(null, content);
}
public Json post(String path, Json content) throws RestException {
WebTarget target = getApiTarget().path(path);
return super.post(target, content);
}
public Json post(MultiPart content) throws RestException {
return super.post(null, content);
}
public Json post(String path, MultiPart content) throws RestException {
WebTarget target = getApiTarget().path(path);
return super.post(target, content);
}
public Json put() throws RestException {
return super.put(null);
}
public Json put(String path) throws RestException {
WebTarget target = getApiTarget().path(path);
return super.put(target);
}
public Json put(Json content) throws RestException {
return super.put(null, content);
}
public Json put(String path, Json content) throws RestException {
WebTarget target = getApiTarget().path(path);
return super.put(target, content);
}
public Json patch() throws RestException {
return super.patch(null);
}
public Json patch(Json content) throws RestException {
return super.patch(null, content);
}
public Json head() throws RestException {
return super.head(null);
}
public Json delete() throws RestException {
return super.delete(null);
}
public Json delete(String path) throws RestException {
WebTarget target = getApiTarget().path(path);
return super.delete(target);
}
public Json options() throws RestException {
return super.options(null);
}
public Json execute(RestMethod method, Json jsonRequest){
switch (method){
case POST: return post(jsonRequest);
case PUT: return put(jsonRequest);
case PATCH: return patch(jsonRequest);
case DELETE: return delete();
case HEAD: return head();
case OPTIONS: return options();
}
return get();
}
public InputStream download(){
return super.download(null);
}
public InputStream download(String path) {
WebTarget target = getApiTarget().path(path);
return super.download(target);
}
public InputStream download(boolean throwException){
return super.download(null, throwException);
}
public InputStream download(String path, boolean throwException) {
WebTarget target = getApiTarget().path(path);
return super.download(target, throwException);
}
}
|
// GUI Java classes
//
// Copyright 1996, Mark Watson. All rights reserved.
package mwa.gui;
import java.awt.*;
public class testGUI extends GUI {
public void init() {
NoInput = true;
super.init();
}
public void paintToDoubleBuffer(Graphics g) {
System.out.println("entered testGUI::paintToDoubleBuffer\n");
paintGridCell(g, 20, 20, 110, 0.5f, 0.0f, 1.0f);
}
public void doRunButton() {
P("OVERRIDDEN doRunButton()\n");
}
}
|
package de.aspera.dataexport.util;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.dbunit.DatabaseUnitException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import de.aspera.dataexport.Repositories.JsonDbRepository;
import de.aspera.dataexport.Repositories.JsonExportCommandRepository;
import de.aspera.dataexport.util.json.ExportJsonCommand;
import de.aspera.dataexport.util.json.ImportJsonCommandException;
import de.aspera.dataexport.util.json.JsonConnectionReadException;
import de.aspera.dataexport.util.json.JsonDatabase;
import de.aspera.dataexport.util.json.TableQuery;
@Component
public class ExporterController {
private static DataSetExporter exporter;
/**
* Get a buffered output stream to transform data or persist on the filesystem.
* A Command must have the same Schema and connection put can have more than one
* Table
*
* @param tableName
* @param columnsComaSeperated
* e.g. "firstname, lastname, ...." or "*" for all columns
* @param whereClause
* @param orderByClause
* @return
* @throws DatabaseUnitException
* @throws SQLException
*/
public ByteArrayOutputStream startExportForTable(JsonDatabase databaseConnection,
ExportJsonCommand exportCommand, boolean editable) throws DatabaseUnitException, SQLException {
List<TableDescriptor> descriptors = new ArrayList<>();
if (databaseConnection == null)
throw new IllegalArgumentException("The databaseConnection can not be null");
exporter = new DataSetExporter(databaseConnection);
for (TableQuery table : exportCommand.getTables()) {
TableDescriptor descriptor = new TableDescriptor(table.getTableName());
descriptor.setSchemaName(databaseConnection.getDbSchema());
if (table.getOrderByClause() != null)
descriptor.setOrderByClause(table.getOrderByClause());
if (table.getWhereClause() != null)
descriptor.setWhereClause(table.getWhereClause());
if (!table.getColumns().isEmpty())
descriptor.addField(table.getColumns());
else
descriptor.addField("*");
descriptors.add(descriptor);
}
return exporter.exportDataSet(descriptors, editable);
}
public Connection getConnection() {
return exporter.getConnection();
}
}
|
/*
* 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.logging.log4j.message;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.apache.logging.log4j.util.Strings;
/**
* Captures information about all running Threads.
*/
public class ThreadDumpMessage implements Message {
private static final long serialVersionUID = -1103400781608841088L;
private static final ThreadInfoFactory FACTORY;
private volatile Map<ThreadInformation, StackTraceElement[]> threads;
private final String title;
private String formattedMessage;
static {
final Method[] methods = ThreadInfo.class.getMethods();
boolean basic = true;
for (final Method method : methods) {
if (method.getName().equals("getLockInfo")) {
basic = false;
break;
}
}
FACTORY = basic ? new BasicThreadInfoFactory() : new ExtendedThreadInfoFactory();
}
/**
* Generate a ThreadDumpMessage with a title.
* @param title The title.
*/
public ThreadDumpMessage(final String title) {
this.title = title == null ? Strings.EMPTY : title;
threads = FACTORY.createThreadInfo();
}
private ThreadDumpMessage(final String formattedMsg, final String title) {
this.formattedMessage = formattedMsg;
this.title = title == null ? Strings.EMPTY : title;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("ThreadDumpMessage[");
if (this.title.length() > 0) {
sb.append("Title=\"").append(this.title).append('"');
}
sb.append(']');
return sb.toString();
}
/**
* Returns the ThreadDump in printable format.
* @return the ThreadDump suitable for logging.
*/
@Override
public String getFormattedMessage() {
if (formattedMessage != null) {
return formattedMessage;
}
final StringBuilder sb = new StringBuilder(title);
if (title.length() > 0) {
sb.append('\n');
}
for (final Map.Entry<ThreadInformation, StackTraceElement[]> entry : threads.entrySet()) {
final ThreadInformation info = entry.getKey();
info.printThreadInfo(sb);
info.printStack(sb, entry.getValue());
sb.append('\n');
}
return sb.toString();
}
/**
* Returns the title.
* @return the title.
*/
@Override
public String getFormat() {
return title == null ? Strings.EMPTY : title;
}
/**
* Returns an array with a single element, a Map containing the ThreadInformation as the key.
* and the StackTraceElement array as the value;
* @return the "parameters" to this Message.
*/
@Override
public Object[] getParameters() {
return null;
}
/**
* Creates a ThreadDumpMessageProxy that can be serialized.
* @return a ThreadDumpMessageProxy.
*/
protected Object writeReplace() {
return new ThreadDumpMessageProxy(this);
}
private void readObject(final ObjectInputStream stream)
throws InvalidObjectException {
throw new InvalidObjectException("Proxy required");
}
/**
* Proxy pattern used to serialize the ThreadDumpMessage.
*/
private static class ThreadDumpMessageProxy implements Serializable {
private static final long serialVersionUID = -3476620450287648269L;
private final String formattedMsg;
private final String title;
public ThreadDumpMessageProxy(final ThreadDumpMessage msg) {
this.formattedMsg = msg.getFormattedMessage();
this.title = msg.title;
}
/**
* Returns a ThreadDumpMessage using the data in the proxy.
* @return a ThreadDumpMessage.
*/
protected Object readResolve() {
return new ThreadDumpMessage(formattedMsg, title);
}
}
/**
* Factory to create Thread information.
*/
private interface ThreadInfoFactory {
Map<ThreadInformation, StackTraceElement[]> createThreadInfo();
}
/**
* Factory to create basic thread information.
*/
private static class BasicThreadInfoFactory implements ThreadInfoFactory {
@Override
public Map<ThreadInformation, StackTraceElement[]> createThreadInfo() {
final Map<Thread, StackTraceElement[]> map = Thread.getAllStackTraces();
final Map<ThreadInformation, StackTraceElement[]> threads =
new HashMap<ThreadInformation, StackTraceElement[]>(map.size());
for (final Map.Entry<Thread, StackTraceElement[]> entry : map.entrySet()) {
threads.put(new BasicThreadInformation(entry.getKey()), entry.getValue());
}
return threads;
}
}
/**
* Factory to create extended thread information.
*/
private static class ExtendedThreadInfoFactory implements ThreadInfoFactory {
@Override
public Map<ThreadInformation, StackTraceElement[]> createThreadInfo() {
final ThreadMXBean bean = ManagementFactory.getThreadMXBean();
final ThreadInfo[] array = bean.dumpAllThreads(true, true);
final Map<ThreadInformation, StackTraceElement[]> threads =
new HashMap<ThreadInformation, StackTraceElement[]>(array.length);
for (final ThreadInfo info : array) {
threads.put(new ExtendedThreadInformation(info), info.getStackTrace());
}
return threads;
}
}
/**
* Always returns null.
*
* @return null
*/
@Override
public Throwable getThrowable() {
return null;
}
}
|
/**
* Autogenerated by Avro
*
* DO NOT EDIT DIRECTLY
*/
package sparqles.avro.discovery;
@SuppressWarnings("all")
@org.apache.avro.specific.AvroGenerated
public class QueryInfo extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord {
public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"QueryInfo\",\"namespace\":\"sparqles.avro.discovery\",\"fields\":[{\"name\":\"URL\",\"type\":\"string\"},{\"name\":\"Operation\",\"type\":\"string\"},{\"name\":\"Exception\",\"type\":[\"string\",\"null\"]},{\"name\":\"allowedByRobotsTXT\",\"type\":\"boolean\",\"default\":true},{\"name\":\"Results\",\"type\":{\"type\":\"array\",\"items\":\"string\"}}]}");
public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
@Deprecated public java.lang.CharSequence URL;
@Deprecated public java.lang.CharSequence Operation;
@Deprecated public java.lang.CharSequence Exception;
@Deprecated public boolean allowedByRobotsTXT;
@Deprecated public java.util.List<java.lang.CharSequence> Results;
/**
* Default constructor. Note that this does not initialize fields
* to their default values from the schema. If that is desired then
* one should use {@link \#newBuilder()}.
*/
public QueryInfo() {}
/**
* All-args constructor.
*/
public QueryInfo(java.lang.CharSequence URL, java.lang.CharSequence Operation, java.lang.CharSequence Exception, java.lang.Boolean allowedByRobotsTXT, java.util.List<java.lang.CharSequence> Results) {
this.URL = URL;
this.Operation = Operation;
this.Exception = Exception;
this.allowedByRobotsTXT = allowedByRobotsTXT;
this.Results = Results;
}
public org.apache.avro.Schema getSchema() { return SCHEMA$; }
// Used by DatumWriter. Applications should not call.
public java.lang.Object get(int field$) {
switch (field$) {
case 0: return URL;
case 1: return Operation;
case 2: return Exception;
case 3: return allowedByRobotsTXT;
case 4: return Results;
default: throw new org.apache.avro.AvroRuntimeException("Bad index");
}
}
// Used by DatumReader. Applications should not call.
@SuppressWarnings(value="unchecked")
public void put(int field$, java.lang.Object value$) {
switch (field$) {
case 0: URL = (java.lang.CharSequence)value$; break;
case 1: Operation = (java.lang.CharSequence)value$; break;
case 2: Exception = (java.lang.CharSequence)value$; break;
case 3: allowedByRobotsTXT = (java.lang.Boolean)value$; break;
case 4: Results = (java.util.List<java.lang.CharSequence>)value$; break;
default: throw new org.apache.avro.AvroRuntimeException("Bad index");
}
}
/**
* Gets the value of the 'URL' field.
*/
public java.lang.CharSequence getURL() {
return URL;
}
/**
* Sets the value of the 'URL' field.
* @param value the value to set.
*/
public void setURL(java.lang.CharSequence value) {
this.URL = value;
}
/**
* Gets the value of the 'Operation' field.
*/
public java.lang.CharSequence getOperation() {
return Operation;
}
/**
* Sets the value of the 'Operation' field.
* @param value the value to set.
*/
public void setOperation(java.lang.CharSequence value) {
this.Operation = value;
}
/**
* Gets the value of the 'Exception' field.
*/
public java.lang.CharSequence getException() {
return Exception;
}
/**
* Sets the value of the 'Exception' field.
* @param value the value to set.
*/
public void setException(java.lang.CharSequence value) {
this.Exception = value;
}
/**
* Gets the value of the 'allowedByRobotsTXT' field.
*/
public java.lang.Boolean getAllowedByRobotsTXT() {
return allowedByRobotsTXT;
}
/**
* Sets the value of the 'allowedByRobotsTXT' field.
* @param value the value to set.
*/
public void setAllowedByRobotsTXT(java.lang.Boolean value) {
this.allowedByRobotsTXT = value;
}
/**
* Gets the value of the 'Results' field.
*/
public java.util.List<java.lang.CharSequence> getResults() {
return Results;
}
/**
* Sets the value of the 'Results' field.
* @param value the value to set.
*/
public void setResults(java.util.List<java.lang.CharSequence> value) {
this.Results = value;
}
/** Creates a new QueryInfo RecordBuilder */
public static sparqles.avro.discovery.QueryInfo.Builder newBuilder() {
return new sparqles.avro.discovery.QueryInfo.Builder();
}
/** Creates a new QueryInfo RecordBuilder by copying an existing Builder */
public static sparqles.avro.discovery.QueryInfo.Builder newBuilder(sparqles.avro.discovery.QueryInfo.Builder other) {
return new sparqles.avro.discovery.QueryInfo.Builder(other);
}
/** Creates a new QueryInfo RecordBuilder by copying an existing QueryInfo instance */
public static sparqles.avro.discovery.QueryInfo.Builder newBuilder(sparqles.avro.discovery.QueryInfo other) {
return new sparqles.avro.discovery.QueryInfo.Builder(other);
}
/**
* RecordBuilder for QueryInfo instances.
*/
public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase<QueryInfo>
implements org.apache.avro.data.RecordBuilder<QueryInfo> {
private java.lang.CharSequence URL;
private java.lang.CharSequence Operation;
private java.lang.CharSequence Exception;
private boolean allowedByRobotsTXT;
private java.util.List<java.lang.CharSequence> Results;
/** Creates a new Builder */
private Builder() {
super(sparqles.avro.discovery.QueryInfo.SCHEMA$);
}
/** Creates a Builder by copying an existing Builder */
private Builder(sparqles.avro.discovery.QueryInfo.Builder other) {
super(other);
if (isValidValue(fields()[0], other.URL)) {
this.URL = data().deepCopy(fields()[0].schema(), other.URL);
fieldSetFlags()[0] = true;
}
if (isValidValue(fields()[1], other.Operation)) {
this.Operation = data().deepCopy(fields()[1].schema(), other.Operation);
fieldSetFlags()[1] = true;
}
if (isValidValue(fields()[2], other.Exception)) {
this.Exception = data().deepCopy(fields()[2].schema(), other.Exception);
fieldSetFlags()[2] = true;
}
if (isValidValue(fields()[3], other.allowedByRobotsTXT)) {
this.allowedByRobotsTXT = data().deepCopy(fields()[3].schema(), other.allowedByRobotsTXT);
fieldSetFlags()[3] = true;
}
if (isValidValue(fields()[4], other.Results)) {
this.Results = data().deepCopy(fields()[4].schema(), other.Results);
fieldSetFlags()[4] = true;
}
}
/** Creates a Builder by copying an existing QueryInfo instance */
private Builder(sparqles.avro.discovery.QueryInfo other) {
super(sparqles.avro.discovery.QueryInfo.SCHEMA$);
if (isValidValue(fields()[0], other.URL)) {
this.URL = data().deepCopy(fields()[0].schema(), other.URL);
fieldSetFlags()[0] = true;
}
if (isValidValue(fields()[1], other.Operation)) {
this.Operation = data().deepCopy(fields()[1].schema(), other.Operation);
fieldSetFlags()[1] = true;
}
if (isValidValue(fields()[2], other.Exception)) {
this.Exception = data().deepCopy(fields()[2].schema(), other.Exception);
fieldSetFlags()[2] = true;
}
if (isValidValue(fields()[3], other.allowedByRobotsTXT)) {
this.allowedByRobotsTXT = data().deepCopy(fields()[3].schema(), other.allowedByRobotsTXT);
fieldSetFlags()[3] = true;
}
if (isValidValue(fields()[4], other.Results)) {
this.Results = data().deepCopy(fields()[4].schema(), other.Results);
fieldSetFlags()[4] = true;
}
}
/** Gets the value of the 'URL' field */
public java.lang.CharSequence getURL() {
return URL;
}
/** Sets the value of the 'URL' field */
public sparqles.avro.discovery.QueryInfo.Builder setURL(java.lang.CharSequence value) {
validate(fields()[0], value);
this.URL = value;
fieldSetFlags()[0] = true;
return this;
}
/** Checks whether the 'URL' field has been set */
public boolean hasURL() {
return fieldSetFlags()[0];
}
/** Clears the value of the 'URL' field */
public sparqles.avro.discovery.QueryInfo.Builder clearURL() {
URL = null;
fieldSetFlags()[0] = false;
return this;
}
/** Gets the value of the 'Operation' field */
public java.lang.CharSequence getOperation() {
return Operation;
}
/** Sets the value of the 'Operation' field */
public sparqles.avro.discovery.QueryInfo.Builder setOperation(java.lang.CharSequence value) {
validate(fields()[1], value);
this.Operation = value;
fieldSetFlags()[1] = true;
return this;
}
/** Checks whether the 'Operation' field has been set */
public boolean hasOperation() {
return fieldSetFlags()[1];
}
/** Clears the value of the 'Operation' field */
public sparqles.avro.discovery.QueryInfo.Builder clearOperation() {
Operation = null;
fieldSetFlags()[1] = false;
return this;
}
/** Gets the value of the 'Exception' field */
public java.lang.CharSequence getException() {
return Exception;
}
/** Sets the value of the 'Exception' field */
public sparqles.avro.discovery.QueryInfo.Builder setException(java.lang.CharSequence value) {
validate(fields()[2], value);
this.Exception = value;
fieldSetFlags()[2] = true;
return this;
}
/** Checks whether the 'Exception' field has been set */
public boolean hasException() {
return fieldSetFlags()[2];
}
/** Clears the value of the 'Exception' field */
public sparqles.avro.discovery.QueryInfo.Builder clearException() {
Exception = null;
fieldSetFlags()[2] = false;
return this;
}
/** Gets the value of the 'allowedByRobotsTXT' field */
public java.lang.Boolean getAllowedByRobotsTXT() {
return allowedByRobotsTXT;
}
/** Sets the value of the 'allowedByRobotsTXT' field */
public sparqles.avro.discovery.QueryInfo.Builder setAllowedByRobotsTXT(boolean value) {
validate(fields()[3], value);
this.allowedByRobotsTXT = value;
fieldSetFlags()[3] = true;
return this;
}
/** Checks whether the 'allowedByRobotsTXT' field has been set */
public boolean hasAllowedByRobotsTXT() {
return fieldSetFlags()[3];
}
/** Clears the value of the 'allowedByRobotsTXT' field */
public sparqles.avro.discovery.QueryInfo.Builder clearAllowedByRobotsTXT() {
fieldSetFlags()[3] = false;
return this;
}
/** Gets the value of the 'Results' field */
public java.util.List<java.lang.CharSequence> getResults() {
return Results;
}
/** Sets the value of the 'Results' field */
public sparqles.avro.discovery.QueryInfo.Builder setResults(java.util.List<java.lang.CharSequence> value) {
validate(fields()[4], value);
this.Results = value;
fieldSetFlags()[4] = true;
return this;
}
/** Checks whether the 'Results' field has been set */
public boolean hasResults() {
return fieldSetFlags()[4];
}
/** Clears the value of the 'Results' field */
public sparqles.avro.discovery.QueryInfo.Builder clearResults() {
Results = null;
fieldSetFlags()[4] = false;
return this;
}
@Override
public QueryInfo build() {
try {
QueryInfo record = new QueryInfo();
record.URL = fieldSetFlags()[0] ? this.URL : (java.lang.CharSequence) defaultValue(fields()[0]);
record.Operation = fieldSetFlags()[1] ? this.Operation : (java.lang.CharSequence) defaultValue(fields()[1]);
record.Exception = fieldSetFlags()[2] ? this.Exception : (java.lang.CharSequence) defaultValue(fields()[2]);
record.allowedByRobotsTXT = fieldSetFlags()[3] ? this.allowedByRobotsTXT : (java.lang.Boolean) defaultValue(fields()[3]);
record.Results = fieldSetFlags()[4] ? this.Results : (java.util.List<java.lang.CharSequence>) defaultValue(fields()[4]);
return record;
} catch (Exception e) {
throw new org.apache.avro.AvroRuntimeException(e);
}
}
}
}
|
package com.fank243.cloud.system.service.impl;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fank243.cloud.common.core.constant.UserConstants;
import com.fank243.cloud.common.core.exception.CustomException;
import com.fank243.cloud.common.core.utils.StringUtils;
import com.fank243.cloud.common.datascope.annotation.DataScope;
import com.fank243.cloud.system.api.domain.SysDept;
import com.fank243.cloud.system.api.domain.SysRole;
import com.fank243.cloud.system.domain.vo.TreeSelect;
import com.fank243.cloud.system.mapper.SysDeptMapper;
import com.fank243.cloud.system.mapper.SysRoleMapper;
import com.fank243.cloud.system.service.ISysDeptService;
import javax.annotation.Resource;
/**
* 部门管理 服务实现
*
* @author FanWeiJie
* @date 2021-04-05 23:41:10
*/
@Service
public class SysDeptServiceImpl implements ISysDeptService {
@Resource
private SysDeptMapper deptMapper;
@Resource
private SysRoleMapper roleMapper;
/**
* 查询部门管理数据
*
* @param dept 部门信息
* @return 部门信息集合
*/
@Override
@DataScope(deptAlias = "d")
public List<SysDept> selectDeptList(SysDept dept) {
return deptMapper.selectDeptList(dept);
}
/**
* 构建前端所需要树结构
*
* @param depts 部门列表
* @return 树结构列表
*/
@Override
public List<SysDept> buildDeptTree(List<SysDept> depts) {
List<SysDept> returnList = new ArrayList<SysDept>();
List<Long> tempList = new ArrayList<Long>();
for (SysDept dept : depts) {
tempList.add(dept.getDeptId());
}
for (Iterator<SysDept> iterator = depts.iterator(); iterator.hasNext();) {
SysDept dept = (SysDept)iterator.next();
// 如果是顶级节点, 遍历该父节点的所有子节点
if (!tempList.contains(dept.getParentId())) {
recursionFn(depts, dept);
returnList.add(dept);
}
}
if (returnList.isEmpty()) {
returnList = depts;
}
return returnList;
}
/**
* 构建前端所需要下拉树结构
*
* @param depts 部门列表
* @return 下拉树结构列表
*/
@Override
public List<TreeSelect> buildDeptTreeSelect(List<SysDept> depts) {
List<SysDept> deptTrees = buildDeptTree(depts);
return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
}
/**
* 根据角色ID查询部门树信息
*
* @param roleId 角色ID
* @return 选中部门列表
*/
@Override
public List<Integer> selectDeptListByRoleId(Long roleId) {
SysRole role = roleMapper.selectRoleById(roleId);
return deptMapper.selectDeptListByRoleId(roleId, role.isDeptCheckStrictly());
}
/**
* 根据部门ID查询信息
*
* @param deptId 部门ID
* @return 部门信息
*/
@Override
public SysDept selectDeptById(Long deptId) {
return deptMapper.selectDeptById(deptId);
}
/**
* 根据ID查询所有子部门(正常状态)
*
* @param deptId 部门ID
* @return 子部门数
*/
@Override
public int selectNormalChildrenDeptById(Long deptId) {
return deptMapper.selectNormalChildrenDeptById(deptId);
}
/**
* 是否存在子节点
*
* @param deptId 部门ID
* @return 结果
*/
@Override
public boolean hasChildByDeptId(Long deptId) {
int result = deptMapper.hasChildByDeptId(deptId);
return result > 0 ? true : false;
}
/**
* 查询部门是否存在用户
*
* @param deptId 部门ID
* @return 结果 true 存在 false 不存在
*/
@Override
public boolean checkDeptExistUser(Long deptId) {
int result = deptMapper.checkDeptExistUser(deptId);
return result > 0 ? true : false;
}
/**
* 校验部门名称是否唯一
*
* @param dept 部门信息
* @return 结果
*/
@Override
public String checkDeptNameUnique(SysDept dept) {
Long deptId = StringUtils.isNull(dept.getDeptId()) ? -1L : dept.getDeptId();
SysDept info = deptMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId());
if (StringUtils.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue()) {
return UserConstants.NOT_UNIQUE;
}
return UserConstants.UNIQUE;
}
/**
* 新增保存部门信息
*
* @param dept 部门信息
* @return 结果
*/
@Override
public int insertDept(SysDept dept) {
SysDept info = deptMapper.selectDeptById(dept.getParentId());
// 如果父节点不为正常状态,则不允许新增子节点
if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
throw new CustomException("部门停用,不允许新增");
}
dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
return deptMapper.insertDept(dept);
}
/**
* 修改保存部门信息
*
* @param dept 部门信息
* @return 结果
*/
@Override
public int updateDept(SysDept dept) {
SysDept newParentDept = deptMapper.selectDeptById(dept.getParentId());
SysDept oldDept = deptMapper.selectDeptById(dept.getDeptId());
if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept)) {
String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
String oldAncestors = oldDept.getAncestors();
dept.setAncestors(newAncestors);
updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
}
int result = deptMapper.updateDept(dept);
if (UserConstants.DEPT_NORMAL.equals(dept.getStatus())) {
// 如果该部门是启用状态,则启用该部门的所有上级部门
updateParentDeptStatus(dept);
}
return result;
}
/**
* 修改该部门的父级部门状态
*
* @param dept 当前部门
*/
private void updateParentDeptStatus(SysDept dept) {
String updateBy = dept.getUpdateBy();
dept = deptMapper.selectDeptById(dept.getDeptId());
dept.setUpdateBy(updateBy);
deptMapper.updateDeptStatus(dept);
}
/**
* 修改子元素关系
*
* @param deptId 被修改的部门ID
* @param newAncestors 新的父ID集合
* @param oldAncestors 旧的父ID集合
*/
public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors) {
List<SysDept> children = deptMapper.selectChildrenDeptById(deptId);
for (SysDept child : children) {
child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors));
}
if (children.size() > 0) {
deptMapper.updateDeptChildren(children);
}
}
/**
* 删除部门管理信息
*
* @param deptId 部门ID
* @return 结果
*/
@Override
public int deleteDeptById(Long deptId) {
return deptMapper.deleteDeptById(deptId);
}
/**
* 递归列表
*/
private void recursionFn(List<SysDept> list, SysDept t) {
// 得到子节点列表
List<SysDept> childList = getChildList(list, t);
t.setChildren(childList);
for (SysDept tChild : childList) {
if (hasChild(list, tChild)) {
recursionFn(list, tChild);
}
}
}
/**
* 得到子节点列表
*/
private List<SysDept> getChildList(List<SysDept> list, SysDept t) {
List<SysDept> tlist = new ArrayList<SysDept>();
Iterator<SysDept> it = list.iterator();
while (it.hasNext()) {
SysDept n = (SysDept)it.next();
if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getDeptId().longValue()) {
tlist.add(n);
}
}
return tlist;
}
/**
* 判断是否有子节点
*/
private boolean hasChild(List<SysDept> list, SysDept t) {
return getChildList(list, t).size() > 0 ? true : false;
}
}
|
package com.larksuite.oapi.sample.api;
import com.larksuite.oapi.core.AppSettings;
import com.larksuite.oapi.core.Config;
import com.larksuite.oapi.core.DefaultStore;
import com.larksuite.oapi.core.Domain;
import com.larksuite.oapi.core.api.request.FormDataFile;
import com.larksuite.oapi.core.api.response.Response;
import com.larksuite.oapi.core.utils.Jsons;
import com.larksuite.oapi.service.im.v1.ImService;
import com.larksuite.oapi.service.im.v1.model.ImageCreateResult;
import java.io.IOException;
import java.io.InputStream;
public class ImSample {
// Configuration of "Custom App", parameter description:
// AppID、AppSecret: "Developer Console" -> "Credentials"(App ID、App Secret)
// VerificationToken、EncryptKey: "Developer Console" -> "Event Subscriptions"(Verification Token、Encrypt Key)
// For more information, please see: Github->README.md->Advanced use->How to build app settings(AppSettings)
private static final AppSettings appSettings = Config.getInternalAppSettingsByEnv();
// Currently, you are visiting Feishu, which uses default storage
// For more information, please see: Github->README.md->Advanced use->How to build overall configuration(Config)
private static final Config config = new Config(Domain.FeiShu, appSettings, new DefaultStore());
public static void main(String[] args) throws Exception {
ImService imService = new ImService(config);
ImService.ImageCreateReqCall reqCall = imService.getImages().create();
reqCall.setImageType("message");
// read files under Resources
try (InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("file path")) {
// method 1: use byte stream
reqCall.setImage(new FormDataFile().setContentStream(inputStream));
// method 2: use byte array
// byte[] bs = IOs.readAll(inputStream);
// reqCall.setImage(new FormDataFile().setContent(bs));
Response<ImageCreateResult> resp = reqCall.execute();
System.out.println(resp.getRequestID());
System.out.println(resp.getHTTPStatusCode());
System.out.println(Jsons.DEFAULT_GSON.toJson(resp));
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
/*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.r2dbc.h2.codecs;
import org.h2.value.Value;
import org.h2.value.ValueDouble;
import org.h2.value.ValueNull;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatNullPointerException;
final class DoubleCodecTest {
@Test
void decode() {
assertThat(new DoubleCodec().decode(ValueDouble.get(100.0d), Double.class))
.isEqualTo(100.0d);
}
@Test
void doCanDecode() {
DoubleCodec codec = new DoubleCodec();
assertThat(codec.doCanDecode(Value.DOUBLE)).isTrue();
assertThat(codec.doCanDecode(Value.UNKNOWN)).isFalse();
assertThat(codec.doCanDecode(Value.INT)).isFalse();
}
@Test
void doEncode() {
assertThat(new DoubleCodec().doEncode(100d))
.isEqualTo(ValueDouble.get(100d));
}
@Test
void doEncodeNoValue() {
assertThatNullPointerException().isThrownBy(() -> new DoubleCodec().doEncode(null))
.withMessage("value must not be null");
}
@Test
void encodeNull() {
assertThat(new DoubleCodec().encodeNull())
.isEqualTo(ValueNull.INSTANCE);
}
}
|
package org.ovirt.engine.api.restapi.resource;
import static org.easymock.EasyMock.expect;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import org.junit.Test;
import org.ovirt.engine.api.model.Host;
import org.ovirt.engine.api.model.LogicalUnit;
import org.ovirt.engine.api.model.Storage;
import org.ovirt.engine.api.model.StorageDomain;
import org.ovirt.engine.api.model.StorageDomainType;
import org.ovirt.engine.api.model.StorageType;
import org.ovirt.engine.api.model.VolumeGroup;
import org.ovirt.engine.core.common.action.AddSANStorageDomainParameters;
import org.ovirt.engine.core.common.action.RemoveStorageDomainParameters;
import org.ovirt.engine.core.common.action.StorageDomainManagementParameter;
import org.ovirt.engine.core.common.action.StorageDomainParametersBase;
import org.ovirt.engine.core.common.action.StorageServerConnectionParametersBase;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.businessentities.LUNs;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.storage_domain_static;
import org.ovirt.engine.core.common.businessentities.storage_domains;
import org.ovirt.engine.core.common.businessentities.storage_server_connections;
import org.ovirt.engine.core.common.interfaces.SearchType;
import org.ovirt.engine.core.common.queries.GetDeviceListQueryParameters;
import org.ovirt.engine.core.common.queries.GetExistingStorageDomainListParameters;
import org.ovirt.engine.core.common.queries.GetLunsByVgIdParameters;
import org.ovirt.engine.core.common.queries.StorageDomainQueryParametersBase;
import org.ovirt.engine.core.common.queries.StorageServerConnectionQueryParametersBase;
import org.ovirt.engine.core.common.queries.VdcQueryType;
public class BackendStorageDomainsResourceTest
extends AbstractBackendCollectionResourceTest<StorageDomain, storage_domains, BackendStorageDomainsResource> {
protected static final StorageDomainType[] TYPES = { StorageDomainType.DATA,
StorageDomainType.ISO, StorageDomainType.EXPORT };
protected static final StorageType[] STORAGE_TYPES = { StorageType.NFS, StorageType.NFS,
StorageType.LOCALFS };
protected static final int LOCAL_IDX = 2;
protected static final String[] ADDRESSES = { "10.11.12.13", "13.12.11.10", "10.01.10.01" };
protected static final String[] PATHS = { "/1", "/2", "/3" };
protected static final String LUN = "1IET_00010001";
protected static final String TARGET = "iqn.2009-08.org.fubar.engine:markmc.test1";
protected static final Integer PORT = 3260;
protected static final org.ovirt.engine.core.common.businessentities.StorageDomainType TYPES_MAPPED[] = {
org.ovirt.engine.core.common.businessentities.StorageDomainType.Data,
org.ovirt.engine.core.common.businessentities.StorageDomainType.ISO,
org.ovirt.engine.core.common.businessentities.StorageDomainType.ImportExport };
protected static final org.ovirt.engine.core.common.businessentities.StorageType STORAGE_TYPES_MAPPED[] = {
org.ovirt.engine.core.common.businessentities.StorageType.NFS,
org.ovirt.engine.core.common.businessentities.StorageType.NFS,
org.ovirt.engine.core.common.businessentities.StorageType.LOCALFS };
public BackendStorageDomainsResourceTest() {
super(new BackendStorageDomainsResource(), SearchType.StorageDomain, "Storage : ");
}
@Test
public void testRemoveBadGuid() throws Exception {
control.replay();
try {
StorageDomain storageDomain = new StorageDomain();
storageDomain.setHost(new Host());
storageDomain.getHost().setId(GUIDS[1].toString());
collection.remove("foo", storageDomain);
fail("expected WebApplicationException");
} catch (WebApplicationException wae) {
verifyNotFoundException(wae);
}
}
@Test
public void testRemoveStorageDomainNull() throws Exception {
control.replay();
try {
collection.remove(GUIDS[0].toString(), null);
fail("expected WebApplicationException");
} catch (WebApplicationException wae) {
assertEquals(400, wae.getResponse().getStatus());
}
}
public void testRemoveWithHostId() throws Exception {
setUpGetEntityExpectations();
setUriInfo(setUpActionExpectations(VdcActionType.RemoveStorageDomain,
RemoveStorageDomainParameters.class,
new String[] { "StorageDomainId", "VdsId", "DoFormat" },
new Object[] { GUIDS[0], GUIDS[1], Boolean.FALSE },
true,
true));
StorageDomain storageDomain = new StorageDomain();
storageDomain.setHost(new Host());
storageDomain.getHost().setId(GUIDS[1].toString());
verifyRemove(collection.remove(GUIDS[0].toString(), storageDomain));
}
private void setUpGetEntityExpectations() throws Exception {
setUpGetEntityExpectations(VdcQueryType.GetStorageDomainById,
StorageDomainQueryParametersBase.class,
new String[] { "StorageDomainId" },
new Object[] { GUIDS[0] },
new storage_domains());
}
@Test
public void testRemoveWithFormat() throws Exception {
setUpGetEntityExpectations();
setUriInfo(setUpActionExpectations(VdcActionType.RemoveStorageDomain,
RemoveStorageDomainParameters.class,
new String[] { "StorageDomainId", "VdsId", "DoFormat" },
new Object[] { GUIDS[0], GUIDS[1], Boolean.TRUE },
true,
true));
StorageDomain storageDomain = new StorageDomain();
storageDomain.setHost(new Host());
storageDomain.getHost().setId(GUIDS[1].toString());
storageDomain.setFormat(true);
verifyRemove(collection.remove(GUIDS[0].toString(), storageDomain));
}
@Test
public void testRemoveWithDestroy() throws Exception {
setUpGetEntityExpectations();
setUriInfo(setUpActionExpectations(VdcActionType.ForceRemoveStorageDomain,
StorageDomainParametersBase.class,
new String[] { "StorageDomainId", "VdsId"},
new Object[] { GUIDS[0], GUIDS[1]},
true,
true));
StorageDomain storageDomain = new StorageDomain();
storageDomain.setHost(new Host());
storageDomain.getHost().setId(GUIDS[1].toString());
storageDomain.setDestroy(true);
verifyRemove(collection.remove(GUIDS[0].toString(), storageDomain));
}
@Test
public void testRemoveWithHostName() throws Exception {
setUpGetEntityExpectations();
VDS host = BackendHostsResourceTest.setUpEntityExpectations(control.createMock(VDS.class), 1);
setUpGetEntityExpectations("Hosts: name=" + NAMES[1],
SearchType.VDS,
host);
setUriInfo(setUpActionExpectations(VdcActionType.RemoveStorageDomain,
RemoveStorageDomainParameters.class,
new String[] { "StorageDomainId", "VdsId", "DoFormat" },
new Object[] { GUIDS[0], GUIDS[1], Boolean.FALSE },
true,
true));
StorageDomain storageDomain = new StorageDomain();
storageDomain.setHost(new Host());
storageDomain.getHost().setName(NAMES[1]);
verifyRemove(collection.remove(GUIDS[0].toString(), storageDomain));
}
@Test
public void testIncompleteRemove() throws Exception {
control.replay();
try {
collection.remove(GUIDS[0].toString(), new StorageDomain());
fail("expected WebApplicationException");
} catch (WebApplicationException wae) {
verifyIncompleteException(wae, "StorageDomain", "remove", "host.id|name");
}
}
@Test
public void testRemoveCantDo() throws Exception {
doTestBadRemove(false, true, CANT_DO);
}
@Test
public void testRemoveFailed() throws Exception {
doTestBadRemove(true, false, FAILURE);
}
protected void doTestBadRemove(boolean canDo, boolean success, String detail) throws Exception {
setUpGetEntityExpectations();
setUriInfo(setUpActionExpectations(VdcActionType.RemoveStorageDomain,
RemoveStorageDomainParameters.class,
new String[] { "StorageDomainId", "VdsId", "DoFormat" },
new Object[] { GUIDS[0], GUIDS[1], Boolean.FALSE },
canDo,
success));
try {
StorageDomain storageDomain = new StorageDomain();
storageDomain.setHost(new Host());
storageDomain.getHost().setId(GUIDS[1].toString());
collection.remove(GUIDS[0].toString(), storageDomain);
fail("expected WebApplicationException");
} catch (WebApplicationException wae) {
verifyFault(wae, detail);
}
}
@Test
public void testAddStorageDomain() throws Exception {
Host host = new Host();
host.setId(GUIDS[0].toString());
doTestAddStorageDomain(0, host, false);
}
@Test
public void testAddStorageDomainWithHostName() throws Exception {
Host host = new Host();
host.setName(NAMES[0]);
setUpGetEntityExpectations("Hosts: name=" + NAMES[0], SearchType.VDS, setUpVDS(0));
doTestAddStorageDomain(0, host, false);
}
@Test
public void testAddExistingStorageDomain() throws Exception {
Host host = new Host();
host.setId(GUIDS[0].toString());
doTestAddStorageDomain(1, host, true);
}
public void doTestAddStorageDomain(int idx, Host host, boolean existing) throws Exception {
setUriInfo(setUpActionExpectations(VdcActionType.AddStorageServerConnection,
StorageServerConnectionParametersBase.class,
new String[] { "StorageServerConnection.connection", "StorageServerConnection.storage_type", "VdsId" },
new Object[] { ADDRESSES[idx] + ":" + PATHS[idx], STORAGE_TYPES_MAPPED[idx], GUIDS[0] },
true,
true,
GUIDS[idx].toString(),
false));
setUpGetEntityExpectations(VdcQueryType.GetStorageServerConnectionById,
StorageServerConnectionQueryParametersBase.class,
new String[] { "ServerConnectionId" },
new Object[] { GUIDS[idx].toString() },
setUpStorageServerConnection(idx));
setUpGetEntityExpectations(VdcQueryType.GetExistingStorageDomainList,
GetExistingStorageDomainListParameters.class,
new String[] { "VdsId", "StorageType", "StorageDomainType", "Path" },
new Object[] { GUIDS[0], STORAGE_TYPES_MAPPED[idx], TYPES_MAPPED[idx], ADDRESSES[idx] + ":" + PATHS[idx] },
getExistingStorageDomains(existing));
setUpCreationExpectations(!existing ? VdcActionType.AddNFSStorageDomain : VdcActionType.AddExistingNFSStorageDomain,
StorageDomainManagementParameter.class,
new String[] {},
new Object[] {},
true,
true,
GUIDS[idx],
VdcQueryType.GetStorageDomainById,
StorageDomainQueryParametersBase.class,
new String[] { "StorageDomainId" },
new Object[] { GUIDS[idx] },
getEntity(idx));
StorageDomain model = getModel(idx);
model.setHost(host);
Response response = collection.add(model);
assertEquals(201, response.getStatus());
assertTrue(response.getEntity() instanceof StorageDomain);
verifyModel((StorageDomain) response.getEntity(), idx);
}
@Test
public void testAddLocalStorageDomain() throws Exception {
setUriInfo(setUpActionExpectations(VdcActionType.AddStorageServerConnection,
StorageServerConnectionParametersBase.class,
new String[] { "StorageServerConnection.connection", "StorageServerConnection.storage_type", "VdsId" },
new Object[] { PATHS[LOCAL_IDX], STORAGE_TYPES_MAPPED[LOCAL_IDX], GUIDS[0] },
true,
true,
GUIDS[LOCAL_IDX].toString(),
false));
setUpGetEntityExpectations(VdcQueryType.GetStorageServerConnectionById,
StorageServerConnectionQueryParametersBase.class,
new String[] { "ServerConnectionId" },
new Object[] { GUIDS[LOCAL_IDX].toString() },
setUpLocalStorageServerConnection(LOCAL_IDX));
setUpCreationExpectations(VdcActionType.AddLocalStorageDomain,
StorageDomainManagementParameter.class,
new String[] { "VdsId" },
new Object[] { GUIDS[0] },
true,
true,
GUIDS[LOCAL_IDX],
VdcQueryType.GetStorageDomainById,
StorageDomainQueryParametersBase.class,
new String[] { "StorageDomainId" },
new Object[] { GUIDS[LOCAL_IDX] },
getEntity(LOCAL_IDX));
StorageDomain model = getModel(LOCAL_IDX);
model.getStorage().setAddress(null);
model.setHost(new Host());
model.getHost().setId(GUIDS[0].toString());
Response response = collection.add(model);
assertEquals(201, response.getStatus());
assertTrue(response.getEntity() instanceof StorageDomain);
verifyModel((StorageDomain) response.getEntity(), LOCAL_IDX);
}
@Test
public void testAddIscsiStorageDomain() throws Exception {
StorageDomain model = getIscsi();
Host host = new Host();
host.setId(GUIDS[0].toString());
model.setHost(host);
setUriInfo(setUpActionExpectations(VdcActionType.ConnectStorageToVds,
StorageServerConnectionParametersBase.class,
new String[] { "StorageServerConnection.connection", "VdsId" },
new Object[] { ADDRESSES[0], GUIDS[0] },
true,
true,
GUIDS[0].toString(),
false));
setUpGetEntityExpectations(VdcQueryType.GetDeviceList,
GetDeviceListQueryParameters.class,
new String[] { "VdsId", "StorageType" },
new Object[] { GUIDS[0], org.ovirt.engine.core.common.businessentities.StorageType.ISCSI },
"this return value isn't used");
setUpGetEntityExpectations(VdcQueryType.GetLunsByVgId,
GetLunsByVgIdParameters.class,
new String[] { "VgId" },
new Object[] { GUIDS[GUIDS.length-1].toString() },
setUpLuns());
setUpCreationExpectations(VdcActionType.AddSANStorageDomain,
AddSANStorageDomainParameters.class,
new String[] { "VdsId" },
new Object[] { GUIDS[0] },
true,
true,
GUIDS[0],
VdcQueryType.GetStorageDomainById,
StorageDomainQueryParametersBase.class,
new String[] { "StorageDomainId" },
new Object[] { GUIDS[0] },
getIscsiEntity());
Response response = collection.add(model);
assertEquals(201, response.getStatus());
assertTrue(response.getEntity() instanceof StorageDomain);
verifyIscsi((StorageDomain) response.getEntity());
}
@Test
public void testAddIscsiStorageDomainAssumingConnection() throws Exception {
StorageDomain model = getIscsi();
Host host = new Host();
host.setId(GUIDS[0].toString());
model.setHost(host);
for (LogicalUnit lun : model.getStorage().getVolumeGroup().getLogicalUnits()) {
lun.setAddress(null);
lun.setTarget(null);
}
setUriInfo(setUpBasicUriExpectations());
setUpGetEntityExpectations(VdcQueryType.GetDeviceList,
GetDeviceListQueryParameters.class,
new String[] { "VdsId", "StorageType" },
new Object[] { GUIDS[0], org.ovirt.engine.core.common.businessentities.StorageType.ISCSI },
"this return value isn't used");
List<LUNs> luns = setUpLuns();
setUpGetEntityExpectations(VdcQueryType.GetLunsByVgId,
GetLunsByVgIdParameters.class,
new String[] { "VgId" },
new Object[] { GUIDS[GUIDS.length-1].toString() },
luns);
setUpCreationExpectations(VdcActionType.AddSANStorageDomain,
AddSANStorageDomainParameters.class,
new String[] { "VdsId" },
new Object[] { GUIDS[0] },
true,
true,
GUIDS[0],
VdcQueryType.GetStorageDomainById,
StorageDomainQueryParametersBase.class,
new String[] { "StorageDomainId" },
new Object[] { GUIDS[0] },
getIscsiEntity());
Response response = collection.add(model);
assertEquals(201, response.getStatus());
assertTrue(response.getEntity() instanceof StorageDomain);
verifyIscsi((StorageDomain) response.getEntity());
}
@Test
public void testAddStorageDomainNoHost() throws Exception {
setUriInfo(setUpBasicUriExpectations());
control.replay();
StorageDomain model = getModel(0);
try {
collection.add(model);
fail("expected WebApplicationException on incomplete parameters");
} catch (WebApplicationException wae) {
verifyIncompleteException(wae, "StorageDomain", "add", "host.id|name");
}
}
@Test
public void testAddStorageDomainCantDo() throws Exception {
doTestBadAddStorageDomain(false, true, CANT_DO);
}
@Test
public void testAddStorageDomainFailure() throws Exception {
doTestBadAddStorageDomain(true, false, FAILURE);
}
private void doTestBadAddStorageDomain(boolean canDo, boolean success, String detail)
throws Exception {
setUriInfo(setUpActionExpectations(VdcActionType.AddStorageServerConnection,
StorageServerConnectionParametersBase.class,
new String[] { "StorageServerConnection.connection", "StorageServerConnection.storage_type", "VdsId" },
new Object[] { ADDRESSES[0] + ":" + PATHS[0], STORAGE_TYPES_MAPPED[0], GUIDS[0] },
true,
true,
GUIDS[0].toString(),
false));
setUpGetEntityExpectations(VdcQueryType.GetExistingStorageDomainList,
GetExistingStorageDomainListParameters.class,
new String[] { "VdsId", "StorageType", "StorageDomainType", "Path" },
new Object[] { GUIDS[0], STORAGE_TYPES_MAPPED[0], TYPES_MAPPED[0], ADDRESSES[0] + ":" + PATHS[0] },
new ArrayList<storage_domain_static>());
setUpActionExpectations(VdcActionType.AddNFSStorageDomain,
StorageDomainManagementParameter.class,
new String[] {},
new Object[] {},
canDo,
success);
StorageDomain model = getModel(0);
model.setHost(new Host());
model.getHost().setId(GUIDS[0].toString());
try {
collection.add(model);
fail("expected WebApplicationException");
} catch (WebApplicationException wae) {
verifyFault(wae, detail);
}
}
@Test
public void testAddStorageDomainCantDoCnxAdd() throws Exception {
doTestBadCnxAdd(false, true, CANT_DO);
}
@Test
public void testAddStorageDomainCnxAddFailure() throws Exception {
doTestBadCnxAdd(true, false, FAILURE);
}
private void doTestBadCnxAdd(boolean canDo, boolean success, String detail) throws Exception {
setUriInfo(setUpActionExpectations(VdcActionType.AddStorageServerConnection,
StorageServerConnectionParametersBase.class,
new String[] { "StorageServerConnection.connection", "StorageServerConnection.storage_type", "VdsId" },
new Object[] { ADDRESSES[0] + ":" + PATHS[0], STORAGE_TYPES_MAPPED[0], GUIDS[0] },
canDo,
success,
GUIDS[0].toString(),
true));
StorageDomain model = getModel(0);
model.setHost(new Host());
model.getHost().setId(GUIDS[0].toString());
try {
collection.add(model);
} catch (WebApplicationException wae) {
verifyFault(wae, detail);
}
}
@Test
public void testAddIncompleteDomainParameters() throws Exception {
StorageDomain model = getModel(0);
model.setName(NAMES[0]);
model.setHost(new Host());
model.getHost().setId(GUIDS[0].toString());
model.setStorage(new Storage());
model.getStorage().setAddress(ADDRESSES[0]);
model.getStorage().setPath(PATHS[0]);
setUriInfo(setUpBasicUriExpectations());
control.replay();
try {
collection.add(model);
fail("expected WebApplicationException on incomplete parameters");
} catch (WebApplicationException wae) {
verifyIncompleteException(wae, "StorageDomain", "add", "storage.type");
}
}
@Test
public void testAddIncompleteNfsStorageParameters() throws Exception {
StorageDomain model = getModel(0);
model.setName(NAMES[0]);
model.setHost(new Host());
model.getHost().setId(GUIDS[0].toString());
model.setStorage(new Storage());
model.getStorage().setType(StorageType.NFS.value());
model.getStorage().setPath(PATHS[0]);
setUriInfo(setUpBasicUriExpectations());
control.replay();
try {
collection.add(model);
fail("expected WebApplicationException on incomplete parameters");
} catch (WebApplicationException wae) {
verifyIncompleteException(wae, "Storage", "add", "address");
}
}
@Override
protected void setUpQueryExpectations(String query, Object failure) throws Exception {
if (failure == null) {
for (int i = 0; i < NAMES.length; i++) {
setUpGetEntityExpectations(VdcQueryType.GetStorageServerConnectionById,
StorageServerConnectionQueryParametersBase.class,
new String[] { "ServerConnectionId" },
new Object[] { GUIDS[i].toString() }, setUpStorageServerConnection(i));
}
}
super.setUpQueryExpectations(query, failure);
}
static storage_server_connections setUpLocalStorageServerConnection(int index) {
return setUpStorageServerConnection(index, index, true);
}
static storage_server_connections setUpStorageServerConnection(int index) {
return setUpStorageServerConnection(index, index, false);
}
static storage_server_connections setUpStorageServerConnection(int idIndex, int index, boolean local) {
storage_server_connections cnx = new storage_server_connections();
if (idIndex != -1) {
cnx.setid(GUIDS[idIndex].toString());
}
if (local) {
cnx.setconnection(PATHS[index]);
} else {
cnx.setconnection(ADDRESSES[index] + ":" + PATHS[index]);
}
return cnx;
}
protected VDS setUpVDS(int index) {
VDS vds = new VDS();
vds.setvds_id(GUIDS[index]);
vds.setvds_name(NAMES[index]);
return vds;
}
@Override
protected storage_domains getEntity(int index) {
return setUpEntityExpectations(control.createMock(storage_domains.class), index);
}
static storage_domains setUpEntityExpectations(storage_domains entity, int index) {
expect(entity.getid()).andReturn(GUIDS[index]).anyTimes();
expect(entity.getstorage_name()).andReturn(NAMES[index]).anyTimes();
// REVIST No descriptions for storage domains
// expect(entity.getdescription()).andReturn(DESCRIPTIONS[index]).anyTimes();
expect(entity.getstorage_domain_type()).andReturn(TYPES_MAPPED[index]).anyTimes();
expect(entity.getstorage_type()).andReturn(STORAGE_TYPES_MAPPED[index]).anyTimes();
expect(entity.getstorage()).andReturn(GUIDS[index].toString()).anyTimes();
return entity;
}
protected List<LUNs> setUpLuns() {
storage_server_connections cnx = new storage_server_connections();
cnx.setconnection(ADDRESSES[0]);
cnx.setiqn(TARGET);
cnx.setport(Integer.toString(PORT));
LUNs lun = new LUNs();
lun.setLUN_id(LUN);
lun.setLunConnections(new ArrayList<storage_server_connections>());
lun.getLunConnections().add(cnx);
List<LUNs> luns = new ArrayList<LUNs>();
luns.add(lun);
return luns;
}
protected storage_domains getIscsiEntity() {
storage_domains entity = control.createMock(storage_domains.class);
expect(entity.getid()).andReturn(GUIDS[0]).anyTimes();
expect(entity.getstorage_name()).andReturn(NAMES[0]).anyTimes();
expect(entity.getstorage_domain_type()).andReturn(TYPES_MAPPED[0]).anyTimes();
expect(entity.getstorage_type()).andReturn(org.ovirt.engine.core.common.businessentities.StorageType.ISCSI).anyTimes();
expect(entity.getstorage()).andReturn(GUIDS[GUIDS.length-1].toString()).anyTimes();
return entity;
}
static StorageDomain getModel(int index) {
StorageDomain model = new StorageDomain();
model.setName(NAMES[index]);
model.setDescription(DESCRIPTIONS[index]);
model.setType(TYPES[index].value());
model.setStorage(new Storage());
model.getStorage().setType(STORAGE_TYPES[index].value());
model.getStorage().setAddress(ADDRESSES[index]);
model.getStorage().setPath(PATHS[index]);
return model;
}
protected List<storage_domains> getExistingStorageDomains(boolean existing) {
List<storage_domains> ret = new ArrayList<storage_domains>();
if (existing) {
ret.add(new storage_domains());
}
return ret;
}
@Override
protected List<StorageDomain> getCollection() {
return collection.list().getStorageDomains();
}
@Override
protected void verifyModel(StorageDomain model, int index) {
verifyModelSpecific(model, index);
verifyLinks(model);
}
static void verifyModelSpecific(StorageDomain model, int index) {
assertEquals(GUIDS[index].toString(), model.getId());
assertEquals(NAMES[index], model.getName());
// REVIST No descriptions for storage domains
// assertEquals(DESCRIPTIONS[index], model.getDescription());
assertEquals(TYPES[index].value(), model.getType());
assertNotNull(model.getStorage());
assertEquals(STORAGE_TYPES[index].value(), model.getStorage().getType());
if (index != LOCAL_IDX) {
assertEquals(ADDRESSES[index], model.getStorage().getAddress());
}
assertEquals(PATHS[index], model.getStorage().getPath());
assertEquals("permissions", model.getLinks().get(0).getRel());
if (StorageDomainType.fromValue(model.getType()) == StorageDomainType.ISO) {
assertEquals(2, model.getLinks().size());
assertEquals("files", model.getLinks().get(1).getRel());
} else if(model.getType().equals(TYPES[2].value())){
assertEquals(3, model.getLinks().size());
assertEquals("templates", model.getLinks().get(1).getRel());
assertEquals("vms", model.getLinks().get(2).getRel());
}
assertNotNull(model.getLinks().get(0).getHref());
}
protected StorageDomain getIscsi() {
StorageDomain model = getModel(0);
model.getStorage().setType(StorageType.ISCSI.value());
model.getStorage().setAddress(null);
model.getStorage().setPath(null);
model.getStorage().setVolumeGroup(new VolumeGroup());
model.getStorage().getVolumeGroup().getLogicalUnits().add(new LogicalUnit());
model.getStorage().getVolumeGroup().getLogicalUnits().get(0).setId(LUN);
model.getStorage().getVolumeGroup().getLogicalUnits().get(0).setTarget(TARGET);
model.getStorage().getVolumeGroup().getLogicalUnits().get(0).setAddress(ADDRESSES[0]);
model.getStorage().getVolumeGroup().getLogicalUnits().get(0).setPort(PORT);
return model;
}
protected void verifyIscsi(StorageDomain model) {
assertEquals(GUIDS[0].toString(), model.getId());
assertEquals(NAMES[0], model.getName());
assertEquals(TYPES[0].value(), model.getType());
assertNotNull(model.getStorage());
assertEquals(StorageType.ISCSI.value(), model.getStorage().getType());
assertNotNull(model.getStorage().getVolumeGroup());
assertEquals(GUIDS[GUIDS.length-1].toString(), model.getStorage().getVolumeGroup().getId());
assertTrue(model.getStorage().getVolumeGroup().isSetLogicalUnits());
assertNotNull(model.getStorage().getVolumeGroup().getLogicalUnits().get(0));
assertEquals(LUN, model.getStorage().getVolumeGroup().getLogicalUnits().get(0).getId());
assertEquals(TARGET, model.getStorage().getVolumeGroup().getLogicalUnits().get(0).getTarget());
assertEquals(ADDRESSES[0], model.getStorage().getVolumeGroup().getLogicalUnits().get(0).getAddress());
assertEquals(PORT, model.getStorage().getVolumeGroup().getLogicalUnits().get(0).getPort());
assertEquals(1, model.getLinks().size());
assertEquals("permissions", model.getLinks().get(0).getRel());
assertNotNull(model.getLinks().get(0).getHref());
verifyLinks(model);
}
}
|
package de.craften.ui.swingmaterial.toast;
import java.awt.*;
/**
* A toast that contains text.
*
* @see <a href="https://www.google.com/design/spec/components/snackbars-toasts.html">Snackbars and toasts</a>
*/
public class TextToast extends Toast {
private final String content;
/**
* Creates a new toast.
*
* @param content the content of this toast
*/
public TextToast(String content) {
this.content = content;
}
/**
* Gets the content of this toast.
*
* @return the content of this toast
*/
public String getContent() {
return content;
}
@Override
public void paint(Graphics g) {
super.paint(g);
FontMetrics metrics = g.getFontMetrics(FONT);
int y = (getHeight() - metrics.getHeight()) / 2 + metrics.getAscent();
g.setFont(FONT);
g.setColor(Color.WHITE);
g.drawString(getContent(), 24, y);
}
}
|
package com.cantalou.skin;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.app.Fragment;
import android.app.Instrumentation;
import android.app.UiAutomation;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.PersistableBundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import com.cantalou.android.util.ReflectUtil;
/**
* 重写Instrumentation的callActivityOnCreate, callActivityOnDestroy方法,
* 在调用Activity的生命周期方法onCreate前调用ResourcesManager.callActivityOnCreate()方法
*
* @author cantalou
* @date 2015年12月5日 下午4:53:44
*/
@SuppressWarnings("deprecation")
public class SkinInstrumentation extends Instrumentation {
private SkinManager skinManager;
private Instrumentation targetInstrumentation;
public SkinInstrumentation(SkinManager skinManager, Instrumentation target) {
this.skinManager = skinManager;
this.targetInstrumentation = target;
}
@Override
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void callActivityOnCreate(Activity activity, Bundle icicle, PersistableBundle persistentState) {
skinManager.beforeActivityOnCreate(activity, icicle);
targetInstrumentation.callActivityOnCreate(activity, icicle, persistentState);
}
@Override
public void callActivityOnCreate(Activity activity, Bundle icicle) {
skinManager.beforeActivityOnCreate(activity, icicle);
targetInstrumentation.callActivityOnCreate(activity, icicle);
}
@Override
public void callActivityOnDestroy(Activity activity) {
targetInstrumentation.callActivityOnDestroy(activity);
skinManager.onActivityDestroyed(activity);
}
@Override
public Activity newActivity(ClassLoader cl, String className, Intent intent) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
return targetInstrumentation.newActivity(cl, className, intent);
}
@Override
public void endPerformanceSnapshot() {
targetInstrumentation.endPerformanceSnapshot();
}
@Override
public Context getContext() {
return targetInstrumentation.getContext();
}
@Override
public ComponentName getComponentName() {
return targetInstrumentation.getComponentName();
}
@Override
public Context getTargetContext() {
return targetInstrumentation.getTargetContext();
}
@Override
public boolean isProfiling() {
return targetInstrumentation.isProfiling();
}
@Override
public void addMonitor(ActivityMonitor monitor) {
targetInstrumentation.addMonitor(monitor);
}
@Override
public ActivityMonitor addMonitor(IntentFilter filter, ActivityResult result, boolean block) {
return targetInstrumentation.addMonitor(filter, result, block);
}
@Override
public ActivityMonitor addMonitor(String cls, ActivityResult result, boolean block) {
return targetInstrumentation.addMonitor(cls, result, block);
}
@Override
public void callActivityOnNewIntent(Activity activity, Intent intent) {
targetInstrumentation.callActivityOnNewIntent(activity, intent);
}
@Override
public void callActivityOnPause(Activity activity) {
targetInstrumentation.callActivityOnPause(activity);
}
@Override
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void callActivityOnPostCreate(Activity activity, Bundle icicle, PersistableBundle persistentState) {
targetInstrumentation.callActivityOnPostCreate(activity, icicle, persistentState);
}
@Override
public void callActivityOnPostCreate(Activity activity, Bundle icicle) {
targetInstrumentation.callActivityOnPostCreate(activity, icicle);
}
@Override
public void callActivityOnRestart(Activity activity) {
targetInstrumentation.callActivityOnRestart(activity);
}
@Override
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void callActivityOnRestoreInstanceState(Activity activity, Bundle savedInstanceState, PersistableBundle persistentState) {
targetInstrumentation.callActivityOnRestoreInstanceState(activity, savedInstanceState, persistentState);
}
@Override
public boolean checkMonitorHit(ActivityMonitor monitor, int minHits) {
return targetInstrumentation.checkMonitorHit(monitor, minHits);
}
@Override
public void callActivityOnRestoreInstanceState(Activity activity, Bundle savedInstanceState) {
targetInstrumentation.callActivityOnRestoreInstanceState(activity, savedInstanceState);
}
@Override
public void callActivityOnStart(Activity activity) {
targetInstrumentation.callActivityOnStart(activity);
}
@Override
public void callActivityOnResume(Activity activity) {
targetInstrumentation.callActivityOnResume(activity);
}
@Override
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void callActivityOnSaveInstanceState(Activity activity, Bundle outState, PersistableBundle outPersistentState) {
targetInstrumentation.callActivityOnSaveInstanceState(activity, outState, outPersistentState);
}
@Override
public void finish(int resultCode, Bundle results) {
targetInstrumentation.finish(resultCode, results);
}
@Override
public boolean invokeMenuActionSync(Activity targetActivity, int id, int flag) {
return targetInstrumentation.invokeMenuActionSync(targetActivity, id, flag);
}
@Override
public boolean invokeContextMenuAction(Activity targetActivity, int id, int flag) {
return targetInstrumentation.invokeContextMenuAction(targetActivity, id, flag);
}
@Override
public void callApplicationOnCreate(Application app) {
targetInstrumentation.callApplicationOnCreate(app);
}
@Override
public void callActivityOnStop(Activity activity) {
targetInstrumentation.callActivityOnStop(activity);
}
@Override
public void callActivityOnSaveInstanceState(Activity activity, Bundle outState) {
targetInstrumentation.callActivityOnSaveInstanceState(activity, outState);
}
@Override
public void callActivityOnUserLeaving(Activity activity) {
targetInstrumentation.callActivityOnUserLeaving(activity);
}
@Override
public Bundle getAllocCounts() {
return targetInstrumentation.getAllocCounts();
}
@Override
public Bundle getBinderCounts() {
return targetInstrumentation.getBinderCounts();
}
@Override
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public UiAutomation getUiAutomation() {
return targetInstrumentation.getUiAutomation();
}
@Override
public void onCreate(Bundle arguments) {
targetInstrumentation.onCreate(arguments);
}
@Override
public void start() {
targetInstrumentation.start();
}
@Override
public void onStart() {
targetInstrumentation.onStart();
}
@Override
public boolean onException(Object obj, Throwable e) {
return targetInstrumentation.onException(obj, e);
}
@Override
public void sendStatus(int resultCode, Bundle results) {
targetInstrumentation.sendStatus(resultCode, results);
}
@Override
public void setAutomaticPerformanceSnapshots() {
targetInstrumentation.setAutomaticPerformanceSnapshots();
}
@Override
public void startPerformanceSnapshot() {
targetInstrumentation.startPerformanceSnapshot();
}
@Override
public void onDestroy() {
targetInstrumentation.onDestroy();
}
@Override
public void startProfiling() {
targetInstrumentation.startProfiling();
}
@Override
public void stopProfiling() {
targetInstrumentation.stopProfiling();
}
@Override
public void setInTouchMode(boolean inTouch) {
targetInstrumentation.setInTouchMode(inTouch);
}
@Override
public void waitForIdle(Runnable recipient) {
targetInstrumentation.waitForIdle(recipient);
}
@Override
public void waitForIdleSync() {
targetInstrumentation.waitForIdleSync();
}
@Override
public void runOnMainSync(Runnable runner) {
targetInstrumentation.runOnMainSync(runner);
}
@Override
public Activity startActivitySync(Intent intent) {
return targetInstrumentation.startActivitySync(intent);
}
@Override
public Activity waitForMonitor(ActivityMonitor monitor) {
return targetInstrumentation.waitForMonitor(monitor);
}
@Override
public Activity waitForMonitorWithTimeout(ActivityMonitor monitor, long timeOut) {
return targetInstrumentation.waitForMonitorWithTimeout(monitor, timeOut);
}
@Override
public void removeMonitor(ActivityMonitor monitor) {
targetInstrumentation.removeMonitor(monitor);
}
@Override
public void sendStringSync(String text) {
targetInstrumentation.sendStringSync(text);
}
@Override
public void sendKeySync(KeyEvent event) {
targetInstrumentation.sendKeySync(event);
}
@Override
public void sendKeyDownUpSync(int key) {
targetInstrumentation.sendKeyDownUpSync(key);
}
@Override
public void sendCharacterSync(int keyCode) {
targetInstrumentation.sendCharacterSync(keyCode);
}
@Override
public void sendPointerSync(MotionEvent event) {
targetInstrumentation.sendPointerSync(event);
}
@Override
public void sendTrackballEventSync(MotionEvent event) {
targetInstrumentation.sendTrackballEventSync(event);
}
@Override
public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
return targetInstrumentation.newApplication(cl, className, context);
}
@Override
public Activity newActivity(Class<?> clazz, Context context, IBinder token, Application application, Intent intent, ActivityInfo info, CharSequence title, Activity parent,
String id, Object lastNonConfigurationInstance) throws InstantiationException, IllegalAccessException {
return targetInstrumentation.newActivity(clazz, context, token, application, intent, info, title, parent, id, lastNonConfigurationInstance);
}
@Override
public void startAllocCounting() {
targetInstrumentation.startAllocCounting();
}
@Override
public void stopAllocCounting() {
targetInstrumentation.stopAllocCounting();
}
public void execStartActivities(Context who, IBinder contextThread, IBinder token, Activity target, Intent[] intents) {
ReflectUtil.invoke(targetInstrumentation, "execStartActivities", new Class<?>[]{Context.class, IBinder.class, IBinder.class, Activity.class, intents.getClass()}, who,
contextThread, token, target, intents);
}
@SuppressLint("NewApi")
public ActivityResult execStartActivity(Context who, IBinder contextThread, IBinder token, Fragment target, Intent intent, int requestCode) {
return (ActivityResult) ReflectUtil.invoke(targetInstrumentation, "execStartActivity", new Class<?>[]{Context.class, IBinder.class, IBinder.class, Activity.class,
Intent.class, int.class}, who, contextThread, token, target, intent, requestCode);
}
}
|
package com.github.mambabosso.ewul.server.error;
public class AlreadyExistsException extends EwulException {
public static final int ERROR_CODE = 2000;
public AlreadyExistsException(Throwable cause) {
super(ERROR_CODE, cause);
}
public AlreadyExistsException() {
super(ERROR_CODE);
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.rocketmq.broker.processor;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import org.apache.rocketmq.broker.BrokerController;
import org.apache.rocketmq.broker.mqtrace.SendMessageContext;
import org.apache.rocketmq.broker.mqtrace.SendMessageHook;
import org.apache.rocketmq.broker.transaction.TransactionalMessageService;
import org.apache.rocketmq.common.BrokerConfig;
import org.apache.rocketmq.common.MixAll;
import org.apache.rocketmq.common.message.MessageConst;
import org.apache.rocketmq.common.message.MessageDecoder;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.RequestCode;
import org.apache.rocketmq.common.protocol.ResponseCode;
import org.apache.rocketmq.common.protocol.header.ConsumerSendMsgBackRequestHeader;
import org.apache.rocketmq.common.protocol.header.SendMessageRequestHeader;
import org.apache.rocketmq.common.sysflag.MessageSysFlag;
import org.apache.rocketmq.remoting.exception.RemotingCommandException;
import org.apache.rocketmq.remoting.netty.NettyClientConfig;
import org.apache.rocketmq.remoting.netty.NettyServerConfig;
import org.apache.rocketmq.remoting.protocol.RemotingCommand;
import org.apache.rocketmq.store.AppendMessageResult;
import org.apache.rocketmq.store.AppendMessageStatus;
import org.apache.rocketmq.store.MessageExtBrokerInner;
import org.apache.rocketmq.store.MessageStore;
import org.apache.rocketmq.store.PutMessageResult;
import org.apache.rocketmq.store.PutMessageStatus;
import org.apache.rocketmq.store.config.MessageStoreConfig;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class SendMessageProcessorTest {
private SendMessageProcessor sendMessageProcessor;
@Mock
private ChannelHandlerContext handlerContext;
@Spy
private BrokerController brokerController = new BrokerController(new BrokerConfig(), new NettyServerConfig(), new NettyClientConfig(), new MessageStoreConfig());
@Mock
private MessageStore messageStore;
@Mock
private TransactionalMessageService transactionMsgService;
private String topic = "FooBar";
private String group = "FooBarGroup";
@Before
public void init() {
brokerController.setMessageStore(messageStore);
when(messageStore.now()).thenReturn(System.currentTimeMillis());
Channel mockChannel = mock(Channel.class);
when(mockChannel.remoteAddress()).thenReturn(new InetSocketAddress(1024));
when(handlerContext.channel()).thenReturn(mockChannel);
when(messageStore.lookMessageByOffset(anyLong())).thenReturn(new MessageExt());
sendMessageProcessor = new SendMessageProcessor(brokerController);
}
@Test
public void testProcessRequest() throws RemotingCommandException {
when(messageStore.putMessage(any(MessageExtBrokerInner.class))).thenReturn(new PutMessageResult(PutMessageStatus.PUT_OK, new AppendMessageResult(AppendMessageStatus.PUT_OK)));
assertPutResult(ResponseCode.SUCCESS);
}
@Test
public void testProcessRequest_WithHook() throws RemotingCommandException {
when(messageStore.putMessage(any(MessageExtBrokerInner.class))).thenReturn(new PutMessageResult(PutMessageStatus.PUT_OK, new AppendMessageResult(AppendMessageStatus.PUT_OK)));
List<SendMessageHook> sendMessageHookList = new ArrayList<>();
final SendMessageContext[] sendMessageContext = new SendMessageContext[1];
SendMessageHook sendMessageHook = new SendMessageHook() {
@Override
public String hookName() {
return null;
}
@Override
public void sendMessageBefore(SendMessageContext context) {
sendMessageContext[0] = context;
}
@Override
public void sendMessageAfter(SendMessageContext context) {
}
};
sendMessageHookList.add(sendMessageHook);
sendMessageProcessor.registerSendMessageHook(sendMessageHookList);
assertPutResult(ResponseCode.SUCCESS);
System.out.println(sendMessageContext[0]);
assertThat(sendMessageContext[0]).isNotNull();
assertThat(sendMessageContext[0].getTopic()).isEqualTo(topic);
assertThat(sendMessageContext[0].getProducerGroup()).isEqualTo(group);
}
@Test
public void testProcessRequest_FlushTimeOut() throws RemotingCommandException {
when(messageStore.putMessage(any(MessageExtBrokerInner.class))).thenReturn(new PutMessageResult(PutMessageStatus.FLUSH_DISK_TIMEOUT, new AppendMessageResult(AppendMessageStatus.UNKNOWN_ERROR)));
assertPutResult(ResponseCode.FLUSH_DISK_TIMEOUT);
}
@Test
public void testProcessRequest_MessageIllegal() throws RemotingCommandException {
when(messageStore.putMessage(any(MessageExtBrokerInner.class))).thenReturn(new PutMessageResult(PutMessageStatus.MESSAGE_ILLEGAL, new AppendMessageResult(AppendMessageStatus.UNKNOWN_ERROR)));
assertPutResult(ResponseCode.MESSAGE_ILLEGAL);
}
@Test
public void testProcessRequest_CreateMappedFileFailed() throws RemotingCommandException {
when(messageStore.putMessage(any(MessageExtBrokerInner.class))).thenReturn(new PutMessageResult(PutMessageStatus.CREATE_MAPEDFILE_FAILED, new AppendMessageResult(AppendMessageStatus.UNKNOWN_ERROR)));
assertPutResult(ResponseCode.SYSTEM_ERROR);
}
@Test
public void testProcessRequest_FlushSlaveTimeout() throws RemotingCommandException {
when(messageStore.putMessage(any(MessageExtBrokerInner.class))).thenReturn(new PutMessageResult(PutMessageStatus.FLUSH_SLAVE_TIMEOUT, new AppendMessageResult(AppendMessageStatus.UNKNOWN_ERROR)));
assertPutResult(ResponseCode.FLUSH_SLAVE_TIMEOUT);
}
@Test
public void testProcessRequest_PageCacheBusy() throws RemotingCommandException {
when(messageStore.putMessage(any(MessageExtBrokerInner.class))).thenReturn(new PutMessageResult(PutMessageStatus.OS_PAGECACHE_BUSY, new AppendMessageResult(AppendMessageStatus.UNKNOWN_ERROR)));
assertPutResult(ResponseCode.SYSTEM_ERROR);
}
@Test
public void testProcessRequest_PropertiesTooLong() throws RemotingCommandException {
when(messageStore.putMessage(any(MessageExtBrokerInner.class))).thenReturn(new PutMessageResult(PutMessageStatus.PROPERTIES_SIZE_EXCEEDED, new AppendMessageResult(AppendMessageStatus.UNKNOWN_ERROR)));
assertPutResult(ResponseCode.MESSAGE_ILLEGAL);
}
@Test
public void testProcessRequest_ServiceNotAvailable() throws RemotingCommandException {
when(messageStore.putMessage(any(MessageExtBrokerInner.class))).thenReturn(new PutMessageResult(PutMessageStatus.SERVICE_NOT_AVAILABLE, new AppendMessageResult(AppendMessageStatus.UNKNOWN_ERROR)));
assertPutResult(ResponseCode.SERVICE_NOT_AVAILABLE);
}
@Test
public void testProcessRequest_SlaveNotAvailable() throws RemotingCommandException {
when(messageStore.putMessage(any(MessageExtBrokerInner.class))).thenReturn(new PutMessageResult(PutMessageStatus.SLAVE_NOT_AVAILABLE, new AppendMessageResult(AppendMessageStatus.UNKNOWN_ERROR)));
assertPutResult(ResponseCode.SLAVE_NOT_AVAILABLE);
}
@Test
public void testProcessRequest_WithMsgBack() throws RemotingCommandException {
when(messageStore.putMessage(any(MessageExtBrokerInner.class))).thenReturn(new PutMessageResult(PutMessageStatus.PUT_OK, new AppendMessageResult(AppendMessageStatus.PUT_OK)));
final RemotingCommand request = createSendMsgBackCommand(RequestCode.CONSUMER_SEND_MSG_BACK);
sendMessageProcessor = new SendMessageProcessor(brokerController);
final RemotingCommand response = sendMessageProcessor.processRequest(handlerContext, request);
assertThat(response).isNotNull();
assertThat(response.getCode()).isEqualTo(ResponseCode.SUCCESS);
}
@Test
public void testProcessRequest_Transaction() throws RemotingCommandException {
brokerController.setTransactionalMessageService(transactionMsgService);
when(brokerController.getTransactionalMessageService().prepareMessage(any(MessageExtBrokerInner.class))).thenReturn(new PutMessageResult(PutMessageStatus.PUT_OK, new AppendMessageResult(AppendMessageStatus.PUT_OK)));
RemotingCommand request = createSendTransactionMsgCommand(RequestCode.SEND_MESSAGE);
final RemotingCommand[] response = new RemotingCommand[1];
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
response[0] = invocation.getArgument(0);
return null;
}
}).when(handlerContext).writeAndFlush(any(Object.class));
RemotingCommand responseToReturn = sendMessageProcessor.processRequest(handlerContext, request);
if (responseToReturn != null) {
assertThat(response[0]).isNull();
response[0] = responseToReturn;
}
assertThat(response[0].getCode()).isEqualTo(ResponseCode.SUCCESS);
}
private RemotingCommand createSendTransactionMsgCommand(int requestCode) {
SendMessageRequestHeader header = createSendMsgRequestHeader();
int sysFlag = header.getSysFlag();
Map<String, String> oriProps = MessageDecoder.string2messageProperties(header.getProperties());
oriProps.put(MessageConst.PROPERTY_TRANSACTION_PREPARED, "true");
header.setProperties(MessageDecoder.messageProperties2String(oriProps));
sysFlag |= MessageSysFlag.TRANSACTION_PREPARED_TYPE;
header.setSysFlag(sysFlag);
RemotingCommand request = RemotingCommand.createRequestCommand(requestCode, header);
request.setBody(new byte[] {'a'});
request.makeCustomHeaderToNet();
return request;
}
private SendMessageRequestHeader createSendMsgRequestHeader() {
SendMessageRequestHeader requestHeader = new SendMessageRequestHeader();
requestHeader.setProducerGroup(group);
requestHeader.setTopic(topic);
requestHeader.setDefaultTopic(MixAll.AUTO_CREATE_TOPIC_KEY_TOPIC);
requestHeader.setDefaultTopicQueueNums(3);
requestHeader.setQueueId(1);
requestHeader.setSysFlag(0);
requestHeader.setBornTimestamp(System.currentTimeMillis());
requestHeader.setFlag(124);
requestHeader.setReconsumeTimes(0);
return requestHeader;
}
private RemotingCommand createSendMsgCommand(int requestCode) {
SendMessageRequestHeader requestHeader = createSendMsgRequestHeader();
RemotingCommand request = RemotingCommand.createRequestCommand(requestCode, requestHeader);
request.setBody(new byte[] {'a'});
request.makeCustomHeaderToNet();
return request;
}
private RemotingCommand createSendMsgBackCommand(int requestCode) {
ConsumerSendMsgBackRequestHeader requestHeader = new ConsumerSendMsgBackRequestHeader();
requestHeader.setMaxReconsumeTimes(3);
requestHeader.setDelayLevel(4);
requestHeader.setGroup(group);
requestHeader.setOffset(123L);
RemotingCommand request = RemotingCommand.createRequestCommand(requestCode, requestHeader);
request.makeCustomHeaderToNet();
return request;
}
private void assertPutResult(int responseCode) throws RemotingCommandException {
final RemotingCommand request = createSendMsgCommand(RequestCode.SEND_MESSAGE);
final RemotingCommand[] response = new RemotingCommand[1];
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
response[0] = invocation.getArgument(0);
return null;
}
}).when(handlerContext).writeAndFlush(any(Object.class));
RemotingCommand responseToReturn = sendMessageProcessor.processRequest(handlerContext, request);
if (responseToReturn != null) {
assertThat(response[0]).isNull();
response[0] = responseToReturn;
}
assertThat(response[0].getCode()).isEqualTo(responseCode);
assertThat(response[0].getOpaque()).isEqualTo(request.getOpaque());
}
}
|
/**
* Copyright 2016 by Metanome Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.metanome.algorithm_integration.results.basic_statistic_values;
import com.fasterxml.jackson.annotation.JsonTypeName;
/**
* Represents a double value for a basic statistic.
*/
@JsonTypeName("BasicStatisticValueDouble")
public class BasicStatisticValueDouble extends BasicStatisticValue<Double> {
public BasicStatisticValueDouble() {
super();
}
public BasicStatisticValueDouble(Double value) {
super(value);
}
@Override
public String toString() {
return this.value.toString();
}
@Override
public int hashCode() {
return this.value.hashCode();
}
@Override
public boolean equals(Object obj) {
return obj instanceof BasicStatisticValueDouble && this.value.equals(((BasicStatisticValueDouble) obj).getValue());
}
@Override
public int compareTo(Object o) {
if (o instanceof BasicStatisticValueDouble) {
BasicStatisticValueDouble other = (BasicStatisticValueDouble) o;
return (other.getValue()).compareTo(this.value);
}
return -1;
}
}
|
package helvidios.uva.utils;
import java.security.*;
import java.security.spec.*;
import java.util.Arrays;
import javax.crypto.*;
import javax.crypto.spec.*;
public class AES {
private String password = "IwAn__t2?^Visit,,SF";
private Cipher cipher;
private SecretKeySpec secretKey;
private final String FMT = "UTF-8";
public AES() throws Exception{
byte[] key = Arrays.copyOf(MessageDigest.getInstance("SHA-1").digest(password.getBytes(FMT)), 16); // generate 128 bit key
cipher = Cipher.getInstance("AES");
secretKey = new SecretKeySpec(key, "AES");
}
public String encrypt(String plainText) {
try {
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] cipherText = cipher.doFinal(plainText.getBytes(FMT));
String encryptedText = javax.xml.bind.DatatypeConverter.printBase64Binary(cipherText);
//System.out.printf("(plain)'%s' => (encrypt)'%s'\n", plainText, encryptedText);
return encryptedText;
} catch (Exception e) {
System.out.printf("Unable to encrypt. Cause: %s.\n", e.getMessage());
}
return plainText;
}
public String decrypt(String encryptedText) {
try {
cipher.init(Cipher.DECRYPT_MODE, secretKey);
//System.out.printf("Decrypt '%s'\n", encryptedText);
return new String(cipher.doFinal(
javax.xml.bind.DatatypeConverter.parseBase64Binary(encryptedText)
),FMT);
} catch (Exception e) {
System.out.printf("Unable to decrypt. Cause: %s.\n", Utils.getStackTrace(e));
}
return encryptedText;
}
}
|
package me.saket.dank.ui.media;
import android.content.Context;
import android.os.Bundle;
import android.text.util.Linkify;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import androidx.annotation.Nullable;
import javax.inject.Inject;
import dagger.Lazy;
import me.saket.dank.data.ErrorResolver;
import me.saket.dank.data.ResolvedError;
import me.saket.dank.di.Dank;
import me.saket.dank.ui.DankFragment;
import me.saket.dank.urlparser.ImgurLink;
import me.saket.dank.urlparser.MediaLink;
import me.saket.dank.utils.DankLinkMovementMethod;
import me.saket.dank.utils.Views;
import me.saket.dank.widgets.MediaAlbumViewerTitleDescriptionView;
import me.saket.dank.widgets.binoculars.FlickGestureListener;
import timber.log.Timber;
/**
* Includes common logic for showing title & description and dimming the image when the description is scrolled.
*/
public abstract class BaseMediaViewerFragment extends DankFragment {
@Inject DankLinkMovementMethod linkMovementMethod;
@Inject Lazy<ErrorResolver> errorResolver;
private MediaAlbumViewerTitleDescriptionView titleDescriptionView;
private View imageDimmingView;
private MediaLink mediaLinkToShow;
/**
* Called when the data-set changes for this fragment. Currently happens when the HD button is toggled.
*/
public abstract void handleMediaItemUpdate(MediaAlbumItem updatedMediaAlbumItem);
public void setTitleDescriptionView(MediaAlbumViewerTitleDescriptionView titleDescriptionView) {
this.titleDescriptionView = titleDescriptionView;
Views.setMarginTop(titleDescriptionView, Views.statusBarHeight(getResources()));
}
public void setImageDimmingView(View imageDimmingView) {
this.imageDimmingView = imageDimmingView;
}
public void setMediaLink(MediaLink mediaLink) {
this.mediaLinkToShow = mediaLink;
}
@Override
public void onAttach(Context context) {
Dank.dependencyInjector().inject(this);
super.onAttach(context);
}
@Override
public void onStart() {
super.onStart();
if (mediaLinkToShow == null) {
throw new AssertionError();
}
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Toggle description's background dimming when the description is scrolled or Activity goes immersive.
((ViewGroup) view).getLayoutTransition().setDuration(200);
//noinspection ConstantConditions
titleDescriptionView.streamDimmingRequiredForTitleAndDescription()
.distinctUntilChanged()
.mergeWith(((MediaFragmentCallbacks) getActivity()).systemUiVisibilityStream()
.map(systemUiVisible -> systemUiVisible && titleDescriptionView.streamDimmingRequiredForTitleAndDescription().getValue())
)
.takeUntil(lifecycle().onDestroy())
.subscribe(dimmingRequired -> imageDimmingView.setVisibility(dimmingRequired ? View.VISIBLE : View.GONE));
// Hide title & description when Activity goes immersive.
((MediaFragmentCallbacks) getActivity()).systemUiVisibilityStream()
.takeUntil(lifecycle().onDestroy())
.subscribe(systemUiVisible -> {
titleDescriptionView.setVisibility(systemUiVisible ? View.VISIBLE : View.INVISIBLE);
});
// Show title and description.
((MediaFragmentCallbacks) getActivity()).optionButtonsHeight()
.takeUntil(lifecycle().onDestroy().ignoreElements())
.subscribe(
optionsHeight -> {
Views.setPaddingBottom(titleDescriptionView, titleDescriptionView.getPaddingBottom() + optionsHeight);
if (mediaLinkToShow instanceof ImgurLink) {
String title = ((ImgurLink) mediaLinkToShow).title();
String description = ((ImgurLink) mediaLinkToShow).description();
titleDescriptionView.setTitleAndDescription(title, description);
if (description != null) {
titleDescriptionView.descriptionView.setMovementMethod(linkMovementMethod);
Linkify.addLinks(titleDescriptionView.descriptionView, Linkify.ALL);
}
}
}, error -> {
ResolvedError resolvedError = errorResolver.get().resolve(error);
resolvedError.ifUnknown(() -> Timber.e(error, "Error while trying to get option buttons' height"));
});
}
public FlickGestureListener createFlickGestureListener(FlickGestureListener.GestureCallbacks wrappedGestureCallbacks) {
FlickGestureListener flickListener = new FlickGestureListener(ViewConfiguration.get(requireContext()));
flickListener.setFlickThresholdSlop(FlickGestureListener.DEFAULT_FLICK_THRESHOLD);
flickListener.setGestureCallbacks(new FlickGestureListener.GestureCallbacks() {
@Override
public void onFlickDismissEnd(long flickAnimationDuration) {
wrappedGestureCallbacks.onFlickDismissEnd(flickAnimationDuration);
}
@Override
public void onMoveMedia(float moveRatio) {
wrappedGestureCallbacks.onMoveMedia(moveRatio);
boolean isImageBeingMoved = moveRatio != 0f;
titleDescriptionView.setVisibility(!isImageBeingMoved ? View.VISIBLE : View.INVISIBLE);
boolean showDimming = !isImageBeingMoved && titleDescriptionView.streamDimmingRequiredForTitleAndDescription().getValue();
imageDimmingView.setVisibility(showDimming ? View.VISIBLE : View.GONE);
}
});
return flickListener;
}
}
|
package de.uni_leipzig.crypto_news_docs.service.assets.countryCurrency;
import de.uni_leipzig.crypto_news_docs.model.assets.currency.country.CountryCurrency;
import de.uni_leipzig.crypto_news_docs.model.assets.currency.country.CountryCurrencyExchange;
import java.util.Date;
import java.util.List;
public interface CountryCurrencyExchangeService {
List<CountryCurrencyExchange> findByShortName(String name);
CountryCurrencyExchange findByExchangeAndShortNameAndUnit(String exchange, String shortName, String unit);
CountryCurrencyExchange create(List<CountryCurrency> countryCurrencyExchange, String exchange,
String shortName, String unit);
List<CountryCurrencyExchange> findByShortNameAndTimeSpan(String shortName, Date startTime, Date endTime);
}
|
/*
* Copyright 2017 Apereo
*
* 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.tle.web.wizard;
import com.tle.web.sections.equella.annotation.PlugURL;
import com.tle.web.sections.equella.annotation.PluginResourceHandler;
import com.tle.web.sections.js.generic.function.IncludeFile;
public final class WizardJSLibrary
{
static
{
PluginResourceHandler.init(WizardJSLibrary.class);
}
@PlugURL("scripts/wizardctrl.js")
private static String URL_LIBRARY;
public static final IncludeFile INCLUDE = new IncludeFile(URL_LIBRARY);
private WizardJSLibrary()
{
throw new Error();
}
}
|
package no.stelvio.batch.support;
import no.stelvio.batch.count.support.BatchCounter;
import no.stelvio.batch.count.support.EventReportFormatter;
import no.stelvio.common.log.InfoLogger;
/**
*
*/
public class ProgressLoggerListener implements ProgressListener {
private InfoLogger logger;
private EventReportFormatter formatter;
private ProgressLoggerListener() {
}
public ProgressLoggerListener(InfoLogger logger, EventReportFormatter formatter) {
this.logger = logger;
this.formatter = formatter;
}
@Override
public void finished(BatchCounter counter) {
logger.info("Batch ended with progress counter status:");
logCounters(counter);
}
@Override
public void progressed(BatchCounter counter) {
logger.info("Batch progress status:");
logCounters(counter);
}
@Override
public void started(BatchCounter counter) {
logger.info("Batch started with following progress counters active:");
logCounters(counter);
}
private void logCounters(BatchCounter counter) {
logger.info(formatter.format(counter.getEventReport()));
}
public void setLogger(InfoLogger logger) {
this.logger = logger;
}
public void setFormatter(EventReportFormatter formatter) {
this.formatter = formatter;
}
}
|
package com.lmax.angler.monitoring.network.monitor.socket.tcp;
import org.agrona.collections.LongHashSet;
import org.junit.Test;
import java.net.InetAddress;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class SocketOwnedByCurrentProcessFilterTest
{
private static final long INODE_OWNED_BY_PROCESS = 8765542L;
private static final long INODE_NOT_OWNED_BY_PROCESS = Long.MAX_VALUE;
private static final int PORT = 55555;
private static final InetAddress INET_ADDRESS = InetAddress.getLoopbackAddress();
private final TcpSocketStatisticsHandler delegate = this::handleStatistics;
private final SocketOwnedByCurrentProcessFilter filter =
new SocketOwnedByCurrentProcessFilter(delegate, this::populateSocketInodes);
private int receivedUpdateCount;
private int socketInodeRequestCount;
@Test
public void shouldNotNotifyDelegateIfInodeIsNotSocketOwnedByCurrentProcess() throws Exception
{
filter.onStatisticsUpdated(INET_ADDRESS, PORT, 17L, INODE_NOT_OWNED_BY_PROCESS, 0L, 0L);
assertThat(receivedUpdateCount, is(0));
}
@Test
public void shouldNotifyDelegateIfInodeIsSocketOwnedByCurrentProcess() throws Exception
{
filter.onStatisticsUpdated(INET_ADDRESS, PORT, 17L, INODE_OWNED_BY_PROCESS, 0L, 0L);
assertThat(receivedUpdateCount, is(1));
}
@Test
public void shouldNotRequestInodeUpdateIfInodeIsAlreadyKnown() throws Exception
{
filter.onStatisticsUpdated(INET_ADDRESS, PORT, 17L, INODE_OWNED_BY_PROCESS, 0L, 0L);
filter.onStatisticsUpdated(INET_ADDRESS, PORT, 17L, INODE_OWNED_BY_PROCESS, 0L, 0L);
assertThat(receivedUpdateCount, is(2));
assertThat(socketInodeRequestCount, is(1));
}
@Test
public void shouldNotRequestInodeUpdateOfNotOwnedInodeWhenInodeHasBeenRequestedBefore() throws Exception
{
filter.onStatisticsUpdated(INET_ADDRESS, PORT, 17L, INODE_NOT_OWNED_BY_PROCESS, 0L, 0L);
filter.onStatisticsUpdated(INET_ADDRESS, PORT, 17L, INODE_NOT_OWNED_BY_PROCESS, 0L, 0L);
assertThat(receivedUpdateCount, is(0));
assertThat(socketInodeRequestCount, is(1));
}
@Test
public void shouldClearNotOwnedInodeCacheToPreventMemoryLeak() throws Exception
{
final int initialNotOwnedInode = 0;
for(int i = 0; i < SocketOwnedByCurrentProcessFilter.MAX_NOT_OWNED_INODE_CACHE_SIZE + 1; i++)
{
filter.onStatisticsUpdated(INET_ADDRESS, PORT, 17L, i, 0L, 0L);
}
socketInodeRequestCount = 0;
filter.onStatisticsUpdated(INET_ADDRESS, PORT, 17L, initialNotOwnedInode, 0L, 0L);
assertThat(socketInodeRequestCount, is(1));
}
private void handleStatistics(final InetAddress inetAddress,
final int port,
final long socketIdentifier,
final long inode,
final long receiveQueueDepth,
final long transmitQueueDepth)
{
receivedUpdateCount++;
}
private void populateSocketInodes(final LongHashSet socketInodes)
{
socketInodes.add(INODE_OWNED_BY_PROCESS);
socketInodeRequestCount++;
}
}
|
package com.alipay.api.response;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.AlipayResponse;
/**
* ALIPAY API: ant.merchant.expand.personal.apply response.
*
* @author auto create
* @since 1.0, 2019-01-07 20:51:15
*/
public class AntMerchantExpandPersonalApplyResponse extends AlipayResponse {
private static final long serialVersionUID = 1121192864159119361L;
/**
* 支付宝端商户入驻申请单据号
*/
@ApiField("order_no")
private String orderNo;
/**
* 外部入驻申请单据号
*/
@ApiField("out_biz_no")
private String outBizNo;
public void setOrderNo(String orderNo) {
this.orderNo = orderNo;
}
public String getOrderNo( ) {
return this.orderNo;
}
public void setOutBizNo(String outBizNo) {
this.outBizNo = outBizNo;
}
public String getOutBizNo( ) {
return this.outBizNo;
}
}
|
/*-------------------------------------------------------------------------+
| |
| Copyright 2005-2011 The ConQAT Project |
| |
| Licensed under the Apache License, Version 2.0 (the "License"); |
| you may not use this file except in compliance with the License. |
| You may obtain a copy of the License at |
| |
| http://www.apache.org/licenses/LICENSE-2.0 |
| |
| Unless required by applicable law or agreed to in writing, software |
| distributed under the License is distributed on an "AS IS" BASIS, |
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| See the License for the specific language governing permissions and |
| limitations under the License. |
+-------------------------------------------------------------------------*/
package org.conqat.engine.resource.scope;
import org.conqat.engine.resource.IContainer;
import org.conqat.engine.resource.text.ITextResource;
import org.conqat.lib.commons.assertion.CCSMPre;
/**
* Base class for parameter objects that allows a processor to bundle several
* outputs into a single object.
* <p>
* In order to allow standard ConQAT processors to work on parameter objects,
* this base class simply implements {@link ITextResource}. This implementation
* of {@link ITextResource} delegates to the root of the resource system tree.
* <p>
* Deriving classes must implement {@link ITextResource#deepClone()}
* <p>
* For an example, look at the class ClassifiedCloneDetectionResult in the
* bundle org.conqat.engine.code_clones.
*
* @author $Author: juergens $
* @version $Rev: 35198 $
* @ConQAT.Rating GREEN Hash: D59F72CBD48FF6E1BAC182B3363F083C
*/
public abstract class TextResourceParameterObjectBase implements ITextResource {
/** Resource tree root parameter. */
private final ITextResource root;
/** Constructor. */
public TextResourceParameterObjectBase(ITextResource root) {
CCSMPre.isNotNull(root);
this.root = root;
}
/** Returns the root element. */
public ITextResource getRoot() {
return root;
}
/** Delegates call to root parameter */
@Override
public ITextResource[] getChildren() {
return root.getChildren();
}
/** Delegates call to root parameter */
@Override
public String getId() {
return root.getId();
}
/** Delegates call to root parameter */
@Override
public String getName() {
return root.getName();
}
/** Delegates call to root parameter */
@Override
public IContainer getParent() {
return root.getParent();
}
/** {@inheritDoc} */
@Override
public void setParent(IContainer parent) {
root.setParent(parent);
}
/** Delegates call to root parameter */
@Override
public Object getValue(String key) {
return root.getValue(key);
}
/** Delegates call to root parameter */
@Override
public boolean hasChildren() {
return root.hasChildren();
}
/** Delegates call to root parameter */
@Override
public void remove() {
root.remove();
}
/** Delegates call to root parameter */
@Override
public void setValue(String key, Object value) {
root.setValue(key, value);
}
}
|
/*
* Copyright (c) 1998, 2002, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package java.beans.beancontext;
/**
* <p>
* This interface is implemented by a JavaBean that does
* not directly have a BeanContext(Child) associated with
* it (via implementing that interface or a subinterface thereof),
* but has a public BeanContext(Child) delegated from it.
* For example, a subclass of java.awt.Container may have a BeanContext
* associated with it that all Component children of that Container shall
* be contained within.
* </p>
* <p>
* An Object may not implement this interface and the
* BeanContextChild interface
* (or any subinterfaces thereof) they are mutually exclusive.
* </p>
* <p>
* Callers of this interface shall examine the return type in order to
* obtain a particular subinterface of BeanContextChild as follows:
* <code>
* BeanContextChild bcc = o.getBeanContextProxy();
*
* if (bcc instanceof BeanContext) {
* // ...
* }
* </code>
* or
* <code>
* BeanContextChild bcc = o.getBeanContextProxy();
* BeanContext bc = null;
*
* try {
* bc = (BeanContext)bcc;
* } catch (ClassCastException cce) {
* // cast failed, bcc is not an instanceof BeanContext
* }
* </code>
* </p>
* <p>
* The return value is a constant for the lifetime of the implementing
* instance
* </p>
* @author Laurence P. G. Cable
* @since 1.2
*
* @see java.beans.beancontext.BeanContextChild
* @see java.beans.beancontext.BeanContextChildSupport
*/
public interface BeanContextProxy {
/**
* Gets the <code>BeanContextChild</code> (or subinterface)
* associated with this object.
* @return the <code>BeanContextChild</code> (or subinterface)
* associated with this object
*/
BeanContextChild getBeanContextProxy();
}
|
package com.packt.androidconcurrency.chapter6.example2;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import com.packt.androidconcurrency.R;
import java.lang.ref.WeakReference;
import java.math.BigInteger;
public class LocalPrimesService extends Service {
public interface Callback {
public boolean onResult(BigInteger result);
}
public class Access extends Binder {
public LocalPrimesService getService() {
return LocalPrimesService.this;
}
};
private final Access binder = new Access();
@Override
public IBinder onBind(Intent intent) {
return binder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
public void calculateNthPrime(final int n, Callback activity) {
final WeakReference<Callback> maybeCallback =
new WeakReference<Callback>(activity);
new AsyncTask<Void,Void,BigInteger>(){
@Override
protected BigInteger doInBackground(Void... params) {
BigInteger prime = new BigInteger("2");
for (int i=0; i<n; i++) {
prime = prime.nextProbablePrime();
}
return prime;
}
@Override
protected void onPostExecute(BigInteger result) {
Callback callback = maybeCallback.get();
if (callback != null) {
if (!callback.onResult(result)) {
notifyUser(n, result.toString());
}
} else {
notifyUser(n, result.toString());
}
}
}.execute();
}
private void notifyUser(int primeToFind, String result) {
String msg = String.format("The %sth prime is %s",
primeToFind, result);
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(android.R.drawable.stat_notify_chat)
.setContentTitle(getString(R.string.primes_service))
.setContentText(msg);
NotificationManager nm = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(primeToFind, builder.build());
}
}
|
package org.sirius.frontend.core.stdlayout;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.stream.Stream;
import org.sirius.common.error.Reporter;
public class ModuleSourcesScanner {
private Path sourceDirPath;
private Reporter reporter;
public ModuleSourcesScanner(Reporter reporter, Path sourceDirPath) {
super();
this.sourceDirPath = sourceDirPath;
this.reporter = reporter;
}
public List<ModuleFiles> scan() {
List<ModuleFiles> currentModuleFiles = new ArrayList<>();
scanDirForModules(Collections.emptyList(), sourceDirPath, currentModuleFiles);
return currentModuleFiles;
}
private Optional<StdInputTextProvider> createTextProvider(File file, List<String> pathElements, Consumer<StdInputTextProvider> handler) {
StdInputTextProvider textProvider;
try {
textProvider = StdInputTextProvider.sourceFile(file, pathElements);
handler.accept(textProvider);
return Optional.of(textProvider);
} catch (IOException e) {
reporter.error("Can't read file " + file.getAbsolutePath(), e);
}
return Optional.empty();
}
private void scanDirForPackages(List<String> pathElements, Path path, List<PackageFiles> packageFiles, boolean inModuleRoot) {
File[] content = path.toFile().listFiles();
Optional<StdInputTextProvider> optPackageDescriptor = Optional.empty();
List<StdInputTextProvider> sourceFiles = new ArrayList<StdInputTextProvider>();
for(File file: content) {
String fname = file.getName();
if(file.isFile()) {
if(fname.equals("module.sirius")) {
if(! inModuleRoot) {
reporter.error("Nested modules not allowed: " + path);
} // else ignore
}
else if(fname.equals("package.sirius")) {
optPackageDescriptor = createTextProvider(file, pathElements, (textProvider) -> {});
}
else if(fname.endsWith(".sirius")){
createTextProvider(file, pathElements, (StdInputTextProvider textProvider) -> {sourceFiles.add(textProvider);});
} else {
reporter.warning("File ignored (source file names should have a '.sirius' extension: " + fname);
}
} else if(file.isDirectory()) {
List<String> childPElts = new ArrayList<String>(pathElements);
childPElts.add(fname);
scanDirForPackages(childPElts, file.toPath(), packageFiles, false /*inModuleRoot*/);
}
}
optPackageDescriptor.ifPresent(itp -> {
packageFiles.add(new PackageFiles(itp, sourceFiles));
});
if(optPackageDescriptor.isEmpty()) {
if(!sourceFiles.isEmpty()) {
reporter.error("Directory " + path + " contains source files but no package descriptor (package.sirius).");
}
}
}
private void scanDirForModules(List<String> pathElements, Path path, List<ModuleFiles> currentModuleFiles/* Collected results */) {
File[] content = path.toFile().listFiles();
Optional<StdInputTextProvider> optModuleDescriptor = Optional.empty();
for(File file: content) {
String fname = file.getName();
if(file.isFile()) {
if(fname.equals("module.sirius")) {
optModuleDescriptor = createTextProvider(file, pathElements, (textProvider) -> {});
List<PackageFiles> packages = new ArrayList<PackageFiles>();
scanDirForPackages(pathElements, path, packages, true /*inModuleRoot*/);
ModuleFiles mf = new ModuleFiles(optModuleDescriptor.get()/*TODO CHECK*/, packages);
currentModuleFiles.add(mf);
}
} else if(file.isDirectory()) {
ArrayList<String> childPathElements = new ArrayList<>(pathElements);
childPathElements.add(file.getName());
scanDirForModules(childPathElements, file.toPath(), currentModuleFiles);
}
}
}
}
|
package com.fishercoder;
import com.fishercoder.solutions._291;
import org.junit.BeforeClass;
import org.junit.Test;
import static junit.framework.TestCase.assertEquals;
/**
* Created by stevesun on 6/6/17.
*/
public class _291Test {
private static _291.Solution1 solution1;
@BeforeClass
public static void setup() {
solution1 = new _291.Solution1();
}
@Test
public void test1() {
assertEquals(true, solution1.wordPatternMatch("abab", "redblueredblue"));
}
}
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.android;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.isSubtypeOf;
import static com.google.errorprone.matchers.Matchers.kindIs;
import static com.google.errorprone.matchers.Matchers.nestingKind;
import static com.sun.source.tree.Tree.Kind.CLASS;
import static javax.lang.model.element.Modifier.ABSTRACT;
import static javax.lang.model.element.Modifier.PUBLIC;
import static javax.lang.model.element.NestingKind.MEMBER;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import java.util.List;
import java.util.stream.Collectors;
/** @author avenet@google.com (Arnaud J. Venet) */
@BugPattern(
name = "FragmentNotInstantiable",
altNames = {"ValidFragment"},
summary =
"Subclasses of Fragment must be instantiable via Class#newInstance():"
+ " the class must be public, static and have a public nullary constructor",
severity = WARNING,
tags = StandardTags.LIKELY_ERROR)
public class FragmentNotInstantiable extends BugChecker implements ClassTreeMatcher {
private static final String MESSAGE_BASE = "Fragment is not instantiable: ";
private static final String FRAGMENT_CLASS = "android.app.Fragment";
// Static library support version of the framework's Fragment. Used to write apps that run on
// platforms prior to Android 3.0.
private static final String FRAGMENT_CLASS_V4 = "android.support.v4.app.Fragment";
private final ImmutableSet<String> fragmentClasses;
private final Matcher<ClassTree> fragmentMatcher;
public FragmentNotInstantiable() {
this(ImmutableSet.of());
}
protected FragmentNotInstantiable(Iterable<String> additionalFragmentClasses) {
fragmentClasses =
ImmutableSet.<String>builder()
.add(FRAGMENT_CLASS)
.add(FRAGMENT_CLASS_V4)
.addAll(additionalFragmentClasses)
.build();
fragmentMatcher =
allOf(
kindIs(CLASS),
anyOf(
fragmentClasses.stream()
.map(fragmentClass -> isSubtypeOf(fragmentClass))
.collect(Collectors.toList())));
}
private Description buildErrorMessage(Tree tree, String explanation) {
Description.Builder description = buildDescription(tree);
description.setMessage(MESSAGE_BASE + explanation + ".");
return description.build();
}
@Override
public Description matchClass(ClassTree classTree, VisitorState state) {
if (!state.isAndroidCompatible()) {
return Description.NO_MATCH;
}
if (!fragmentMatcher.matches(classTree, state)) {
return Description.NO_MATCH;
}
String className = ASTHelpers.getSymbol(classTree).toString();
if (fragmentClasses.contains(className)) {
// Do not check the base class declarations (or their stubs).
return Description.NO_MATCH;
}
// The check doesn't apply to abstract classes.
if (classTree.getModifiers().getFlags().contains(ABSTRACT)) {
return Description.NO_MATCH;
}
// A fragment must be public.
if (!classTree.getModifiers().getFlags().contains(PUBLIC)) {
return buildErrorMessage(classTree, "a fragment must be public");
}
// A fragment that is an inner class must be static.
if (nestingKind(MEMBER).matches(classTree, state)
&& !ASTHelpers.getSymbol(classTree).isStatic()) {
return buildErrorMessage(classTree, "a fragment inner class must be static");
}
List<MethodTree> constructors = ASTHelpers.getConstructors(classTree);
for (MethodTree constructor : constructors) {
if (constructor.getParameters().isEmpty()) {
// The nullary constructor exists. We must make sure that it is public.
if (!constructor.getModifiers().getFlags().contains(PUBLIC)) {
return buildErrorMessage(constructor, "the nullary constructor must be public");
}
return Description.NO_MATCH;
}
}
// If we reach this point, we know for sure that the class has at least one constructor
// but no nullary constructor.
return buildErrorMessage(classTree, "the nullary constructor is missing");
}
}
|
/*
* 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.forrest.eclipse.views;
import java.io.File;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.DropTargetListener;
import org.eclipse.swt.widgets.Display;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
* Handles dropping of files onto the siteXMLView.
*
*/
public class SiteDropListener extends SiteXMLView implements DropTargetListener {
protected NavigationView view;
protected Document activeDocument;
final Display display = Display.getDefault();
public SiteDropListener() {
// TODO Auto-generated constructor stub
activeDocument = document;
}
public void dragEnter(DropTargetEvent event) {
// TODO Auto-generated method stub
}
public void dragLeave(DropTargetEvent event) {
// TODO Auto-generated method stub
}
public void dragOperationChanged(DropTargetEvent event) {
// TODO Auto-generated method stub
}
public void dragOver(DropTargetEvent event) {
// TODO Auto-generated method stub
}
/**
* Handle files that are dropped into the site tree.
*/
public void drop(DropTargetEvent event) {
if (event.data instanceof String[]) {
String[] files = (String[]) event.data;
File strFilename;
String filePath = null;
String relativePath = null;
for (int i = 0; i < files.length; i++) {
strFilename = new File(files[i]);
filePath = strFilename.getPath();
strFilename = new File(files[i]);
filePath = strFilename.getPath();
Node insertionElement = (Element) event.item.getData();
Element element = activeDocument.createElement("NewElement");
relativePath = filePath.substring(xDocPath.length());
element.setAttribute("href", relativePath);
element.setAttribute("description", relativePath);
element.setAttribute("label", relativePath);
insertionElement.appendChild(element);
treeViewer.refresh();
}
}
}
public void dropAccept(DropTargetEvent event) {
// TODO Auto-generated method stub
}
}
|
package ch.bbcag.mdriver.views;
import ch.bbcag.mdriver.common.Record;
import ch.bbcag.mdriver.map.MapDrawer;
import ch.bbcag.mdriver.scenes.ItemBuilder;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import static ch.bbcag.mdriver.Constants.*;
public class MapView extends StackPane {
public MapView(Record record) {
setMaxSize(WINDOW_MIN_WIDTH, WINDOW_MIN_HEIGHT);
setMinSize(WINDOW_MIN_WIDTH, WINDOW_MIN_HEIGHT);
StackPane rootNode = new StackPane();
rootNode.setBorder(ItemBuilder.buildBorder(COLOR_BLUE));
rootNode.setBackground(ItemBuilder.buildBackground(Color.WHITE));
setAlignment(Pos.CENTER);
setBackground(ItemBuilder.buildBackground(Color.WHITE));
MapDrawer drawer = new MapDrawer();
ImageView path = new ImageView(drawer.draw(record));
path.setPreserveRatio(true);
rootNode.maxWidthProperty().bind(maxWidthProperty().subtract(HORIZONTAL_INSET_SIZE * 2));
rootNode.maxHeightProperty().bind(maxHeightProperty().subtract(VERTICAL_INSET_SIZE * 2));
path.fitHeightProperty().bind(rootNode.maxHeightProperty());
path.fitWidthProperty().bind(rootNode.maxWidthProperty());
StackPane.setMargin(rootNode, new Insets(VERTICAL_INSET_SIZE, HORIZONTAL_INSET_SIZE, VERTICAL_INSET_SIZE, HORIZONTAL_INSET_SIZE));
getChildren().add(rootNode);
rootNode.getChildren().add(path);
}
}
|
package org.vaadin.bread.test.repo;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDate;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
/**
* @author Alejandro Duarte
*/
@Entity
public class User {
@NotNull
@Id
@GeneratedValue
private Long id;
@NotNull
private String name;
@Past
private LocalDate birthDate;
@NotNull
private Integer phoneNumber;
@NotNull
@Email
private String email;
@NotNull
@Size(min = 6, max = 100)
private String password;
private Boolean active = true;
private boolean testBool;
private int testInt;
private long testLong;
private float testFloat;
private double testDouble;
private char testChar;
private Integer testIntObj;
private Long testLongObj;
private Float testFloatObj;
private Double testDoubleObj;
private BigInteger testBigInteger;
private BigDecimal testBigDecimal;
@ManyToOne
private Group mainGroup;
@ManyToMany
@Fetch(FetchMode.JOIN)
private Set<Group> groups = new HashSet<>();
private Gender gender;
public User() {
}
public User(Long id, String name, LocalDate birthDate, String email, Integer phoneNumber , String password, Boolean active, Group mainGroup, Set<Group> groups) {
this();
this.id = id;
this.name = name;
this.birthDate = birthDate;
this.email = email;
this.phoneNumber = phoneNumber;
this.password = password;
this.active = active;
this.mainGroup = mainGroup;
this.groups = groups;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return id != null ? id.equals(user.id) : user.id == null;
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LocalDate getBirthDate() {
return birthDate;
}
public void setBirthDate(LocalDate birthDate) {
this.birthDate = birthDate;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(Integer phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public Group getMainGroup() {
return mainGroup;
}
public void setMainGroup(Group mainGroup) {
this.mainGroup = mainGroup;
}
public Set<Group> getGroups() {
return groups;
}
public void setGroups(Set<Group> groups) {
this.groups = groups;
}
public boolean isTestBool() {
return testBool;
}
public void setTestBool(boolean testBool) {
this.testBool = testBool;
}
public int getTestInt() {
return testInt;
}
public void setTestInt(int testInt) {
this.testInt = testInt;
}
public long getTestLong() {
return testLong;
}
public void setTestLong(long testLong) {
this.testLong = testLong;
}
public float getTestFloat() {
return testFloat;
}
public void setTestFloat(float testFloat) {
this.testFloat = testFloat;
}
public double getTestDouble() {
return testDouble;
}
public void setTestDouble(double testDouble) {
this.testDouble = testDouble;
}
public char getTestChar() {
return testChar;
}
public void setTestChar(char testChar) {
this.testChar = testChar;
}
public Integer getTestIntObj() {
return testIntObj;
}
public void setTestIntObj(Integer testIntObj) {
this.testIntObj = testIntObj;
}
public Long getTestLongObj() {
return testLongObj;
}
public void setTestLongObj(Long testLongObj) {
this.testLongObj = testLongObj;
}
public Float getTestFloatObj() {
return testFloatObj;
}
public void setTestFloatObj(Float testFloatObj) {
this.testFloatObj = testFloatObj;
}
public Double getTestDoubleObj() {
return testDoubleObj;
}
public void setTestDoubleObj(Double testDoubleObj) {
this.testDoubleObj = testDoubleObj;
}
public BigInteger getTestBigInteger() {
return testBigInteger;
}
public void setTestBigInteger(BigInteger testBigInteger) {
this.testBigInteger = testBigInteger;
}
public BigDecimal getTestBigDecimal() {
return testBigDecimal;
}
public void setTestBigDecimal(BigDecimal testBigDecimal) {
this.testBigDecimal = testBigDecimal;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
}
|
/**
* ****************************************************************************
* Copyright (c) 2010-2016 by Min Cai (min.cai.china@gmail.com).
* <p>
* This file is part of the Archimulator multicore architectural simulator.
* <p>
* Archimulator is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p>
* Archimulator 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.
* <p>
* You should have received a copy of the GNU General Public License
* along with Archimulator. If not, see <http://www.gnu.org/licenses/>.
* ****************************************************************************
*/
package archimulator.uncore.coherence.msi.message;
import archimulator.uncore.MemoryHierarchyAccess;
import archimulator.uncore.coherence.msi.controller.Controller;
import archimulator.uncore.coherence.msi.flow.CacheCoherenceFlow;
/**
* "Data" message.
*
* @author Min Cai
*/
public class DataMessage extends CoherenceMessage {
private Controller sender;
private int numInvAcks;
/**
* Create a "data" message.
*
* @param generator the generator controller
* @param producerFlow the producer cache coherence flow
* @param sender the sender controller
* @param tag the tag
* @param numInvAcks the number of pending invalidation acknowledgements expected
* @param access the memory hierarchy access
*/
public DataMessage(Controller generator, CacheCoherenceFlow producerFlow, Controller sender, int tag, int numInvAcks, MemoryHierarchyAccess access) {
super(generator, producerFlow, CoherenceMessageType.DATA, access, tag);
this.sender = sender;
this.numInvAcks = numInvAcks;
}
/**
* Get the sender controller.
*
* @return the sender controller
*/
public Controller getSender() {
return sender;
}
/**
* Get the number of pending invalidation acknowledgements expected.
*
* @return the number of pending invalidation acknowledgements expected
*/
public int getNumInvAcks() {
return numInvAcks;
}
@Override
public String toString() {
return String.format("[%d] %s: DataMessage{%d, sender=%s, tag=0x%08x, numInvAcks=%d}", getBeginCycle(), getGenerator(), getId(), sender, getTag(), numInvAcks);
}
}
|
package netherwulf.springframework.recipeapp.converters;
import lombok.Synchronized;
import netherwulf.springframework.recipeapp.commands.CategoryCommand;
import netherwulf.springframework.recipeapp.domain.Category;
import org.springframework.core.convert.converter.Converter;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
@Component
public class CategoryCommandToCategory implements Converter<CategoryCommand, Category> {
@Synchronized
@Nullable
@Override
public Category convert(CategoryCommand source) {
if (source == null) {
return null;
}
final Category category = new Category();
category.setId(source.getId());
category.setDescription(source.getDescription());
return category;
}
}
|
/*
* Copyright 2002-2020 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.transaction.support;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.Constants;
import org.springframework.lang.Nullable;
import org.springframework.transaction.IllegalTransactionStateException;
import org.springframework.transaction.InvalidTimeoutException;
import org.springframework.transaction.NestedTransactionNotSupportedException;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.TransactionSuspensionNotSupportedException;
import org.springframework.transaction.UnexpectedRollbackException;
/**
* Abstract base class that implements Spring's standard transaction workflow,
* serving as basis for concrete platform transaction managers like
* {@link org.springframework.transaction.jta.JtaTransactionManager}.
*
* <p>This base class provides the following workflow handling:
* <ul>
* <li>determines if there is an existing transaction;
* <li>applies the appropriate propagation behavior;
* <li>suspends and resumes transactions if necessary;
* <li>checks the rollback-only flag on commit;
* <li>applies the appropriate modification on rollback
* (actual rollback or setting rollback-only);
* <li>triggers registered synchronization callbacks
* (if transaction synchronization is active).
* </ul>
*
* <p>Subclasses have to implement specific template methods for specific
* states of a transaction, e.g.: begin, suspend, resume, commit, rollback.
* The most important of them are abstract and must be provided by a concrete
* implementation; for the rest, defaults are provided, so overriding is optional.
*
* <p>Transaction synchronization is a generic mechanism for registering callbacks
* that get invoked at transaction completion time. This is mainly used internally
* by the data access support classes for JDBC, Hibernate, JPA, etc when running
* within a JTA transaction: They register resources that are opened within the
* transaction for closing at transaction completion time, allowing e.g. for reuse
* of the same Hibernate Session within the transaction. The same mechanism can
* also be leveraged for custom synchronization needs in an application.
*
* <p>The state of this class is serializable, to allow for serializing the
* transaction strategy along with proxies that carry a transaction interceptor.
* It is up to subclasses if they wish to make their state to be serializable too.
* They should implement the {@code java.io.Serializable} marker interface in
* that case, and potentially a private {@code readObject()} method (according
* to Java serialization rules) if they need to restore any transient state.
*
* @author Juergen Hoeller
* @see #setTransactionSynchronization
* @see TransactionSynchronizationManager
* @see org.springframework.transaction.jta.JtaTransactionManager
* @since 28.03.2003
*/
@SuppressWarnings("serial")
public abstract class AbstractPlatformTransactionManager implements PlatformTransactionManager, Serializable {
/**
* Always activate transaction synchronization, even for "empty" transactions
* that result from PROPAGATION_SUPPORTS with no existing backend transaction.
*
* @see org.springframework.transaction.TransactionDefinition#PROPAGATION_SUPPORTS
* @see org.springframework.transaction.TransactionDefinition#PROPAGATION_NOT_SUPPORTED
* @see org.springframework.transaction.TransactionDefinition#PROPAGATION_NEVER
*/
public static final int SYNCHRONIZATION_ALWAYS = 0;
/**
* Activate transaction synchronization only for actual transactions,
* that is, not for empty ones that result from PROPAGATION_SUPPORTS with
* no existing backend transaction.
*
* @see org.springframework.transaction.TransactionDefinition#PROPAGATION_REQUIRED
* @see org.springframework.transaction.TransactionDefinition#PROPAGATION_MANDATORY
* @see org.springframework.transaction.TransactionDefinition#PROPAGATION_REQUIRES_NEW
*/
public static final int SYNCHRONIZATION_ON_ACTUAL_TRANSACTION = 1;
/**
* Never active transaction synchronization, not even for actual transactions.
*/
public static final int SYNCHRONIZATION_NEVER = 2;
/**
* Constants instance for AbstractPlatformTransactionManager.
*/
private static final Constants constants = new Constants(AbstractPlatformTransactionManager.class);
protected transient Log logger = LogFactory.getLog(getClass());
private int transactionSynchronization = SYNCHRONIZATION_ALWAYS;
private int defaultTimeout = TransactionDefinition.TIMEOUT_DEFAULT;
private boolean nestedTransactionAllowed = false;
private boolean validateExistingTransaction = false;
private boolean globalRollbackOnParticipationFailure = true;
private boolean failEarlyOnGlobalRollbackOnly = false;
private boolean rollbackOnCommitFailure = false;
/**
* Set the transaction synchronization by the name of the corresponding constant
* in this class, e.g. "SYNCHRONIZATION_ALWAYS".
*
* @param constantName name of the constant
* @see #SYNCHRONIZATION_ALWAYS
*/
public final void setTransactionSynchronizationName(String constantName) {
setTransactionSynchronization(constants.asNumber(constantName).intValue());
}
/**
* Set when this transaction manager should activate the thread-bound
* transaction synchronization support. Default is "always".
* <p>Note that transaction synchronization isn't supported for
* multiple concurrent transactions by different transaction managers.
* Only one transaction manager is allowed to activate it at any time.
*
* @see #SYNCHRONIZATION_ALWAYS
* @see #SYNCHRONIZATION_ON_ACTUAL_TRANSACTION
* @see #SYNCHRONIZATION_NEVER
* @see TransactionSynchronizationManager
* @see TransactionSynchronization
*/
public final void setTransactionSynchronization(int transactionSynchronization) {
this.transactionSynchronization = transactionSynchronization;
}
/**
* Return if this transaction manager should activate the thread-bound
* transaction synchronization support.
*/
public final int getTransactionSynchronization() {
return this.transactionSynchronization;
}
/**
* Specify the default timeout that this transaction manager should apply
* if there is no timeout specified at the transaction level, in seconds.
* <p>Default is the underlying transaction infrastructure's default timeout,
* e.g. typically 30 seconds in case of a JTA provider, indicated by the
* {@code TransactionDefinition.TIMEOUT_DEFAULT} value.
*
* @see org.springframework.transaction.TransactionDefinition#TIMEOUT_DEFAULT
*/
public final void setDefaultTimeout(int defaultTimeout) {
if (defaultTimeout < TransactionDefinition.TIMEOUT_DEFAULT) {
throw new InvalidTimeoutException("Invalid default timeout", defaultTimeout);
}
this.defaultTimeout = defaultTimeout;
}
/**
* Return the default timeout that this transaction manager should apply
* if there is no timeout specified at the transaction level, in seconds.
* <p>Returns {@code TransactionDefinition.TIMEOUT_DEFAULT} to indicate
* the underlying transaction infrastructure's default timeout.
*/
public final int getDefaultTimeout() {
return this.defaultTimeout;
}
/**
* Set whether nested transactions are allowed. Default is "false".
* <p>Typically initialized with an appropriate default by the
* concrete transaction manager subclass.
*/
public final void setNestedTransactionAllowed(boolean nestedTransactionAllowed) {
this.nestedTransactionAllowed = nestedTransactionAllowed;
}
/**
* Return whether nested transactions are allowed.
*/
public final boolean isNestedTransactionAllowed() {
return this.nestedTransactionAllowed;
}
/**
* Set whether existing transactions should be validated before participating
* in them.
* <p>When participating in an existing transaction (e.g. with
* PROPAGATION_REQUIRED or PROPAGATION_SUPPORTS encountering an existing
* transaction), this outer transaction's characteristics will apply even
* to the inner transaction scope. Validation will detect incompatible
* isolation level and read-only settings on the inner transaction definition
* and reject participation accordingly through throwing a corresponding exception.
* <p>Default is "false", leniently ignoring inner transaction settings,
* simply overriding them with the outer transaction's characteristics.
* Switch this flag to "true" in order to enforce strict validation.
*
* @since 2.5.1
*/
public final void setValidateExistingTransaction(boolean validateExistingTransaction) {
this.validateExistingTransaction = validateExistingTransaction;
}
/**
* Return whether existing transactions should be validated before participating
* in them.
*
* @since 2.5.1
*/
public final boolean isValidateExistingTransaction() {
return this.validateExistingTransaction;
}
/**
* Set whether to globally mark an existing transaction as rollback-only
* after a participating transaction failed.
* <p>Default is "true": If a participating transaction (e.g. with
* PROPAGATION_REQUIRED or PROPAGATION_SUPPORTS encountering an existing
* transaction) fails, the transaction will be globally marked as rollback-only.
* The only possible outcome of such a transaction is a rollback: The
* transaction originator <i>cannot</i> make the transaction commit anymore.
* <p>Switch this to "false" to let the transaction originator make the rollback
* decision. If a participating transaction fails with an exception, the caller
* can still decide to continue with a different path within the transaction.
* However, note that this will only work as long as all participating resources
* are capable of continuing towards a transaction commit even after a data access
* failure: This is generally not the case for a Hibernate Session, for example;
* neither is it for a sequence of JDBC insert/update/delete operations.
* <p><b>Note:</b>This flag only applies to an explicit rollback attempt for a
* subtransaction, typically caused by an exception thrown by a data access operation
* (where TransactionInterceptor will trigger a {@code PlatformTransactionManager.rollback()}
* call according to a rollback rule). If the flag is off, the caller can handle the exception
* and decide on a rollback, independent of the rollback rules of the subtransaction.
* This flag does, however, <i>not</i> apply to explicit {@code setRollbackOnly}
* calls on a {@code TransactionStatus}, which will always cause an eventual
* global rollback (as it might not throw an exception after the rollback-only call).
* <p>The recommended solution for handling failure of a subtransaction
* is a "nested transaction", where the global transaction can be rolled
* back to a savepoint taken at the beginning of the subtransaction.
* PROPAGATION_NESTED provides exactly those semantics; however, it will
* only work when nested transaction support is available. This is the case
* with DataSourceTransactionManager, but not with JtaTransactionManager.
*
* @see #setNestedTransactionAllowed
* @see org.springframework.transaction.jta.JtaTransactionManager
*/
public final void setGlobalRollbackOnParticipationFailure(boolean globalRollbackOnParticipationFailure) {
this.globalRollbackOnParticipationFailure = globalRollbackOnParticipationFailure;
}
/**
* Return whether to globally mark an existing transaction as rollback-only
* after a participating transaction failed.
*/
public final boolean isGlobalRollbackOnParticipationFailure() {
return this.globalRollbackOnParticipationFailure;
}
/**
* Set whether to fail early in case of the transaction being globally marked
* as rollback-only.
* <p>Default is "false", only causing an UnexpectedRollbackException at the
* outermost transaction boundary. Switch this flag on to cause an
* UnexpectedRollbackException as early as the global rollback-only marker
* has been first detected, even from within an inner transaction boundary.
* <p>Note that, as of Spring 2.0, the fail-early behavior for global
* rollback-only markers has been unified: All transaction managers will by
* default only cause UnexpectedRollbackException at the outermost transaction
* boundary. This allows, for example, to continue unit tests even after an
* operation failed and the transaction will never be completed. All transaction
* managers will only fail earlier if this flag has explicitly been set to "true".
*
* @see org.springframework.transaction.UnexpectedRollbackException
* @since 2.0
*/
public final void setFailEarlyOnGlobalRollbackOnly(boolean failEarlyOnGlobalRollbackOnly) {
this.failEarlyOnGlobalRollbackOnly = failEarlyOnGlobalRollbackOnly;
}
/**
* Return whether to fail early in case of the transaction being globally marked
* as rollback-only.
*
* @since 2.0
*/
public final boolean isFailEarlyOnGlobalRollbackOnly() {
return this.failEarlyOnGlobalRollbackOnly;
}
/**
* Set whether {@code doRollback} should be performed on failure of the
* {@code doCommit} call. Typically not necessary and thus to be avoided,
* as it can potentially override the commit exception with a subsequent
* rollback exception.
* <p>Default is "false".
*
* @see #doCommit
* @see #doRollback
*/
public final void setRollbackOnCommitFailure(boolean rollbackOnCommitFailure) {
this.rollbackOnCommitFailure = rollbackOnCommitFailure;
}
/**
* Return whether {@code doRollback} should be performed on failure of the
* {@code doCommit} call.
*/
public final boolean isRollbackOnCommitFailure() {
return this.rollbackOnCommitFailure;
}
//---------------------------------------------------------------------
// Implementation of PlatformTransactionManager
//---------------------------------------------------------------------
/**
* This implementation handles propagation behavior. Delegates to
* {@code doGetTransaction}, {@code isExistingTransaction}
* and {@code doBegin}.
*
* @see #doGetTransaction
* @see #isExistingTransaction
* @see #doBegin
*/
@Override
public final TransactionStatus getTransaction(@Nullable TransactionDefinition definition)
throws TransactionException {
// Use defaults if no transaction definition given.
/** 使用默认的事物定义,如果哭没有给定的话 **/
TransactionDefinition def = (definition != null ? definition : TransactionDefinition.withDefaults());
Object transaction = doGetTransaction();
boolean debugEnabled = logger.isDebugEnabled();
/** 重点:是否存在事务 特殊处理 **/
if (isExistingTransaction(transaction)) {
// Existing transaction found -> check propagation behavior to find out how to behave.
/** 如果已经存在事物了,那么就找到 propagation 存在的行为,其处理结果在方法中。。。**/
return handleExistingTransaction(def, transaction, debugEnabled);
}
// Check definition settings for new transaction.
if (def.getTimeout() < TransactionDefinition.TIMEOUT_DEFAULT) {
throw new InvalidTimeoutException("Invalid transaction timeout", def.getTimeout());
}
/** 下面是当当前方法不存在事务的处理
PROPAGATION_MANDATORY 不存在事务则抛出异常 **/
// No existing transaction found -> check propagation behavior to find out how to proceed.
if (def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_MANDATORY) {
throw new IllegalTransactionStateException(
"No existing transaction found for transaction marked with propagation 'mandatory'");
} else if (def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED ||
def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW ||
def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {
SuspendedResourcesHolder suspendedResources = suspend(null);
if (debugEnabled) {
logger.debug("Creating new transaction with name [" + def.getName() + "]: " + def);
}
try {
// 开启事务
return startTransaction(def, transaction, debugEnabled, suspendedResources);
} catch (RuntimeException | Error ex) {
resume(null, suspendedResources);
throw ex;
}
}
// 剩下的PROPAGATION_SUPPORTS、PROPAGATION_NOT_SUPPORTS、PROPAGATION_NERVER 不创建事务
else {
// Create "empty" transaction: no actual transaction, but potentially synchronization.
if (def.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT && logger.isWarnEnabled()) {
logger.warn("Custom isolation level specified but no actual transaction initiated; " +
"isolation level will effectively be ignored: " + def);
}
boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);
return prepareTransactionStatus(def, null, true, newSynchronization, debugEnabled, null);
}
}
/**
* Start a new transaction.
*/
private TransactionStatus startTransaction(TransactionDefinition definition, Object transaction,
boolean debugEnabled, @Nullable SuspendedResourcesHolder suspendedResources) {
boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
DefaultTransactionStatus status = newTransactionStatus(
definition, transaction, true, newSynchronization, debugEnabled, suspendedResources);
doBegin(transaction, definition);
prepareSynchronization(status, definition);
return status;
}
/**
* Create a TransactionStatus for an existing transaction.
* <p>
* 如果已经存在事务,则处理逻辑如下
*/
private TransactionStatus handleExistingTransaction(
TransactionDefinition definition, Object transaction, boolean debugEnabled)
throws TransactionException {
// PROPAGATION_NEVER 直接抛出异常
if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NEVER) {
throw new IllegalTransactionStateException(
"Existing transaction found for transaction marked with propagation 'never'");
}
// PROPAGATION_NOT_SUPPORTED suspend挂起当前事务,当前方法不使用事务
if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NOT_SUPPORTED) {
if (debugEnabled) {
logger.debug("Suspending current transaction");
}
Object suspendedResources = suspend(transaction);
boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);
return prepareTransactionStatus(
definition, null, false, newSynchronization, debugEnabled, suspendedResources);
}
// PROPAGATION_REQUIRES_NEW suspend挂起当前事务,doBegin创建一个新事务
if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW) {
if (debugEnabled) {
logger.debug("Suspending current transaction, creating new transaction with name [" +
definition.getName() + "]");
}
SuspendedResourcesHolder suspendedResources = suspend(transaction);
try {
return startTransaction(definition, transaction, debugEnabled, suspendedResources);
} catch (RuntimeException | Error beginEx) {
resumeAfterBeginException(transaction, suspendedResources, beginEx);
throw beginEx;
}
}
// PROPAGATION_NESTED 嵌套事务
if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {
if (!isNestedTransactionAllowed()) {
throw new NestedTransactionNotSupportedException(
"Transaction manager does not allow nested transactions by default - " +
"specify 'nestedTransactionAllowed' property with value 'true'");
}
if (debugEnabled) {
logger.debug("Creating nested transaction with name [" + definition.getName() + "]");
}
if (useSavepointForNestedTransaction()) {
// Create savepoint within existing Spring-managed transaction,
// through the SavepointManager API implemented by TransactionStatus.
// Usually uses JDBC 3.0 savepoints. Never activates Spring synchronization.
DefaultTransactionStatus status =
prepareTransactionStatus(definition, transaction, false, false, debugEnabled, null);
status.createAndHoldSavepoint();
return status;
} else {
// Nested transaction through nested begin and commit/rollback calls.
// Usually only for JTA: Spring synchronization might get activated here
// in case of a pre-existing JTA transaction.
return startTransaction(definition, transaction, debugEnabled, null);
}
}
// Assumably PROPAGATION_SUPPORTS or PROPAGATION_REQUIRED.
if (debugEnabled) {
logger.debug("Participating in existing transaction");
}
// PROPAGATION_REQUIRED、PROPAGATION_SUPPORTS、PROPAGATION_MANDATORY 使用当前事务
if (isValidateExistingTransaction()) {
if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
Integer currentIsolationLevel = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel();
if (currentIsolationLevel == null || currentIsolationLevel != definition.getIsolationLevel()) {
Constants isoConstants = DefaultTransactionDefinition.constants;
throw new IllegalTransactionStateException("Participating transaction with definition [" +
definition + "] specifies isolation level which is incompatible with existing transaction: " +
(currentIsolationLevel != null ?
isoConstants.toCode(currentIsolationLevel, DefaultTransactionDefinition.PREFIX_ISOLATION) :
"(unknown)"));
}
}
if (!definition.isReadOnly()) {
if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
throw new IllegalTransactionStateException("Participating transaction with definition [" +
definition + "] is not marked as read-only but existing transaction is");
}
}
}
boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
return prepareTransactionStatus(definition, transaction, false, newSynchronization, debugEnabled, null);
}
/**
* Create a new TransactionStatus for the given arguments,
* also initializing transaction synchronization as appropriate.
*
* @see #newTransactionStatus
* @see #prepareTransactionStatus
*/
protected final DefaultTransactionStatus prepareTransactionStatus(
TransactionDefinition definition, @Nullable Object transaction, boolean newTransaction,
boolean newSynchronization, boolean debug, @Nullable Object suspendedResources) {
DefaultTransactionStatus status = newTransactionStatus(
definition, transaction, newTransaction, newSynchronization, debug, suspendedResources);
prepareSynchronization(status, definition);
return status;
}
/**
* Create a TransactionStatus instance for the given arguments.
*/
protected DefaultTransactionStatus newTransactionStatus(
TransactionDefinition definition, @Nullable Object transaction, boolean newTransaction,
boolean newSynchronization, boolean debug, @Nullable Object suspendedResources) {
boolean actualNewSynchronization = newSynchronization &&
!TransactionSynchronizationManager.isSynchronizationActive();
return new DefaultTransactionStatus(
transaction, newTransaction, actualNewSynchronization,
definition.isReadOnly(), debug, suspendedResources);
}
/**
* Initialize transaction synchronization as appropriate.
*/
protected void prepareSynchronization(DefaultTransactionStatus status, TransactionDefinition definition) {
if (status.isNewSynchronization()) {
TransactionSynchronizationManager.setActualTransactionActive(status.hasTransaction());
TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(
definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT ?
definition.getIsolationLevel() : null);
TransactionSynchronizationManager.setCurrentTransactionReadOnly(definition.isReadOnly());
TransactionSynchronizationManager.setCurrentTransactionName(definition.getName());
TransactionSynchronizationManager.initSynchronization();
}
}
/**
* Determine the actual timeout to use for the given definition.
* Will fall back to this manager's default timeout if the
* transaction definition doesn't specify a non-default value.
*
* @param definition the transaction definition
* @return the actual timeout to use
* @see org.springframework.transaction.TransactionDefinition#getTimeout()
* @see #setDefaultTimeout
*/
protected int determineTimeout(TransactionDefinition definition) {
if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) {
return definition.getTimeout();
}
return getDefaultTimeout();
}
/**
* Suspend the given transaction. Suspends transaction synchronization first,
* then delegates to the {@code doSuspend} template method.
*
* @param transaction the current transaction object
* (or {@code null} to just suspend active synchronizations, if any)
* @return an object that holds suspended resources
* (or {@code null} if neither transaction nor synchronization active)
* @see #doSuspend
* @see #resume
*/
@Nullable
protected final SuspendedResourcesHolder suspend(@Nullable Object transaction) throws TransactionException {
if (TransactionSynchronizationManager.isSynchronizationActive()) {
List<TransactionSynchronization> suspendedSynchronizations = doSuspendSynchronization();
try {
Object suspendedResources = null;
if (transaction != null) {
suspendedResources = doSuspend(transaction);
}
String name = TransactionSynchronizationManager.getCurrentTransactionName();
TransactionSynchronizationManager.setCurrentTransactionName(null);
boolean readOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly();
TransactionSynchronizationManager.setCurrentTransactionReadOnly(false);
Integer isolationLevel = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel();
TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(null);
boolean wasActive = TransactionSynchronizationManager.isActualTransactionActive();
TransactionSynchronizationManager.setActualTransactionActive(false);
return new SuspendedResourcesHolder(
suspendedResources, suspendedSynchronizations, name, readOnly, isolationLevel, wasActive);
} catch (RuntimeException | Error ex) {
// doSuspend failed - original transaction is still active...
doResumeSynchronization(suspendedSynchronizations);
throw ex;
}
} else if (transaction != null) {
// Transaction active but no synchronization active.
Object suspendedResources = doSuspend(transaction);
return new SuspendedResourcesHolder(suspendedResources);
} else {
// Neither transaction nor synchronization active.
return null;
}
}
/**
* Resume the given transaction. Delegates to the {@code doResume}
* template method first, then resuming transaction synchronization.
*
* @param transaction the current transaction object
* @param resourcesHolder the object that holds suspended resources,
* as returned by {@code suspend} (or {@code null} to just
* resume synchronizations, if any)
* @see #doResume
* @see #suspend
*/
protected final void resume(@Nullable Object transaction, @Nullable SuspendedResourcesHolder resourcesHolder)
throws TransactionException {
if (resourcesHolder != null) {
Object suspendedResources = resourcesHolder.suspendedResources;
if (suspendedResources != null) {
doResume(transaction, suspendedResources);
}
List<TransactionSynchronization> suspendedSynchronizations = resourcesHolder.suspendedSynchronizations;
if (suspendedSynchronizations != null) {
TransactionSynchronizationManager.setActualTransactionActive(resourcesHolder.wasActive);
TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(resourcesHolder.isolationLevel);
TransactionSynchronizationManager.setCurrentTransactionReadOnly(resourcesHolder.readOnly);
TransactionSynchronizationManager.setCurrentTransactionName(resourcesHolder.name);
doResumeSynchronization(suspendedSynchronizations);
}
}
}
/**
* Resume outer transaction after inner transaction begin failed.
*/
private void resumeAfterBeginException(
Object transaction, @Nullable SuspendedResourcesHolder suspendedResources, Throwable beginEx) {
try {
resume(transaction, suspendedResources);
} catch (RuntimeException | Error resumeEx) {
String exMessage = "Inner transaction begin exception overridden by outer transaction resume exception";
logger.error(exMessage, beginEx);
throw resumeEx;
}
}
/**
* Suspend all current synchronizations and deactivate transaction
* synchronization for the current thread.
*
* @return the List of suspended TransactionSynchronization objects
*/
private List<TransactionSynchronization> doSuspendSynchronization() {
List<TransactionSynchronization> suspendedSynchronizations =
TransactionSynchronizationManager.getSynchronizations();
for (TransactionSynchronization synchronization : suspendedSynchronizations) {
synchronization.suspend();
}
TransactionSynchronizationManager.clearSynchronization();
return suspendedSynchronizations;
}
/**
* Reactivate transaction synchronization for the current thread
* and resume all given synchronizations.
*
* @param suspendedSynchronizations a List of TransactionSynchronization objects
*/
private void doResumeSynchronization(List<TransactionSynchronization> suspendedSynchronizations) {
TransactionSynchronizationManager.initSynchronization();
for (TransactionSynchronization synchronization : suspendedSynchronizations) {
synchronization.resume();
TransactionSynchronizationManager.registerSynchronization(synchronization);
}
}
/**
* This implementation of commit handles participating in existing
* transactions and programmatic rollback requests.
* Delegates to {@code isRollbackOnly}, {@code doCommit}
* and {@code rollback}.
*
* @see org.springframework.transaction.TransactionStatus#isRollbackOnly()
* @see #doCommit
* @see #rollback
*/
@Override
public final void commit(TransactionStatus status) throws TransactionException {
if (status.isCompleted()) {
throw new IllegalTransactionStateException(
"Transaction is already completed - do not call commit or rollback more than once per transaction");
}
DefaultTransactionStatus defStatus = (DefaultTransactionStatus) status;
if (defStatus.isLocalRollbackOnly()) {
if (defStatus.isDebug()) {
logger.debug("Transactional code has requested rollback");
}
processRollback(defStatus, false);
return;
}
if (!shouldCommitOnGlobalRollbackOnly() && defStatus.isGlobalRollbackOnly()) {
if (defStatus.isDebug()) {
logger.debug("Global transaction is marked as rollback-only but transactional code requested commit");
}
processRollback(defStatus, true);
return;
}
processCommit(defStatus);
}
/**
* Process an actual commit.
* Rollback-only flags have already been checked and applied.
*
* @param status object representing the transaction
* @throws TransactionException in case of commit failure
*/
private void processCommit(DefaultTransactionStatus status) throws TransactionException {
try {
boolean beforeCompletionInvoked = false;
try {
boolean unexpectedRollback = false;
prepareForCommit(status);
triggerBeforeCommit(status);
triggerBeforeCompletion(status);
beforeCompletionInvoked = true;
if (status.hasSavepoint()) {
if (status.isDebug()) {
logger.debug("Releasing transaction savepoint");
}
unexpectedRollback = status.isGlobalRollbackOnly();
status.releaseHeldSavepoint();
} else if (status.isNewTransaction()) {
if (status.isDebug()) {
logger.debug("Initiating transaction commit");
}
unexpectedRollback = status.isGlobalRollbackOnly();
doCommit(status);
} else if (isFailEarlyOnGlobalRollbackOnly()) {
unexpectedRollback = status.isGlobalRollbackOnly();
}
// Throw UnexpectedRollbackException if we have a global rollback-only
// marker but still didn't get a corresponding exception from commit.
if (unexpectedRollback) {
throw new UnexpectedRollbackException(
"Transaction silently rolled back because it has been marked as rollback-only");
}
} catch (UnexpectedRollbackException ex) {
// can only be caused by doCommit
triggerAfterCompletion(status, TransactionSynchronization.STATUS_ROLLED_BACK);
throw ex;
} catch (TransactionException ex) {
// can only be caused by doCommit
if (isRollbackOnCommitFailure()) {
doRollbackOnCommitException(status, ex);
} else {
triggerAfterCompletion(status, TransactionSynchronization.STATUS_UNKNOWN);
}
throw ex;
} catch (RuntimeException | Error ex) {
if (!beforeCompletionInvoked) {
triggerBeforeCompletion(status);
}
doRollbackOnCommitException(status, ex);
throw ex;
}
// Trigger afterCommit callbacks, with an exception thrown there
// propagated to callers but the transaction still considered as committed.
try {
triggerAfterCommit(status);
} finally {
triggerAfterCompletion(status, TransactionSynchronization.STATUS_COMMITTED);
}
} finally {
cleanupAfterCompletion(status);
}
}
/**
* This implementation of rollback handles participating in existing
* transactions. Delegates to {@code doRollback} and
* {@code doSetRollbackOnly}.
*
* @see #doRollback
* @see #doSetRollbackOnly
*/
@Override
public final void rollback(TransactionStatus status) throws TransactionException {
if (status.isCompleted()) {
throw new IllegalTransactionStateException(
"Transaction is already completed - do not call commit or rollback more than once per transaction");
}
DefaultTransactionStatus defStatus = (DefaultTransactionStatus) status;
processRollback(defStatus, false);
}
/**
* Process an actual rollback.
* The completed flag has already been checked.
*
* @param status object representing the transaction
* @throws TransactionException in case of rollback failure
*/
private void processRollback(DefaultTransactionStatus status, boolean unexpected) {
try {
boolean unexpectedRollback = unexpected;
try {
triggerBeforeCompletion(status);
if (status.hasSavepoint()) {
if (status.isDebug()) {
logger.debug("Rolling back transaction to savepoint");
}
status.rollbackToHeldSavepoint();
} else if (status.isNewTransaction()) {
if (status.isDebug()) {
logger.debug("Initiating transaction rollback");
}
doRollback(status);
} else {
// Participating in larger transaction
if (status.hasTransaction()) {
if (status.isLocalRollbackOnly() || isGlobalRollbackOnParticipationFailure()) {
if (status.isDebug()) {
logger.debug("Participating transaction failed - marking existing transaction as rollback-only");
}
doSetRollbackOnly(status);
} else {
if (status.isDebug()) {
logger.debug("Participating transaction failed - letting transaction originator decide on rollback");
}
}
} else {
logger.debug("Should roll back transaction but cannot - no transaction available");
}
// Unexpected rollback only matters here if we're asked to fail early
if (!isFailEarlyOnGlobalRollbackOnly()) {
unexpectedRollback = false;
}
}
} catch (RuntimeException | Error ex) {
triggerAfterCompletion(status, TransactionSynchronization.STATUS_UNKNOWN);
throw ex;
}
triggerAfterCompletion(status, TransactionSynchronization.STATUS_ROLLED_BACK);
// Raise UnexpectedRollbackException if we had a global rollback-only marker
if (unexpectedRollback) {
throw new UnexpectedRollbackException(
"Transaction rolled back because it has been marked as rollback-only");
}
} finally {
cleanupAfterCompletion(status);
}
}
/**
* Invoke {@code doRollback}, handling rollback exceptions properly.
*
* @param status object representing the transaction
* @param ex the thrown application exception or error
* @throws TransactionException in case of rollback failure
* @see #doRollback
*/
private void doRollbackOnCommitException(DefaultTransactionStatus status, Throwable ex) throws TransactionException {
try {
if (status.isNewTransaction()) {
if (status.isDebug()) {
logger.debug("Initiating transaction rollback after commit exception", ex);
}
doRollback(status);
} else if (status.hasTransaction() && isGlobalRollbackOnParticipationFailure()) {
if (status.isDebug()) {
logger.debug("Marking existing transaction as rollback-only after commit exception", ex);
}
doSetRollbackOnly(status);
}
} catch (RuntimeException | Error rbex) {
logger.error("Commit exception overridden by rollback exception", ex);
triggerAfterCompletion(status, TransactionSynchronization.STATUS_UNKNOWN);
throw rbex;
}
triggerAfterCompletion(status, TransactionSynchronization.STATUS_ROLLED_BACK);
}
/**
* Trigger {@code beforeCommit} callbacks.
*
* @param status object representing the transaction
*/
protected final void triggerBeforeCommit(DefaultTransactionStatus status) {
if (status.isNewSynchronization()) {
if (status.isDebug()) {
logger.trace("Triggering beforeCommit synchronization");
}
TransactionSynchronizationUtils.triggerBeforeCommit(status.isReadOnly());
}
}
/**
* Trigger {@code beforeCompletion} callbacks.
*
* @param status object representing the transaction
*/
protected final void triggerBeforeCompletion(DefaultTransactionStatus status) {
if (status.isNewSynchronization()) {
if (status.isDebug()) {
logger.trace("Triggering beforeCompletion synchronization");
}
TransactionSynchronizationUtils.triggerBeforeCompletion();
}
}
/**
* Trigger {@code afterCommit} callbacks.
*
* @param status object representing the transaction
*/
private void triggerAfterCommit(DefaultTransactionStatus status) {
if (status.isNewSynchronization()) {
if (status.isDebug()) {
logger.trace("Triggering afterCommit synchronization");
}
TransactionSynchronizationUtils.triggerAfterCommit();
}
}
/**
* Trigger {@code afterCompletion} callbacks.
*
* @param status object representing the transaction
* @param completionStatus completion status according to TransactionSynchronization constants
*/
private void triggerAfterCompletion(DefaultTransactionStatus status, int completionStatus) {
if (status.isNewSynchronization()) {
List<TransactionSynchronization> synchronizations = TransactionSynchronizationManager.getSynchronizations();
TransactionSynchronizationManager.clearSynchronization();
if (!status.hasTransaction() || status.isNewTransaction()) {
if (status.isDebug()) {
logger.trace("Triggering afterCompletion synchronization");
}
// No transaction or new transaction for the current scope ->
// invoke the afterCompletion callbacks immediately
invokeAfterCompletion(synchronizations, completionStatus);
} else if (!synchronizations.isEmpty()) {
// Existing transaction that we participate in, controlled outside
// of the scope of this Spring transaction manager -> try to register
// an afterCompletion callback with the existing (JTA) transaction.
registerAfterCompletionWithExistingTransaction(status.getTransaction(), synchronizations);
}
}
}
/**
* Actually invoke the {@code afterCompletion} methods of the
* given Spring TransactionSynchronization objects.
* <p>To be called by this abstract manager itself, or by special implementations
* of the {@code registerAfterCompletionWithExistingTransaction} callback.
*
* @param synchronizations a List of TransactionSynchronization objects
* @param completionStatus the completion status according to the
* constants in the TransactionSynchronization interface
* @see #registerAfterCompletionWithExistingTransaction(Object, java.util.List)
* @see TransactionSynchronization#STATUS_COMMITTED
* @see TransactionSynchronization#STATUS_ROLLED_BACK
* @see TransactionSynchronization#STATUS_UNKNOWN
*/
protected final void invokeAfterCompletion(List<TransactionSynchronization> synchronizations, int completionStatus) {
TransactionSynchronizationUtils.invokeAfterCompletion(synchronizations, completionStatus);
}
/**
* Clean up after completion, clearing synchronization if necessary,
* and invoking doCleanupAfterCompletion.
*
* @param status object representing the transaction
* @see #doCleanupAfterCompletion
*/
private void cleanupAfterCompletion(DefaultTransactionStatus status) {
status.setCompleted();
if (status.isNewSynchronization()) {
TransactionSynchronizationManager.clear();
}
if (status.isNewTransaction()) {
doCleanupAfterCompletion(status.getTransaction());
}
if (status.getSuspendedResources() != null) {
if (status.isDebug()) {
logger.debug("Resuming suspended transaction after completion of inner transaction");
}
Object transaction = (status.hasTransaction() ? status.getTransaction() : null);
resume(transaction, (SuspendedResourcesHolder) status.getSuspendedResources());
}
}
//---------------------------------------------------------------------
// Template methods to be implemented in subclasses
//---------------------------------------------------------------------
/**
* Return a transaction object for the current transaction state.
* <p>The returned object will usually be specific to the concrete transaction
* manager implementation, carrying corresponding transaction state in a
* modifiable fashion. This object will be passed into the other template
* methods (e.g. doBegin and doCommit), either directly or as part of a
* DefaultTransactionStatus instance.
* <p>The returned object should contain information about any existing
* transaction, that is, a transaction that has already started before the
* current {@code getTransaction} call on the transaction manager.
* Consequently, a {@code doGetTransaction} implementation will usually
* look for an existing transaction and store corresponding state in the
* returned transaction object.
*
* @return the current transaction object
* @throws org.springframework.transaction.CannotCreateTransactionException if transaction support is not available
* @throws TransactionException in case of lookup or system errors
* @see #doBegin
* @see #doCommit
* @see #doRollback
* @see DefaultTransactionStatus#getTransaction
*/
protected abstract Object doGetTransaction() throws TransactionException;
/**
* Check if the given transaction object indicates an existing transaction
* (that is, a transaction which has already started).
* <p>The result will be evaluated according to the specified propagation
* behavior for the new transaction. An existing transaction might get
* suspended (in case of PROPAGATION_REQUIRES_NEW), or the new transaction
* might participate in the existing one (in case of PROPAGATION_REQUIRED).
* <p>The default implementation returns {@code false}, assuming that
* participating in existing transactions is generally not supported.
* Subclasses are of course encouraged to provide such support.
*
* @param transaction transaction object returned by doGetTransaction
* @return if there is an existing transaction
* @throws TransactionException in case of system errors
* @see #doGetTransaction
*/
protected boolean isExistingTransaction(Object transaction) throws TransactionException {
return false;
}
/**
* Return whether to use a savepoint for a nested transaction.
* <p>Default is {@code true}, which causes delegation to DefaultTransactionStatus
* for creating and holding a savepoint. If the transaction object does not implement
* the SavepointManager interface, a NestedTransactionNotSupportedException will be
* thrown. Else, the SavepointManager will be asked to create a new savepoint to
* demarcate the start of the nested transaction.
* <p>Subclasses can override this to return {@code false}, causing a further
* call to {@code doBegin} - within the context of an already existing transaction.
* The {@code doBegin} implementation needs to handle this accordingly in such
* a scenario. This is appropriate for JTA, for example.
*
* @see DefaultTransactionStatus#createAndHoldSavepoint
* @see DefaultTransactionStatus#rollbackToHeldSavepoint
* @see DefaultTransactionStatus#releaseHeldSavepoint
* @see #doBegin
*/
protected boolean useSavepointForNestedTransaction() {
return true;
}
/**
* Begin a new transaction with semantics according to the given transaction
* definition. Does not have to care about applying the propagation behavior,
* as this has already been handled by this abstract manager.
* <p>This method gets called when the transaction manager has decided to actually
* start a new transaction. Either there wasn't any transaction before, or the
* previous transaction has been suspended.
* <p>A special scenario is a nested transaction without savepoint: If
* {@code useSavepointForNestedTransaction()} returns "false", this method
* will be called to start a nested transaction when necessary. In such a context,
* there will be an active transaction: The implementation of this method has
* to detect this and start an appropriate nested transaction.
*
* @param transaction transaction object returned by {@code doGetTransaction}
* @param definition a TransactionDefinition instance, describing propagation
* behavior, isolation level, read-only flag, timeout, and transaction name
* @throws TransactionException in case of creation or system errors
* @throws org.springframework.transaction.NestedTransactionNotSupportedException if the underlying transaction does not support nesting
*/
protected abstract void doBegin(Object transaction, TransactionDefinition definition)
throws TransactionException;
/**
* Suspend the resources of the current transaction.
* Transaction synchronization will already have been suspended.
* <p>The default implementation throws a TransactionSuspensionNotSupportedException,
* assuming that transaction suspension is generally not supported.
*
* @param transaction transaction object returned by {@code doGetTransaction}
* @return an object that holds suspended resources
* (will be kept unexamined for passing it into doResume)
* @throws org.springframework.transaction.TransactionSuspensionNotSupportedException if suspending is not supported by the transaction manager implementation
* @throws TransactionException in case of system errors
* @see #doResume
*/
protected Object doSuspend(Object transaction) throws TransactionException {
throw new TransactionSuspensionNotSupportedException(
"Transaction manager [" + getClass().getName() + "] does not support transaction suspension");
}
/**
* Resume the resources of the current transaction.
* Transaction synchronization will be resumed afterwards.
* <p>The default implementation throws a TransactionSuspensionNotSupportedException,
* assuming that transaction suspension is generally not supported.
*
* @param transaction transaction object returned by {@code doGetTransaction}
* @param suspendedResources the object that holds suspended resources,
* as returned by doSuspend
* @throws org.springframework.transaction.TransactionSuspensionNotSupportedException if resuming is not supported by the transaction manager implementation
* @throws TransactionException in case of system errors
* @see #doSuspend
*/
protected void doResume(@Nullable Object transaction, Object suspendedResources) throws TransactionException {
throw new TransactionSuspensionNotSupportedException(
"Transaction manager [" + getClass().getName() + "] does not support transaction suspension");
}
/**
* Return whether to call {@code doCommit} on a transaction that has been
* marked as rollback-only in a global fashion.
* <p>Does not apply if an application locally sets the transaction to rollback-only
* via the TransactionStatus, but only to the transaction itself being marked as
* rollback-only by the transaction coordinator.
* <p>Default is "false": Local transaction strategies usually don't hold the rollback-only
* marker in the transaction itself, therefore they can't handle rollback-only transactions
* as part of transaction commit. Hence, AbstractPlatformTransactionManager will trigger
* a rollback in that case, throwing an UnexpectedRollbackException afterwards.
* <p>Override this to return "true" if the concrete transaction manager expects a
* {@code doCommit} call even for a rollback-only transaction, allowing for
* special handling there. This will, for example, be the case for JTA, where
* {@code UserTransaction.commit} will check the read-only flag itself and
* throw a corresponding RollbackException, which might include the specific reason
* (such as a transaction timeout).
* <p>If this method returns "true" but the {@code doCommit} implementation does not
* throw an exception, this transaction manager will throw an UnexpectedRollbackException
* itself. This should not be the typical case; it is mainly checked to cover misbehaving
* JTA providers that silently roll back even when the rollback has not been requested
* by the calling code.
*
* @see #doCommit
* @see DefaultTransactionStatus#isGlobalRollbackOnly()
* @see DefaultTransactionStatus#isLocalRollbackOnly()
* @see org.springframework.transaction.TransactionStatus#setRollbackOnly()
* @see org.springframework.transaction.UnexpectedRollbackException
* @see javax.transaction.UserTransaction#commit()
* @see javax.transaction.RollbackException
*/
protected boolean shouldCommitOnGlobalRollbackOnly() {
return false;
}
/**
* Make preparations for commit, to be performed before the
* {@code beforeCommit} synchronization callbacks occur.
* <p>Note that exceptions will get propagated to the commit caller
* and cause a rollback of the transaction.
*
* @param status the status representation of the transaction
* @throws RuntimeException in case of errors; will be <b>propagated to the caller</b>
* (note: do not throw TransactionException subclasses here!)
*/
protected void prepareForCommit(DefaultTransactionStatus status) {
}
/**
* Perform an actual commit of the given transaction.
* <p>An implementation does not need to check the "new transaction" flag
* or the rollback-only flag; this will already have been handled before.
* Usually, a straight commit will be performed on the transaction object
* contained in the passed-in status.
*
* @param status the status representation of the transaction
* @throws TransactionException in case of commit or system errors
* @see DefaultTransactionStatus#getTransaction
*/
protected abstract void doCommit(DefaultTransactionStatus status) throws TransactionException;
/**
* Perform an actual rollback of the given transaction.
* <p>An implementation does not need to check the "new transaction" flag;
* this will already have been handled before. Usually, a straight rollback
* will be performed on the transaction object contained in the passed-in status.
*
* @param status the status representation of the transaction
* @throws TransactionException in case of system errors
* @see DefaultTransactionStatus#getTransaction
*/
protected abstract void doRollback(DefaultTransactionStatus status) throws TransactionException;
/**
* Set the given transaction rollback-only. Only called on rollback
* if the current transaction participates in an existing one.
* <p>The default implementation throws an IllegalTransactionStateException,
* assuming that participating in existing transactions is generally not
* supported. Subclasses are of course encouraged to provide such support.
*
* @param status the status representation of the transaction
* @throws TransactionException in case of system errors
*/
protected void doSetRollbackOnly(DefaultTransactionStatus status) throws TransactionException {
throw new IllegalTransactionStateException(
"Participating in existing transactions is not supported - when 'isExistingTransaction' " +
"returns true, appropriate 'doSetRollbackOnly' behavior must be provided");
}
/**
* Register the given list of transaction synchronizations with the existing transaction.
* <p>Invoked when the control of the Spring transaction manager and thus all Spring
* transaction synchronizations end, without the transaction being completed yet. This
* is for example the case when participating in an existing JTA or EJB CMT transaction.
* <p>The default implementation simply invokes the {@code afterCompletion} methods
* immediately, passing in "STATUS_UNKNOWN". This is the best we can do if there's no
* chance to determine the actual outcome of the outer transaction.
*
* @param transaction transaction object returned by {@code doGetTransaction}
* @param synchronizations a List of TransactionSynchronization objects
* @throws TransactionException in case of system errors
* @see #invokeAfterCompletion(java.util.List, int)
* @see TransactionSynchronization#afterCompletion(int)
* @see TransactionSynchronization#STATUS_UNKNOWN
*/
protected void registerAfterCompletionWithExistingTransaction(
Object transaction, List<TransactionSynchronization> synchronizations) throws TransactionException {
logger.debug("Cannot register Spring after-completion synchronization with existing transaction - " +
"processing Spring after-completion callbacks immediately, with outcome status 'unknown'");
invokeAfterCompletion(synchronizations, TransactionSynchronization.STATUS_UNKNOWN);
}
/**
* Cleanup resources after transaction completion.
* <p>Called after {@code doCommit} and {@code doRollback} execution,
* on any outcome. The default implementation does nothing.
* <p>Should not throw any exceptions but just issue warnings on errors.
*
* @param transaction transaction object returned by {@code doGetTransaction}
*/
protected void doCleanupAfterCompletion(Object transaction) {
}
//---------------------------------------------------------------------
// Serialization support
//---------------------------------------------------------------------
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
// Rely on default serialization; just initialize state after deserialization.
ois.defaultReadObject();
// Initialize transient fields.
this.logger = LogFactory.getLog(getClass());
}
/**
* Holder for suspended resources.
* Used internally by {@code suspend} and {@code resume}.
*/
protected static final class SuspendedResourcesHolder {
@Nullable
private final Object suspendedResources;
@Nullable
private List<TransactionSynchronization> suspendedSynchronizations;
@Nullable
private String name;
private boolean readOnly;
@Nullable
private Integer isolationLevel;
private boolean wasActive;
private SuspendedResourcesHolder(Object suspendedResources) {
this.suspendedResources = suspendedResources;
}
private SuspendedResourcesHolder(
@Nullable Object suspendedResources, List<TransactionSynchronization> suspendedSynchronizations,
@Nullable String name, boolean readOnly, @Nullable Integer isolationLevel, boolean wasActive) {
this.suspendedResources = suspendedResources;
this.suspendedSynchronizations = suspendedSynchronizations;
this.name = name;
this.readOnly = readOnly;
this.isolationLevel = isolationLevel;
this.wasActive = wasActive;
}
}
}
|
package github.Louwind.entityutils.core.mixin;
import net.minecraft.entity.ai.brain.sensor.Sensor;
import net.minecraft.entity.ai.brain.sensor.SensorType;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Invoker;
import java.util.function.Supplier;
@Mixin(SensorType.class)
public interface InvokerSensorType {
@Invoker("<init>")
static <U extends Sensor<?>> SensorType<U> create(Supplier<U> supplier) {
throw new AssertionError();
}
}
|
package org.anddev.andengine.collision;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:50:19 - 11.03.2010
*/
public class BaseCollisionChecker {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static boolean checkAxisAlignedRectangleCollision(final float pLeftA, final float pTopA, final float pRightA, final float pBottomA, final float pLeftB, final float pTopB, final float pRightB, final float pBottomB) {
return pLeftA < pRightB &&
pLeftB < pRightA &&
pTopA < pBottomB &&
pTopB < pBottomA;
}
/**
* Returns an indicator of where the specified point (PX, PY) lies with
* respect to the line segment from (X1, Y1) to (X2, Y2). The
* return value can be either 1, -1, or 0 and indicates in which direction
* the specified line must pivot around its first endpoint, (X1, Y1),
* in order to point at the specified point (PX, PY).
* <p>
* A return value of 1 indicates that the line segment must turn in the
* direction that takes the positive X axis towards the negative Y axis. In
* the default coordinate system used by Java 2D, this direction is
* counterclockwise.
* <p>
* A return value of -1 indicates that the line segment must turn in the
* direction that takes the positive X axis towards the positive Y axis. In
* the default coordinate system, this direction is clockwise.
* <p>
* A return value of 0 indicates that the point lies exactly on the line
* segment. Note that an indicator value of 0 is rare and not useful for
* determining colinearity because of floating point rounding issues.
* <p>
* If the point is colinear with the line segment, but not between the
* endpoints, then the value will be -1 if the point lies
* "beyond (X1, Y1)" or 1 if the point lies "beyond (X2, Y2)".
*
* @param pX1
* , Y1 the coordinates of the beginning of the specified
* line segment
* @param pX2
* , Y2 the coordinates of the end of the specified line
* segment
* @param pPX
* , PY the coordinates of the specified point to be
* compared with the specified line segment
* @return an integer that indicates the position of the third specified
* coordinates with respect to the line segment formed by the first
* two specified coordinates.
*/
public static int relativeCCW(final float pX1, final float pY1, float pX2, float pY2, float pPX, float pPY) {
pX2 -= pX1;
pY2 -= pY1;
pPX -= pX1;
pPY -= pY1;
float ccw = pPX * pY2 - pPY * pX2;
if (ccw == 0.0f) {
// The point is colinear, classify based on which side of
// the segment the point falls on. We can calculate a
// relative value using the projection of PX,PY onto the
// segment - a negative value indicates the point projects
// outside of the segment in the direction of the particular
// endpoint used as the origin for the projection.
ccw = pPX * pX2 + pPY * pY2;
if (ccw > 0.0f) {
// Reverse the projection to be relative to the original X2,Y2
// X2 and Y2 are simply negated.
// PX and PY need to have (X2 - X1) or (Y2 - Y1) subtracted
// from them (based on the original values)
// Since we really want to get a positive answer when the
// point is "beyond (X2,Y2)", then we want to calculate
// the inverse anyway - thus we leave X2 & Y2 negated.
pPX -= pX2;
pPY -= pY2;
ccw = pPX * pX2 + pPY * pY2;
if (ccw < 0.0f) {
ccw = 0.0f;
}
}
}
return (ccw < 0.0f) ? -1 : ((ccw > 0.0f) ? 1 : 0);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
|
// AUTOGENERATED CODE. DO NOT MODIFY DIRECTLY! Instead, please modify the util/function/MethodReference.ftl file.
// See the README in the module's src/template directory for details.
package com.linkedin.dagli.util.function;
import com.linkedin.dagli.util.named.Named;
import java.io.IOException;
import java.lang.invoke.LambdaMetafactory;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodType;
/**
* Represents a safely serializable method reference (assuming the JVM supports {@link MethodReference}, which is not
* guaranteed). If the JVM does not support {@link MethodReference}, an exception may be thrown when creating the
* method reference; fortunately, however, deserialization will not be affected: if you can serialize it, you'll be able
* to deserialize later on any JVM.
*/
class IntMethodReference1<A> implements IntFunction1.Serializable<A>, Named {
private static final long serialVersionUID = 1;
// hash and equality distinguish between different types of MethodReferenceX classes even when the underlying method
// references are identical
private static final int CLASS_HASH = IntMethodReference1.class.hashCode();
private final MethodReference _methodReference;
private transient IntFunction1<A> _cachedFunction = null;
IntMethodReference1(MethodReference mr) {
_methodReference = mr;
initCachedFunction();
}
/**
* Creates a new instance.
*
* The passed func parameter must be a method reference, such as Object::toString or String::length. A runtime
* exception will be thrown if func is a function object or an anonymous lambda (e.g. "a -> a + 5"). An exception
* may also be thrown if your JVM implementation does not support the library's internal method for retrieving
* information about the passed method reference.
*
* @param func a method reference lambda to wrap. If this function is not safely serializable, a runtime exception
* will be thrown.
*/
public IntMethodReference1(Serializable<A> func) {
if (func instanceof IntMethodReference1) {
// multiple applications of this constructor are idempotent:
_methodReference = ((IntMethodReference1) func)._methodReference;
} else {
// this line will thrown an exception if func is not a method reference:
_methodReference = new MethodReference(func);
}
initCachedFunction();
}
// deserialization hook to ensure _cachedFunction is always set
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
initCachedFunction();
}
private void initCachedFunction() {
if (_cachedFunction == null) {
_cachedFunction = fromMethodReference();
}
}
private IntFunction1<A> fromMethodReference() {
if (_methodReference.isBound()) {
IntMethodReference2<Object, A> unbound = new IntMethodReference2<>(_methodReference.unbind());
return (A value1) -> unbound.apply(_methodReference.getBoundInstance(), value1);
}
MethodHandle mh = _methodReference.getMethodHandle();
try {
MethodType type = mh.type().generic().changeReturnType(int.class);
return (IntFunction1<A>) LambdaMetafactory
.metafactory(_methodReference.getLookup(), "apply", MethodType.methodType(IntFunction1.class), type, mh,
mh.type().wrap().changeReturnType(int.class)).getTarget().invokeExact();
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
public int apply(A value1) {
return _cachedFunction.apply(value1);
}
@Override
public int hashCode() {
return CLASS_HASH + _methodReference.hashCode();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof IntMethodReference1)) {
return false;
}
return _methodReference.equals(((IntMethodReference1) obj)._methodReference);
}
@Override
public String toString() {
return _methodReference.toString();
}
@Override
public String getName() {
return _methodReference.getName();
}
@Override
public String getShortName() {
return _methodReference.getShortName();
}
}
|
package dao;
/**
* 继承自库中jntoo-query.jar
*/
public class Query extends net.jntoo.db.Query {
}
|
package com.blamejared.crafttweaker.impl.loot.conditions;
import com.blamejared.crafttweaker.api.annotations.ZenRegister;
import com.blamejared.crafttweaker.api.loot.conditions.ILootCondition;
import com.blamejared.crafttweaker_annotations.annotations.Document;
import net.minecraft.loot.LootContext;
import org.openzen.zencode.java.ZenCodeType;
/**
* Represents a vanilla or mod-added loot condition.
*/
@ZenRegister
@ZenCodeType.Name("crafttweaker.api.loot.conditions.MCLootCondition")
@Document("vanilla/api/loot/conditions/MCLootCondition")
public final class MCLootCondition implements ILootCondition {
private final net.minecraft.loot.conditions.ILootCondition wrapped;
public MCLootCondition(final net.minecraft.loot.conditions.ILootCondition wrapped) {
this.wrapped = wrapped;
}
@Override
public boolean test(LootContext context) {
return this.wrapped.test(context);
}
public net.minecraft.loot.conditions.ILootCondition getInternal() {
return this.wrapped;
}
}
|
/**
* Copyright 2015 MKL Software
*
* 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.mkl.websuites.internal.command.impl.select;
import java.util.Map;
import org.openqa.selenium.support.ui.Select;
import com.mkl.websuites.command.CommandDescriptor;
@CommandDescriptor(name = "deselectByIndex", argumentTypes = {String.class, Integer.class})
public class DeselectByIndexCommand extends SelectByIndexCommand {
public DeselectByIndexCommand(Map<String, String> parameterMap) {
super(parameterMap);
}
public DeselectByIndexCommand(String selector, Integer index) {
super(selector, index);
}
@Override
protected void doSelect(int index, Select select) {
select.deselectByIndex(index);
}
}
|
package net.coobird.thumbnailator.util.exif;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import javax.imageio.ImageReader;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.metadata.IIOMetadataNode;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* An utility class used to obtain the orientation information from a given
* Exif metadata.
*
* @author coobird
*
*/
public final class ExifUtils
{
private static final String EXIF_MAGIC_STRING = "Exif";
/**
* This class should not be instantiated.
*/
private ExifUtils() {};
/**
* Returns the orientation obtained from the Exif metadata.
*
* @param reader An {@link ImageReader} which is reading the
* target image.
* @param imageIndex The index of the image from which the Exif
* metadata should be read from.
* @return The orientation information obtained from the
* Exif metadata, as a {@link Orientation} enum.
* @throws IOException When an error occurs during reading.
* @throws IllegalArgumentException If the {@link ImageReader} does not
* have the target image set, or if the
* reader does not have a JPEG open.
*/
public static Orientation getExifOrientation(ImageReader reader, int imageIndex) throws IOException
{
IIOMetadata metadata = reader.getImageMetadata(imageIndex);
Node rootNode = metadata.getAsTree("javax_imageio_jpeg_image_1.0");
NodeList childNodes = rootNode.getChildNodes();
// Look for the APP1 containing Exif data, and retrieve it.
for (int i = 0; i < childNodes.getLength(); i++)
{
if ("markerSequence".equals(childNodes.item(i).getNodeName()))
{
NodeList markerSequenceChildren = childNodes.item(i).getChildNodes();
for (int j = 0; j < markerSequenceChildren.getLength(); j++)
{
IIOMetadataNode metadataNode = (IIOMetadataNode)(markerSequenceChildren.item(j));
byte[] bytes = (byte[])metadataNode.getUserObject();
if (bytes == null)
{
continue;
}
byte[] magicNumber = new byte[4];
ByteBuffer.wrap(bytes).get(magicNumber);
if (EXIF_MAGIC_STRING.equals(new String(magicNumber)))
{
return getOrientationFromExif(bytes);
}
}
}
}
return null;
}
private static Orientation getOrientationFromExif(byte[] exifData)
{
// Needed to make byte-wise reading easier.
ByteBuffer buffer = ByteBuffer.wrap(exifData);
byte[] exifId = new byte[4];
buffer.get(exifId);
if (!EXIF_MAGIC_STRING.equals(new String(exifId)))
{
return null;
}
// read the \0 after the Exif
buffer.get();
// read the padding byte
buffer.get();
byte[] tiffHeader = new byte[8];
buffer.get(tiffHeader);
/*
* The first 2 bytes of the TIFF header contains either:
* "II" for Intel byte alignment (little endian), or
* "MM" for Motorola byte alignment (big endian)
*/
ByteOrder bo;
if (tiffHeader[0] == 'I' && tiffHeader[1] == 'I')
{
bo = ByteOrder.LITTLE_ENDIAN;
}
else
{
bo = ByteOrder.BIG_ENDIAN;
}
byte[] numFields = new byte[2];
buffer.get(numFields);
int nFields = ByteBuffer.wrap(numFields).order(bo).getShort();
byte[] ifd = new byte[12];
for (int i = 0; i < nFields; i++)
{
buffer.get(ifd);
IfdStructure ifdStructure = readIFD(ifd, bo);
// Return the orientation from the orientation IFD
if (ifdStructure.getTag() == 0x0112)
{
return Orientation.typeOf(ifdStructure.getOffsetValue());
}
}
return null;
}
private static IfdStructure readIFD(byte[] ifd, ByteOrder bo)
{
ByteBuffer buffer = ByteBuffer.wrap(ifd).order(bo);
short tag = buffer.getShort();
short type = buffer.getShort();
int count = buffer.getInt();
IfdType ifdType = IfdType.typeOf(type);
int offsetValue = 0;
/*
* Per section 4.6.2 of the Exif Spec, if value is smaller than
* 4 bytes, it will exist in the earlier byte.
*/
int byteSize = count * ifdType.size();
if (byteSize <= 4) {
if (ifdType == IfdType.SHORT)
{
for (int i = 0; i < count; i++)
{
offsetValue = (int)buffer.getShort();
}
}
else if (ifdType == IfdType.BYTE || ifdType == IfdType.ASCII || ifdType == IfdType.UNDEFINED)
{
for (int i = 0; i < count; i++)
{
offsetValue = (int)buffer.get();
}
}
else
{
offsetValue = buffer.getInt();
}
}
else
{
offsetValue = buffer.getInt();
}
return new IfdStructure(tag, type, count, offsetValue);
}
}
|
package fi.joniaromaa.parinacorelibrary.bungee.commands;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import codecrafter47.bungeetablistplus.BungeeTabListPlus;
import codecrafter47.bungeetablistplus.data.BTLPBungeeDataKeys;
import fi.joniaromaa.parinacorelibrary.api.user.User;
import fi.joniaromaa.parinacorelibrary.bungee.ParinaCoreBungeePlugin;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.plugin.Command;
public class BungeeGlobalListCommand extends Command
{
private ParinaCoreBungeePlugin plugin;
public BungeeGlobalListCommand(ParinaCoreBungeePlugin plugin)
{
super("globallist", "parina.command.globallist.use", "glist", "gl");
this.plugin = plugin;
}
@Override
public void execute(CommandSender sender, String[] args)
{
ProxyServer.getInstance().getServers().values().stream().sorted(Comparator.comparing(ServerInfo::getName)).forEach((serverInfo) ->
{
if (serverInfo.canAccess(sender))
{
List<User> players = new ArrayList<>();
for(ProxiedPlayer player : serverInfo.getPlayers())
{
if (!Boolean.TRUE.equals(BungeeTabListPlus.getInstance().getBungeePlayerProvider().getPlayer(player).getLocalDataCache().get(BTLPBungeeDataKeys.DATA_KEY_IS_HIDDEN)) || sender.hasPermission("bungeetablistplus.seevanished"))
{
this.plugin.getApi().getUserManager().getUser(player.getUniqueId()).ifPresent((u) -> players.add(u));
}
}
//Skip empty servers
if (players.isEmpty())
{
return;
}
ComponentBuilder componentBuilder = new ComponentBuilder(serverInfo.getName() + " (" + players.size() + "): ").color(ChatColor.AQUA);
Iterator<User> users = players.stream().sorted(Comparator.comparing(User::getWeight).reversed().thenComparing(User::getDisplayName)).iterator();
while (users.hasNext())
{
componentBuilder.append(TextComponent.fromLegacyText(users.next().getFormattedDisplayName()));
if (users.hasNext())
{
componentBuilder.append(", ");
componentBuilder.color(ChatColor.GRAY);
}
}
sender.sendMessage(componentBuilder.create());
}
});
}
}
|
// This is a generated file. Not intended for manual editing.
package com.sqlplugin.psi.impl;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import static com.sqlplugin.psi.SqlTypes.*;
import com.intellij.extapi.psi.ASTWrapperPsiElement;
import com.sqlplugin.psi.*;
public class SqlNextValueExpressionImpl extends ASTWrapperPsiElement implements SqlNextValueExpression {
public SqlNextValueExpressionImpl(@NotNull ASTNode node) {
super(node);
}
public void accept(@NotNull SqlVisitor visitor) {
visitor.visitNextValueExpression(this);
}
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof SqlVisitor) accept((SqlVisitor)visitor);
else super.accept(visitor);
}
@Override
@NotNull
public SqlSequenceGeneratorName getSequenceGeneratorName() {
return findNotNullChildByClass(SqlSequenceGeneratorName.class);
}
}
|
package org.cloudfoundry.credhub.helpers;
import java.util.HashMap;
import java.util.Map;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import com.google.common.collect.ImmutableMap;
import com.jayway.jsonpath.JsonPath;
import org.cloudfoundry.credhub.views.PermissionsView;
import org.hamcrest.core.IsEqual;
import static java.lang.String.join;
import static org.cloudfoundry.credhub.AuthConstants.ALL_PERMISSIONS_TOKEN;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
final public class RequestHelper {
private RequestHelper() {
super();
}
public static String setPassword(
final MockMvc mockMvc, final String credentialName, final String passwordValue, final String token) throws Exception {
final Map<String, Object> passwordRequestBody = new HashMap() {
{
put("name", credentialName);
put("type", "password");
put("value", passwordValue);
}
};
final String content = JsonTestHelper.serializeToString(passwordRequestBody);
final MockHttpServletRequestBuilder put = put("/api/v1/data")
.header("Authorization", "Bearer " + token)
.accept(APPLICATION_JSON)
.contentType(APPLICATION_JSON)
.content(content);
final String response;
if (credentialName.length() <= 1024) {
response = mockMvc.perform(put)
.andExpect(status().isOk())
.andDo(print())
.andReturn().getResponse().getContentAsString();
} else {
response = mockMvc.perform(put)
.andExpect(status().isBadRequest())
.andDo(print())
.andReturn().getResponse().getContentAsString();
}
return response;
}
public static String generatePassword(final MockMvc mockMvc, final String credentialName, final boolean overwrite, final Integer length, final String token) throws Exception {
final Map<String, Object> passwordRequestBody = new HashMap() {
{
put("name", credentialName);
put("type", "password");
}
};
if (overwrite) {
passwordRequestBody.put("overwrite", true);
}
if (length != null) {
passwordRequestBody.put("parameters", ImmutableMap.of("length", length));
}
final String content = JsonTestHelper.serializeToString(passwordRequestBody);
final MockHttpServletRequestBuilder post = post("/api/v1/data")
.header("Authorization", "Bearer " + token)
.accept(APPLICATION_JSON)
.contentType(APPLICATION_JSON)
.content(content);
final String response;
if (credentialName.length() <= 1024) {
response = mockMvc.perform(post)
.andExpect(status().isOk())
.andReturn().getResponse().getContentAsString();
} else {
response = mockMvc.perform(post)
.andExpect(status().isBadRequest())
.andReturn().getResponse().getContentAsString();
}
return response;
}
public static String generateUser(
final MockMvc mockMvc, final String credentialName, final boolean overwrite, final Integer length, final String username, final boolean excludeUpper)
throws Exception {
final Map<String, Object> userRequestBody = new HashMap() {
{
put("name", credentialName);
put("type", "user");
}
};
if (overwrite) {
userRequestBody.put("overwrite", true);
}
final Map parameters = new HashMap<String, Object>();
if (length != null) {
parameters.put("length", length);
}
if (username != null) {
parameters.put("username", username);
}
if (excludeUpper) {
parameters.put("exclude_upper", true);
}
userRequestBody.put("parameters", parameters);
final String content = JsonTestHelper.serializeToString(userRequestBody);
final MockHttpServletRequestBuilder post = post("/api/v1/data")
.header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN)
.accept(APPLICATION_JSON)
.contentType(APPLICATION_JSON)
.content(content);
final String response = mockMvc.perform(post)
.andExpect(status().isOk())
.andReturn().getResponse().getContentAsString();
return response;
}
public static String generateSsh(
final MockMvc mockMvc, final String credentialName, final boolean overwrite, final Integer length, final String sshComment)
throws Exception {
final Map<String, Object> sshRequestBody = new HashMap() {
{
put("name", credentialName);
put("type", "ssh");
}
};
if (overwrite) {
sshRequestBody.put("overwrite", true);
}
final Map parameters = new HashMap<String, Object>();
if (length != null) {
parameters.put("key_length", length);
}
if (sshComment != null) {
parameters.put("ssh_comment", sshComment);
}
sshRequestBody.put("parameters", parameters);
final String content = JsonTestHelper.serializeToString(sshRequestBody);
final MockHttpServletRequestBuilder post = post("/api/v1/data")
.header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN)
.accept(APPLICATION_JSON)
.contentType(APPLICATION_JSON)
.content(content);
final String response = mockMvc.perform(post)
.andExpect(status().isOk())
.andReturn().getResponse().getContentAsString();
return response;
}
public static String getCertificateCredentials(final MockMvc mockMvc, final String token)
throws Exception {
final MockHttpServletRequestBuilder get = get("/api/v1/certificates")
.header("Authorization", "Bearer " + token)
.accept(APPLICATION_JSON)
.contentType(APPLICATION_JSON);
final String response = mockMvc.perform(get)
.andDo(print())
.andExpect(status().isOk())
.andReturn().getResponse().getContentAsString();
return response;
}
public static String getCertificateCredentialsByName(final MockMvc mockMvc, final String token, final String name)
throws Exception {
final MockHttpServletRequestBuilder get = get("/api/v1/certificates?name=" + name)
.header("Authorization", "Bearer " + token)
.accept(APPLICATION_JSON)
.contentType(APPLICATION_JSON);
final String response = mockMvc.perform(get)
.andDo(print())
.andExpect(status().isOk())
.andReturn().getResponse().getContentAsString();
return response;
}
public static String getCertificateId(final MockMvc mockMvc, final String certificateName) throws Exception {
final String response = getCertificateCredentialsByName(mockMvc, ALL_PERMISSIONS_TOKEN, certificateName);
return JsonPath.parse(response)
.read("$.certificates[0].id");
}
public static String generateCertificateCredential(final MockMvc mockMvc, final String credentialName, final boolean overwrite, final String commonName, final String caName, final String token) throws Exception {
final Map<String, Object> certRequestBody = new HashMap() {
{
put("name", credentialName);
put("type", "certificate");
}
};
if (overwrite) {
certRequestBody.put("overwrite", true);
}
final Map parameters = new HashMap<String, Object>();
if (caName == null) {
parameters.put("self_sign", true);
parameters.put("is_ca", true);
} else {
parameters.put("ca", caName);
}
parameters.put("common_name", commonName);
certRequestBody.put("parameters", parameters);
final String content = JsonTestHelper.serializeToString(certRequestBody);
final MockHttpServletRequestBuilder post = post("/api/v1/data")
.header("Authorization", "Bearer " + token)
.accept(APPLICATION_JSON)
.contentType(APPLICATION_JSON)
.content(content);
final String response = mockMvc.perform(post)
.andExpect(status().isOk())
.andReturn().getResponse().getContentAsString();
return response;
}
public static String generateRsa(
final MockMvc mockMvc, final String credentialName, final boolean overwrite, final Integer length)
throws Exception {
final Map<String, Object> rsaRequestBody = new HashMap() {
{
put("name", credentialName);
put("type", "rsa");
}
};
if (overwrite) {
rsaRequestBody.put("overwrite", true);
}
if (length != null) {
rsaRequestBody.put("parameters", ImmutableMap.of("key_length", length));
}
final String content = JsonTestHelper.serializeToString(rsaRequestBody);
final MockHttpServletRequestBuilder post = post("/api/v1/data")
.header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN)
.accept(APPLICATION_JSON)
.contentType(APPLICATION_JSON)
.content(content);
final String response = mockMvc.perform(post)
.andExpect(status().isOk())
.andReturn().getResponse().getContentAsString();
return response;
}
public static String generateCa(final MockMvc mockMvc, final String caName, final String token) throws Exception {
final MockHttpServletRequestBuilder caPost = post("/api/v1/data")
.header("Authorization", "Bearer " + token)
.accept(APPLICATION_JSON)
.contentType(APPLICATION_JSON)
//language=JSON
.content("{\n"
+ " \"name\" : \"" + caName + "\",\n"
+ " \"type\" : \"certificate\",\n"
+ " \"overwrite\": true,\n"
+ " \"parameters\" : {\n"
+ " \"common_name\" : \"federation\",\n"
+ " \"is_ca\" : true,\n"
+ " \"self_sign\" : true\n"
+ " }\n"
+ "}");
final String caResult = mockMvc.perform(caPost)
.andExpect(status().isOk())
.andReturn().getResponse().getContentAsString();
return caResult;
}
private static MockHttpServletRequestBuilder createRequestForGenerateCertificate(final String certName,
final String caName, final String token) {
return post("/api/v1/data")
.header("Authorization", "Bearer " + token)
.accept(APPLICATION_JSON)
.contentType(APPLICATION_JSON)
//language=JSON
.content("{\n"
+ " \"name\" : \"" + certName + "\",\n"
+ " \"type\" : \"certificate\",\n"
+ " \"parameters\" : {\n"
+ " \"common_name\" : \"federation\",\n"
+ " \"ca\" : \"" + caName + "\"\n"
+ " }\n"
+ "}");
}
public static void generateCertificate(final MockMvc mockMvc, final String certName, final String caName,
final String token) throws Exception {
final MockHttpServletRequestBuilder certPost = createRequestForGenerateCertificate(certName, caName,
token);
mockMvc.perform(certPost)
.andDo(print())
.andExpect(status().isOk());
}
public static void expect404WhileGeneratingCertificate(final MockMvc mockMvc, final String certName,
final String token, final String expectedMessage) throws Exception {
final MockHttpServletRequestBuilder certPost = post("/api/v1/data")
.header("Authorization", "Bearer " + token)
.accept(APPLICATION_JSON)
.contentType(APPLICATION_JSON)
//language=JSON
.content("{\n"
+ " \"name\" : \"" + certName + "\",\n"
+ " \"type\" : \"certificate\",\n"
+ " \"parameters\" : {\n"
+ " \"common_name\" : \"federation\",\n"
+ " \"ca\" : \"picard\"\n"
+ " }\n"
+ "}");
mockMvc.perform(certPost)
.andDo(print())
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.error", equalTo(expectedMessage)));
}
public static void expect404WhileRegeneratingCertificate(final MockMvc mockMvc, final String certName,
final String token, final String message) throws Exception {
final MockHttpServletRequestBuilder certPost = post("/api/v1/data")
.header("Authorization", "Bearer " + token)
.accept(APPLICATION_JSON)
.contentType(APPLICATION_JSON)
//language=JSON
.content("{\"regenerate\":true,\"name\":\"" + certName + "\"}");
mockMvc.perform(certPost)
.andDo(print())
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.error", IsEqual.equalTo(message)));
}
public static void grantPermissions(
final MockMvc mockMvc,
final String credentialName,
final String grantorToken,
final String granteeName,
final String... permissions
) throws Exception {
final MockHttpServletRequestBuilder post = createAddPermissionsRequest(
grantorToken, credentialName, granteeName,
permissions);
mockMvc.perform(post)
.andExpect(status().isCreated());
}
public static void expectErrorWhenAddingPermissions(
final MockMvc mockMvc,
final int status,
final String message,
final String credentialName,
final String grantorToken,
final String grantee,
final String... permissions
) throws Exception {
final MockHttpServletRequestBuilder post = createAddPermissionsRequest(
grantorToken, credentialName, grantee,
permissions);
mockMvc.perform(post)
.andExpect(status().is(status))
.andExpect(content().contentTypeCompatibleWith(APPLICATION_JSON))
.andExpect(jsonPath("$.error").value(message));
}
public static PermissionsView getPermissions(
final MockMvc mockMvc,
final String credentialName,
final String requesterToken
) throws Exception {
final String content = mockMvc.perform(get("/api/v1/permissions?credential_name=" + credentialName)
.header("Authorization", "Bearer " + requesterToken))
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(APPLICATION_JSON))
.andReturn()
.getResponse()
.getContentAsString();
return JsonTestHelper.deserialize(content, PermissionsView.class);
}
public static void expectErrorWhenGettingPermissions(
final MockMvc mockMvc,
final int status,
final String expectedErrorMessage,
final String credentialName,
final String requesterToken
) throws Exception {
mockMvc.perform(get("/api/v1/permissions" +
(credentialName == null ? "" : "?credential_name=" + credentialName))
.header("Authorization", "Bearer " + requesterToken))
.andExpect(status().is(status))
.andExpect(jsonPath("$.error", equalTo(expectedErrorMessage)));
}
public static void revokePermissions(
final MockMvc mockMvc,
final String credentialName,
final String grantorToken,
final String grantee
) throws Exception {
expectStatusWhenDeletingPermissions(mockMvc, 204, credentialName, grantee,
grantorToken
);
}
public static void expectStatusWhenDeletingPermissions(
final MockMvc mockMvc,
final int status, final String credentialName,
final String grantee,
final String grantorToken) throws Exception {
expectErrorWhenDeletingPermissions(mockMvc, status, null, credentialName, grantorToken, grantee
);
}
public static void expectErrorWhenDeletingPermissions(
final MockMvc mockMvc,
final int status,
final String expectedErrorMessage,
final String credentialName,
final String grantorToken,
final String grantee
) throws Exception {
final ResultActions result = mockMvc.perform(
delete("/api/v1/permissions?" +
(credentialName == null ? "" : "credential_name=" + credentialName) +
(grantee == null ? "" : "&actor=" + grantee)
).header("Authorization", "Bearer " + grantorToken)
);
result.andExpect(status().is(status));
if (expectedErrorMessage != null) {
result.andExpect(jsonPath("$.error", equalTo(expectedErrorMessage)));
}
}
private static MockHttpServletRequestBuilder createAddPermissionsRequest(final String grantorToken,
final String credentialName,
final String grantee, final String... permissions) {
return post("/api/v1/permissions")
.header("Authorization", "Bearer " + grantorToken)
.accept(APPLICATION_JSON)
.contentType(APPLICATION_JSON)
.content("{"
+ " \"credential_name\": \"" + credentialName + "\",\n"
+ " \"permissions\": [\n"
+ " { \n"
+ " \"actor\": \"" + grantee + "\",\n"
+ " \"path\": \"" + credentialName + "\",\n"
+ " \"operations\": [\"" + join("\", \"", permissions) + "\"]\n"
+ " }]"
+ "}");
}
public static String regenerateCertificate(
final MockMvc mockMvc, final String uuid, final boolean transitional, final String token) throws Exception {
final MockHttpServletRequestBuilder regenerateRequest = post("/api/v1/certificates/" + uuid + "/regenerate")
.header("Authorization", "Bearer " + token)
.accept(APPLICATION_JSON)
.contentType(APPLICATION_JSON)
//language=JSON
.content("{\"set_as_transitional\" : " + transitional + "}");
return mockMvc.perform(regenerateRequest)
.andExpect(status().is2xxSuccessful())
.andReturn().getResponse().getContentAsString();
}
}
|
/*
* (C) Copyright IBM Corp. 2021
*
* SPDX-License-Identifier: Apache-2.0
*/
package com.ibm.fhir.database.utils.query;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;
import com.ibm.fhir.database.utils.query.expression.StringExpNodeVisitor;
import com.ibm.fhir.database.utils.query.node.ExpNode;
import com.ibm.fhir.database.utils.query.node.PredicateParser;
/**
* Test the {@link PredicateParser}
*/
public class PredicateParserTest {
@Test
public void expression1() {
PredicateParser pp = new PredicateParser();
pp.column("foo_id");
pp.eq();
pp.literal(1L);
pp.add();
pp.column("x");
ExpNode expression = pp.parse();
StringExpNodeVisitor visitor = new StringExpNodeVisitor();
String exprString = expression.visit(visitor);
assertEquals(exprString, "foo_id = 1 + x");
}
@Test
public void expressionParens() {
PredicateParser pp = new PredicateParser();
pp.column("foo_id");
pp.eq();
pp.leftParen();
pp.literal(1L);
pp.add();
pp.column("x");
pp.rightParen();
ExpNode expression = pp.parse();
StringExpNodeVisitor visitor = new StringExpNodeVisitor();
String exprString = expression.visit(visitor);
assertEquals(exprString, "foo_id = (1 + x)");
}
@Test
public void expressionLogic() {
PredicateParser pp = new PredicateParser();
pp.column("foo_id");
pp.eq();
pp.literal(1234L);
pp.and();
pp.column("foo_name");
pp.eq();
pp.column("other_name");
pp.or();
pp.column("something");
pp.eq();
pp.literal("blank");
ExpNode expression = pp.parse();
StringExpNodeVisitor visitor = new StringExpNodeVisitor();
String exprString = expression.visit(visitor);
assertEquals(exprString, "foo_id = 1234 AND foo_name = other_name OR something = 'blank'");
}
@Test
public void expressionLogicWithParen() {
PredicateParser pp = new PredicateParser();
pp.column("foo_id");
pp.eq();
pp.literal(1234L);
pp.and();
pp.leftParen();
pp.column("foo_name");
pp.eq();
pp.column("other_name");
pp.or();
pp.column("something");
pp.eq();
pp.literal("blank");
pp.rightParen();
ExpNode expression = pp.parse();
StringExpNodeVisitor visitor = new StringExpNodeVisitor();
String exprString = expression.visit(visitor);
assertEquals(exprString, "foo_id = 1234 AND (foo_name = other_name OR something = 'blank')");
}
}
|
/*
* 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.camel.component.mqtt;
import org.apache.camel.EndpointInject;
import org.apache.camel.LoggingLevel;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.Test;
/**
* Tests bridging between two mqtt topic using Camel
*/
public class MQTTBrigeTest extends MQTTBaseTest {
@EndpointInject(uri = "mock:result")
protected MockEndpoint resultEndpoint;
@Produce(uri = "direct:start")
protected ProducerTemplate template;
@Produce(uri = "direct:startWorkaround")
protected ProducerTemplate workaroundTemplate;
@Test
public void testMqttBridge() throws Exception {
String expectedBody = "Dummy!";
resultEndpoint.expectedBodiesReceived(expectedBody);
template.sendBody(expectedBody);
resultEndpoint.assertIsSatisfied();
}
@Test
public void testMqttBridgeWorkAround() throws Exception {
String expectedBody = "Dummy!";
resultEndpoint.expectedBodiesReceived(expectedBody);
workaroundTemplate.sendBody(expectedBody);
resultEndpoint.assertIsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
// Bridge message over two MQTT topics
from("direct:start").to("mqtt:foo?publishTopicName=test/topic1&lazySessionCreation=false&host=" + MQTTTestSupport.getHostForMQTTEndpoint());
from("mqtt:foo?subscribeTopicName=test/topic1&host=" + MQTTTestSupport.getHostForMQTTEndpoint()).to("log:testlogger?showAll=true")
.to("mqtt:foo?publishTopicName=test/resulttopic&lazySessionCreation=false&host=" + MQTTTestSupport.getHostForMQTTEndpoint())
.log(LoggingLevel.ERROR, "Message processed");
// Bridge message over two MQTT topics with a seda in between
from("direct:startWorkaround").to("mqtt:foo?publishTopicName=test/topic2&host=" + MQTTTestSupport.getHostForMQTTEndpoint());
from("mqtt:foo?subscribeTopicName=test/topic2&host=" + MQTTTestSupport.getHostForMQTTEndpoint()).to("log:testlogger?showAll=true")
.to("seda:a");
from("seda:a").to("mqtt:foo?publishTopicName=test/resulttopic&host=" + MQTTTestSupport.getHostForMQTTEndpoint())
.log(LoggingLevel.ERROR, "Message processed");
// Forward the result to a mock endpoint to test
from("mqtt:foo?subscribeTopicName=test/resulttopic&host=" + MQTTTestSupport.getHostForMQTTEndpoint()).to("mock:result");
}
};
}
}
|
package net.anweisen.cloud.driver.config.global;
import net.anweisen.cloud.driver.CloudDriver;
import net.anweisen.cloud.driver.config.global.objects.CommandObject;
import net.anweisen.utility.document.Document;
import javax.annotation.Nonnull;
import java.util.Collection;
/**
* @author anweisen | https://github.com/anweisen
* @since 1.0
*
* @see CloudDriver#getGlobalConfig()
*/
public interface GlobalConfig {
@Nonnull
Document getRawData();
@Nonnull
GlobalConfig setRawData(@Nonnull Document rawData);
default int getMaxPlayers() {
return getRawData().getInt("maxPlayers");
}
@Nonnull
default GlobalConfig setMaxPlayers(int maxPlayers) {
return set("maxPlayers", maxPlayers);
}
default boolean getMaintenance() {
return getRawData().getBoolean("maintenance");
}
@Nonnull
default GlobalConfig setMaintenance(boolean maintenance) {
return set("maintenance", maintenance);
}
@Nonnull
default Collection<CommandObject> getIngameCommands() {
return getRawData().getBundle("ingameCommands").toInstances(CommandObject.class);
}
@Nonnull
default GlobalConfig setIngameCommands(@Nonnull Collection<CommandObject> commands) {
return set("ingameCommands", commands);
}
@Nonnull
default GlobalConfig set(@Nonnull String path, @Nonnull Object value) {
getRawData().set(path, value);
return this;
}
default <T> T get(@Nonnull String path, @Nonnull Class<T> classOfT) {
return getRawData().getInstance(path, classOfT);
}
/**
* Synchronizes all global config instances with the properties of this instance
*/
void update();
/**
* Reloads this global config instance
*/
void fetch();
}
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2016 abel533@gmail.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 com.team.mybatis.common.base.select;
import org.apache.ibatis.annotations.SelectProvider;
import com.team.mybatis.provider.base.BaseSelectProvider;
/**
* 通用Mapper接口,查询
*
* @param <T> 不能为空
* @author liuzh
*/
public interface SelectOneMapper<T> {
/**
* 根据实体中的属性进行查询,只能有一个返回值,有多个结果是抛出异常,查询条件使用等号
*
* @param record
* @return
*/
@SelectProvider(type = BaseSelectProvider.class, method = "dynamicSQL")
T selectOne(T record);
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.fs.azure.security;
/**
* Constants for used with WASB security implementation.
*/
public final class Constants {
/**
* The configuration property to enable Kerberos support.
*/
public static final String AZURE_KERBEROS_SUPPORT_PROPERTY_NAME =
"fs.azure.enable.kerberos.support";
/**
* The configuration property to enable SPNEGO token cache.
*/
public static final String AZURE_ENABLE_SPNEGO_TOKEN_CACHE =
"fs.azure.enable.spnego.token.cache";
/**
* Parameter to be used for impersonation.
*/
public static final String DOAS_PARAM = "doas";
/**
* Error message for Authentication failures.
*/
public static final String AUTHENTICATION_FAILED_ERROR_MESSAGE =
"Authentication Failed ";
private Constants() {
}
}
|
package serenitymodel.net.thucydides.core.statistics.service;
import serenitymodel.net.thucydides.core.model.TestOutcome;
import serenitymodel.net.thucydides.core.model.TestTag;
import java.util.Set;
public interface TagProvider {
/**
* Returns the tags associated with a given test outcome.
* @param testOutcome the outcome for a specific test
* @return the tags associated with a given test outcome.
*/
Set<TestTag> getTagsFor(final TestOutcome testOutcome);
}
|
package net.glowstone.processor.block.data.annotations;
import org.bukkit.block.data.BlockData;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public @interface AssociatedWithProps {
PropertyAssociation[] props();
Class<? extends BlockData> interfaceClass();
}
|
package com.github.jespersm.proxynaut.example;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
@Controller("/")
public class AppController {
@Get(uri="/", produces=MediaType.TEXT_PLAIN)
public HttpResponse<String> index() {
return HttpResponse.ok("This is the root");
}
@Get(uri="/page1", produces=MediaType.TEXT_PLAIN)
public HttpResponse<String> page1() {
return HttpResponse.ok("This is page 1 of your app");
}
}
|
/**
* 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.jadice.jpeg2000.internal.image;
import org.jadice.jpeg2000.internal.image.DefaultGridRegion;
import org.jadice.jpeg2000.internal.image.Resolution;
import org.jadice.jpeg2000.internal.image.TileComponent;
public class TileComponentMock extends TileComponent {
public void setGridRegion(DefaultGridRegion gridElement) {
this.gridRegion = gridElement;
}
public void setResolutions(Resolution[] resolutions) {
this.resolutions = resolutions;
}
public void setNumResolutions(int numResolutions) {
this.dwtLevels = numResolutions - 1;
}
}
|
/*
* Copyright 2021 The University of Pennsylvania and Penn Medicine
*
* Originally created at the University of Pennsylvania and Penn Medicine by:
* Dr. David Asch; Dr. Lisa Bellini; Dr. Cecilia Livesey; Kelley Kugler; and Dr. Matthew Press.
*
* 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.cobaltplatform.api.integration.acuity.model;
import com.google.gson.annotations.SerializedName;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import javax.annotation.Nullable;
import javax.annotation.concurrent.NotThreadSafe;
/**
* @author Transmogrify, LLC.
*/
@NotThreadSafe
public class AcuityClass {
@Nullable
private Long id;
@Nullable
@SerializedName("appointmentTypeID")
private Long appointmentTypeId;
@Nullable
@SerializedName("calendarID")
private Long calendarId;
@Nullable
@SerializedName("serviceGroupID")
private Long serviceGroupId;
@Nullable
private String name;
@Nullable
private String time;
@Nullable
private String calendar;
@Nullable
private Long duration;
@Nullable
private Boolean isSeries;
@Nullable
private Long slots;
@Nullable
private Long slotsAvailable;
@Nullable
private String color;
@Nullable
private String price;
@Nullable
private String category;
@Nullable
private String description;
@Nullable
private String calendarTimezone;
@Nullable
private String localeTime;
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
@Nullable
public Long getId() {
return id;
}
public void setId(@Nullable Long id) {
this.id = id;
}
@Nullable
public Long getAppointmentTypeId() {
return appointmentTypeId;
}
public void setAppointmentTypeId(@Nullable Long appointmentTypeId) {
this.appointmentTypeId = appointmentTypeId;
}
@Nullable
public Long getCalendarId() {
return calendarId;
}
public void setCalendarId(@Nullable Long calendarId) {
this.calendarId = calendarId;
}
@Nullable
public Long getServiceGroupId() {
return serviceGroupId;
}
public void setServiceGroupId(@Nullable Long serviceGroupId) {
this.serviceGroupId = serviceGroupId;
}
@Nullable
public String getName() {
return name;
}
public void setName(@Nullable String name) {
this.name = name;
}
@Nullable
public String getTime() {
return time;
}
public void setTime(@Nullable String time) {
this.time = time;
}
@Nullable
public String getCalendar() {
return calendar;
}
public void setCalendar(@Nullable String calendar) {
this.calendar = calendar;
}
@Nullable
public Long getDuration() {
return duration;
}
public void setDuration(@Nullable Long duration) {
this.duration = duration;
}
@Nullable
public Boolean getSeries() {
return isSeries;
}
public void setSeries(@Nullable Boolean series) {
isSeries = series;
}
@Nullable
public Long getSlots() {
return slots;
}
public void setSlots(@Nullable Long slots) {
this.slots = slots;
}
@Nullable
public Long getSlotsAvailable() {
return slotsAvailable;
}
public void setSlotsAvailable(@Nullable Long slotsAvailable) {
this.slotsAvailable = slotsAvailable;
}
@Nullable
public String getColor() {
return color;
}
public void setColor(@Nullable String color) {
this.color = color;
}
@Nullable
public String getPrice() {
return price;
}
public void setPrice(@Nullable String price) {
this.price = price;
}
@Nullable
public String getCategory() {
return category;
}
public void setCategory(@Nullable String category) {
this.category = category;
}
@Nullable
public String getDescription() {
return description;
}
public void setDescription(@Nullable String description) {
this.description = description;
}
@Nullable
public String getCalendarTimezone() {
return calendarTimezone;
}
public void setCalendarTimezone(@Nullable String calendarTimezone) {
this.calendarTimezone = calendarTimezone;
}
@Nullable
public String getLocaleTime() {
return localeTime;
}
public void setLocaleTime(@Nullable String localeTime) {
this.localeTime = localeTime;
}
}
|
package com.opzpy123.product.controller;
import java.util.Arrays;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.opzpy123.product.entity.SpuInfoEntity;
import com.opzpy123.product.service.SpuInfoService;
import com.opzpy123.common.utils.PageUtils;
import com.opzpy123.common.utils.R;
/**
* spu信息
*
* @author opzpy123
* @email 1441120973@qq.com
* @date 2021-01-09 19:08:16
*/
@RestController
@RequestMapping("product/spuinfo")
public class SpuInfoController {
@Autowired
private SpuInfoService spuInfoService;
/**
* 列表
*/
@RequestMapping("/list")
//@RequiresPermissions("product:spuinfo:list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = spuInfoService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 信息
*/
@RequestMapping("/info/{id}")
//@RequiresPermissions("product:spuinfo:info")
public R info(@PathVariable("id") Long id){
SpuInfoEntity spuInfo = spuInfoService.getById(id);
return R.ok().put("spuInfo", spuInfo);
}
/**
* 保存
*/
@RequestMapping("/save")
//@RequiresPermissions("product:spuinfo:save")
public R save(@RequestBody SpuInfoEntity spuInfo){
spuInfoService.save(spuInfo);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
//@RequiresPermissions("product:spuinfo:update")
public R update(@RequestBody SpuInfoEntity spuInfo){
spuInfoService.updateById(spuInfo);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
//@RequiresPermissions("product:spuinfo:delete")
public R delete(@RequestBody Long[] ids){
spuInfoService.removeByIds(Arrays.asList(ids));
return R.ok();
}
}
|
package searchingAndSorting;
public class BubbleSorting {
public static void main(String[] args) {
int[] arr = {3,84,15,9,2};
int n = arr.length;
for(int i = 0;i<n-1;i++) {
for(int j = 0;j<n-i-1;j++) {
if(arr[j] < arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
for(int i = 0;i<n;i++) {
System.out.println(arr[i]+" ");
}
}
}
|
package com.kuaiyou.utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.widget.AppCompatTextView;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.kuaiyou.interfaces.KyInstalListener;
import com.kuaiyou.interfaces.KyViewListener;
import com.kuaiyou.mraid.MRAIDView;
import com.kuaiyou.mraid.interfaces.MRAIDNativeFeatureListener;
import com.kuaiyou.mraid.interfaces.MRAIDViewListener;
import com.kuaiyou.obj.AdsBean;
import com.kuaiyou.utils.AdViewUtils;
import com.kuaiyou.utils.ConstantValues;
import java.lang.ref.SoftReference;
import java.util.HashMap;
public class InstlView extends RelativeLayout implements View.OnTouchListener {
private double density = 2.0;
private float scaledDensity;
private int padding = 4;
private SoftReference<Bitmap> titleBitmap;
private int titleHeight;
private Paint backgroudPaint;
private float downX, downY;
private HashMap<String, Integer> sizeMap;
private KyInstalListener instlViewListener;
private Matrix matrix;
private Rect rect;
private int adType;
private int screenSize[];
public InstlView(Context context, HashMap<String, Integer> sizeMap, MRAIDNativeFeatureListener nativeFeatureListener, MRAIDViewListener mraidViewListener) {
this(context, sizeMap, ConstantValues.HTML, nativeFeatureListener, mraidViewListener);
}
public InstlView(Context context, HashMap<String, Integer> sizeMap, int adType, MRAIDNativeFeatureListener nativeFeatureListener, MRAIDViewListener mraidViewListener) {
super(context);
setWillNotDraw(false);
this.setBackgroundColor(Color.WHITE);
this.adType = adType;
try {
this.sizeMap = sizeMap;
screenSize = AdViewUtils.getWidthAndHeight(context, false, true);
if (adType == ConstantValues.MIXED) {
titleBitmap = new SoftReference<Bitmap>(new BitmapDrawable(getResources(),
AdViewUtils.getImageFromAssetsFile("mixed_bg.jpg")).getBitmap());
// titleBitmap = new SoftReference<Bitmap>(BitmapFactory.decodeStream(getClass()
// .getResourceAsStream(ConstantValues.WEBVIEW_IMAGE_BASE_PATH + "mixed_bg.jpg")));
if (null != titleBitmap || null != titleBitmap.get()) {
matrix = new Matrix();
float scale = (float) sizeMap.get(ConstantValues.INSTLWIDTH) / (float) titleBitmap.get().getWidth();
titleHeight = (int) (titleBitmap.get().getHeight() * scale);
matrix.setScale(scale, scale);
}
backgroudPaint = new Paint();
backgroudPaint.setColor(Color.parseColor("#ece8e5"));
}
padding = (int) (padding * density);
initLayout(adType, nativeFeatureListener, mraidViewListener);
density = AdViewUtils.getDensity(getContext());
scaledDensity = AdViewUtils.getScaledDensity(getContext());
} catch (Exception e) {
e.printStackTrace();
}
}
public void setInstlViewListener(KyInstalListener instlViewListener) {
this.instlViewListener = instlViewListener;
}
@Override
protected void onWindowVisibilityChanged(int visibility) {
super.onWindowVisibilityChanged(visibility);
if (null != instlViewListener)
instlViewListener.onVisiblityChange(visibility);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
measureChildren(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(sizeMap.get(ConstantValues.INSTLWIDTH), sizeMap.get(ConstantValues.INSTLHEIGHT));
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
try {
int instlWidth = sizeMap.get(ConstantValues.INSTLWIDTH), instlHeight = sizeMap.get(ConstantValues.INSTLHEIGHT);
if (titleHeight == 0)
titleHeight = instlHeight / 3;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
switch (child.getId()) {
case ConstantValues.TITLEID:
child.layout(titleHeight, titleHeight / 6, instlWidth - titleHeight / 4, (titleHeight / 2));
break;
case ConstantValues.SUBTITLEID:
child.layout(titleHeight, (titleHeight / 2), instlWidth - titleHeight / 4, titleHeight / 6 * 5);
break;
case ConstantValues.DESCRIPTTEXTID:
child.layout(titleHeight / 5, titleHeight / 6 * 7, instlWidth - titleHeight / 5, instlHeight - (instlWidth / 5) - (titleHeight / 5));
break;
case ConstantValues.BEHAVICONID:
child.layout(instlWidth / 3, instlHeight - (instlWidth / 5), instlWidth / 3 * 2, instlHeight - (instlWidth / 5) + (instlWidth / 10));
break;
case ConstantValues.ICONID:
child.layout(titleHeight / 6, titleHeight / 6, titleHeight / 6 * 5, titleHeight / 6 * 5);
break;
case ConstantValues.ADLOGOID:
child.layout(instlWidth - (instlWidth / 8), instlHeight - (instlWidth / 25), instlWidth, instlHeight);
break;
case ConstantValues.ADICONID:
child.layout(0, instlHeight - (instlWidth / 25), (instlWidth / 8), instlHeight);
break;
case ConstantValues.CLOSEBTNID:
try {
if (null == screenSize)
screenSize = AdViewUtils.getWidthAndHeight(getContext(), false, true);
if (null == screenSize)
screenSize = new int[]{1080, 1920};
if (screenSize[0] == 0) {
screenSize[0] = 1080;
screenSize[1] = 1920;
}
child.layout(instlWidth - screenSize[0] / 14, padding, instlWidth - padding, screenSize[0] / 14);
} catch (Exception e) {
e.printStackTrace();
}
// else
// child.layout(instlWidth - titleHeight / 3, padding, instlWidth - padding, titleHeight / 3);
break;
case ConstantValues.WEBVIEWID:
// child.getLayoutParams().width = instlWidth;
// child.getLayoutParams().height = instlHeight;
case ConstantValues.MRAIDVIEWID:
child.layout(0, 0, instlWidth, instlHeight);
// ((MRAIDView) child).setLayoutParmas(instlWidth, instlHeight);
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
try {
if (adType != ConstantValues.MIXED)
return;
if (null != backgroudPaint) {
if (rect == null)
rect = new Rect(0, 0, sizeMap.get(ConstantValues.INSTLWIDTH), sizeMap.get(ConstantValues.INSTLHEIGHT));
canvas.drawRect(rect, backgroudPaint);
}
if (null != titleBitmap && null != titleBitmap.get())
canvas.drawBitmap(titleBitmap.get(), matrix, null);
} catch (Exception e) {
e.printStackTrace();
}
}
private void initLayout(int adType, MRAIDNativeFeatureListener nativeFeatureListener, MRAIDViewListener mraidViewListener) {
ImageView closeBtn = new ImageView(getContext());
ImageView adLogo = new ImageView(getContext());
ImageView adIcon = new ImageView(getContext());
if (adType == ConstantValues.MIXED) {
ImageView icon = new ImageView(getContext());
TextView title = new TextView(getContext());
TextView subTitle = new TextView(getContext());
TextView descript = new TextView(getContext());
CenterTextView behaveBtn = new CenterTextView(getContext());
title.setId(ConstantValues.TITLEID);
subTitle.setId(ConstantValues.SUBTITLEID);
descript.setId(ConstantValues.DESCRIPTTEXTID);
behaveBtn.setId(ConstantValues.BEHAVICONID);
icon.setId(ConstantValues.ICONID);
title.setTextColor(Color.WHITE);
subTitle.setTextColor(Color.WHITE);
descript.setTextColor(Color.BLACK);
behaveBtn.setTextColor(Color.WHITE);
behaveBtn.setBackgroundDrawable(AdViewUtils.getColorDrawable(getContext(), "#2c91a6"));
addView(icon);
addView(behaveBtn);
addView(title);
addView(subTitle);
addView(descript);
} else {
MRAIDView mraidView = new MRAIDView(getContext(), nativeFeatureListener, mraidViewListener, true, sizeMap.get(ConstantValues.INSTLWIDTH), sizeMap.get(ConstantValues.INSTLHEIGHT));
WebView webView = mraidView.getMraidWebView();
mraidView.setId(ConstantValues.MRAIDVIEWID);
webView.setId(ConstantValues.WEBVIEWID);
addView(mraidView);
}
adLogo.setId(ConstantValues.ADLOGOID);
adIcon.setId(ConstantValues.ADICONID);
closeBtn.setId(ConstantValues.CLOSEBTNID);
addView(closeBtn);
addView(adLogo);
addView(adIcon);
adIcon.setScaleType(ImageView.ScaleType.FIT_START);
adLogo.setScaleType(ImageView.ScaleType.FIT_END);
closeBtn.setOnTouchListener(this);
setOnTouchListener(this);
}
public void setActionBtnText(int adAction) {
try {
CenterTextView iBtn = (CenterTextView) findViewById(ConstantValues.BEHAVICONID);
if (null != iBtn) {
switch (adAction) {
case ConstantValues.ACT_DOWNLOAD:
iBtn.text = ("免费下载");
break;
case ConstantValues.ACT_OPENWEB:
iBtn.text = ("免费查看");
break;
default:
iBtn.text = ("免费查看");
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void setContent(AdsBean adsBean, String imagePath) {
try {
switch (adsBean.getAdType()) {
case ConstantValues.MIXED:
ImageView icon = (ImageView) findViewById(ConstantValues.ICONID);
TextView title = (TextView) findViewById(ConstantValues.TITLEID);
TextView subTitle = (TextView) findViewById(ConstantValues.SUBTITLEID);
TextView description = (TextView) findViewById(ConstantValues.DESCRIPTTEXTID);
if (null != imagePath) {
icon.setImageDrawable(new BitmapDrawable(getResources(), getClass().getResourceAsStream(imagePath)));
}
if (!TextUtils.isEmpty(adsBean.getAdTitle()))
title.setText(adsBean.getAdTitle());
if (!TextUtils.isEmpty(adsBean.getAdSubTitle()))
subTitle.setText(adsBean.getAdSubTitle());
if (!TextUtils.isEmpty(adsBean.getAdText()))
description.setText(adsBean.getAdText());
setActionBtnText(adsBean.getAdAct());
setTextSize();
invalidate();
break;
}
if (null != instlViewListener) {
if (instlViewListener.getCloseble())
setCloseBtn();
}
if (null != instlViewListener) {
setAdLogo(0, instlViewListener.getAdLogo());
setAdLogo(1, instlViewListener.getAdIcon());
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void setCloseBtn() {
try {
ImageView view = (ImageView) findViewById(ConstantValues.CLOSEBTNID);
if (null != view) {
String resoursePath = ConstantValues.WEBVIEW_IMAGE_BASE_PATH + "close_ad_btn.png";
//if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
Bitmap bm = AdViewUtils.getImageFromAssetsFile("close_ad_btn.png");
view.setImageDrawable(new BitmapDrawable(this.getResources(), bm));
//view.setImageDrawable(new BitmapDrawable(this.getResources(), getClass().getResourceAsStream(resoursePath)));
// }
// else {
// view.setImageDrawable(new BitmapDrawable(this.getResources(), getClass().getResourceAsStream(resoursePath)));
// }
}
} catch (Exception e) {
e.printStackTrace();
try {
findViewById(ConstantValues.CLOSEBTNID).setBackgroundColor(Color.GRAY);
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
private void setAdLogo(int isLogo, String path) {
ImageView view;
try {
if (null == path)
return;
if (isLogo == 0)
view = (ImageView) findViewById(ConstantValues.ADLOGOID);
else
view = (ImageView) findViewById(ConstantValues.ADICONID);
if (TextUtils.isEmpty(path))
return;
if (path.startsWith("/assets")) {
//wilder load assets file
Bitmap bm = AdViewUtils.getImageFromAssetsFile(path.replace("/assets/", ""));
view.setImageDrawable(new BitmapDrawable(this.getResources(), bm));
//view.setImageDrawable(new BitmapDrawable(this.getResources(), getClass().getResourceAsStream(path)));
}
else {
view.setImageDrawable(new BitmapDrawable(this.getResources(), path));
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void setTextSize() {
try {
TextView title = (TextView) findViewById(ConstantValues.TITLEID);
TextView subTitle = (TextView) findViewById(ConstantValues.SUBTITLEID);
TextView content = (TextView) findViewById(ConstantValues.DESCRIPTTEXTID);
CenterTextView clickBtn = (CenterTextView) findViewById(ConstantValues.BEHAVICONID);
if (density <= 1.5) {
title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
subTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
content.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
clickBtn.textSize = (int) (14 * scaledDensity);//(TypedValue.COMPLEX_UNIT_SP, 14);
} else if (density == 2) {
title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 17);
subTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
content.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
clickBtn.textSize = (int) (15 * scaledDensity);//(TypedValue.COMPLEX_UNIT_SP, 15);
} else if (density == 3) {
title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
subTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 17);
content.setTextSize(TypedValue.COMPLEX_UNIT_SP, 17);
clickBtn.textSize = (int) (16 * scaledDensity);//(TypedValue.COMPLEX_UNIT_SP, 16);
} else if (density >= 4) {
title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 19);
subTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
content.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
clickBtn.textSize = (int) (17 * scaledDensity);//(TypedValue.COMPLEX_UNIT_SP, 17);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public MRAIDView getMraidView() {
return (MRAIDView) findViewById(ConstantValues.MRAIDVIEWID);
}
public WebView getWebView() {
return (WebView) findViewById(ConstantValues.WEBVIEWID);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
downX = event.getX();
downY = event.getY();
break;
case MotionEvent.ACTION_UP:
if (Math.abs(event.getX() - downX) < padding * padding / 2 && Math.abs(event.getY() - downY) < padding * padding / 2 && event.getEventTime() - event.getDownTime() < 1000) {
int instlWidth = sizeMap.get(ConstantValues.INSTLWIDTH);
int instlHeight = sizeMap.get(ConstantValues.INSTLHEIGHT);
if (v.getId() == ConstantValues.CLOSEBTNID) {
if (null != instlViewListener)
instlViewListener.onCloseBtnClicked();
} else if (event.getX() < instlWidth && event.getY() > instlHeight / 3 * 2) {
if (adType == ConstantValues.MIXED) {
if (null != instlViewListener)
instlViewListener.onViewClicked(event, null,null, event.getX(), event.getY());
}
}
}
break;
}
return true;
}
public static class CenterTextView extends /*TextView*/ AppCompatTextView {
public String text;
private String[] multiLineStr;
public int textSize;
private TextPaint mPaint;
private Rect mBound;
private float startX, startY;
private int color;
public CenterTextView(Context context) {
super(context);
}
public void setTextColor(int color) {
this.color = color;
}
/**
* 最大支持3行
*
* @param maxSize
* @return
*/
private Rect measureTextSize(int maxSize) {
Rect mBound = new Rect();
try {
int[] line = new int[3];
int lineCount = 0;
mPaint.getTextBounds(text, 0, text.length(), mBound);
if (mBound.width() < maxSize) {
return mBound;
} else {
for (int i = 0; i < text.length(); i++) {
mPaint.getTextBounds(text, line[(lineCount - 1) < 0 ? 0 : lineCount - 1], i + 1, mBound);
if (mBound.width() < maxSize)
continue;
else {
if (lineCount == 2)
continue;
line[lineCount] = i + 1;
lineCount++;
}
}
multiLineStr = new String[lineCount + 1];
if (lineCount == 1) {
multiLineStr[0] = text.substring(0, line[0] - 1);
multiLineStr[1] = text.substring(line[0] - 1, text.length());
} else if (lineCount == 2) {
multiLineStr[0] = text.substring(0, line[0] - 1);
multiLineStr[1] = text.substring(line[0] - 1, line[1] - 1);
multiLineStr[2] = text.substring(line[1] - 1, text.length());
}
mPaint.getTextBounds(multiLineStr[0], 0, multiLineStr[0].length(), mBound);
}
} catch (Exception e) {
e.printStackTrace();
}
return mBound;
}
private void initCenterSize(int maxWidth) {
mBound = new Rect();
mPaint = new TextPaint();
mPaint.setColor(color);
mPaint.setAntiAlias(true);
mPaint.setStyle(Paint.Style.FILL);
mPaint.setTextSize(textSize);
mBound = measureTextSize(maxWidth);
Paint.FontMetricsInt fm = mPaint.getFontMetricsInt();
startX = getWidth() / 2 - mBound.width() / 2;
startY = getHeight() / 2 - fm.descent + (fm.descent - fm.ascent) / 2;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
try {
if (!TextUtils.isEmpty(text)) {
initCenterSize(canvas.getWidth());
/*
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
//paint.setStrokeWidth(3);
//paint.setTextSize(80);
//String testString = "测试:ijkJQKA:1234";
paint.setColor(Color.CYAN);
canvas.drawRect(mBound, paint);
*/
if (null != multiLineStr) {
if (multiLineStr.length == 2) {
canvas.drawText(multiLineStr[0], startX, (float) (startY - 0.5f * ((float) mBound.height() * 1.5)), mPaint);
canvas.drawText(multiLineStr[1], startX, (float) (startY + 0.5f * ((float) mBound.height() * 1.5)), mPaint);
} else if (multiLineStr.length == 3) {
canvas.drawText(multiLineStr[0], startX, (float) (startY - ((float) mBound.height() * 1.5)), mPaint);
canvas.drawText(multiLineStr[1], startX, (float) (startY), mPaint);
canvas.drawText(multiLineStr[2], startX, (float) (startY + ((float) mBound.height() * 1.5)), mPaint);
}
} else {
canvas.drawText(text, startX, startY, mPaint);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by jextract
package org.apache.tomcat.util.openssl;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.VarHandle;
import java.nio.ByteOrder;
import jdk.incubator.foreign.*;
import static jdk.incubator.foreign.CLinker.*;
class constants$3 {
static final FunctionDescriptor BN_get_rfc2409_prime_768$FUNC = FunctionDescriptor.of(C_POINTER,
C_POINTER
);
static final MethodHandle BN_get_rfc2409_prime_768$MH = RuntimeHelper.downcallHandle(
openssl_h.LIBRARIES, "BN_get_rfc2409_prime_768",
"(Ljdk/incubator/foreign/MemoryAddress;)Ljdk/incubator/foreign/MemoryAddress;",
constants$3.BN_get_rfc2409_prime_768$FUNC, false
);
static final FunctionDescriptor BN_get_rfc2409_prime_1024$FUNC = FunctionDescriptor.of(C_POINTER,
C_POINTER
);
static final MethodHandle BN_get_rfc2409_prime_1024$MH = RuntimeHelper.downcallHandle(
openssl_h.LIBRARIES, "BN_get_rfc2409_prime_1024",
"(Ljdk/incubator/foreign/MemoryAddress;)Ljdk/incubator/foreign/MemoryAddress;",
constants$3.BN_get_rfc2409_prime_1024$FUNC, false
);
static final FunctionDescriptor BN_get_rfc3526_prime_1536$FUNC = FunctionDescriptor.of(C_POINTER,
C_POINTER
);
static final MethodHandle BN_get_rfc3526_prime_1536$MH = RuntimeHelper.downcallHandle(
openssl_h.LIBRARIES, "BN_get_rfc3526_prime_1536",
"(Ljdk/incubator/foreign/MemoryAddress;)Ljdk/incubator/foreign/MemoryAddress;",
constants$3.BN_get_rfc3526_prime_1536$FUNC, false
);
static final FunctionDescriptor BN_get_rfc3526_prime_2048$FUNC = FunctionDescriptor.of(C_POINTER,
C_POINTER
);
static final MethodHandle BN_get_rfc3526_prime_2048$MH = RuntimeHelper.downcallHandle(
openssl_h.LIBRARIES, "BN_get_rfc3526_prime_2048",
"(Ljdk/incubator/foreign/MemoryAddress;)Ljdk/incubator/foreign/MemoryAddress;",
constants$3.BN_get_rfc3526_prime_2048$FUNC, false
);
static final FunctionDescriptor BN_get_rfc3526_prime_3072$FUNC = FunctionDescriptor.of(C_POINTER,
C_POINTER
);
static final MethodHandle BN_get_rfc3526_prime_3072$MH = RuntimeHelper.downcallHandle(
openssl_h.LIBRARIES, "BN_get_rfc3526_prime_3072",
"(Ljdk/incubator/foreign/MemoryAddress;)Ljdk/incubator/foreign/MemoryAddress;",
constants$3.BN_get_rfc3526_prime_3072$FUNC, false
);
static final FunctionDescriptor BN_get_rfc3526_prime_4096$FUNC = FunctionDescriptor.of(C_POINTER,
C_POINTER
);
static final MethodHandle BN_get_rfc3526_prime_4096$MH = RuntimeHelper.downcallHandle(
openssl_h.LIBRARIES, "BN_get_rfc3526_prime_4096",
"(Ljdk/incubator/foreign/MemoryAddress;)Ljdk/incubator/foreign/MemoryAddress;",
constants$3.BN_get_rfc3526_prime_4096$FUNC, false
);
}
|
/*-
* #%L
* utils-commons
* %%
* Copyright (C) 2016 - 2018 Gilles Landel
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package fr.landel.utils.commons.function;
import java.util.function.Supplier;
import fr.landel.utils.commons.tuple.Nona;
/**
* Represents a supplier of nine results.
*
* <p>
* There is no requirement that a new or distinct result be returned each time
* the supplier is invoked.
*
* <p>
* This is a <a href="package-summary.html">functional interface</a> whose
* functional method is {@link #get()}.
*
* @since Nov 16, 2017
* @author Gilles
*
* @param <A>
* The first type result
* @param <B>
* The second type result
* @param <C>
* The third type result
* @param <D>
* The fourth type result
* @param <E>
* the fifth argument type
* @param <F>
* the sixth argument type
* @param <G>
* the seventh argument type
* @param <H>
* the eighth argument type
* @param <I>
* the ninth argument type
*/
@FunctionalInterface
public interface NonaSupplier<A, B, C, D, E, F, G, H, I> extends Supplier<Nona<A, B, C, D, E, F, G, H, I>> {
}
|
// Copyright 2015 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.actions.util;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.truth.Truth.assertThat;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Streams;
import com.google.common.eventbus.EventBus;
import com.google.devtools.build.lib.actions.AbstractAction;
import com.google.devtools.build.lib.actions.Action;
import com.google.devtools.build.lib.actions.ActionAnalysisMetadata;
import com.google.devtools.build.lib.actions.ActionExecutionContext;
import com.google.devtools.build.lib.actions.ActionExecutionContext.LostInputsCheck;
import com.google.devtools.build.lib.actions.ActionGraph;
import com.google.devtools.build.lib.actions.ActionInput;
import com.google.devtools.build.lib.actions.ActionInputHelper;
import com.google.devtools.build.lib.actions.ActionInputPrefetcher;
import com.google.devtools.build.lib.actions.ActionKeyContext;
import com.google.devtools.build.lib.actions.ActionLookupData;
import com.google.devtools.build.lib.actions.ActionLookupValue;
import com.google.devtools.build.lib.actions.ActionLookupValue.ActionLookupKey;
import com.google.devtools.build.lib.actions.ActionOwner;
import com.google.devtools.build.lib.actions.ActionResult;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.Artifact.ArtifactExpander;
import com.google.devtools.build.lib.actions.Artifact.SpecialArtifact;
import com.google.devtools.build.lib.actions.Artifact.TreeFileArtifact;
import com.google.devtools.build.lib.actions.ArtifactOwner;
import com.google.devtools.build.lib.actions.ArtifactResolver;
import com.google.devtools.build.lib.actions.ArtifactRoot;
import com.google.devtools.build.lib.actions.Executor;
import com.google.devtools.build.lib.actions.FileArtifactValue;
import com.google.devtools.build.lib.actions.FileArtifactValue.RemoteFileArtifactValue;
import com.google.devtools.build.lib.actions.MutableActionGraph;
import com.google.devtools.build.lib.actions.MutableActionGraph.ActionConflictException;
import com.google.devtools.build.lib.actions.PackageRootResolver;
import com.google.devtools.build.lib.actions.cache.MetadataHandler;
import com.google.devtools.build.lib.actions.cache.Protos.ActionCacheStatistics.MissDetail;
import com.google.devtools.build.lib.actions.cache.Protos.ActionCacheStatistics.MissReason;
import com.google.devtools.build.lib.analysis.actions.CustomCommandLine;
import com.google.devtools.build.lib.analysis.actions.SpawnActionTemplate;
import com.google.devtools.build.lib.analysis.actions.SpawnActionTemplate.OutputPathMapper;
import com.google.devtools.build.lib.analysis.configuredtargets.RuleConfiguredTarget;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.cmdline.RepositoryName;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.collect.nestedset.NestedSetExpander;
import com.google.devtools.build.lib.collect.nestedset.Order;
import com.google.devtools.build.lib.events.EventHandler;
import com.google.devtools.build.lib.events.ExtendedEventHandler;
import com.google.devtools.build.lib.events.Reporter;
import com.google.devtools.build.lib.exec.SingleBuildFileCache;
import com.google.devtools.build.lib.packages.AspectDescriptor;
import com.google.devtools.build.lib.skyframe.serialization.autocodec.AutoCodec;
import com.google.devtools.build.lib.util.FileType;
import com.google.devtools.build.lib.util.Fingerprint;
import com.google.devtools.build.lib.util.ResourceUsage;
import com.google.devtools.build.lib.util.io.FileOutErr;
import com.google.devtools.build.lib.vfs.FileStatus;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.build.lib.vfs.Root;
import com.google.devtools.build.lib.vfs.inmemoryfs.InMemoryFileSystem;
import com.google.devtools.build.skyframe.AbstractSkyFunctionEnvironment;
import com.google.devtools.build.skyframe.BuildDriver;
import com.google.devtools.build.skyframe.ErrorInfo;
import com.google.devtools.build.skyframe.EvaluationContext;
import com.google.devtools.build.skyframe.EvaluationResult;
import com.google.devtools.build.skyframe.SkyFunction;
import com.google.devtools.build.skyframe.SkyFunctionName;
import com.google.devtools.build.skyframe.SkyKey;
import com.google.devtools.build.skyframe.SkyValue;
import com.google.devtools.build.skyframe.ValueOrUntypedException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
/**
* A bunch of utilities that are useful for test concerning actions, artifacts,
* etc.
*/
public final class ActionsTestUtil {
private final ActionGraph actionGraph;
public ActionsTestUtil(ActionGraph actionGraph) {
this.actionGraph = actionGraph;
}
private static final Label NULL_LABEL = Label.parseAbsoluteUnchecked("//null/action:owner");
public static ActionExecutionContext createContext(
Executor executor,
ExtendedEventHandler eventHandler,
ActionKeyContext actionKeyContext,
FileOutErr fileOutErr,
Path execRoot,
MetadataHandler metadataHandler,
@Nullable ActionGraph actionGraph) {
return createContext(
executor,
eventHandler,
actionKeyContext,
fileOutErr,
execRoot,
metadataHandler,
ImmutableMap.of(),
actionGraph);
}
public static ActionExecutionContext createContext(
Executor executor,
ExtendedEventHandler eventHandler,
ActionKeyContext actionKeyContext,
FileOutErr fileOutErr,
Path execRoot,
MetadataHandler metadataHandler,
Map<String, String> clientEnv,
@Nullable ActionGraph actionGraph) {
return new ActionExecutionContext(
executor,
new SingleBuildFileCache(execRoot.getPathString(), execRoot.getFileSystem()),
ActionInputPrefetcher.NONE,
actionKeyContext,
metadataHandler,
/*rewindingEnabled=*/ false,
LostInputsCheck.NONE,
fileOutErr,
eventHandler,
ImmutableMap.copyOf(clientEnv),
/*topLevelFilesets=*/ ImmutableMap.of(),
actionGraph == null
? createDummyArtifactExpander()
: ActionInputHelper.actionGraphArtifactExpander(actionGraph),
/*actionFileSystem=*/ null,
/*skyframeDepsResult=*/ null,
NestedSetExpander.DEFAULT);
}
public static ActionExecutionContext createContext(ExtendedEventHandler eventHandler) {
DummyExecutor dummyExecutor = new DummyExecutor();
return new ActionExecutionContext(
dummyExecutor,
/*actionInputFileCache=*/ null,
ActionInputPrefetcher.NONE,
new ActionKeyContext(),
/*metadataHandler=*/ null,
/*rewindingEnabled=*/ false,
LostInputsCheck.NONE,
/*fileOutErr=*/ null,
eventHandler,
/*clientEnv=*/ ImmutableMap.of(),
/*topLevelFilesets=*/ ImmutableMap.of(),
createDummyArtifactExpander(),
/*actionFileSystem=*/ null,
/*skyframeDepsResult=*/ null,
NestedSetExpander.DEFAULT);
}
public static ActionExecutionContext createContextForInputDiscovery(
Executor executor,
ExtendedEventHandler eventHandler,
ActionKeyContext actionKeyContext,
FileOutErr fileOutErr,
Path execRoot,
MetadataHandler metadataHandler,
BuildDriver buildDriver,
NestedSetExpander nestedSetExpander) {
return ActionExecutionContext.forInputDiscovery(
executor,
new SingleBuildFileCache(execRoot.getPathString(), execRoot.getFileSystem()),
ActionInputPrefetcher.NONE,
actionKeyContext,
metadataHandler,
/*rewindingEnabled=*/ false,
LostInputsCheck.NONE,
fileOutErr,
eventHandler,
ImmutableMap.of(),
new BlockingSkyFunctionEnvironment(buildDriver, eventHandler),
/*actionFileSystem=*/ null,
nestedSetExpander);
}
private static ArtifactExpander createDummyArtifactExpander() {
return new ArtifactExpander() {
@Override
public void expand(Artifact artifact, Collection<? super Artifact> output) {
return;
}
};
}
public static Artifact createArtifact(ArtifactRoot root, Path path) {
return createArtifactWithRootRelativePath(root, root.getRoot().relativize(path));
}
public static Artifact createArtifact(ArtifactRoot root, String path) {
return createArtifactWithRootRelativePath(root, PathFragment.create(path));
}
public static Artifact createArtifactWithRootRelativePath(
ArtifactRoot root, PathFragment rootRelativePath) {
PathFragment execPath = root.getExecPath().getRelative(rootRelativePath);
return createArtifactWithExecPath(root, execPath);
}
public static Artifact createArtifactWithExecPath(ArtifactRoot root, PathFragment execPath) {
return root.isSourceRoot()
? new Artifact.SourceArtifact(root, execPath, ArtifactOwner.NullArtifactOwner.INSTANCE)
: new Artifact.DerivedArtifact(root, execPath, NULL_ARTIFACT_OWNER);
}
public static TreeFileArtifact createTreeFileArtifactWithNoGeneratingAction(
SpecialArtifact parent, String relativePath) {
return ActionInputHelper.treeFileArtifactWithNoGeneratingActionSet(
parent, PathFragment.create(relativePath), parent.getArtifactOwner());
}
public static void assertNoArtifactEndingWith(RuleConfiguredTarget target, String path) {
Pattern endPattern = Pattern.compile(path + "$");
for (ActionAnalysisMetadata action : target.getActions()) {
for (Artifact output : action.getOutputs()) {
assertThat(output.getExecPathString()).doesNotMatch(endPattern);
}
}
}
public static ArtifactRoot createArtifactRootFromTwoPaths(Path root, Path execPath) {
return ArtifactRoot.asDerivedRoot(
root, execPath.relativeTo(root).getSegments().toArray(new String[0]));
}
/**
* {@link SkyFunction.Environment} that internally makes a full Skyframe evaluate call for the
* requested keys, blocking until the values are ready.
*/
private static class BlockingSkyFunctionEnvironment extends AbstractSkyFunctionEnvironment {
private final BuildDriver driver;
private final EventHandler eventHandler;
private BlockingSkyFunctionEnvironment(BuildDriver driver, EventHandler eventHandler) {
this.driver = driver;
this.eventHandler = eventHandler;
}
@Override
protected Map<SkyKey, ValueOrUntypedException> getValueOrUntypedExceptions(
Iterable<? extends SkyKey> depKeys) {
EvaluationResult<SkyValue> evaluationResult;
Map<SkyKey, ValueOrUntypedException> result = new HashMap<>();
try {
EvaluationContext evaluationContext =
EvaluationContext.newBuilder()
.setKeepGoing(false)
.setNumThreads(ResourceUsage.getAvailableProcessors())
.setEventHander(new Reporter(new EventBus(), eventHandler))
.build();
evaluationResult = driver.evaluate(depKeys, evaluationContext);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
for (SkyKey key : depKeys) {
result.put(key, ValueOrUntypedException.ofNull());
}
return result;
}
for (SkyKey key : depKeys) {
SkyValue value = evaluationResult.get(key);
if (value != null) {
result.put(key, ValueOrUntypedException.ofValueUntyped(value));
continue;
}
errorMightHaveBeenFound = true;
ErrorInfo errorInfo = evaluationResult.getError(key);
if (errorInfo == null || errorInfo.getException() == null) {
result.put(key, ValueOrUntypedException.ofNull());
continue;
}
result.put(key, ValueOrUntypedException.ofExn(errorInfo.getException()));
}
return result;
}
@Override
public ExtendedEventHandler getListener() {
return null;
}
@Override
public boolean inErrorBubblingForTesting() {
return false;
}
@Override
public boolean restartPermitted() {
return false;
}
}
static class NullArtifactOwner implements ArtifactOwner {
private NullArtifactOwner() {}
@Override
public Label getLabel() {
return NULL_LABEL;
}
}
@AutoCodec
public static final ActionLookupKey NULL_ARTIFACT_OWNER =
new ActionLookupValue.ActionLookupKey() {
@Override
public SkyFunctionName functionName() {
return null;
}
@Override
public Label getLabel() {
return NULL_LABEL;
}
};
public static final Artifact DUMMY_ARTIFACT =
new Artifact.SourceArtifact(
ArtifactRoot.asSourceRoot(Root.absoluteRoot(new InMemoryFileSystem())),
PathFragment.create("/dummy"),
NULL_ARTIFACT_OWNER);
public static final ActionOwner NULL_ACTION_OWNER =
ActionOwner.create(
NULL_LABEL,
ImmutableList.<AspectDescriptor>of(),
null,
"dummy-configuration-mnemonic",
null,
"dummy-configuration",
null,
null,
ImmutableMap.<String, String>of(),
null);
@AutoCodec
public static final ActionLookupData NULL_ACTION_LOOKUP_DATA =
ActionLookupData.create(NULL_ARTIFACT_OWNER, 0);
/** An unchecked exception class for action conflicts. */
public static class UncheckedActionConflictException extends RuntimeException {
public UncheckedActionConflictException(ActionConflictException e) {
super(e);
}
}
/**
* A dummy Action class for use in tests.
*/
public static class NullAction extends AbstractAction {
public NullAction() {
super(
NULL_ACTION_OWNER,
NestedSetBuilder.emptySet(Order.STABLE_ORDER),
ImmutableList.of(DUMMY_ARTIFACT));
}
public NullAction(ActionOwner owner, Artifact... outputs) {
super(owner, NestedSetBuilder.emptySet(Order.STABLE_ORDER), ImmutableList.copyOf(outputs));
}
public NullAction(Artifact... outputs) {
super(
NULL_ACTION_OWNER,
NestedSetBuilder.emptySet(Order.STABLE_ORDER),
ImmutableList.copyOf(outputs));
}
public NullAction(List<Artifact> inputs, Artifact... outputs) {
super(
NULL_ACTION_OWNER,
NestedSetBuilder.wrap(Order.STABLE_ORDER, inputs),
ImmutableList.copyOf(outputs));
}
@Override
public ActionResult execute(ActionExecutionContext actionExecutionContext) {
return ActionResult.EMPTY;
}
@Override
protected void computeKey(ActionKeyContext actionKeyContext, Fingerprint fp) {
fp.addString("action");
}
@Override
public String getMnemonic() {
return "Null";
}
}
/**
* A mocked action containing the inputs and outputs of the action and determines whether or not
* the action is a middleman. Used for tests that do not need to execute the action.
*/
public static class MockAction extends AbstractAction {
private final boolean middleman;
private final boolean isShareable;
public MockAction(Iterable<Artifact> inputs, ImmutableSet<Artifact> outputs) {
this(inputs, outputs, /*middleman=*/ false, /*isShareable=*/ true);
}
public MockAction(
Iterable<Artifact> inputs, ImmutableSet<Artifact> outputs, boolean middleman) {
this(inputs, outputs, middleman, /*isShareable*/ true);
}
public MockAction(
Iterable<Artifact> inputs,
ImmutableSet<Artifact> outputs,
boolean middleman,
boolean isShareable) {
super(
NULL_ACTION_OWNER,
NestedSetBuilder.<Artifact>stableOrder().addAll(inputs).build(),
outputs);
this.middleman = middleman;
this.isShareable = isShareable;
}
@Override
public MiddlemanType getActionType() {
return middleman ? MiddlemanType.AGGREGATING_MIDDLEMAN : super.getActionType();
}
@Override
public String getMnemonic() {
return "Mock action";
}
@Override
protected void computeKey(ActionKeyContext actionKeyContext, Fingerprint fp) {
fp.addString("Mock Action " + getPrimaryOutput());
}
@Override
public ActionResult execute(ActionExecutionContext actionExecutionContext) {
throw new UnsupportedOperationException();
}
@Override
public boolean isShareable() {
return isShareable;
}
}
/**
* For a bunch of actions, gets the basenames of the paths and accumulates them in a space
* separated string, like <code>foo.o bar.o baz.a</code>.
*/
public static String baseNamesOf(NestedSet<Artifact> artifacts) {
return baseNamesOf(artifacts.toList());
}
/**
* For a bunch of actions, gets the basenames of the paths and accumulates
* them in a space separated string, like <code>foo.o bar.o baz.a</code>.
*/
public static String baseNamesOf(Iterable<Artifact> artifacts) {
List<String> baseNames = baseArtifactNames(artifacts);
return Joiner.on(' ').join(baseNames);
}
/**
* For a bunch of actions, gets the basenames of the paths, sorts them in alphabetical order and
* accumulates them in a space separated string, for example <code>bar.o baz.a foo.o</code>.
*/
public static String sortedBaseNamesOf(NestedSet<Artifact> artifacts) {
return sortedBaseNamesOf(artifacts.toList());
}
/**
* For a bunch of actions, gets the basenames of the paths, sorts them in alphabetical
* order and accumulates them in a space separated string, for example
* <code>bar.o baz.a foo.o</code>.
*/
public static String sortedBaseNamesOf(Iterable<Artifact> artifacts) {
List<String> baseNames = baseArtifactNames(artifacts);
Collections.sort(baseNames);
return Joiner.on(' ').join(baseNames);
}
/** For a bunch of artifacts, gets the basenames and accumulates them in a List. */
public static List<String> baseArtifactNames(NestedSet<Artifact> artifacts) {
return transform(artifacts.toList(), artifact -> artifact.getExecPath().getBaseName());
}
/** For a bunch of artifacts, gets the basenames and accumulates them in a List. */
public static List<String> baseArtifactNames(Iterable<Artifact> artifacts) {
return transform(artifacts, artifact -> artifact.getExecPath().getBaseName());
}
/** For a bunch of artifacts, gets the exec paths and accumulates them in a List. */
public static List<String> execPaths(NestedSet<Artifact> artifacts) {
return execPaths(artifacts.toList());
}
/** For a bunch of artifacts, gets the exec paths and accumulates them in a List. */
public static List<String> execPaths(Iterable<Artifact> artifacts) {
return transform(artifacts, Artifact::getExecPathString);
}
/**
* For a bunch of artifacts, gets the pretty printed names and accumulates them in a List. Note
* that this returns the root-relative paths, not the exec paths.
*/
public static List<String> prettyArtifactNames(NestedSet<Artifact> artifacts) {
return prettyArtifactNames(artifacts.toList());
}
/**
* For a bunch of artifacts, gets the pretty printed names and accumulates them in a List. Note
* that this returns the root-relative paths, not the exec paths.
*/
public static List<String> prettyArtifactNames(Iterable<Artifact> artifacts) {
return transform(artifacts, Artifact::prettyPrint);
}
public static <T, R> List<R> transform(Iterable<T> iterable, Function<T, R> mapper) {
// Can not use com.google.common.collect.Iterables.transform() there, as it returns Iterable.
return Streams.stream(iterable)
.map(mapper)
.collect(Collectors.toList());
}
/**
* Returns the closure of the predecessors of any of the given types, joining the basenames of the
* artifacts into a space-separated string like "libfoo.a libbar.a libbaz.a".
*/
public String predecessorClosureOf(Artifact artifact, FileType... types) {
return predecessorClosureOf(Collections.singleton(artifact), types);
}
/**
* Returns the closure of the predecessors of any of the given types, joining the basenames of the
* artifacts into a space-separated string like "libfoo.a libbar.a libbaz.a".
*/
public String predecessorClosureOf(NestedSet<Artifact> artifacts, FileType... types) {
return predecessorClosureOf(artifacts.toList(), types);
}
/**
* Returns the closure of the predecessors of any of the given types, joining the basenames of the
* artifacts into a space-separated string like "libfoo.a libbar.a libbaz.a".
*/
public String predecessorClosureOf(Iterable<Artifact> artifacts, FileType... types) {
Set<Artifact> visited = artifactClosureOf(artifacts);
return baseNamesOf(FileType.filter(visited, types));
}
/** Returns the closure of the predecessors of any of the given types. */
public Collection<String> predecessorClosureAsCollection(Artifact artifact, FileType... types) {
return predecessorClosureAsCollection(Collections.singleton(artifact), types);
}
/** Returns the closure of the predecessors of any of the given types. */
public Collection<String> predecessorClosureAsCollection(
NestedSet<Artifact> artifacts, FileType... types) {
return predecessorClosureAsCollection(artifacts.toList(), types);
}
/** Returns the closure of the predecessors of any of the given types. */
public Collection<String> predecessorClosureAsCollection(
Iterable<Artifact> artifacts, FileType... types) {
return baseArtifactNames(FileType.filter(artifactClosureOf(artifacts), types));
}
public String predecessorClosureOfJars(Iterable<Artifact> artifacts, FileType... types) {
return baseNamesOf(FileType.filter(artifactClosureOf(artifacts), types));
}
public Collection<String> predecessorClosureJarsAsCollection(Iterable<Artifact> artifacts,
FileType... types) {
Set<Artifact> visited = artifactClosureOf(artifacts);
return baseArtifactNames(FileType.filter(visited, types));
}
/**
* Returns the closure over the input files of an action.
*/
public Set<Artifact> inputClosureOf(ActionAnalysisMetadata action) {
return artifactClosureOf(action.getInputs().toList());
}
/** Returns the closure over the input files of an artifact. */
public Set<Artifact> artifactClosureOf(Artifact artifact) {
return artifactClosureOf(Collections.singleton(artifact));
}
/** Returns the closure over the input files of a set of artifacts. */
public Set<Artifact> artifactClosureOf(NestedSet<Artifact> artifacts) {
return artifactClosureOf(artifacts.toList());
}
/** Returns the closure over the input files of a set of artifacts. */
public Set<Artifact> artifactClosureOf(Iterable<Artifact> artifacts) {
Set<Artifact> visited = new LinkedHashSet<>();
List<Artifact> toVisit = Lists.newArrayList(artifacts);
while (!toVisit.isEmpty()) {
Artifact current = toVisit.remove(0);
if (!visited.add(current)) {
continue;
}
ActionAnalysisMetadata generatingAction = actionGraph.getGeneratingAction(current);
if (generatingAction != null) {
toVisit.addAll(generatingAction.getInputs().toList());
}
}
return visited;
}
/** Returns the closure over the input files of an artifact, filtered by the given matcher. */
public Set<Artifact> filteredArtifactClosureOf(Artifact artifact, Predicate<Artifact> matcher) {
return ImmutableSet.copyOf(Iterables.filter(artifactClosureOf(artifact), matcher));
}
/**
* Returns the closure over the input files of a set of artifacts, filtered by the given matcher.
*/
public Set<Artifact> filteredArtifactClosureOf(
Iterable<Artifact> artifacts, Predicate<Artifact> matcher) {
return ImmutableSet.copyOf(Iterables.filter(artifactClosureOf(artifacts), matcher));
}
/** Returns a predicate to match {@link Artifact}s with the given root-relative path suffix. */
public static Predicate<Artifact> getArtifactSuffixMatcher(final String suffix) {
return new Predicate<Artifact>() {
@Override
public boolean apply(Artifact input) {
return input.getRootRelativePath().getPathString().endsWith(suffix);
}
};
}
/**
* Finds all the actions that are instances of <code>actionClass</code>
* in the transitive closure of prerequisites.
*/
public <A extends Action> List<A> findTransitivePrerequisitesOf(Artifact artifact,
Class<A> actionClass, Predicate<Artifact> allowedArtifacts) {
List<A> actions = new ArrayList<>();
Set<Artifact> visited = new LinkedHashSet<>();
List<Artifact> toVisit = new LinkedList<>();
toVisit.add(artifact);
while (!toVisit.isEmpty()) {
Artifact current = toVisit.remove(0);
if (!visited.add(current)) {
continue;
}
ActionAnalysisMetadata generatingAction = actionGraph.getGeneratingAction(current);
if (generatingAction != null) {
Iterables.addAll(
toVisit, Iterables.filter(generatingAction.getInputs().toList(), allowedArtifacts));
if (actionClass.isInstance(generatingAction)) {
actions.add(actionClass.cast(generatingAction));
}
}
}
return actions;
}
public <A extends Action> List<A> findTransitivePrerequisitesOf(
Artifact artifact, Class<A> actionClass) {
return findTransitivePrerequisitesOf(artifact, actionClass, Predicates.<Artifact>alwaysTrue());
}
/**
* Looks in the given artifacts Iterable for the first Artifact whose path ends with the given
* suffix and returns its generating Action.
*/
public Action getActionForArtifactEndingWith(NestedSet<Artifact> artifacts, String suffix) {
return getActionForArtifactEndingWith(artifacts.toList(), suffix);
}
/**
* Looks in the given artifacts Iterable for the first Artifact whose path ends with the given
* suffix and returns its generating Action.
*/
public Action getActionForArtifactEndingWith(Iterable<Artifact> artifacts, String suffix) {
Artifact a = getFirstArtifactEndingWith(artifacts, suffix);
if (a == null) {
return null;
}
ActionAnalysisMetadata action = actionGraph.getGeneratingAction(a);
if (action != null) {
Preconditions.checkState(
action instanceof Action,
"%s is not a proper Action object",
action.prettyPrint());
return (Action) action;
} else {
return null;
}
}
/**
* Looks in the given artifacts Iterable for the first Artifact whose path ends with the given
* suffix and returns the Artifact.
*/
public static Artifact getFirstArtifactEndingWith(
NestedSet<? extends Artifact> artifacts, String suffix) {
return getFirstArtifactEndingWith(artifacts.toList(), suffix);
}
/**
* Looks in the given artifacts Iterable for the first Artifact whose path ends with the given
* suffix and returns the Artifact.
*/
public static Artifact getFirstArtifactEndingWith(
Iterable<? extends Artifact> artifacts, String suffix) {
for (Artifact a : artifacts) {
if (a.getExecPath().getPathString().endsWith(suffix)) {
return a;
}
}
return null;
}
/**
* Returns a list of the Artifacts in <code>artifacts</code> whose paths end with the given
* suffix.
*/
public static List<Artifact> getArtifactsEndingWith(
Iterable<? extends Artifact> artifacts, String suffix) {
List<Artifact> result = new ArrayList<>();
for (Artifact a : artifacts) {
if (a.getExecPath().getPathString().endsWith(suffix)) {
result.add(a);
}
}
return result;
}
/**
* Returns the first artifact which is an input to "action" and has the
* specified basename. An assertion error is raised if none is found.
*/
public static Artifact getInput(ActionAnalysisMetadata action, String basename) {
for (Artifact artifact : action.getInputs().toList()) {
if (artifact.getExecPath().getBaseName().equals(basename)) {
return artifact;
}
}
throw new AssertionError("No input with basename '" + basename + "' in action " + action);
}
/**
* Returns true if an artifact that is an input to "action" with the specific
* basename exists.
*/
public static boolean hasInput(ActionAnalysisMetadata action, String basename) {
try {
getInput(action, basename);
return true;
} catch (AssertionError e) {
return false;
}
}
/**
* Assert that an artifact is the primary output of its generating action.
*/
public void assertPrimaryInputAndOutputArtifacts(Artifact input, Artifact output) {
ActionAnalysisMetadata generatingAction = actionGraph.getGeneratingAction(output);
assertThat(generatingAction).isNotNull();
assertThat(generatingAction.getPrimaryOutput()).isEqualTo(output);
assertThat(generatingAction.getPrimaryInput()).isEqualTo(input);
}
/**
* Returns the first artifact which is an output of "action" and has the
* specified basename. An assertion error is raised if none is found.
*/
public static Artifact getOutput(ActionAnalysisMetadata action, String basename) {
for (Artifact artifact : action.getOutputs()) {
if (artifact.getExecPath().getBaseName().equals(basename)) {
return artifact;
}
}
throw new AssertionError("No output with basename '" + basename + "' in action " + action);
}
public static void registerActionWith(ActionAnalysisMetadata action,
MutableActionGraph actionGraph) {
try {
actionGraph.registerAction(action);
} catch (ActionConflictException e) {
throw new UncheckedActionConflictException(e);
}
}
public static SpawnActionTemplate createDummySpawnActionTemplate(
SpecialArtifact inputTreeArtifact, SpecialArtifact outputTreeArtifact) {
return new SpawnActionTemplate.Builder(inputTreeArtifact, outputTreeArtifact)
.setCommandLineTemplate(CustomCommandLine.builder().build())
.setExecutable(PathFragment.create("bin/executable"))
.setOutputPathMapper(new OutputPathMapper() {
@Override
public PathFragment parentRelativeOutputPath(TreeFileArtifact inputTreeFileArtifact) {
return inputTreeFileArtifact.getParentRelativePath();
}
})
.build(NULL_ACTION_OWNER);
}
/** Builder for a list of {@link MissDetail}s with defaults set to zero for all possible items. */
public static class MissDetailsBuilder {
private final Map<MissReason, Integer> details = new EnumMap<>(MissReason.class);
/** Constructs a new builder with all possible cache miss reasons set to zero counts. */
public MissDetailsBuilder() {
for (MissReason reason : MissReason.values()) {
if (reason == MissReason.UNRECOGNIZED) {
// The presence of this enum value is a protobuf artifact and not part of our metrics
// collection. Just skip it.
continue;
}
details.put(reason, 0);
}
}
/** Sets the count of the given miss reason to the given value. */
public MissDetailsBuilder set(MissReason reason, int count) {
checkArgument(details.containsKey(reason));
details.put(reason, count);
return this;
}
/** Constructs the list of {@link MissDetail}s. */
public Iterable<MissDetail> build() {
List<MissDetail> result = new ArrayList<>(details.size());
for (Map.Entry<MissReason, Integer> entry : details.entrySet()) {
MissDetail detail = MissDetail.newBuilder()
.setReason(entry.getKey())
.setCount(entry.getValue())
.build();
result.add(detail);
}
return result;
}
/** Counts the total number of misses registered so far regardless of their reason. */
public int countMisses() {
int total = 0;
for (Map.Entry<MissReason, Integer> entry : details.entrySet()) {
total += entry.getValue();
}
return total;
}
}
/**
* An {@link ArtifactResolver} all of whose operations throw an exception.
*
* <p>This is to be used as a base class by other test programs that need to implement only a
* few of the hooks required by the scenario under test.
*/
public static class FakeArtifactResolverBase implements ArtifactResolver {
@Override
public Artifact getSourceArtifact(PathFragment execPath, Root root, ArtifactOwner owner) {
throw new UnsupportedOperationException();
}
@Override
public Artifact getSourceArtifact(PathFragment execPath, Root root) {
throw new UnsupportedOperationException();
}
@Override
public Artifact resolveSourceArtifact(
PathFragment execPath, RepositoryName repositoryName) {
throw new UnsupportedOperationException();
}
@Override
public Map<PathFragment, Artifact> resolveSourceArtifacts(
Iterable<PathFragment> execPaths, PackageRootResolver resolver) {
throw new UnsupportedOperationException();
}
@Override
public Path getPathFromSourceExecPath(Path execRoot, PathFragment execPath) {
throw new UnsupportedOperationException();
}
}
/**
* A {@link MetadataHandler} all of whose operations throw an exception.
*
* <p>This is to be used as a base class by other test programs that need to implement only a
* few of the hooks required by the scenario under test.
*/
public static class FakeMetadataHandlerBase implements MetadataHandler {
@Override
public FileArtifactValue getMetadata(ActionInput input) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public ActionInput getInput(String execPath) {
throw new UnsupportedOperationException();
}
@Override
public void setDigestForVirtualArtifact(Artifact artifact, byte[] digest) {
throw new UnsupportedOperationException();
}
@Override
public void addExpandedTreeOutput(TreeFileArtifact output) {
throw new UnsupportedOperationException();
}
@Override
public Iterable<TreeFileArtifact> getExpandedOutputs(Artifact artifact) {
throw new UnsupportedOperationException();
}
@Override
public void injectDigest(ActionInput output, FileStatus statNoFollow, byte[] digest) {
throw new UnsupportedOperationException();
}
@Override
public void injectRemoteFile(Artifact output, byte[] digest, long size, int locationIndex) {
throw new UnsupportedOperationException();
}
@Override
public void injectRemoteDirectory(
SpecialArtifact treeArtifact, Map<PathFragment, RemoteFileArtifactValue> children) {
throw new UnsupportedOperationException();
}
@Override
public void markOmitted(ActionInput output) {
throw new UnsupportedOperationException();
}
@Override
public boolean artifactOmitted(Artifact artifact) {
return false;
}
@Override
public void discardOutputMetadata() {
throw new UnsupportedOperationException();
}
@Override
public void resetOutputs(Iterable<Artifact> outputs) {
throw new UnsupportedOperationException();
}
}
}
|
/*
* Copyright (c) 2009-2010, Sergey Karakovskiy and Julian Togelius
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Mario AI nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package ch.idsia.benchmark.mario.environments;
import ch.idsia.agents.Agent;
import ch.idsia.benchmark.mario.engine.*;
import ch.idsia.benchmark.mario.engine.level.Level;
import ch.idsia.benchmark.mario.engine.sprites.Mario;
import ch.idsia.benchmark.mario.engine.sprites.Sprite;
import ch.idsia.benchmark.tasks.SystemOfValues;
import ch.idsia.tools.EvaluationInfo;
import ch.idsia.tools.MarioAIOptions;
import ch.idsia.tools.punj.PunctualJudge;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
/**
* Created by IntelliJ IDEA.
* User: Sergey Karakovskiy, sergey@idsia.ch
* Date: Mar 3, 2010 Time: 10:08:13 PM
* Package: ch.idsia.benchmark.mario.environments
*/
public final class MarioEnvironment implements Environment
{
private int[] marioEgoPos = new int[2];
private int receptiveFieldHeight = -1; // to be setup via MarioAIOptions
private int receptiveFieldWidth = -1; // to be setup via MarioAIOptions
private int prevRFH = -1;
private int prevRFW = -1;
private byte[][] levelSceneZ; // memory is allocated in reset
private byte[][] enemiesZ; // memory is allocated in reset
private byte[][] mergedZZ; // memory is allocated in reset
public List<Sprite> sprites;
private int[] serializedLevelScene; // memory is allocated in reset
private int[] serializedEnemies; // memory is allocated in reset
private int[] serializedMergedObservation; // memory is allocated in reset
private final LevelScene levelScene;
// private int frame = 0;
private MarioVisualComponent marioVisualComponent;
private Agent agent;
private static final MarioEnvironment ourInstance = new MarioEnvironment();
private static final EvaluationInfo evaluationInfo = new EvaluationInfo();
private static String marioTraceFile;
private Recorder recorder;
public static SystemOfValues IntermediateRewardsSystemOfValues = new SystemOfValues();
DecimalFormat df = new DecimalFormat("######.#");
public static MarioEnvironment getInstance()
{
return ourInstance;
}
private MarioEnvironment()
{
// System.out.println("System.getProperty(\"java.awt.headless\") = " + System.getProperty("java.awt.headless"));
// System.out.println("System.getProperty(\"verbose\") = " + System.getProperty("-verbose"));
// System.out.println("Java: JA ZDES'!!");
// System.out.flush();
System.out.println(GlobalOptions.getBenchmarkName());
levelScene = new LevelScene();
}
public void resetDefault()
{
levelScene.resetDefault();
}
public void reset(String args)
{
MarioAIOptions marioAIOptions = MarioAIOptions.getOptionsByString(args);
this.reset(marioAIOptions);
// MarioAIOptions opts = new MarioAIOptions(setUpOptions);
// int[] intOpts = opts.toIntArray();
// this.reset(intOpts);
}
public void reset(MarioAIOptions setUpOptions)
{
/*System.out.println("\nsetUpOptions = " + setUpOptions);
for (int i = 0; i < setUpOptions.length; ++i)
{
System.out.print(" op[" + i +"] = " + setUpOptions[i]);
}
System.out.println("");
System.out.flush();*/
// if (!setUpOptions.getReplayOptions().equals(""))
this.setAgent(setUpOptions.getAgent());
receptiveFieldWidth = setUpOptions.getReceptiveFieldWidth();
receptiveFieldHeight = setUpOptions.getReceptiveFieldHeight();
if (receptiveFieldHeight != this.prevRFH || receptiveFieldWidth != this.prevRFW)
{
serializedLevelScene = new int[receptiveFieldHeight * receptiveFieldWidth];
serializedEnemies = new int[receptiveFieldHeight * receptiveFieldWidth];
serializedMergedObservation = new int[receptiveFieldHeight * receptiveFieldWidth];
levelSceneZ = new byte[receptiveFieldHeight][receptiveFieldWidth];
enemiesZ = new byte[receptiveFieldHeight][receptiveFieldWidth];
mergedZZ = new byte[receptiveFieldHeight][receptiveFieldWidth];
this.prevRFH = this.receptiveFieldHeight;
this.prevRFW = this.receptiveFieldWidth;
}
marioEgoPos[0] = setUpOptions.getMarioEgoPosRow();
marioEgoPos[1] = setUpOptions.getMarioEgoPosCol();
if (marioEgoPos[0] == 9 && getReceptiveFieldWidth() != 19)
marioEgoPos[0] = getReceptiveFieldWidth() / 2;
if (marioEgoPos[1] == 9 && getReceptiveFieldHeight() != 19)
marioEgoPos[1] = getReceptiveFieldHeight() / 2;
marioTraceFile = setUpOptions.getTraceFileName();
if (setUpOptions.isVisualization())
{
if (marioVisualComponent == null)
marioVisualComponent = MarioVisualComponent.getInstance(setUpOptions, this);
levelScene.reset(setUpOptions);
marioVisualComponent.reset();
marioVisualComponent.postInitGraphicsAndLevel();
marioVisualComponent.setAgent(agent);
marioVisualComponent.setLocation(setUpOptions.getViewLocation());
marioVisualComponent.setAlwaysOnTop(setUpOptions.isViewAlwaysOnTop());
if (setUpOptions.isScale2X())
GlobalOptions.changeScale2x();
} else
levelScene.reset(setUpOptions);
sprites = levelScene.sprites;
//create recorder
String recordingFileName = setUpOptions.getRecordingFileName();
if (!recordingFileName.equals("off"))
{
if (recordingFileName.equals("on"))
recordingFileName = GlobalOptions.getTimeStamp() + ".zip";
try
{
if (recordingFileName.equals("lazy"))
recorder = new Recorder();
else
recorder = new Recorder(recordingFileName);
recorder.createFile("level.lvl");
recorder.writeObject(levelScene.level);
recorder.closeFile();
recorder.createFile("options");
recorder.writeObject(setUpOptions.asString());
recorder.closeFile();
recorder.createFile("actions.act");
} catch (FileNotFoundException e)
{
System.err.println("[Mario AI EXCEPTION] : Some of the recording components were not created. Recording failed");
} catch (IOException e)
{
System.err.println("[Mario AI EXCEPTION] : Some of the recording components were not created. Recording failed");
e.printStackTrace();
}
}
evaluationInfo.reset();
PunctualJudge.resetCounter();
}
public void tick()
{
levelScene.tick();
if (GlobalOptions.isVisualization)
marioVisualComponent.tick();
}
public float[] getMarioFloatPos()
{
return levelScene.getMarioFloatPos();
}
public int getMarioMode()
{
return levelScene.getMarioMode();
}
public byte[][] getLevelSceneObservationZ(int ZLevel)
{
int mCol = marioEgoPos[1];
int mRow = marioEgoPos[0];
for (int y = levelScene.mario.mapY - mRow, row = 0; y <= levelScene.mario.mapY + (receptiveFieldHeight - mRow - 1); y++, row++)
{
for (int x = levelScene.mario.mapX - mCol, col = 0; x <= levelScene.mario.mapX + (receptiveFieldWidth - mCol - 1); x++, col++)
{
if (x >= 0 && x < levelScene.level.length && y >= 0 && y < levelScene.level.height)
{
mergedZZ[row][col] = levelSceneZ[row][col] = GeneralizerLevelScene.ZLevelGeneralization(levelScene.level.map[x][y], ZLevel);
} else
{
mergedZZ[row][col] = levelSceneZ[row][col] = 0;
}
}
}
return levelSceneZ;
}
public byte[][] getEnemiesObservationZ(int ZLevel)
{
int marioEgoCol = marioEgoPos[1];
int marioEgoRow = marioEgoPos[0];
for (int w = 0; w < enemiesZ.length; w++)
for (int h = 0; h < enemiesZ[0].length; h++)
enemiesZ[w][h] = 0;
for (Sprite sprite : sprites)
{
if (sprite.isDead() || sprite.kind == levelScene.mario.kind)
continue;
if (sprite.mapX >= 0 &&
sprite.mapX >= levelScene.mario.mapX - marioEgoCol &&
sprite.mapX <= levelScene.mario.mapX + (receptiveFieldWidth - marioEgoCol - 1) &&
sprite.mapY >= 0 &&
sprite.mapY >= levelScene.mario.mapY - marioEgoRow &&
sprite.mapY <= levelScene.mario.mapY + (receptiveFieldHeight - marioEgoRow - 1) &&
sprite.kind != Sprite.KIND_PRINCESS)
{
int row = sprite.mapY - levelScene.mario.mapY + marioEgoRow;
int col = sprite.mapX - levelScene.mario.mapX + marioEgoCol;
// TODO:!H! take care about side effects of line 243 and be sure not to contaminate levelSceneObservation
mergedZZ[row][col] = enemiesZ[row][col] = GeneralizerEnemies.ZLevelGeneralization(sprite.kind, ZLevel);
}
}
return enemiesZ;
}
// TODO: !H! substitute the content of getMergedObservationZZ by getLevelSceneObservationZ,
// TODO: !H! getEnemiesObservationZ, called one after another!
public byte[][] getMergedObservationZZ(int ZLevelScene, int ZLevelEnemies)
{
// int MarioXInMap = (int) mario.x / cellSize;
// int MarioYInMap = (int) mario.y / cellSize;
// if (MarioXInMap != (int) mario.x / cellSize ||MarioYInMap != (int) mario.y / cellSize )
// throw new Error("WRONG mario x or y pos");
int mCol = marioEgoPos[1];
int mRow = marioEgoPos[0];
for (int y = levelScene.mario.mapY - mRow/*receptiveFieldHeight / 2*/, row = 0; y <= levelScene.mario.mapY + (receptiveFieldHeight - mRow - 1)/*receptiveFieldHeight / 2*/; y++, row++)
{
for (int x = levelScene.mario.mapX - mCol/*receptiveFieldWidth / 2*/, col = 0; x <= levelScene.mario.mapX + (receptiveFieldWidth - mCol - 1)/*receptiveFieldWidth / 2*/; x++, col++)
{
if (x >= 0 && x < levelScene.level.xExit && y >= 0 && y < levelScene.level.height)
{
mergedZZ[row][col] = GeneralizerLevelScene.ZLevelGeneralization(levelScene.level.map[x][y], ZLevelScene);
} else
mergedZZ[row][col] = 0;
// if (x == MarioXInMap && y == MarioYInMap)
// mergedZZ[row][col] = mario.kind;
}
}
// for (int w = 0; w < mergedZZ.length; w++)
// for (int h = 0; h < mergedZZ[0].length; h++)
// mergedZZ[w][h] = -1;
for (Sprite sprite : sprites)
{
if (sprite.isDead() || sprite.kind == levelScene.mario.kind)
continue;
if (sprite.mapX >= 0 &&
sprite.mapX >= levelScene.mario.mapX - mCol &&
sprite.mapX <= levelScene.mario.mapX + (receptiveFieldWidth - mCol - 1) &&
sprite.mapY >= 0 &&
sprite.mapY >= levelScene.mario.mapY - mRow &&
sprite.mapY <= levelScene.mario.mapY + (receptiveFieldHeight - mRow - 1) &&
sprite.kind != Sprite.KIND_PRINCESS)
{
int row = sprite.mapY - levelScene.mario.mapY + mRow;
int col = sprite.mapX - levelScene.mario.mapX + mCol;
byte tmp = GeneralizerEnemies.ZLevelGeneralization(sprite.kind, ZLevelEnemies);
if (tmp != Sprite.KIND_NONE)
mergedZZ[row][col] = tmp;
}
}
return mergedZZ;
}
public List<String> getObservationStrings(boolean Enemies, boolean LevelMap,
boolean mergedObservationFlag,
int ZLevelScene, int ZLevelEnemies)
{
List<String> ret = new ArrayList<String>();
if (levelScene.level != null && levelScene.mario != null)
{
ret.add("Total levelScene length = " + levelScene.level.length);
ret.add("Total levelScene height = " + levelScene.level.height);
ret.add("Physical Mario Position (x,y): (" + df.format(levelScene.mario.x) + "," + df.format(levelScene.mario.y) + ")");
ret.add("Mario Observation (Receptive Field) Width: " + receptiveFieldWidth + " Height: " + receptiveFieldHeight);
ret.add("X Exit Position: " + levelScene.level.xExit);
int MarioXInMap = (int) levelScene.mario.x / levelScene.cellSize; //TODO: !!H! doublcheck and replace with levelScene.mario.mapX
int MarioYInMap = (int) levelScene.mario.y / levelScene.cellSize; //TODO: !!H! doublcheck and replace with levelScene.mario.mapY
ret.add("Calibrated Mario Position (x,y): (" + MarioXInMap + "," + MarioYInMap + ")\n");
byte[][] levelScene = getLevelSceneObservationZ(ZLevelScene);
if (LevelMap)
{
ret.add("~ZLevel: Z" + ZLevelScene + " map:\n");
for (int x = 0; x < levelScene.length; ++x)
{
String tmpData = "";
for (int y = 0; y < levelScene[0].length; ++y)
tmpData += levelSceneCellToString(levelScene[x][y]);
ret.add(tmpData);
}
}
byte[][] enemiesObservation = null;
if (Enemies || mergedObservationFlag)
enemiesObservation = getEnemiesObservationZ(ZLevelEnemies);
if (Enemies)
{
ret.add("~ZLevel: Z" + ZLevelScene + " Enemies Observation:\n");
for (int x = 0; x < enemiesObservation.length; x++)
{
String tmpData = "";
for (int y = 0; y < enemiesObservation[0].length; y++)
{
// if (x >=0 && x <= level.xExit)
tmpData += enemyToStr(enemiesObservation[x][y]);
}
ret.add(tmpData);
}
}
if (mergedObservationFlag)
{
byte[][] mergedObs = getMergedObservationZZ(ZLevelScene, ZLevelEnemies);
ret.add("~ZLevelScene: Z" + ZLevelScene + " ZLevelEnemies: Z" + ZLevelEnemies + " ; Merged observation /* Mario ~> #M.# */");
for (int x = 0; x < levelScene.length; ++x)
{
String tmpData = "";
for (int y = 0; y < levelScene[0].length; ++y)
tmpData += levelSceneCellToString(mergedObs[x][y]);
ret.add(tmpData);
}
}
} else
ret.add("~[MarioAI ERROR] level : " + levelScene.level + " mario : " + levelScene.mario);
return ret;
}
private String levelSceneCellToString(int el)
{
String s = "";
if (el == 0 || el == 1)
s = "##";
s += (el == levelScene.mario.kind) ? "#M.#" : el;
while (s.length() < 4)
s += "#";
return s + " ";
}
private String enemyToStr(int el)
{
String s = "";
if (el == 0)
s = "";
s += (el == levelScene.mario.kind) ? "-m" : el;
while (s.length() < 2)
s += "#";
return s + " ";
}
public float[] getEnemiesFloatPos()
{
return levelScene.getEnemiesFloatPos();
}
public boolean isMarioOnGround()
{
return levelScene.isMarioOnGround();
}
public boolean isMarioAbleToJump()
{
return levelScene.isMarioAbleToJump();
}
public boolean isMarioCarrying()
{
return levelScene.isMarioCarrying();
}
public boolean isMarioAbleToShoot()
{
return levelScene.isMarioAbleToShoot();
}
public int getReceptiveFieldWidth()
{
return receptiveFieldWidth;
}
public int getReceptiveFieldHeight()
{
return receptiveFieldHeight;
}
public int getKillsTotal()
{
return levelScene.getKillsTotal();
}
public int getKillsByFire()
{
return levelScene.getKillsByFire();
}
public int getKillsByStomp()
{
return levelScene.getKillsByStomp();
}
public int getKillsByShell()
{
return levelScene.getKillsByShell();
}
public int getMarioStatus()
{
return levelScene.getMarioStatus();
}
public int[] getObservationDetails()
{
return new int[]{receptiveFieldWidth, receptiveFieldHeight, marioEgoPos[0], marioEgoPos[1]};
}
public List<Sprite> getSprites()
{
return sprites;
}
public int[] getSerializedFullObservationZZ(int ZLevelScene, int ZLevelEnemies)
{
int[] obs = new int[receptiveFieldHeight * receptiveFieldWidth * 2 + 11]; // 11 is a size of the MarioState array
int receptiveFieldSize = receptiveFieldWidth * receptiveFieldHeight;
System.arraycopy(getSerializedLevelSceneObservationZ(ZLevelScene), 0, obs, 0, receptiveFieldSize);
System.arraycopy(getSerializedEnemiesObservationZ(ZLevelScene), 0, obs, receptiveFieldSize, receptiveFieldSize);
System.arraycopy(getMarioState(), 0, obs, receptiveFieldSize * 2, 11);
return obs;
}
public int[] getSerializedLevelSceneObservationZ(int ZLevelScene)
{
// serialization into arrays of primitive types to speed up the data transfer.
byte[][] levelScene = this.getLevelSceneObservationZ(ZLevelScene);
for (int i = 0; i < serializedLevelScene.length; ++i)
{
final int i1 = i / receptiveFieldWidth;
final int i2 = i % receptiveFieldWidth;
serializedLevelScene[i] = (int) levelScene[i1][i2];
}
return serializedLevelScene;
}
public int[] getSerializedEnemiesObservationZ(int ZLevelEnemies)
{
// serialization into arrays of primitive types to speed up the data transfer.
byte[][] enemies = this.getEnemiesObservationZ(ZLevelEnemies);
for (int i = 0; i < serializedEnemies.length; ++i)
serializedEnemies[i] = (int) enemies[i / receptiveFieldWidth][i % receptiveFieldWidth];
return serializedEnemies;
}
public int[] getSerializedMergedObservationZZ(int ZLevelScene, int ZLevelEnemies)
{
// serialization into arrays of primitive types to speed up the data transfer.
byte[][] merged = this.getMergedObservationZZ(ZLevelScene, ZLevelEnemies);
for (int i = 0; i < serializedMergedObservation.length; ++i)
serializedMergedObservation[i] = (int) merged[i / receptiveFieldWidth][i % receptiveFieldWidth];
return serializedMergedObservation;
}
public float[] getCreaturesFloatPos()
{
return levelScene.getCreaturesFloatPos();
}
public int[] getMarioState()
{
return levelScene.getMarioState();
}
public void performAction(boolean[] action)
{
try
{
if (recorder != null && recorder.canRecord() && action != null)
{
recorder.writeAction(action);
recorder.changeRecordingState(GlobalOptions.isRecording, getTimeSpent());
}
} catch (IOException e)
{
e.printStackTrace();
}
levelScene.performAction(action);
}
public boolean isLevelFinished()
{
return levelScene.isLevelFinished();
}
public int[] getEvaluationInfoAsInts()
{
return this.getEvaluationInfo().toIntArray();
}
public String getEvaluationInfoAsString()
{
return this.getEvaluationInfo().toString();
}
public EvaluationInfo getEvaluationInfo()
{
computeEvaluationInfo();
return evaluationInfo;
}
public Mario getMario()
{
return levelScene.mario;
}
public int getTick()
{
return levelScene.tickCount;
}
public int getLevelDifficulty()
{
return levelScene.getLevelDifficulty();
}
public long getLevelSeed()
{
return levelScene.getLevelSeed();
}
public int getLevelType()
{
return levelScene.getLevelType();
}
public int getKilledCreaturesTotal()
{
return levelScene.getKillsTotal();
}
public int getLevelLength()
{
return levelScene.getLevelLength();
}
public int getLevelHeight()
{
return levelScene.getLevelHeight();
}
public int getKilledCreaturesByFireBall()
{
return levelScene.getKillsByFire();
}
public int getKilledCreaturesByShell()
{
return levelScene.getKillsByShell();
}
public int getKilledCreaturesByStomp()
{
return levelScene.getKillsByStomp();
}
public int getTimeLeft()
{
return levelScene.getTimeLeft();
}
public Level getLevel()
{
return levelScene.level;
}
private void computeEvaluationInfo()
{
if (recorder != null)
closeRecorder();
// evaluationInfo.agentType = agent.getClass().getSimpleName();
// evaluationInfo.agentName = agent.getName();
evaluationInfo.marioStatus = levelScene.getMarioStatus();
evaluationInfo.flowersDevoured = Mario.flowersDevoured;
evaluationInfo.distancePassedPhys = (int) levelScene.mario.x;
evaluationInfo.distancePassedCells = levelScene.mario.mapX;
// evaluationInfo.totalLengthOfLevelCells = levelScene.level.getWidthCells();
// evaluationInfo.totalLengthOfLevelPhys = levelScene.level.getWidthPhys();
evaluationInfo.timeSpent = levelScene.getTimeSpent();
evaluationInfo.timeLeft = levelScene.getTimeLeft();
evaluationInfo.coinsGained = Mario.coins;
evaluationInfo.totalNumberOfCoins = levelScene.level.counters.coinsCount;
evaluationInfo.totalNumberOfHiddenBlocks = levelScene.level.counters.hiddenBlocksCount;
evaluationInfo.totalNumberOfFlowers = levelScene.level.counters.flowers;
evaluationInfo.totalNumberOfMushrooms = levelScene.level.counters.mushrooms;
evaluationInfo.totalNumberOfCreatures = levelScene.level.counters.creatures;
evaluationInfo.marioMode = levelScene.getMarioMode();
evaluationInfo.mushroomsDevoured = Mario.mushroomsDevoured;
evaluationInfo.killsTotal = levelScene.getKillsTotal();
evaluationInfo.killsByStomp = levelScene.getKillsByStomp();
evaluationInfo.killsByFire = levelScene.getKillsByFire();
evaluationInfo.killsByShell = levelScene.getKillsByShell();
evaluationInfo.hiddenBlocksFound = Mario.hiddenBlocksFound;
evaluationInfo.collisionsWithCreatures = Mario.collisionsWithCreatures;
evaluationInfo.Memo = levelScene.memo;
evaluationInfo.levelLength = levelScene.level.length;
evaluationInfo.marioTraceFileName = marioTraceFile;
evaluationInfo.marioTrace = levelScene.level.marioTrace;
evaluationInfo.greenMushroomsDevoured = Mario.greenMushroomsDevoured;
// EH: the below line causes problems when calling from Python
// evaluationInfo.bytecodeInstructions = PunctualJudge.getCounter();
}
public void setAgent(Agent agent)
{
this.agent = agent;
}
public int getIntermediateReward()
{
// TODO: reward for coins, killed creatures, cleared dead-ends, bypassed gaps, hidden blocks found
return levelScene.getBonusPoints();
}
public int[] getMarioEgoPos()
{
return marioEgoPos;
}
public void closeRecorder()
{
if (recorder != null)
{
try
{
// recorder.closeFile();
recorder.closeRecorder(getTimeSpent());
//recorder = null;
} catch (IOException e)
{
e.printStackTrace();
}
}
}
public int getTimeSpent()
{
return levelScene.getTimeSpent();
}
public byte[][] getScreenCapture()
{
return null;
}
public void setReplayer(Replayer replayer)
{
levelScene.setReplayer(replayer);
}
public void saveLastRun(String filename)
{
if (recorder != null && recorder.canSave())
{
try
{
recorder.saveLastRun(filename);
} catch (IOException ex)
{
System.err.println("[Mario AI EXCEPTION] : Recording could not be saved.");
ex.printStackTrace();
}
}
}
//public void setRecording(boolean isRecording)
//{
// this.isRecording = isRecording;
//}
}
|
/*
* Copyright (C) 2014-2018 Samuel Audet
*
* Licensed either under the Apache License, Version 2.0, or (at your option)
* under the terms of the GNU General Public License as published by
* the Free Software Foundation (subject to the "Classpath" exception),
* either version 2, or any later version (collectively, 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
* http://www.gnu.org/licenses/
* http://www.gnu.org/software/classpath/license.html
*
* or as provided in the LICENSE.txt file that accompanied this code.
* 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.bytedeco.javacpp.tools;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A {@link Map} containing {@link Info} objects consumed by the {@link Parser}.
* Also contains a few utility methods to facilitate its use for both the user
* and the {@link Parser}.
*
* @author Samuel Audet
*/
public class InfoMap extends HashMap<String,List<Info>> {
public InfoMap() { this.parent = defaults; }
public InfoMap(InfoMap parent) { this.parent = parent; }
InfoMap parent = null;
static final InfoMap defaults = new InfoMap(null)
.put(new Info("basic/containers").cppTypes("std::array", "std::bitset", "std::deque", "std::list", "std::map", "std::queue", "std::set",
"std::stack", "std::vector", "std::valarray", "std::pair", "std::forward_list",
"std::priority_queue", "std::unordered_map", "std::unordered_set"))
.put(new Info("basic/types").cppTypes("signed", "unsigned", "char", "short", "int", "long", "bool", "float", "double",
"_Bool", "_Complex", "_Imaginary", "complex", "imaginary"))
.put(new Info("noexcept").annotations("@NoException"))
.put(new Info("__COUNTER__").cppText("#define __COUNTER__ 0"))
.put(new Info(" __attribute__", "__declspec", "static_assert").annotations().skip())
.put(new Info("void").valueTypes("void").pointerTypes("Pointer"))
.put(new Info("std::nullptr_t").valueTypes("Pointer").pointerTypes("PointerPointer"))
.put(new Info("FILE", "time_t", "va_list", "std::exception", "std::istream", "std::ostream", "std::iostream",
"std::ifstream", "std::ofstream", "std::fstream").cast().pointerTypes("Pointer"))
.put(new Info("int8_t", "__int8", "jbyte", "signed char")
.valueTypes("byte").pointerTypes("BytePointer", "ByteBuffer", "byte[]"))
.put(new Info("uint8_t", "unsigned __int8", "char", "unsigned char").cast()
.valueTypes("byte").pointerTypes("BytePointer", "ByteBuffer", "byte[]"))
.put(new Info("int16_t", "__int16", "jshort", "short", "signed short", "short int", "signed short int")
.valueTypes("short").pointerTypes("ShortPointer", "ShortBuffer", "short[]"))
.put(new Info("uint16_t", "unsigned __int16", "unsigned short", "unsigned short int").cast()
.valueTypes("short").pointerTypes("ShortPointer", "ShortBuffer", "short[]"))
.put(new Info("int32_t", "__int32", "jint", "int", "signed int", "signed")
.valueTypes("int").pointerTypes("IntPointer", "IntBuffer", "int[]"))
.put(new Info("uint32_t", "unsigned __int32", "unsigned int", "unsigned").cast()
.valueTypes("int").pointerTypes("IntPointer", "IntBuffer", "int[]"))
.put(new Info("jlong", "long long", "signed long long", "long long int", "signed long long int")
.valueTypes("long").pointerTypes("LongPointer", "LongBuffer", "long[]"))
.put(new Info("int64_t", "__int64", "uint64_t", "unsigned __int64", "unsigned long long", "unsigned long long int").cast()
.valueTypes("long").pointerTypes("LongPointer", "LongBuffer", "long[]"))
.put(new Info("long", "signed long", "long int", "signed long int")
.valueTypes("long").pointerTypes("CLongPointer"))
.put(new Info("unsigned long", "unsigned long int").cast()
.valueTypes("long").pointerTypes("CLongPointer"))
.put(new Info("size_t", "ssize_t", "ptrdiff_t", "intptr_t", "uintptr_t", "off_t").cast().valueTypes("long").pointerTypes("SizeTPointer"))
.put(new Info("float", "jfloat").valueTypes("float").pointerTypes("FloatPointer", "FloatBuffer", "float[]"))
.put(new Info("double", "jdouble").valueTypes("double").pointerTypes("DoublePointer", "DoubleBuffer", "double[]"))
.put(new Info("long double").cast().valueTypes("double").pointerTypes("Pointer"))
.put(new Info("std::complex<float>", "float _Complex", "float _Imaginary", "float complex", "float imaginary").cast()
.pointerTypes("FloatPointer", "FloatBuffer", "float[]"))
.put(new Info("std::complex<double>", "double _Complex", "double _Imaginary", "double complex", "double imaginary").cast()
.pointerTypes("DoublePointer", "DoubleBuffer", "double[]"))
.put(new Info("jboolean").valueTypes("boolean").pointerTypes("BooleanPointer", "boolean[]"))
.put(new Info("_Bool", "bool").cast().valueTypes("boolean").pointerTypes("BoolPointer", "boolean[]"))
.put(new Info("jchar").valueTypes("char").pointerTypes("CharPointer", "char[]"))
.put(new Info("char16_t").cast().valueTypes("char").pointerTypes("CharPointer", "char[]"))
.put(new Info("char32_t").cast().valueTypes("int").pointerTypes("IntPointer", "int[]"))
.put(new Info("wchar_t", "WCHAR").cast().valueTypes("char", "int").pointerTypes("CharPointer", "IntPointer"))
.put(new Info("const char").valueTypes("@Cast(\"const char\") byte").pointerTypes("@Cast(\"const char*\") BytePointer", "String"))
.put(new Info("boost::shared_ptr", "std::shared_ptr").annotations("@SharedPtr"))
.put(new Info("boost::movelib::unique_ptr", "std::unique_ptr").annotations("@UniquePtr"))
.put(new Info("std::string").annotations("@StdString").valueTypes("BytePointer", "String").pointerTypes("BytePointer"))
.put(new Info("std::u16string").annotations("@StdString(\"char16_t\")").valueTypes("CharPointer").pointerTypes("CharPointer"))
.put(new Info("std::u32string").annotations("@StdString(\"char32_t\")").valueTypes("IntPointer").pointerTypes("IntPointer"))
.put(new Info("std::wstring").annotations("@StdWString").valueTypes("CharPointer", "IntPointer").pointerTypes("CharPointer", "IntPointer"))
.put(new Info("std::vector").annotations("@StdVector"))
.put(new Info("abstract").javaNames("_abstract"))
.put(new Info("boolean").javaNames("_boolean"))
.put(new Info("byte").javaNames("_byte"))
.put(new Info("extends").javaNames("_extends"))
.put(new Info("finally").javaNames("_finally"))
.put(new Info("implements").javaNames("_implements"))
.put(new Info("import").javaNames("_import"))
.put(new Info("instanceof").javaNames("_instanceof"))
.put(new Info("native").javaNames("_native"))
.put(new Info("null").javaNames("_null"))
.put(new Info("package").javaNames("_package"))
.put(new Info("super").javaNames("_super"))
.put(new Info("synchronized").javaNames("_synchronized"))
.put(new Info("transient").javaNames("_transient"))
.put(new Info("operator ->").javaNames("access"))
.put(new Info("operator ()").javaNames("apply"))
.put(new Info("operator []").javaNames("get"))
.put(new Info("operator =").javaNames("put"))
.put(new Info("operator +").javaNames("add"))
.put(new Info("operator -").javaNames("subtract"))
.put(new Info("operator *").javaNames("multiply"))
.put(new Info("operator /").javaNames("divide"))
.put(new Info("operator %").javaNames("mod"))
.put(new Info("operator ++").javaNames("increment"))
.put(new Info("operator --").javaNames("decrement"))
.put(new Info("operator ==").javaNames("equals"))
.put(new Info("operator !=").javaNames("notEquals"))
.put(new Info("operator <").javaNames("lessThan"))
.put(new Info("operator >").javaNames("greaterThan"))
.put(new Info("operator <=").javaNames("lessThanEquals"))
.put(new Info("operator >=").javaNames("greaterThanEquals"))
.put(new Info("operator !").javaNames("not"))
.put(new Info("operator &&").javaNames("and"))
.put(new Info("operator ||").javaNames("or"))
.put(new Info("operator &").javaNames("and"))
.put(new Info("operator |").javaNames("or"))
.put(new Info("operator ^").javaNames("xor"))
.put(new Info("operator ~").javaNames("not"))
.put(new Info("operator <<").javaNames("shiftLeft"))
.put(new Info("operator >>").javaNames("shiftRight"))
.put(new Info("operator +=").javaNames("addPut"))
.put(new Info("operator -=").javaNames("subtractPut"))
.put(new Info("operator *=").javaNames("multiplyPut"))
.put(new Info("operator /=").javaNames("dividePut"))
.put(new Info("operator %=").javaNames("modPut"))
.put(new Info("operator &=").javaNames("andPut"))
.put(new Info("operator |=").javaNames("orPut"))
.put(new Info("operator ^=").javaNames("xorPut"))
.put(new Info("operator <<=").javaNames("shiftLeftPut"))
.put(new Info("operator >>=").javaNames("shiftRightPut"))
.put(new Info("operator new").javaNames("_new"))
.put(new Info("operator delete").javaNames("_delete"))
.put(new Info("getClass").javaNames("_getClass"))
.put(new Info("notify").javaNames("_notify"))
.put(new Info("notifyAll").javaNames("_notifyAll"))
.put(new Info("wait").javaNames("_wait"))
.put(new Info("allocate").javaNames("_allocate"))
.put(new Info("close").javaNames("_close"))
.put(new Info("deallocate").javaNames("_deallocate"))
.put(new Info("free").javaNames("_free"))
.put(new Info("address").javaNames("_address"))
.put(new Info("position").javaNames("_position"))
.put(new Info("limit").javaNames("_limit"))
.put(new Info("capacity").javaNames("_capacity"))
.put(new Info("fill").javaNames("_fill"))
.put(new Info("zero").javaNames("_zero"));
String normalize(String name, boolean unconst, boolean untemplate) {
if (name == null || name.length() == 0 || name.startsWith("basic/")) {
return name;
}
boolean foundConst = false, simpleType = true;
String prefix = null;
Token[] tokens = new Tokenizer(name, null, 0).tokenize();
int n = tokens.length;
Info info = getFirst("basic/types");
String[] basicTypes = info != null ? info.cppTypes : new String[0];
Arrays.sort(basicTypes);
for (int i = 0; i < n; i++) {
if (tokens[i].match(Token.CONST, Token.CONSTEXPR)) {
foundConst = true;
for (int j = i + 1; j < n; j++) {
tokens[j - 1] = tokens[j];
}
i--; n--;
} else if (tokens[i].match(Token.CLASS, Token.STRUCT, Token.UNION)) {
prefix = tokens[i].value;
for (int j = i + 1; j < n; j++) {
tokens[j - 1] = tokens[j];
}
i--; n--;
} else if (Arrays.binarySearch(basicTypes, tokens[i].value) < 0) {
simpleType = false;
break;
}
}
if (simpleType) {
Arrays.sort(tokens, 0, n);
name = (foundConst ? "const " : "") + tokens[0].value;
for (int i = 1; i < n; i++) {
name += " " + tokens[i].value;
}
} else if (untemplate) {
int count = 0, lastColon = -1, template = -1;
for (int i = 0; i < n; i++) {
if (tokens[i].match('<')) {
count++;
} else if (tokens[i].match('>')) {
count--;
}
if (count == 0 && tokens[i].match("::")) {
lastColon = i;
}
}
for (int i = 0; i < n; i++) {
if (i > lastColon && tokens[i].match('<')) {
if (count == 0) {
template = i;
}
count++;
} else if (i > lastColon && tokens[i].match('>')) {
count--;
if (count == 0 && i + 1 != n) {
template = -1;
}
}
}
if (template >= 0) {
name = foundConst ? "const " : "";
for (int i = 0; i < template; i++) {
name += tokens[i];
}
}
}
if (unconst && foundConst) {
name = name.substring(name.indexOf("const") + 5);
}
if (prefix != null) {
name = name.substring(name.indexOf(prefix) + prefix.length());
}
return name.trim();
}
@Override public boolean containsKey(Object key) {
return super.containsKey(key) || (parent != null && parent.containsKey(key));
}
public List<Info> get(String cppName) {
return get(cppName, true);
}
public List<Info> get(String cppName, boolean partial) {
String key = normalize(cppName, false, false);
List<Info> infoList = super.get(key);
boolean partialMatch = false;
if (infoList == null) {
key = normalize(cppName, true, false);
infoList = super.get(key);
}
if (infoList == null && partial) {
key = normalize(cppName, true, true);
infoList = super.get(key);
partialMatch = true;
}
if (infoList == null) {
infoList = new ArrayList<Info>();
}
if (parent != null) {
List<Info> l = parent.get(cppName, partial);
if (l != null && l.size() > 0) {
infoList = new ArrayList<Info>(infoList);
// prioritize parent when we only have a partial match
if (partialMatch) {
infoList.addAll(0, l);
} else {
infoList.addAll(l);
}
}
}
return infoList;
}
public Info get(int index, String cppName) {
return get(index, cppName, true);
}
public Info get(int index, String cppName, boolean partial) {
List<Info> infoList = get(cppName, partial);
return infoList.size() > 0 ? infoList.get(index) : null;
}
public Info getFirst(String cppName) {
return getFirst(cppName, true);
}
public Info getFirst(String cppName, boolean partial) {
List<Info> infoList = get(cppName, partial);
return infoList.size() > 0 ? infoList.get(0) : null;
}
public InfoMap put(int index, Info info) {
for (String cppName : info.cppNames != null ? info.cppNames : new String[] { null }) {
String[] keys = { normalize(cppName, false, false),
normalize(cppName, false, true) };
for (String key : keys) {
List<Info> infoList = super.get(key);
if (infoList == null) {
super.put(key, infoList = new ArrayList<Info>());
}
if (!infoList.contains(info)) {
switch (index) {
case -1: infoList.add(info); break;
default: infoList.add(index, info); break;
}
}
}
}
return this;
}
public InfoMap put(Info info) {
return put(-1, info);
}
public InfoMap putFirst(Info info) {
return put(0, info);
}
}
|
package xianyu;
import java.util.Scanner;
/**
* This is a program hat will read from the user the sky condition (string) and the current temperature (int).
* Your program will inform the user if they need a jacket and/or sunglasses.
* The user will need a jacket if the temperature is lower than 15 (inclusive)
* and they will need sunglasses if the sky is "sunny".
* If neither condition is true the user will need nothing.
*
* @authorXiaoyiWang date:07/10/2021
*/
public class P1 {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
String nameOfSky = kb.next();
int numberOfTemper = kb.nextInt();
if ("sunny".equals(nameOfSky)) {
if (numberOfTemper > 15){
System.out.println("You'll need sunglasses");
}else if (numberOfTemper <= 15) {
System.out.println("You'll need a jacket and sunglasses");
System.out.println();
}
}else {
System.out.println("You'll need nothing");
System.out.println();
}
}
}
|
package com.kore.ai.widgetsdk.net;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import com.kore.ai.widgetsdk.koranet.KORestBuilder;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.concurrent.TimeUnit;
import okhttp3.Dispatcher;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by Ramachandra Pradeep on 27-Oct-18.
*/
public class KaRestBuilder {
private static KaRestAPI kaRestAPI;
private KaRestBuilder(){}
public static KaRestAPI getKaRestAPI(){
if(kaRestAPI == null) {
kaRestAPI = new Retrofit.Builder()
.baseUrl(SDKConfiguration.Server.SERVER_URL)
.addConverterFactory(new NullOnEmptyConverterFactory())
.addConverterFactory(createConverter())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(getClient())
.build().create(KaRestAPI.class);
}
return kaRestAPI;
}
public static KaRestAPI getWidgetKaRestAPI(){
if(kaRestAPI == null) {
kaRestAPI = new Retrofit.Builder()
.baseUrl(SDKConfiguration.Server.WIDGETS_SERVER_URL)
.addConverterFactory(new NullOnEmptyConverterFactory())
.addConverterFactory(createConverter())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(getClient())
.build().create(KaRestAPI.class);
}
return kaRestAPI;
}
private static OkHttpClient getClient(){
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
Dispatcher dispatcher = new Dispatcher();
dispatcher.setMaxRequests(1);
// client.interceptors().add(KoreRequestInterceptor.getInstance(mContext));
return new OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.addInterceptor(interceptor)
.dispatcher(dispatcher)
.authenticator(new KoraRequestAuthenticator(KORestBuilder.mContext))
.build();
}
private static GsonConverterFactory createConverter() {
final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(boolean.class, new BooleanDeserializer());
gsonBuilder.excludeFieldsWithModifiers(Modifier.STATIC, Modifier.TRANSIENT);
final Gson gson = gsonBuilder.create();
return GsonConverterFactory.create(gson);
}
static class BooleanDeserializer implements JsonDeserializer {
@Override
public Object deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws com.google.gson.JsonParseException {
boolean value;
try {
value = json.getAsInt() > 0 ? true : false;
} catch (NumberFormatException ex) {
value = json.getAsBoolean();
}
return value;
}
}
static class NullOnEmptyConverterFactory extends Converter.Factory {
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
final Converter<ResponseBody, ?> delegate = retrofit.nextResponseBodyConverter(this, type, annotations);
return new Converter<ResponseBody, Object>() {
@Override
public Object convert(ResponseBody body) throws IOException {
if (body.contentLength() == 0) return null;
return delegate.convert(body); }
};
}
}
}
|
/*
* 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.
*/
/*
* $Id$
*/
package org.apache.xalan.xsltc.compiler;
import org.apache.bcel.generic.ALOAD;
import org.apache.bcel.generic.ASTORE;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.INVOKEINTERFACE;
import org.apache.bcel.generic.INVOKESPECIAL;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.LocalVariableGen;
import org.apache.bcel.generic.NEW;
import org.apache.xalan.xsltc.compiler.util.ClassGenerator;
import org.apache.xalan.xsltc.compiler.util.MethodGenerator;
import org.apache.xalan.xsltc.compiler.util.NodeType;
import org.apache.xalan.xsltc.compiler.util.Type;
import org.apache.xalan.xsltc.compiler.util.TypeCheckError;
import org.apache.xalan.xsltc.compiler.util.Util;
/**
* @author G. Todd Miller
*/
final class FilteredAbsoluteLocationPath extends Expression {
private Expression _path; // may be null
public FilteredAbsoluteLocationPath() {
_path = null;
}
public FilteredAbsoluteLocationPath(Expression path) {
_path = path;
if (path != null) {
_path.setParent(this);
}
}
public void setParser(Parser parser) {
super.setParser(parser);
if (_path != null) {
_path.setParser(parser);
}
}
public Expression getPath() {
return(_path);
}
public String toString() {
return "FilteredAbsoluteLocationPath(" +
(_path != null ? _path.toString() : "null") + ')';
}
public Type typeCheck(SymbolTable stable) throws TypeCheckError {
if (_path != null) {
final Type ptype = _path.typeCheck(stable);
if (ptype instanceof NodeType) { // promote to node-set
_path = new CastExpr(_path, Type.NodeSet);
}
}
return _type = Type.NodeSet;
}
public void translate(ClassGenerator classGen, MethodGenerator methodGen) {
final ConstantPoolGen cpg = classGen.getConstantPool();
final InstructionList il = methodGen.getInstructionList();
if (_path != null) {
final int initDFI = cpg.addMethodref(DUP_FILTERED_ITERATOR,
"<init>",
"("
+ NODE_ITERATOR_SIG
+ ")V");
// Backwards branches are prohibited if an uninitialized object is
// on the stack by section 4.9.4 of the JVM Specification, 2nd Ed.
// We don't know whether this code might contain backwards branches,
// so we mustn't create the new object until after we've created
// the suspect arguments to its constructor. Instead we calculate
// the values of the arguments to the constructor first, store them
// in temporary variables, create the object and reload the
// arguments from the temporaries to avoid the problem.
// Compile relative path iterator(s)
LocalVariableGen pathTemp =
methodGen.addLocalVariable("filtered_absolute_location_path_tmp",
Util.getJCRefType(NODE_ITERATOR_SIG),
null, null);
_path.translate(classGen, methodGen);
pathTemp.setStart(il.append(new ASTORE(pathTemp.getIndex())));
// Create new Dup Filter Iterator
il.append(new NEW(cpg.addClass(DUP_FILTERED_ITERATOR)));
il.append(DUP);
pathTemp.setEnd(il.append(new ALOAD(pathTemp.getIndex())));
// Initialize Dup Filter Iterator with iterator from the stack
il.append(new INVOKESPECIAL(initDFI));
}
else {
final int git = cpg.addInterfaceMethodref(DOM_INTF,
"getIterator",
"()"+NODE_ITERATOR_SIG);
il.append(methodGen.loadDOM());
il.append(new INVOKEINTERFACE(git, 1));
}
}
}
|
package com.inadco.hbl.math.pig;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;
import org.apache.hadoop.io.DataInputBuffer;
import org.apache.hadoop.io.DataOutputBuffer;
import org.apache.pig.Accumulator;
import org.apache.pig.Algebraic;
import org.apache.pig.EvalFunc;
import org.apache.pig.data.DataBag;
import org.apache.pig.data.DataByteArray;
import org.apache.pig.data.DataType;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
import org.apache.pig.impl.logicalLayer.FrontendException;
import org.apache.pig.impl.logicalLayer.schema.Schema;
import org.apache.pig.impl.logicalLayer.schema.Schema.FieldSchema;
import com.inadco.hbl.math.aggregators.IrregularSamplingSummarizer;
/**
* Accepts parameters:
* <P>
*
* bag of (x,t) observations
*
* size of 2 should be the same as size of 3
*
* @author dmitriy
*
*/
public class ExpAvgUpdate extends EvalFunc<DataByteArray> implements Algebraic, Accumulator<DataByteArray> {
private EAInitial m_delegate;
public ExpAvgUpdate(String dtStr) {
super();
m_delegate = new EAInitial(dtStr);
}
public void accumulate(Tuple bag) throws IOException {
m_delegate.accumulate(bag);
}
public DataByteArray exec(Tuple input) throws IOException {
return (DataByteArray) m_delegate.exec(input).get(0);
}
public DataByteArray getValue() {
try {
return (DataByteArray) m_delegate.getValue().get(0);
} catch (IOException exc) {
throw new IllegalArgumentException(exc);
}
}
@Override
public void cleanup() {
}
@Override
public String getInitial() {
return EAInitial.class.getName();
}
@Override
public String getIntermed() {
return EAIntermediate.class.getName();
}
@Override
public String getFinal() {
return EAFinal.class.getName();
}
@Override
public Type getReturnType() {
return DataByteArray.class;
}
@Override
public Schema outputSchema(Schema input) {
try {
// this is strange. some of invocations send in {sample:(x,t)} and
// some send {{sample:(x,t)}} for obviously
// same invocation pattern.
if (input.size() != 1 || DataType.BAG != input.getField(0).type)
throw new IllegalArgumentException("Bag argument expected");
Schema bagTupleSchema = input.getField(0).schema;
// workaround for what seems to be a pig bug?
if (bagTupleSchema.getField(0).type == DataType.TUPLE)
bagTupleSchema = bagTupleSchema.getField(0).schema;
List<FieldSchema> fields = bagTupleSchema.getFields();
if (fields.size() != 2 || !DataType.isNumberType(fields.get(0).type)
|| !DataType.isNumberType(fields.get(1).type))
throw new IllegalArgumentException("Bag of 2 doubles expected");
return super.outputSchema(input);
} catch (FrontendException exc) {
throw new RuntimeException(exc);
}
}
static IrregularSamplingSummarizer accumulate(Tuple bag, IrregularSamplingSummarizer summarizer, String initStr)
throws IOException {
if (summarizer == null)
summarizer = PigSummarizerHelper.createSummarizer(initStr, false);
DataBag db = DataType.toBag(bag.get(0));
if (db == null)
throw new IOException("bag argument is null");
for (Tuple tup : db) {
Double x = DataType.toDouble(tup.get(0));
Double t = DataType.toDouble(tup.get(1));
if (x == null || tup == null)
throw new IOException("bad x or t parameter");
summarizer.update(x, t);
}
return summarizer;
}
public static class EAInitial extends EvalFunc<Tuple> implements Accumulator<Tuple> {
private String m_initStr;
private IrregularSamplingSummarizer m_summarizer;
private DataOutputBuffer m_dob = new DataOutputBuffer();
public EAInitial() {
super();
}
public EAInitial(String initStr) {
super();
m_initStr = initStr;
}
@Override
public void accumulate(Tuple bag) throws IOException {
m_summarizer = ExpAvgUpdate.accumulate(bag, m_summarizer, m_initStr);
}
@Override
public Tuple getValue() {
try {
if (m_summarizer == null)
// group's '0'
m_summarizer = PigSummarizerHelper.createSummarizer(m_initStr, false);
DataOutputBuffer dob = PigSummarizerHelper.ser2bytes(m_summarizer, m_dob);
return TupleFactory.getInstance().newTuple(dob == null ? null : new DataByteArray(
dob.getData(),
0,
dob.getLength()));
} catch (IOException exc) {
throw new RuntimeException(exc);
}
}
@Override
public void cleanup() {
m_summarizer = null;
}
@Override
public Tuple exec(Tuple input) throws IOException {
try {
m_summarizer = null;
accumulate(input);
return getValue();
} finally {
m_summarizer = null;
}
}
}
public static class EAIntermediate extends EvalFunc<Tuple> implements Accumulator<Tuple> {
private String m_initStr;
private IrregularSamplingSummarizer m_summarizer;
private IrregularSamplingSummarizer m_buffer;
private DataOutputBuffer m_dob = new DataOutputBuffer();
private DataInputBuffer m_dib = new DataInputBuffer();
public EAIntermediate() {
super();
}
public EAIntermediate(String initStr) {
super();
m_initStr = initStr;
m_buffer = PigSummarizerHelper.createSummarizer(initStr, true);
}
@Override
public void accumulate(Tuple b) throws IOException {
m_summarizer = PigSummarizerHelper.combine(b, m_dib, m_initStr, m_summarizer, m_buffer);
}
@Override
public Tuple getValue() {
try {
DataOutputBuffer dob = PigSummarizerHelper.ser2bytes(m_summarizer, m_dob);
return TupleFactory.getInstance().newTuple(dob == null ? null : new DataByteArray(
dob.getData(),
0,
dob.getLength()));
} catch (IOException exc) {
throw new RuntimeException(exc);
}
}
@Override
public void cleanup() {
m_summarizer = null;
}
@Override
public Tuple exec(Tuple input) throws IOException {
try {
m_summarizer = null;
accumulate(input);
return getValue();
} finally {
m_summarizer = null;
}
}
}
public static class EAFinal extends EvalFunc<DataByteArray> implements Accumulator<DataByteArray> {
private String m_initStr;
private IrregularSamplingSummarizer m_summarizer;
private IrregularSamplingSummarizer m_buffer;
private DataOutputBuffer m_dob = new DataOutputBuffer();
private DataInputBuffer m_dib = new DataInputBuffer();
public EAFinal() {
super();
}
public EAFinal(String initStr) {
super();
m_buffer = PigSummarizerHelper.createSummarizer(initStr, true);
m_initStr = initStr;
}
@Override
public void accumulate(Tuple b) throws IOException {
m_summarizer = PigSummarizerHelper.combine(b, m_dib, m_initStr, m_summarizer, m_buffer);
}
@Override
public DataByteArray getValue() {
try {
DataOutputBuffer dob = PigSummarizerHelper.ser2bytes(m_summarizer, m_dob);
return dob == null ? null : new DataByteArray(dob.getData(), 0, dob.getLength());
} catch (IOException exc) {
throw new RuntimeException(exc);
}
}
@Override
public void cleanup() {
m_summarizer = null;
}
@Override
public DataByteArray exec(Tuple input) throws IOException {
try {
m_summarizer = null;
accumulate(input);
return getValue();
} finally {
m_summarizer = null;
}
}
}
}
|
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/gaming/v1alpha/common.proto
package com.google.cloud.gaming.v1alpha;
public final class Common {
private Common() {}
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {}
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry);
}
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_gaming_v1alpha_OperationMetadata_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_gaming_v1alpha_OperationMetadata_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_gaming_v1alpha_OperationMetadata_OperationStatusEntry_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_gaming_v1alpha_OperationMetadata_OperationStatusEntry_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_gaming_v1alpha_OperationStatus_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_gaming_v1alpha_OperationStatus_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_gaming_v1alpha_LabelSelector_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_gaming_v1alpha_LabelSelector_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_gaming_v1alpha_LabelSelector_LabelsEntry_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_gaming_v1alpha_LabelSelector_LabelsEntry_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_gaming_v1alpha_RealmSelector_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_gaming_v1alpha_RealmSelector_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_gaming_v1alpha_Schedule_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_gaming_v1alpha_Schedule_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_gaming_v1alpha_FleetDetails_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_gaming_v1alpha_FleetDetails_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_gaming_v1alpha_FleetDetails_AutoscalerDetails_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_gaming_v1alpha_FleetDetails_AutoscalerDetails_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_gaming_v1alpha_DeployedState_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_gaming_v1alpha_DeployedState_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_gaming_v1alpha_SpecSource_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_gaming_v1alpha_SpecSource_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_gaming_v1alpha_TargetDetails_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_gaming_v1alpha_TargetDetails_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_gaming_v1alpha_TargetDetails_TargetFleetDetails_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_gaming_v1alpha_TargetDetails_TargetFleetDetails_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_gaming_v1alpha_TargetDetails_TargetFleetDetails_TargetFleet_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_gaming_v1alpha_TargetDetails_TargetFleetDetails_TargetFleet_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_gaming_v1alpha_TargetDetails_TargetFleetDetails_TargetFleetAutoscaler_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_gaming_v1alpha_TargetDetails_TargetFleetDetails_TargetFleetAutoscaler_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_gaming_v1alpha_TargetState_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_gaming_v1alpha_TargetState_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor descriptor;
static {
java.lang.String[] descriptorData = {
"\n(google/cloud/gaming/v1alpha/common.pro"
+ "to\022\033google.cloud.gaming.v1alpha\032\037google/"
+ "api/field_behavior.proto\032\036google/protobu"
+ "f/duration.proto\032\037google/protobuf/timest"
+ "amp.proto\032\034google/api/annotations.proto\""
+ "\344\003\n\021OperationMetadata\0224\n\013create_time\030\001 \001"
+ "(\0132\032.google.protobuf.TimestampB\003\340A\003\0221\n\010e"
+ "nd_time\030\002 \001(\0132\032.google.protobuf.Timestam"
+ "pB\003\340A\003\022\023\n\006target\030\003 \001(\tB\003\340A\003\022\021\n\004verb\030\004 \001("
+ "\tB\003\340A\003\022\033\n\016status_message\030\005 \001(\tB\003\340A\003\022#\n\026r"
+ "equested_cancellation\030\006 \001(\010B\003\340A\003\022\030\n\013api_"
+ "version\030\007 \001(\tB\003\340A\003\022\030\n\013unreachable\030\010 \003(\tB"
+ "\003\340A\003\022b\n\020operation_status\030\t \003(\0132C.google."
+ "cloud.gaming.v1alpha.OperationMetadata.O"
+ "perationStatusEntryB\003\340A\003\032d\n\024OperationSta"
+ "tusEntry\022\013\n\003key\030\001 \001(\t\022;\n\005value\030\002 \001(\0132,.g"
+ "oogle.cloud.gaming.v1alpha.OperationStat"
+ "us:\0028\001\"\363\001\n\017OperationStatus\022\021\n\004done\030\001 \001(\010"
+ "B\003\340A\003\022J\n\nerror_code\030\002 \001(\01626.google.cloud"
+ ".gaming.v1alpha.OperationStatus.ErrorCod"
+ "e\022\025\n\rerror_message\030\003 \001(\t\"j\n\tErrorCode\022\032\n"
+ "\026ERROR_CODE_UNSPECIFIED\020\000\022\022\n\016INTERNAL_ER"
+ "ROR\020\001\022\025\n\021PERMISSION_DENIED\020\002\022\026\n\022CLUSTER_"
+ "CONNECTION\020\003\"\206\001\n\rLabelSelector\022F\n\006labels"
+ "\030\001 \003(\01326.google.cloud.gaming.v1alpha.Lab"
+ "elSelector.LabelsEntry\032-\n\013LabelsEntry\022\013\n"
+ "\003key\030\001 \001(\t\022\r\n\005value\030\002 \001(\t:\0028\001\"\037\n\rRealmSe"
+ "lector\022\016\n\006realms\030\001 \003(\t\"\261\001\n\010Schedule\022.\n\ns"
+ "tart_time\030\001 \001(\0132\032.google.protobuf.Timest"
+ "amp\022,\n\010end_time\030\002 \001(\0132\032.google.protobuf."
+ "Timestamp\0224\n\021cron_job_duration\030\003 \001(\0132\031.g"
+ "oogle.protobuf.Duration\022\021\n\tcron_spec\030\004 \001"
+ "(\t\"\211\002\n\014FleetDetails\022 \n\030game_server_clust"
+ "er_name\030\001 \001(\t\022\022\n\nfleet_name\030\002 \001(\t\022\037\n\027gam"
+ "e_server_config_name\030\003 \001(\t\022W\n\022autoscaler"
+ "_details\030\004 \001(\0132;.google.cloud.gaming.v1a"
+ "lpha.FleetDetails.AutoscalerDetails\032I\n\021A"
+ "utoscalerDetails\022\027\n\017autoscaler_name\030\001 \001("
+ "\t\022\033\n\023scaling_config_name\030\002 \001(\t\"N\n\rDeploy"
+ "edState\0229\n\006fleets\030\001 \003(\0132).google.cloud.g"
+ "aming.v1alpha.FleetDetails:\002\030\001\";\n\nSpecSo"
+ "urce\022\037\n\027game_server_config_name\030\001 \001(\t\022\014\n"
+ "\004name\030\002 \001(\t\"\306\004\n\rTargetDetails\022 \n\030game_se"
+ "rver_cluster_name\030\001 \001(\t\022#\n\033game_server_d"
+ "eployment_name\030\002 \001(\t\022T\n\rfleet_details\030\003 "
+ "\003(\0132=.google.cloud.gaming.v1alpha.Target"
+ "Details.TargetFleetDetails\032\227\003\n\022TargetFle"
+ "etDetails\022X\n\005fleet\030\001 \001(\0132I.google.cloud."
+ "gaming.v1alpha.TargetDetails.TargetFleet"
+ "Details.TargetFleet\022g\n\nautoscaler\030\002 \001(\0132"
+ "S.google.cloud.gaming.v1alpha.TargetDeta"
+ "ils.TargetFleetDetails.TargetFleetAutosc"
+ "aler\032Y\n\013TargetFleet\022\014\n\004name\030\001 \001(\t\022<\n\013spe"
+ "c_source\030\002 \001(\0132\'.google.cloud.gaming.v1a"
+ "lpha.SpecSource\032c\n\025TargetFleetAutoscaler"
+ "\022\014\n\004name\030\001 \001(\t\022<\n\013spec_source\030\002 \001(\0132\'.go"
+ "ogle.cloud.gaming.v1alpha.SpecSource\"J\n\013"
+ "TargetState\022;\n\007details\030\001 \003(\0132*.google.cl"
+ "oud.gaming.v1alpha.TargetDetailsBf\n\037com."
+ "google.cloud.gaming.v1alphaP\001ZAgoogle.go"
+ "lang.org/genproto/googleapis/cloud/gamin"
+ "g/v1alpha;gamingb\006proto3"
};
descriptor =
com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(
descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
com.google.api.FieldBehaviorProto.getDescriptor(),
com.google.protobuf.DurationProto.getDescriptor(),
com.google.protobuf.TimestampProto.getDescriptor(),
com.google.api.AnnotationsProto.getDescriptor(),
});
internal_static_google_cloud_gaming_v1alpha_OperationMetadata_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_google_cloud_gaming_v1alpha_OperationMetadata_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_gaming_v1alpha_OperationMetadata_descriptor,
new java.lang.String[] {
"CreateTime",
"EndTime",
"Target",
"Verb",
"StatusMessage",
"RequestedCancellation",
"ApiVersion",
"Unreachable",
"OperationStatus",
});
internal_static_google_cloud_gaming_v1alpha_OperationMetadata_OperationStatusEntry_descriptor =
internal_static_google_cloud_gaming_v1alpha_OperationMetadata_descriptor
.getNestedTypes()
.get(0);
internal_static_google_cloud_gaming_v1alpha_OperationMetadata_OperationStatusEntry_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_gaming_v1alpha_OperationMetadata_OperationStatusEntry_descriptor,
new java.lang.String[] {
"Key", "Value",
});
internal_static_google_cloud_gaming_v1alpha_OperationStatus_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_google_cloud_gaming_v1alpha_OperationStatus_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_gaming_v1alpha_OperationStatus_descriptor,
new java.lang.String[] {
"Done", "ErrorCode", "ErrorMessage",
});
internal_static_google_cloud_gaming_v1alpha_LabelSelector_descriptor =
getDescriptor().getMessageTypes().get(2);
internal_static_google_cloud_gaming_v1alpha_LabelSelector_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_gaming_v1alpha_LabelSelector_descriptor,
new java.lang.String[] {
"Labels",
});
internal_static_google_cloud_gaming_v1alpha_LabelSelector_LabelsEntry_descriptor =
internal_static_google_cloud_gaming_v1alpha_LabelSelector_descriptor
.getNestedTypes()
.get(0);
internal_static_google_cloud_gaming_v1alpha_LabelSelector_LabelsEntry_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_gaming_v1alpha_LabelSelector_LabelsEntry_descriptor,
new java.lang.String[] {
"Key", "Value",
});
internal_static_google_cloud_gaming_v1alpha_RealmSelector_descriptor =
getDescriptor().getMessageTypes().get(3);
internal_static_google_cloud_gaming_v1alpha_RealmSelector_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_gaming_v1alpha_RealmSelector_descriptor,
new java.lang.String[] {
"Realms",
});
internal_static_google_cloud_gaming_v1alpha_Schedule_descriptor =
getDescriptor().getMessageTypes().get(4);
internal_static_google_cloud_gaming_v1alpha_Schedule_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_gaming_v1alpha_Schedule_descriptor,
new java.lang.String[] {
"StartTime", "EndTime", "CronJobDuration", "CronSpec",
});
internal_static_google_cloud_gaming_v1alpha_FleetDetails_descriptor =
getDescriptor().getMessageTypes().get(5);
internal_static_google_cloud_gaming_v1alpha_FleetDetails_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_gaming_v1alpha_FleetDetails_descriptor,
new java.lang.String[] {
"GameServerClusterName", "FleetName", "GameServerConfigName", "AutoscalerDetails",
});
internal_static_google_cloud_gaming_v1alpha_FleetDetails_AutoscalerDetails_descriptor =
internal_static_google_cloud_gaming_v1alpha_FleetDetails_descriptor.getNestedTypes().get(0);
internal_static_google_cloud_gaming_v1alpha_FleetDetails_AutoscalerDetails_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_gaming_v1alpha_FleetDetails_AutoscalerDetails_descriptor,
new java.lang.String[] {
"AutoscalerName", "ScalingConfigName",
});
internal_static_google_cloud_gaming_v1alpha_DeployedState_descriptor =
getDescriptor().getMessageTypes().get(6);
internal_static_google_cloud_gaming_v1alpha_DeployedState_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_gaming_v1alpha_DeployedState_descriptor,
new java.lang.String[] {
"Fleets",
});
internal_static_google_cloud_gaming_v1alpha_SpecSource_descriptor =
getDescriptor().getMessageTypes().get(7);
internal_static_google_cloud_gaming_v1alpha_SpecSource_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_gaming_v1alpha_SpecSource_descriptor,
new java.lang.String[] {
"GameServerConfigName", "Name",
});
internal_static_google_cloud_gaming_v1alpha_TargetDetails_descriptor =
getDescriptor().getMessageTypes().get(8);
internal_static_google_cloud_gaming_v1alpha_TargetDetails_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_gaming_v1alpha_TargetDetails_descriptor,
new java.lang.String[] {
"GameServerClusterName", "GameServerDeploymentName", "FleetDetails",
});
internal_static_google_cloud_gaming_v1alpha_TargetDetails_TargetFleetDetails_descriptor =
internal_static_google_cloud_gaming_v1alpha_TargetDetails_descriptor
.getNestedTypes()
.get(0);
internal_static_google_cloud_gaming_v1alpha_TargetDetails_TargetFleetDetails_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_gaming_v1alpha_TargetDetails_TargetFleetDetails_descriptor,
new java.lang.String[] {
"Fleet", "Autoscaler",
});
internal_static_google_cloud_gaming_v1alpha_TargetDetails_TargetFleetDetails_TargetFleet_descriptor =
internal_static_google_cloud_gaming_v1alpha_TargetDetails_TargetFleetDetails_descriptor
.getNestedTypes()
.get(0);
internal_static_google_cloud_gaming_v1alpha_TargetDetails_TargetFleetDetails_TargetFleet_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_gaming_v1alpha_TargetDetails_TargetFleetDetails_TargetFleet_descriptor,
new java.lang.String[] {
"Name", "SpecSource",
});
internal_static_google_cloud_gaming_v1alpha_TargetDetails_TargetFleetDetails_TargetFleetAutoscaler_descriptor =
internal_static_google_cloud_gaming_v1alpha_TargetDetails_TargetFleetDetails_descriptor
.getNestedTypes()
.get(1);
internal_static_google_cloud_gaming_v1alpha_TargetDetails_TargetFleetDetails_TargetFleetAutoscaler_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_gaming_v1alpha_TargetDetails_TargetFleetDetails_TargetFleetAutoscaler_descriptor,
new java.lang.String[] {
"Name", "SpecSource",
});
internal_static_google_cloud_gaming_v1alpha_TargetState_descriptor =
getDescriptor().getMessageTypes().get(9);
internal_static_google_cloud_gaming_v1alpha_TargetState_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_gaming_v1alpha_TargetState_descriptor,
new java.lang.String[] {
"Details",
});
com.google.protobuf.ExtensionRegistry registry =
com.google.protobuf.ExtensionRegistry.newInstance();
registry.add(com.google.api.FieldBehaviorProto.fieldBehavior);
com.google.protobuf.Descriptors.FileDescriptor.internalUpdateFileDescriptor(
descriptor, registry);
com.google.api.FieldBehaviorProto.getDescriptor();
com.google.protobuf.DurationProto.getDescriptor();
com.google.protobuf.TimestampProto.getDescriptor();
com.google.api.AnnotationsProto.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
}
|
package hr.fer.zemris.ml.training.random_forest;
/**
* Interface for observers of random forest building.
*
* @author Dan
*/
public interface IRFGeneratorObserver {
/**
* Called when a classification decision tree is constructed.
*
* @param depth depth of the tree
* @param oobCorrect correctly classified samples that were not used for
* training
* @param oobSize number of samples that were not used for training
*/
void classificationTreeConstructed(int depth, int oobCorrect, int oobSize);
/**
* Called when a regression decision tree is constructed.
*
* @param depth depth of the tree
* @param mse mean squared error of predictions on samples that were not
* used for training
*/
void regressionTreeConstructed(int depth, double mse);
}
|
/*
* (C) Copyright IBM Corp. 2020
*
* SPDX-License-Identifier: Apache-2.0
*/
package com.ibm.fhir.search.group;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.logging.Logger;
import javax.ws.rs.core.MultivaluedMap;
import com.ibm.fhir.model.resource.Group;
import com.ibm.fhir.model.type.CodeableConcept;
import com.ibm.fhir.model.type.Quantity;
import com.ibm.fhir.model.type.Range;
import com.ibm.fhir.model.type.Reference;
import com.ibm.fhir.path.FHIRPathNode;
import com.ibm.fhir.path.evaluator.FHIRPathEvaluator;
import com.ibm.fhir.path.evaluator.FHIRPathEvaluator.EvaluationContext;
import com.ibm.fhir.path.exception.FHIRPathException;
import com.ibm.fhir.search.group.characteristic.AdministrativeGenderCharacteristicProcessor;
import com.ibm.fhir.search.group.characteristic.CharacteristicProcessor;
import com.ibm.fhir.search.group.characteristic.NoOpCharacteristicProcessor;
import com.ibm.fhir.search.group.characteristic.PatientAgeCharacteristicProcessor;
import com.ibm.fhir.search.group.characteristic.PregnancyStatusCharacteristicProcessor;
/**
* Group Search Compiler routes the Group based on characteristics to each of the corresponding processors for the
* Supported Elements, and generates the corresponding Search QueryParameters based on the relevant target.
*/
public class GroupSearchCompilerImpl implements GroupSearchCompiler {
private static final Logger logger = Logger.getLogger(GroupSearchCompilerImpl.class.getName());
// For any new processors, add them to the appropriate Group.Characteristic choice element.
private static final List<CharacteristicProcessor> CODEABLE_CONCEPT_PROCESSORS = Arrays.asList(new PregnancyStatusCharacteristicProcessor(), new AdministrativeGenderCharacteristicProcessor());
private static final List<CharacteristicProcessor> BOOLEAN_PROCESSORS = Arrays.asList(new NoOpCharacteristicProcessor());
private static final List<CharacteristicProcessor> RANGE_PROCESSORS = Arrays.asList(new NoOpCharacteristicProcessor());
private static final List<CharacteristicProcessor> REFERENCE_PROCESSORS = Arrays.asList(new NoOpCharacteristicProcessor());
private static final List<CharacteristicProcessor> QUANTITY_PROCESSORS = Arrays.asList(new PatientAgeCharacteristicProcessor());
@Override
public MultivaluedMap<String, String> groupToSearch(Group group, String target) throws GroupSearchCompilerException {
Objects.requireNonNull(group, "The Group must not be null");
Objects.requireNonNull(group.getActive(), "The group.active must not be null");
if (!group.getActive().getValue().booleanValue()) {
throw new GroupSearchCompilerException("The Group must be active");
}
MultivaluedMap<String, String> queryParams = new javax.ws.rs.core.MultivaluedHashMap<>();
try {
FHIRPathEvaluator evaluator = FHIRPathEvaluator.evaluator();
EvaluationContext evaluationContext = new EvaluationContext(group);
String expr = "characteristic";
Collection<FHIRPathNode> tmpResults = evaluator.evaluate(evaluationContext, expr);
for (FHIRPathNode node : tmpResults) {
Group.Characteristic characteristic = node.asElementNode().element().as(Group.Characteristic.class);
// Quantity also takes care of assignable values.
if (characteristic.getValue().is(Quantity.class)) {
QUANTITY_PROCESSORS.stream().forEach(m -> m.process(characteristic, target, queryParams));
} else if (characteristic.getValue().is(CodeableConcept.class)) {
CODEABLE_CONCEPT_PROCESSORS.stream().forEach(m -> m.process(characteristic, target, queryParams));
} else if (characteristic.getValue().is(com.ibm.fhir.model.type.Boolean.class)) {
BOOLEAN_PROCESSORS.stream().forEach(m -> m.process(characteristic, target, queryParams));
} else if (characteristic.getValue().is(Range.class)) {
RANGE_PROCESSORS.stream().forEach(m -> m.process(characteristic, target, queryParams));
} else if (characteristic.getValue().is(Reference.class)) {
REFERENCE_PROCESSORS.stream().forEach(m -> m.process(characteristic, target, queryParams));
}
}
} catch (FHIRPathException exception) {
logger.warning("Issue processing the Group into Search Query");
throw new GroupSearchCompilerException("Issue with Search Query");
}
return queryParams;
}
}
|
package kodlamaio.Hrms.dataAccess.abstracts;
import org.springframework.data.jpa.repository.JpaRepository;
import kodlamaio.Hrms.entities.concretes.Employer;
public interface EmployerDao extends JpaRepository<Employer, Integer>{
Employer getByEmail(String email);
Employer getByCompanyName(String companyName);
Employer getByWebsite(String website);
boolean existsEmployerByCompanyName(String companyName);
boolean existsEmployerByEmail(String email);
boolean existsEmployerByWebsite(String website);
boolean existsEmployerByPhoneNumber(String phoneNumber);
}
|
package com.togo.c_sms;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.togo.c_sms", appContext.getPackageName());
}
}
|
/* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009-2020, Arnaud Roques
*
* Project Info: https://plantuml.com
*
* If you like this project or if you find it useful, you can support us at:
*
* https://plantuml.com/patreon (only 1$ per month!)
* https://plantuml.com/paypal
*
* This file is part of PlantUML.
*
* Licensed under The MIT License (Massachusetts Institute of Technology License)
*
* See http://opensource.org/licenses/MIT
*
* 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.
*
*
* Original Author: Arnaud Roques
*/
package net.sourceforge.plantuml.ugraphic;
import java.awt.geom.Dimension2D;
import net.sourceforge.plantuml.graphic.StringBounder;
import net.sourceforge.plantuml.ugraphic.color.ColorMapper;
import net.sourceforge.plantuml.ugraphic.color.HColor;
public class TextLimitFinder extends UGraphicNo implements UGraphic {
public boolean matchesProperty(String propertyName) {
return false;
}
public double dpiFactor() {
return 1;
}
public UGraphic apply(UChange change) {
if (change instanceof UTranslate) {
return new TextLimitFinder(stringBounder, minmax, translate.compose((UTranslate) change));
} else if (change instanceof UStroke) {
return new TextLimitFinder(this);
} else if (change instanceof UBackground) {
return new TextLimitFinder(this);
} else if (change instanceof HColor) {
return new TextLimitFinder(this);
}
throw new UnsupportedOperationException();
}
private final StringBounder stringBounder;
private final UTranslate translate;
private final MinMaxMutable minmax;
public TextLimitFinder(StringBounder stringBounder, boolean initToZero) {
this(stringBounder, MinMaxMutable.getEmpty(initToZero), new UTranslate());
}
private TextLimitFinder(StringBounder stringBounder, MinMaxMutable minmax, UTranslate translate) {
this.stringBounder = stringBounder;
this.minmax = minmax;
this.translate = translate;
}
private TextLimitFinder(TextLimitFinder other) {
this(other.stringBounder, other.minmax, other.translate);
}
public StringBounder getStringBounder() {
return stringBounder;
}
public UParam getParam() {
return new UParamNull();
}
public void draw(UShape shape) {
if (shape instanceof UText) {
final double x = translate.getDx();
final double y = translate.getDy();
drawText(x, y, (UText) shape);
}
}
public ColorMapper getColorMapper() {
throw new UnsupportedOperationException();
}
private void drawText(double x, double y, UText text) {
final Dimension2D dim = stringBounder.calculateDimension(text.getFontConfiguration().getFont(), text.getText());
y -= dim.getHeight() - 1.5;
minmax.addPoint(x, y);
minmax.addPoint(x, y + dim.getHeight());
minmax.addPoint(x + dim.getWidth(), y);
minmax.addPoint(x + dim.getWidth(), y + dim.getHeight());
}
public double getMaxX() {
return minmax.getMaxX();
}
public double getMaxY() {
return minmax.getMaxY();
}
public double getMinX() {
return minmax.getMinX();
}
public double getMinY() {
return minmax.getMinY();
}
public void flushUg() {
}
}
|
/*
*
* 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.qpid.server.protocol.converter.v0_10_v1_0;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.google.common.io.ByteStreams;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
import org.apache.qpid.server.model.NamedAddressSpace;
import org.apache.qpid.server.protocol.converter.MessageConversionException;
import org.apache.qpid.server.protocol.v0_10.MessageTransferMessage;
import org.apache.qpid.server.protocol.v0_10.transport.mimecontentconverter.AmqpListToListConverter;
import org.apache.qpid.server.protocol.v0_10.transport.mimecontentconverter.AmqpMapToMapConverter;
import org.apache.qpid.server.protocol.v0_10.transport.mimecontentconverter.ListToAmqpListConverter;
import org.apache.qpid.server.protocol.v0_10.transport.mimecontentconverter.MapToAmqpMapConverter;
import org.apache.qpid.server.protocol.v1_0.MessageMetaData_1_0;
import org.apache.qpid.server.protocol.v1_0.Message_1_0;
import org.apache.qpid.server.protocol.v1_0.type.Binary;
import org.apache.qpid.server.protocol.v1_0.type.Symbol;
import org.apache.qpid.server.protocol.v1_0.type.messaging.AmqpSequence;
import org.apache.qpid.server.protocol.v1_0.type.messaging.AmqpValue;
import org.apache.qpid.server.protocol.v1_0.type.messaging.ApplicationProperties;
import org.apache.qpid.server.protocol.v1_0.type.messaging.Data;
import org.apache.qpid.server.protocol.v1_0.type.messaging.DeliveryAnnotations;
import org.apache.qpid.server.protocol.v1_0.type.messaging.EncodingRetainingSection;
import org.apache.qpid.server.protocol.v1_0.type.messaging.Footer;
import org.apache.qpid.server.protocol.v1_0.type.messaging.Header;
import org.apache.qpid.server.protocol.v1_0.type.messaging.MessageAnnotations;
import org.apache.qpid.server.protocol.v1_0.type.messaging.Properties;
import org.apache.qpid.server.protocol.v1_0.type.messaging.Source;
import org.apache.qpid.server.store.StoredMessage;
import org.apache.qpid.server.typedmessage.mimecontentconverter.JmsMapMessageToMap;
import org.apache.qpid.server.typedmessage.mimecontentconverter.JmsStreamMessageToList;
import org.apache.qpid.server.typedmessage.mimecontentconverter.ListToJmsStreamMessage;
import org.apache.qpid.server.typedmessage.mimecontentconverter.MapToJmsMapMessage;
import org.apache.qpid.test.utils.UnitTestBase;
public class MessageConverter_1_0_to_v0_10Test extends UnitTestBase
{
private static final MessageAnnotations MESSAGE_MESSAGE_ANNOTATION =
new MessageAnnotations(Collections.singletonMap(Symbol.valueOf("x-opt-jms-msg-type"), (byte) 0));
private static final MessageAnnotations OBJECT_MESSAGE_MESSAGE_ANNOTATION =
new MessageAnnotations(Collections.singletonMap(Symbol.valueOf("x-opt-jms-msg-type"), (byte) 1));
private static final MessageAnnotations MAP_MESSAGE_MESSAGE_ANNOTATION =
new MessageAnnotations(Collections.singletonMap(Symbol.valueOf("x-opt-jms-msg-type"), (byte) 2));
private static final MessageAnnotations BYTE_MESSAGE_MESSAGE_ANNOTATION =
new MessageAnnotations(Collections.singletonMap(Symbol.valueOf("x-opt-jms-msg-type"), (byte) 3));
private static final MessageAnnotations STREAM_MESSAGE_MESSAGE_ANNOTATION =
new MessageAnnotations(Collections.singletonMap(Symbol.valueOf("x-opt-jms-msg-type"), (byte) 4));
private static final MessageAnnotations TEXT_MESSAGE_MESSAGE_ANNOTATION =
new MessageAnnotations(Collections.singletonMap(Symbol.valueOf("x-opt-jms-msg-type"), (byte) 5));
private MessageConverter_1_0_to_v0_10 _converter;
@Before
public void setUp() throws Exception
{
_converter = new MessageConverter_1_0_to_v0_10();
}
@Test
public void testAmqpValueWithNullWithTextMessageAnnotation() throws Exception
{
final Object expected = null;
final AmqpValue amqpValue = new AmqpValue(expected);
Message_1_0 sourceMessage =
createTestMessage(TEXT_MESSAGE_MESSAGE_ANNOTATION, amqpValue.createEncodingRetainingSection());
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type", "text/plain", convertedMessage.getMessageHeader().getMimeType());
assertEquals("Unexpected content size", (long) 0, convertedMessage.getSize());
}
@Test
public void testAmqpValueWithNullWithMessageAnnotation() throws Exception
{
final Object expected = null;
final AmqpValue amqpValue = new AmqpValue(expected);
Message_1_0 sourceMessage =
createTestMessage(MESSAGE_MESSAGE_ANNOTATION, amqpValue.createEncodingRetainingSection());
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type", null, convertedMessage.getMessageHeader().getMimeType());
assertEquals("Unexpected content size", (long) 0, convertedMessage.getSize());
}
@Test
public void testAmqpValueWithNullWithObjectMessageAnnotation() throws Exception
{
final Object expected = null;
final AmqpValue amqpValue = new AmqpValue(expected);
Message_1_0 sourceMessage = createTestMessage(OBJECT_MESSAGE_MESSAGE_ANNOTATION, amqpValue.createEncodingRetainingSection());
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
assertEquals("Unexpected mime type",
"application/java-object-stream",
convertedMessage.getMessageHeader().getMimeType());
assertArrayEquals("Unexpected content size", getObjectBytes(null), getBytes(content));
}
@Test
public void testAmqpValueWithNullWithMapMessageAnnotation() throws Exception
{
final Object expected = null;
final AmqpValue amqpValue = new AmqpValue(expected);
Message_1_0 sourceMessage = createTestMessage(MAP_MESSAGE_MESSAGE_ANNOTATION, amqpValue.createEncodingRetainingSection());
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
assertEquals("Unexpected mime type",
"jms/map-message",
convertedMessage.getMessageHeader().getMimeType());
assertArrayEquals("Unexpected content size",
new MapToJmsMapMessage().toMimeContent(Collections.emptyMap()),
getBytes(content));
}
@Test
public void testAmqpValueWithNullWithBytesMessageAnnotation() throws Exception
{
final Object expected = null;
final AmqpValue amqpValue = new AmqpValue(expected);
Message_1_0 sourceMessage = createTestMessage(BYTE_MESSAGE_MESSAGE_ANNOTATION, amqpValue.createEncodingRetainingSection());
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type",
"application/octet-stream",
convertedMessage.getMessageHeader().getMimeType());
assertEquals("Unexpected content size", (long) 0, convertedMessage.getSize());
}
@Test
public void testAmqpValueWithNullWithStreamMessageAnnotation() throws Exception
{
final Object expected = null;
final AmqpValue amqpValue = new AmqpValue(expected);
Message_1_0 sourceMessage = createTestMessage(STREAM_MESSAGE_MESSAGE_ANNOTATION, amqpValue.createEncodingRetainingSection());
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type",
"jms/stream-message",
convertedMessage.getMessageHeader().getMimeType());
assertEquals("Unexpected content size", (long) 0, convertedMessage.getSize());
}
@Test
public void testAmqpValueWithNullWithUnknownMessageAnnotation() throws Exception
{
final Object expected = null;
final AmqpValue amqpValue = new AmqpValue(expected);
Message_1_0 sourceMessage =
createTestMessage(new MessageAnnotations(Collections.singletonMap(Symbol.valueOf("x-opt-jms-msg-type"),
(byte) 11)),
amqpValue.createEncodingRetainingSection());
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type", null, convertedMessage.getMessageHeader().getMimeType());
assertEquals("Unexpected content size", (long) 0, convertedMessage.getSize());
}
@Test
public void testAmqpValueWithNullWithContentTypeApplicationOctetStream() throws Exception
{
Properties properties = new Properties();
properties.setContentType(Symbol.valueOf("application/octet-stream"));
final Object expected = null;
final AmqpValue amqpValue = new AmqpValue(expected);
Message_1_0 sourceMessage = createTestMessage(properties, amqpValue.createEncodingRetainingSection());
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type",
"application/octet-stream",
convertedMessage.getMessageHeader().getMimeType());
assertEquals("Unexpected content size", (long) 0, convertedMessage.getSize());
}
@Test
public void testAmqpValueWithNullWithObjectMessageContentType() throws Exception
{
final Properties properties = new Properties();
properties.setContentType(Symbol.valueOf("application/x-java-serialized-object"));
final Object expected = null;
final AmqpValue amqpValue = new AmqpValue(expected);
Message_1_0 sourceMessage = createTestMessage(properties, amqpValue.createEncodingRetainingSection());
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type",
"application/java-object-stream",
convertedMessage.getMessageHeader().getMimeType());
assertEquals("Unexpected content size", (long) getObjectBytes(null).length, convertedMessage.getSize());
}
@Test
public void testAmqpValueWithNullWithJmsMapContentType() throws Exception
{
final Properties properties = new Properties();
properties.setContentType(Symbol.valueOf("jms/map-message"));
final Object expected = null;
final AmqpValue amqpValue = new AmqpValue(expected);
Message_1_0 sourceMessage = createTestMessage(properties, amqpValue.createEncodingRetainingSection());
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
assertEquals("Unexpected mime type",
"jms/map-message",
convertedMessage.getMessageHeader().getMimeType());
assertArrayEquals("Unexpected content size",
new MapToJmsMapMessage().toMimeContent(Collections.emptyMap()),
getBytes(content));
}
@Test
public void testAmqpValueWithNull() throws Exception
{
final Object expected = null;
final AmqpValue amqpValue = new AmqpValue(expected);
Message_1_0 sourceMessage = createTestMessage(amqpValue.createEncodingRetainingSection());
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type", null, convertedMessage.getMessageHeader().getMimeType());
assertEquals("Unexpected content size", (long) 0, convertedMessage.getSize());
}
@Test
public void testAmqpValueWithString() throws Exception
{
final String expected = "testContent";
final AmqpValue amqpValue = new AmqpValue(expected);
Message_1_0 sourceMessage = createTestMessage(amqpValue.createEncodingRetainingSection());
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type", "text/plain", convertedMessage.getMessageHeader().getMimeType());
final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
assertEquals("Unexpected content", expected, new String(getBytes(content), UTF_8));
}
@Test
public void testAmqpValueWithStringWithTextMessageAnnotation() throws Exception
{
final String expected = "testContent";
final AmqpValue amqpValue = new AmqpValue(expected);
Message_1_0 sourceMessage =
createTestMessage(TEXT_MESSAGE_MESSAGE_ANNOTATION, amqpValue.createEncodingRetainingSection());
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type", "text/plain", convertedMessage.getMessageHeader().getMimeType());
final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
assertEquals("Unexpected content", expected, new String(getBytes(content), UTF_8));
}
@Test
public void testAmqpValueWithMap() throws Exception
{
final Map<String, Object> originalMap = new LinkedHashMap<>();
originalMap.put("binaryEntry", new Binary(new byte[]{0x00, (byte) 0xFF}));
originalMap.put("intEntry", 42);
originalMap.put("nullEntry", null);
final AmqpValue amqpValue = new AmqpValue(originalMap);
Message_1_0 sourceMessage = createTestMessage(amqpValue.createEncodingRetainingSection());
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type",
"jms/map-message",
convertedMessage.getMessageHeader().getMimeType());
final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
Map<String, Object> convertedMap = new JmsMapMessageToMap().toObject(getBytes(content));
assertEquals("Unexpected size", (long) originalMap.size(), (long) convertedMap.size());
assertArrayEquals("Unexpected binary entry", ((Binary) originalMap.get("binaryEntry")).getArray(),
(byte[]) convertedMap.get("binaryEntry"));
assertEquals("Unexpected int entry", originalMap.get("intEntry"), convertedMap.get("intEntry"));
assertEquals("Unexpected null entry", originalMap.get("nullEntry"), convertedMap.get("nullEntry"));
}
@Test
public void testAmqpValueWithMapContainingMap() throws Exception
{
final Map<String, Object> originalMap =
Collections.singletonMap("testMap", Collections.singletonMap("innerKey", "testValue"));
final AmqpValue amqpValue = new AmqpValue(originalMap);
Message_1_0 sourceMessage = createTestMessage(amqpValue.createEncodingRetainingSection());
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type", "amqp/map", convertedMessage.getMessageHeader().getMimeType());
final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
Map<String, Object> convertedMap = new AmqpMapToMapConverter().toObject(getBytes(content));
assertEquals("Unexpected size", (long) originalMap.size(), (long) convertedMap.size());
assertEquals("Unexpected binary entry",
new HashMap((Map<String, Object>) originalMap.get("testMap")),
new HashMap((Map<String, Object>) convertedMap.get("testMap")));
}
@Test
public void testAmqpValueWithMapContainingNonFieldTableCompliantEntries() throws Exception
{
final AmqpValue amqpValue = new AmqpValue(Collections.<Object, Object>singletonMap(13, 42));
Message_1_0 sourceMessage = createTestMessage(amqpValue.createEncodingRetainingSection());
try
{
_converter.convert(sourceMessage, mock(NamedAddressSpace.class));
fail("expected exception not thrown.");
}
catch (MessageConversionException e)
{
// pass
}
}
@Test
public void testAmqpValueWithList() throws Exception
{
final List<Object> originalList = new ArrayList<>();
originalList.add(new Binary(new byte[]{0x00, (byte) 0xFF}));
originalList.add(42);
originalList.add(null);
final AmqpValue amqpValue = new AmqpValue(originalList);
Message_1_0 sourceMessage = createTestMessage(amqpValue.createEncodingRetainingSection());
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type",
"jms/stream-message",
convertedMessage.getMessageHeader().getMimeType());
final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
List<Object> convertedList = new JmsStreamMessageToList().toObject(getBytes(content));
assertEquals("Unexpected size", (long) originalList.size(), (long) convertedList.size());
assertArrayEquals("Unexpected binary item", ((Binary) originalList.get(0)).getArray(),
(byte[]) convertedList.get(0));
assertEquals("Unexpected int item", originalList.get(1), convertedList.get(1));
assertEquals("Unexpected null item", originalList.get(2), convertedList.get(2));
}
@Test
public void testAmqpValueWithListContainingMap() throws Exception
{
final List<Object> originalList = Collections.singletonList(Collections.singletonMap("testKey", "testValue"));
final AmqpValue amqpValue = new AmqpValue(originalList);
Message_1_0 sourceMessage = createTestMessage(amqpValue.createEncodingRetainingSection());
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type", "amqp/list", convertedMessage.getMessageHeader().getMimeType());
final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
List<Object> convertedList = new AmqpListToListConverter().toObject(getBytes(content));
assertEquals("Unexpected size", (long) originalList.size(), (long) convertedList.size());
assertEquals("Unexpected map item",
new HashMap<String, Object>((Map) originalList.get(0)),
new HashMap<String, Object>((Map) convertedList.get(0)));
}
@Test
public void testAmqpValueWithListContainingUnsupportedType() throws Exception
{
final List<Object> originalList = Collections.singletonList(new Source());
final AmqpValue amqpValue = new AmqpValue(originalList);
Message_1_0 sourceMessage = createTestMessage(amqpValue.createEncodingRetainingSection());
try
{
_converter.convert(sourceMessage, mock(NamedAddressSpace.class));
fail("expected exception not thrown.");
}
catch (MessageConversionException e)
{
// pass
}
}
@Test
public void testAmqpValueWithUnsupportedType() throws Exception
{
final Integer originalValue = 42;
final AmqpValue amqpValue = new AmqpValue(originalValue);
Message_1_0 sourceMessage = createTestMessage(amqpValue.createEncodingRetainingSection());
try
{
_converter.convert(sourceMessage, mock(NamedAddressSpace.class));
fail("expected exception not thrown.");
}
catch (MessageConversionException e)
{
// pass
}
}
@Test
public void testAmqpSequenceWithSimpleTypes() throws Exception
{
final List<Integer> expected = new ArrayList<>();
expected.add(37);
expected.add(42);
final AmqpSequence amqpSequence = new AmqpSequence(expected);
Message_1_0 sourceMessage = createTestMessage(amqpSequence.createEncodingRetainingSection());
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type",
"jms/stream-message",
convertedMessage.getMessageHeader().getMimeType());
final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
assertEquals("Unexpected content", expected, new JmsStreamMessageToList().toObject(getBytes(content)));
}
@Test
public void testAmqpSequenceWithMap() throws Exception
{
final List<Object> originalList = Collections.singletonList(Collections.singletonMap("testKey", "testValue"));
final AmqpSequence amqpSequence = new AmqpSequence(originalList);
Message_1_0 sourceMessage = createTestMessage(amqpSequence.createEncodingRetainingSection());
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type", "amqp/list", convertedMessage.getMessageHeader().getMimeType());
final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
List<Object> convertedList = new AmqpListToListConverter().toObject(getBytes(content));
assertEquals("Unexpected size", (long) originalList.size(), (long) convertedList.size());
assertEquals("Unexpected map item",
new HashMap<String, Object>((Map) originalList.get(0)),
new HashMap<String, Object>((Map) convertedList.get(0)));
}
@Test
public void testAmqpSequenceWithUnsupportedType() throws Exception
{
final List<Object> originalList = Collections.singletonList(new Source());
final AmqpSequence amqpSequence = new AmqpSequence(originalList);
Message_1_0 sourceMessage = createTestMessage(amqpSequence.createEncodingRetainingSection());
try
{
_converter.convert(sourceMessage, mock(NamedAddressSpace.class));
fail("expected exception not thrown.");
}
catch (MessageConversionException e)
{
// pass
}
}
@Test
public void testDataWithMessageAnnotation() throws Exception
{
doTestDataWithAnnotation("helloworld".getBytes(UTF_8), MESSAGE_MESSAGE_ANNOTATION, "application/octet-stream");
}
@Test
public void testDataWithObjectMessageAnnotation() throws Exception
{
byte[] bytes = "helloworld".getBytes(UTF_8);
final byte[] expected = getObjectBytes(bytes);
doTestDataWithAnnotation(expected, OBJECT_MESSAGE_MESSAGE_ANNOTATION, "application/java-object-stream");
}
@Test
public void testDataWithMapMessageAnnotation() throws Exception
{
doTestDataWithAnnotation("helloworld".getBytes(UTF_8),
MAP_MESSAGE_MESSAGE_ANNOTATION,
"application/octet-stream");
}
@Test
public void testDataWithMapMessageAnnotationAndContentTypeJmsMapMessage() throws Exception
{
Map<String, Object> originalMap = Collections.singletonMap("testKey", "testValue");
byte[] data = new MapToJmsMapMessage().toMimeContent(originalMap);
String expectedMimeType = "jms/map-message";
final Data value = new Data(new Binary(data));
Properties properties = new Properties();
properties.setContentType(Symbol.valueOf(expectedMimeType));
Message_1_0 sourceMessage = createTestMessage(properties,
MAP_MESSAGE_MESSAGE_ANNOTATION,
value.createEncodingRetainingSection());
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type", expectedMimeType, convertedMessage.getMessageHeader().getMimeType());
final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
assertArrayEquals("Unexpected content", data, getBytes(content));
}
@Test
public void testDataWithMapMessageAnnotationAndContentTypeAmqpMap() throws Exception
{
Map<String, Object> originalMap = Collections.singletonMap("testKey", "testValue");
byte[] data = new MapToAmqpMapConverter().toMimeContent(originalMap);
String expectedMimeType = "amqp/map";
final Data value = new Data(new Binary(data));
Properties properties = new Properties();
properties.setContentType(Symbol.valueOf(expectedMimeType));
Message_1_0 sourceMessage = createTestMessage(properties,
MAP_MESSAGE_MESSAGE_ANNOTATION,
value.createEncodingRetainingSection());
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type", expectedMimeType, convertedMessage.getMessageHeader().getMimeType());
final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
assertArrayEquals("Unexpected content", data, getBytes(content));
}
@Test
public void testDataWithBytesMessageAnnotation() throws Exception
{
doTestDataWithAnnotation("helloworld".getBytes(UTF_8),
BYTE_MESSAGE_MESSAGE_ANNOTATION,
"application/octet-stream");
}
@Test
public void testDataWithStreamMessageAnnotation() throws Exception
{
doTestDataWithAnnotation("helloworld".getBytes(UTF_8), STREAM_MESSAGE_MESSAGE_ANNOTATION,
"application/octet-stream");
}
@Test
public void testDataWithStreamMessageAnnotationAndContentTypeJmsStreamMessage() throws Exception
{
List<Object> originalList = Collections.singletonList("testValue");
byte[] data = new ListToJmsStreamMessage().toMimeContent(originalList);
String expectedMimeType = "jms/stream-message";
final Data value = new Data(new Binary(data));
Properties properties = new Properties();
properties.setContentType(Symbol.valueOf(expectedMimeType));
Message_1_0 sourceMessage = createTestMessage(properties,
STREAM_MESSAGE_MESSAGE_ANNOTATION,
value.createEncodingRetainingSection());
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type", expectedMimeType, convertedMessage.getMessageHeader().getMimeType());
final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
assertArrayEquals("Unexpected content", data, getBytes(content));
}
@Test
public void testDataWithStreamMessageAnnotationAndContentTypeAmqpList() throws Exception
{
List<Object> originalList = Collections.singletonList("testValue");
byte[] data = new ListToAmqpListConverter().toMimeContent(originalList);
String expectedMimeType = "amqp/list";
final Data value = new Data(new Binary(data));
Properties properties = new Properties();
properties.setContentType(Symbol.valueOf(expectedMimeType));
Message_1_0 sourceMessage = createTestMessage(properties,
STREAM_MESSAGE_MESSAGE_ANNOTATION,
value.createEncodingRetainingSection());
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type", expectedMimeType, convertedMessage.getMessageHeader().getMimeType());
final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
assertArrayEquals("Unexpected content", data, getBytes(content));
}
@Test
public void testDataWithTextMessageAnnotation() throws Exception
{
doTestDataWithAnnotation("helloworld".getBytes(UTF_8), TEXT_MESSAGE_MESSAGE_ANNOTATION, "text/plain");
}
@Test
public void testDataWithUnsupportedMessageAnnotation() throws Exception
{
doTestDataWithAnnotation("helloworld".getBytes(UTF_8),
new MessageAnnotations(Collections.singletonMap(Symbol.valueOf("x-opt-jms-msg-type"),
(byte) 11)),
"application/octet-stream");
}
@Test
public void testDataWithContentTypeText() throws Exception
{
doTestConvertOfDataSectionForTextualType("text/foobar");
}
@Test
public void testDataWithContentTypeApplicationXml() throws Exception
{
doTestConvertOfDataSectionForTextualType("application/xml");
}
@Test
public void testDataWithContentTypeApplicationXmlDtd() throws Exception
{
doTestConvertOfDataSectionForTextualType("application/xml-dtd");
}
@Test
public void testDataWithContentTypeApplicationFooXml() throws Exception
{
doTestConvertOfDataSectionForTextualType("application/foo+xml");
}
@Test
public void testDataWithContentTypeApplicationJson() throws Exception
{
doTestConvertOfDataSectionForTextualType("application/json");
}
@Test
public void testDataWithContentTypeApplicationFooJson() throws Exception
{
doTestConvertOfDataSectionForTextualType("application/foo+json");
}
@Test
public void testDataWithContentTypeApplicationJavascript() throws Exception
{
doTestConvertOfDataSectionForTextualType("application/javascript");
}
@Test
public void testDataWithContentTypeApplicationEcmascript() throws Exception
{
doTestConvertOfDataSectionForTextualType("application/ecmascript");
}
@Test
public void testDataWithContentTypeAmqpMap() throws Exception
{
Map<String, Object> originalMap = Collections.singletonMap("testKey", "testValue");
byte[] bytes = new MapToAmqpMapConverter().toMimeContent(originalMap);
final Data value = new Data(new Binary(bytes));
Properties properties = new Properties();
properties.setContentType(Symbol.valueOf("amqp/map"));
Message_1_0 sourceMessage = createTestMessage(properties, value.createEncodingRetainingSection());
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type", "amqp/map", convertedMessage.getMessageHeader().getMimeType());
final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
assertArrayEquals("Unexpected content", bytes, getBytes(content));
}
@Test
public void testDataWithContentTypeJmsMapMessage() throws Exception
{
Map<String, Object> originalMap = Collections.singletonMap("testKey", "testValue");
byte[] bytes = new MapToJmsMapMessage().toMimeContent(originalMap);
final Data value = new Data(new Binary(bytes));
Properties properties = new Properties();
properties.setContentType(Symbol.valueOf("jms/map-message"));
Message_1_0 sourceMessage = createTestMessage(properties, value.createEncodingRetainingSection());
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type",
"jms/map-message",
convertedMessage.getMessageHeader().getMimeType());
final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
assertArrayEquals("Unexpected content", bytes, getBytes(content));
}
@Test
public void testDataWithContentTypeAmqpList() throws Exception
{
List<Object> originalMap = Collections.singletonList("testValue");
byte[] bytes = new ListToAmqpListConverter().toMimeContent(originalMap);
final Data value = new Data(new Binary(bytes));
Properties properties = new Properties();
properties.setContentType(Symbol.valueOf("amqp/list"));
Message_1_0 sourceMessage = createTestMessage(properties, value.createEncodingRetainingSection());
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type", "amqp/list", convertedMessage.getMessageHeader().getMimeType());
final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
assertArrayEquals("Unexpected content", bytes, getBytes(content));
}
@Test
public void testDataWithContentTypeJmsStreamMessage() throws Exception
{
List<Object> originalMap = Collections.singletonList("testValue");
byte[] bytes = new ListToJmsStreamMessage().toMimeContent(originalMap);
final Data value = new Data(new Binary(bytes));
Properties properties = new Properties();
properties.setContentType(Symbol.valueOf("jms/stream-message"));
Message_1_0 sourceMessage = createTestMessage(properties, value.createEncodingRetainingSection());
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type",
"jms/stream-message",
convertedMessage.getMessageHeader().getMimeType());
final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
assertArrayEquals("Unexpected content", bytes, getBytes(content));
}
@Test
public void testDataWithContentTypeJavaSerializedObject() throws Exception
{
final byte[] expected = getObjectBytes("helloworld".getBytes(UTF_8));
final Data value = new Data(new Binary(expected));
Properties properties = new Properties();
properties.setContentType(Symbol.valueOf("application/x-java-serialized-object"));
Message_1_0 sourceMessage = createTestMessage(properties, value.createEncodingRetainingSection());
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type",
"application/java-object-stream",
convertedMessage.getMessageHeader().getMimeType());
final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
assertArrayEquals("Unexpected content", expected, getBytes(content));
}
@Test
public void testDataWithContentTypeJavaObjectStream() throws Exception
{
final byte[] expected = getObjectBytes("helloworld".getBytes(UTF_8));
final Data value = new Data(new Binary(expected));
Properties properties = new Properties();
properties.setContentType(Symbol.valueOf("application/java-object-stream"));
Message_1_0 sourceMessage = createTestMessage(properties, value.createEncodingRetainingSection());
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type",
"application/java-object-stream",
convertedMessage.getMessageHeader().getMimeType());
final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
assertArrayEquals("Unexpected content", expected, getBytes(content));
}
@Test
public void testDataWithContentTypeOther() throws Exception
{
final byte[] expected = "helloworld".getBytes(UTF_8);
final Data value = new Data(new Binary(expected));
final Properties properties = new Properties();
properties.setContentType(Symbol.valueOf("application/bin"));
Message_1_0 sourceMessage = createTestMessage(properties, value.createEncodingRetainingSection());
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type",
"application/octet-stream",
convertedMessage.getMessageHeader().getMimeType());
final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
assertArrayEquals("Unexpected content", expected, getBytes(content));
}
@Test
public void testData() throws Exception
{
final byte[] expected = getObjectBytes("helloworld".getBytes(UTF_8));
final Data value = new Data(new Binary(expected));
final Message_1_0 sourceMessage = createTestMessage(value.createEncodingRetainingSection());
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type",
"application/octet-stream",
convertedMessage.getMessageHeader().getMimeType());
final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
assertArrayEquals("Unexpected content", expected, getBytes(content));
}
@Test
public void testNoBodyWithMessageAnnotation() throws Exception
{
Message_1_0 sourceMessage = createTestMessage(MESSAGE_MESSAGE_ANNOTATION, null);
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type", null, convertedMessage.getMessageHeader().getMimeType());
assertEquals("Unexpected content size", (long) 0, convertedMessage.getSize());
}
@Test
public void testNoBodyWithObjectMessageAnnotation() throws Exception
{
Message_1_0 sourceMessage = createTestMessage(OBJECT_MESSAGE_MESSAGE_ANNOTATION, null);
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
assertEquals("Unexpected mime type",
"application/java-object-stream",
convertedMessage.getMessageHeader().getMimeType());
assertArrayEquals("Unexpected content size", getObjectBytes(null), getBytes(content));
}
@Test
public void testNoBodyWithMapMessageAnnotation() throws Exception
{
Message_1_0 sourceMessage = createTestMessage(MAP_MESSAGE_MESSAGE_ANNOTATION, null);
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
assertEquals("Unexpected mime type",
"jms/map-message",
convertedMessage.getMessageHeader().getMimeType());
assertArrayEquals("Unexpected content size",
new MapToJmsMapMessage().toMimeContent(Collections.emptyMap()),
getBytes(content));
}
@Test
public void testNoBodyWithBytesMessageAnnotation() throws Exception
{
Message_1_0 sourceMessage = createTestMessage(BYTE_MESSAGE_MESSAGE_ANNOTATION, null);
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type",
"application/octet-stream",
convertedMessage.getMessageHeader().getMimeType());
assertEquals("Unexpected content size", (long) 0, convertedMessage.getSize());
}
@Test
public void testNoBodyWithStreamMessageAnnotation() throws Exception
{
Message_1_0 sourceMessage = createTestMessage(STREAM_MESSAGE_MESSAGE_ANNOTATION, null);
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type",
"jms/stream-message",
convertedMessage.getMessageHeader().getMimeType());
assertEquals("Unexpected content size", (long) 0, convertedMessage.getSize());
}
@Test
public void testNoBodyWithTextMessageAnnotation() throws Exception
{
Message_1_0 sourceMessage = createTestMessage(TEXT_MESSAGE_MESSAGE_ANNOTATION, null);
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type", "text/plain", convertedMessage.getMessageHeader().getMimeType());
assertEquals("Unexpected content size", (long) 0, convertedMessage.getSize());
}
@Test
public void testNoBodyWithUnknownMessageAnnotation() throws Exception
{
Message_1_0 sourceMessage =
createTestMessage(new MessageAnnotations(Collections.singletonMap(Symbol.valueOf("x-opt-jms-msg-type"),
(byte) 11)), null);
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type", null, convertedMessage.getMessageHeader().getMimeType());
assertEquals("Unexpected content size", (long) 0, convertedMessage.getSize());
}
@Test
public void testNoBody() throws Exception
{
final Message_1_0 sourceMessage = createTestMessage(null);
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type", null, convertedMessage.getMessageHeader().getMimeType());
assertEquals("Unexpected content size", (long) 0, convertedMessage.getSize());
}
@Test
public void testNoBodyWithContentTypeApplicationOctetStream() throws Exception
{
Properties properties = new Properties();
properties.setContentType(Symbol.valueOf("application/octet-stream"));
final Message_1_0 sourceMessage = createTestMessage(properties, null);
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type",
"application/octet-stream",
convertedMessage.getMessageHeader().getMimeType());
assertEquals("Unexpected content size", (long) 0, convertedMessage.getSize());
}
@Test
public void testNoBodyWithObjectMessageContentType() throws Exception
{
final Properties properties = new Properties();
properties.setContentType(Symbol.valueOf("application/x-java-serialized-object"));
final Message_1_0 sourceMessage = createTestMessage(properties, null);
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type",
"application/java-object-stream",
convertedMessage.getMessageHeader().getMimeType());
assertEquals("Unexpected content size", (long) getObjectBytes(null).length, convertedMessage.getSize());
}
@Test
public void testNoBodyWithJmsMapContentType() throws Exception
{
final Properties properties = new Properties();
properties.setContentType(Symbol.valueOf("jms/map-message"));
final Message_1_0 sourceMessage = createTestMessage(properties, null);
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
assertEquals("Unexpected mime type",
"jms/map-message",
convertedMessage.getMessageHeader().getMimeType());
assertArrayEquals("Unexpected content size",
new MapToJmsMapMessage().toMimeContent(Collections.emptyMap()),
getBytes(content));
}
@Test
public void testMessageAnnotationTakesPrecedenceOverContentType() throws Exception
{
final Properties properties = new Properties();
properties.setContentType(Symbol.valueOf("application/octet-stream"));
final Message_1_0 sourceMessage = createTestMessage(OBJECT_MESSAGE_MESSAGE_ANNOTATION, null);
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type",
"application/java-object-stream",
convertedMessage.getMessageHeader().getMimeType());
assertEquals("Unexpected content size", (long) getObjectBytes(null).length, convertedMessage.getSize());
}
private void doTestConvertOfDataSectionForTextualType(final String contentType) throws Exception
{
final String expected = "testContent";
final Data value = new Data(new Binary(expected.getBytes(UTF_8)));
final Properties properties = new Properties();
properties.setContentType(Symbol.valueOf(contentType));
Message_1_0 sourceMessage = createTestMessage(properties, value.createEncodingRetainingSection());
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
assertEquals("Unexpected content", expected, new String(getBytes(content), UTF_8));
assertEquals("Unexpected mime type", "text/plain", convertedMessage.getMessageHeader().getMimeType());
}
private byte[] getBytes(final QpidByteBuffer content) throws Exception
{
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
InputStream contentInputStream = content.asInputStream())
{
ByteStreams.copy(contentInputStream, bos);
content.dispose();
return bos.toByteArray();
}
}
private Message_1_0 createTestMessage(final EncodingRetainingSection encodingRetainingSection)
{
return createTestMessage(new Properties(), encodingRetainingSection);
}
private Message_1_0 createTestMessage(final Properties properties, final EncodingRetainingSection section)
{
return createTestMessage(new Header(),
new DeliveryAnnotations(Collections.emptyMap()),
new MessageAnnotations(Collections.emptyMap()),
properties,
new ApplicationProperties(Collections.emptyMap()),
0,
section);
}
private Message_1_0 createTestMessage(final Properties properties,
final MessageAnnotations messageAnnotations,
final EncodingRetainingSection section)
{
return createTestMessage(new Header(),
new DeliveryAnnotations(Collections.emptyMap()),
messageAnnotations,
properties,
new ApplicationProperties(Collections.emptyMap()),
0,
section);
}
private Message_1_0 createTestMessage(final MessageAnnotations messageAnnotations,
final EncodingRetainingSection section)
{
return createTestMessage(new Header(),
new DeliveryAnnotations(Collections.emptyMap()),
messageAnnotations,
new Properties(),
new ApplicationProperties(Collections.emptyMap()),
0,
section);
}
private Message_1_0 createTestMessage(final Header header,
final DeliveryAnnotations deliveryAnnotations,
final MessageAnnotations messageAnnotations,
final Properties properties,
final ApplicationProperties applicationProperties,
final long arrivalTime,
final EncodingRetainingSection section)
{
final StoredMessage<MessageMetaData_1_0> storedMessage = mock(StoredMessage.class);
MessageMetaData_1_0 metaData = new MessageMetaData_1_0(header.createEncodingRetainingSection(),
deliveryAnnotations.createEncodingRetainingSection(),
messageAnnotations.createEncodingRetainingSection(),
properties.createEncodingRetainingSection(),
applicationProperties.createEncodingRetainingSection(),
new Footer(Collections.emptyMap()).createEncodingRetainingSection(),
arrivalTime,
0);
when(storedMessage.getMetaData()).thenReturn(metaData);
if (section != null)
{
// TODO this seems to leak QBBs
final QpidByteBuffer combined = section.getEncodedForm();
when(storedMessage.getContentSize()).thenReturn((int) section.getEncodedSize());
final ArgumentCaptor<Integer> offsetCaptor = ArgumentCaptor.forClass(Integer.class);
final ArgumentCaptor<Integer> sizeCaptor = ArgumentCaptor.forClass(Integer.class);
when(storedMessage.getContent(offsetCaptor.capture(),
sizeCaptor.capture())).then(invocation -> combined.view(offsetCaptor.getValue(),
sizeCaptor.getValue()));
}
else
{
when(storedMessage.getContent(0,0)).thenReturn(QpidByteBuffer.emptyQpidByteBuffer());
}
return new Message_1_0(storedMessage);
}
private byte[] getObjectBytes(final Object object) throws IOException
{
final byte[] expected;
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos))
{
oos.writeObject(object);
expected = baos.toByteArray();
}
return expected;
}
private void doTestDataWithAnnotation(final byte[] data,
final MessageAnnotations messageAnnotations,
final String expectedMimeType) throws Exception
{
final Data value = new Data(new Binary(data));
Message_1_0 sourceMessage = createTestMessage(messageAnnotations, value.createEncodingRetainingSection());
final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
assertEquals("Unexpected mime type", expectedMimeType, convertedMessage.getMessageHeader().getMimeType());
final QpidByteBuffer content = convertedMessage.getContent();
assertArrayEquals("Unexpected content", data, getBytes(content));
}
}
|
package com.algorithmlx.liaveres.api.interfaces;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
public interface IArmorTick {
void armorTick(ItemStack stack, Player player);
}
|
package com.Sample;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
@EntityScan(basePackageClasses=com.Sample.Entity.Person.class)
@SpringBootApplication
public class AppleApplication {
public static void main(String[] args) {
SpringApplication.run(AppleApplication.class, args);
}
}
|
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.vulkan;
/**
* Applications may wish to export memory to other Vulkan instances or other APIs, or import memory from other Vulkan instances or other APIs to enable Vulkan workloads to be split up across application module, process, or API boundaries. This extension enables applications to create exportable Vulkan memory objects such that the underlying resources can be referenced outside the Vulkan instance that created them.
*
* <h5>Examples</h5>
*
* <pre><code>
* // TODO: Write some sample code here.</code></pre>
*
* <dl>
* <dt><b>Name String</b></dt>
* <dd>{@code VK_NV_external_memory}</dd>
* <dt><b>Extension Type</b></dt>
* <dd>Device extension</dd>
* <dt><b>Registered Extension Number</b></dt>
* <dd>57</dd>
* <dt><b>Revision</b></dt>
* <dd>1</dd>
* <dt><b>Extension and Version Dependencies</b></dt>
* <dd><ul>
* <li>Requires Vulkan 1.0</li>
* <li>Requires {@link NVExternalMemoryCapabilities VK_NV_external_memory_capabilities}</li>
* </ul></dd>
* <dt><b>Deprecation state</b></dt>
* <dd><ul>
* <li><em>Deprecated</em> by {@link KHRExternalMemory VK_KHR_external_memory} extension
*
* <ul>
* <li>Which in turn was <em>promoted</em> to <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#versions-1.1-promotions">Vulkan 1.1</a></li>
* </ul>
* </li>
* </ul></dd>
* <dt><b>Contact</b></dt>
* <dd><ul>
* <li>James Jones <a target="_blank" href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?title=VK_NV_external_memory:%20&body=@cubanismo%20">cubanismo</a></li>
* </ul></dd>
* <dt><b>Last Modified Date</b></dt>
* <dd>2016-08-19</dd>
* <dt><b>IP Status</b></dt>
* <dd>No known IP claims.</dd>
* <dt><b>Contributors</b></dt>
* <dd><ul>
* <li>James Jones, NVIDIA</li>
* <li>Carsten Rohde, NVIDIA</li>
* </ul></dd>
* </dl>
*/
public final class NVExternalMemory {
/** The extension specification version. */
public static final int VK_NV_EXTERNAL_MEMORY_SPEC_VERSION = 1;
/** The extension name. */
public static final String VK_NV_EXTERNAL_MEMORY_EXTENSION_NAME = "VK_NV_external_memory";
/**
* Extends {@code VkStructureType}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO_NV STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO_NV}</li>
* <li>{@link #VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_NV STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_NV}</li>
* </ul>
*/
public static final int
VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO_NV = 1000056000,
VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_NV = 1000056001;
private NVExternalMemory() {}
}
|
/*******************************************************************************
* Copyright (c) 2004 Actuate 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:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.core.framework.eclipse;
import org.eclipse.birt.core.framework.FrameworkException;
import org.eclipse.birt.core.framework.IConfigurationElement;
import org.eclipse.birt.core.framework.IExecutableExtension;
/**
*
*/
class EclispeExecutableExtension implements IExecutableExtension
{
/* (non-Javadoc)
* @see org.eclipse.birt.core.framework.IExecutableExtension#setInitializationData(org.eclipse.birt.core.framework.IConfigurationElement, java.lang.String, java.lang.Object)
*/
public void setInitializationData( IConfigurationElement config,
String propertyName, Object data ) throws FrameworkException
{
// TODO Auto-generated method stub
}
}
|
package com.mawen.mybatisplus.mapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.test.autoconfigure.MybatisPlusTest;
import com.mawen.mybatisplus.entity.User;
import org.assertj.core.util.Maps;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
/**
* @author mawen
* @create 2022-01-21 11:46
*/
@MybatisPlusTest
public class UserMapperDeleteTest {
@Autowired
private UserMapper userMapper;
@Test
public void delete() {
Long count = userMapper.selectCount(null);
int i = userMapper.delete(new QueryWrapper<User>().lambda().eq(User::getId, 1L));
System.out.println("delete user ret: " + i);
Long ret = userMapper.selectCount(null);
Assertions.assertEquals(count - i, ret);
}
@Test
public void deleteBatchIds() {
List<User> userList = userMapper.selectList(null);
List<Long> ids = userList.stream().map(User::getId).collect(Collectors.toList());
int i = userMapper.deleteBatchIds(ids);
System.out.println("delete ids ret:" + i);
Long ret = userMapper.selectCount(null);
Assertions.assertEquals(0, ret);
}
@Test
public void deleteById() {
int i = userMapper.deleteById(1L);
System.out.println("delete id ret:" + i);
User user = userMapper.selectById(1L);
Assertions.assertNull(user);
}
@Test
public void deleteByMap() {
Map<String, Object> paramMap = Maps.newHashMap("id", 1L);
int i = userMapper.deleteByMap(paramMap);
System.out.println("delete map ret:" + i);
User user = userMapper.selectById(1L);
Assertions.assertNull(user);
}
}
|
package io.github.fatihbozik.ch9.interactingwithfiles;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Example6 {
public static void main(String[] args) {
try {
Files.move(Paths.get("/zoo"), Paths.get("/zoo-new"));
Files.move(Paths.get("/user/addresses.txt"), Paths.get("/zoo-new/addresses.txt"));
} catch (IOException e) {
// Handle file I/O exception...
}
}
}
|
package com.esri.soap;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for Polygon complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="Polygon"&gt;
* &lt;complexContent&gt;
* &lt;extension base="{http://www.esri.com/schemas/ArcGIS/10.7}Polycurve"&gt;
* &lt;/extension&gt;
* &lt;/complexContent&gt;
* &lt;/complexType&gt;
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Polygon")
@XmlSeeAlso({
PolygonN.class,
PolygonB.class
})
public abstract class Polygon
extends Polycurve
{
}
|
package com.dq.easy.cloud.model.common.properties.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
/**
*
* @ClassName : PropertiesUtils
* @Description : 读取配置文件工具类
* @author daiqi
* @date 2017年12月6日 上午9:59:04
*
*/
@Component
public class DqPropertiesUtils {
// 默认从application.properties中取数据
private static Environment environment;
public static Environment getEnvironment() {
return environment;
}
@Autowired
public void setEnvironment(Environment environment) {
DqPropertiesUtils.environment = environment;
}
/**
* <p></p>
*
* <pre>
* </pre>
*
* @param key
* @param targetType
* @return
* @author daiqi
* @date 2017年12月6日 下午3:32:29
*/
private static <T> T getProperty(String key, Class<T> targetType){
return environment.getProperty(key, targetType);
}
/**
*
* <p>根据指定key获取String类型的Value值,当值不存在的时候返回null</p>
*
* <pre>
* DqStringUtils.getStringValue(null) = null
* DqStringUtils.getStringValue("") = null
* </pre>
*
* @param key : propertis中的key
* @return <code>null</code>当key对应的值不存在的
* @author daiqi
* @date 2017年12月6日 上午10:56:57
*/
public static String getStringValue(String key){
return getProperty(key,String.class);
}
/**
*
* <p>根据指定key获取Integer类型的值,当值不存在的时候返回null</p>
*
* <pre>
* DqStringUtils.getIntegerValue(null) = null
* DqStringUtils.getIntegerValue("") = null
* DqStringUtils.getIntegerValue("intKey") = 2
* </pre>
*
* @param key
* @return 值存在返回对应的值不存在返回null
* @author daiqi
* @date 2017年12月6日 上午11:01:41
*/
public static Integer getIntegerValue(String key){
return getProperty(key, Integer.class);
}
/**
*
* <p>根据指定key获取Double类型的值,当值不存在的时候返回null</p>
*
* <pre>
* DqStringUtils.getDoubleValue(null) = null
* DqStringUtils.getDoubleValue("") = null
* DqStringUtils.getDoubleValue("doublekey") = 2.0
* </pre>
*
* @param key
* @return 值存在返回对应的值不存在返回null
* @author daiqi
* @date 2017年12月6日 上午11:03:35
*/
public static Double getDoubleValue(String key){
return getProperty(key, Double.class);
}
/**
*
* <p>根据指定key获取Boolean类型的值,当值不存在的时候返回 null</p>
*
* <pre>
* DqStringUtils.getDoubleValue(null) = null
* DqStringUtils.getDoubleValue("") = null
* DqStringUtils.getDoubleValue("booleankey") = true
* </pre>
*
* @param key
* @return 值存在返回对应的值不存在返回null
* @author daiqi
* @date 2017年12月6日 上午11:03:35
*/
public static Boolean getBooleanValue(String key){
return getProperty(key, Boolean.class);
}
/**
*
* <p>根据指定key获取Long类型的值,当值不存在的时候返回 null</p>
*
* <pre>
* DqStringUtils.getDoubleValue(null) = null
* DqStringUtils.getDoubleValue("") = null
* DqStringUtils.getDoubleValue("longkey") = 1
* </pre>
*
* @param key
* @return 值存在返回对应的值不存在返回null
* @author daiqi
* @date 2017年12月6日 上午11:03:35
*/
public static Long getLongValue(String key){
return getProperty(key, Long.class);
}
/**
*
* <p>根据指定key获取Float类型的值,当值不存在的时候返回 null</p>
*
* <pre>
* DqStringUtils.getDoubleValue(null) = null
* DqStringUtils.getDoubleValue("") = null
* DqStringUtils.getDoubleValue("floatkey") = 1.0
* </pre>
*
* @param key
* @return 值存在返回对应的值不存在返回null
* @author daiqi
* @date 2017年12月6日 上午11:03:35
*/
public static Float getFloutValue(String key){
return getProperty(key, Float.class);
}
}
|
package cn.test.test_03;
// 构造函数的例子
public class StudentTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Student s = new Student();
s.setName("linggg");
s.setAge(29);
s.show();
}
}
class Student {
private String name;
private int age;
public Student() {}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void show() {
System.out.println("姓名是:"+name+"年龄是"+age);
}
}
|
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package guardian.events;
import com.megacrit.cardcrawl.cards.AbstractCard;
import com.megacrit.cardcrawl.cards.CardGroup;
import com.megacrit.cardcrawl.core.CardCrawlGame;
import com.megacrit.cardcrawl.core.Settings;
import com.megacrit.cardcrawl.dungeons.AbstractDungeon;
import com.megacrit.cardcrawl.events.AbstractImageEvent;
import com.megacrit.cardcrawl.localization.EventStrings;
import com.megacrit.cardcrawl.vfx.UpgradeShineEffect;
import com.megacrit.cardcrawl.vfx.cardManip.PurgeCardEffect;
import com.megacrit.cardcrawl.vfx.cardManip.ShowCardAndObtainEffect;
import com.megacrit.cardcrawl.vfx.cardManip.ShowCardBrieflyEffect;
import guardian.GuardianMod;
import guardian.cards.*;
import java.util.ArrayList;
public class CrystalForge extends AbstractImageEvent {
public static final String ID = "Guardian:CrystalForge";
public static final String NAME;
public static final String[] DESCRIPTIONS;
public static final String[] OPTIONS;
private static final EventStrings eventStrings;
private static final String INTRO;
private static final String TRANSMUTE;
private static final String SALVAGE;
private static final String PRY;
private static final String LEAVE;
private static final String ENHANCE;
static {
eventStrings = CardCrawlGame.languagePack.getEventString("Guardian:CrystalForge");
NAME = eventStrings.NAME;
DESCRIPTIONS = eventStrings.DESCRIPTIONS;
OPTIONS = eventStrings.OPTIONS;
INTRO = DESCRIPTIONS[0];
SALVAGE = DESCRIPTIONS[1];
PRY = DESCRIPTIONS[2];
TRANSMUTE = DESCRIPTIONS[3];
LEAVE = DESCRIPTIONS[4];
ENHANCE = DESCRIPTIONS[10];
}
private int screenNum = 0;
private boolean pickCardForGemRemoval = false;
private boolean pickCardForSalvageGems = false;
private boolean pickCardForTransmute = false;
private AbstractGuardianCard cardChosen = null;
private AbstractGuardianCard gemChosen = null;
private ArrayList<String> cardsRemoved = new ArrayList<>();
private ArrayList<String> cardsTransformed = new ArrayList<>();
private ArrayList<String> cardsAdded = new ArrayList<>();
private ArrayList<String> cardsUpgraded = new ArrayList<>();
public CrystalForge() {
super(NAME, INTRO, GuardianMod.getResourcePath("/events/grimForge.jpg"));
for (AbstractCard c : AbstractDungeon.player.masterDeck.group) {
c.update();
}
if (GuardianMod.getCardsWithFilledSockets().size() == 0) {
this.imageEventText.setDialogOption(OPTIONS[1], true);
} else {
this.imageEventText.setDialogOption(OPTIONS[0]);
}
if (GuardianMod.getCardsWithFilledSockets().size() == 0) {
this.imageEventText.setDialogOption(OPTIONS[1], true);
} else {
this.imageEventText.setDialogOption(OPTIONS[2]);
}
this.imageEventText.setDialogOption(OPTIONS[3]);
if (GuardianMod.getSocketableCards().size() == 0 || GuardianMod.getGemCards().size() == 0) {
this.imageEventText.setDialogOption(OPTIONS[7], true);
} else {
this.imageEventText.setDialogOption(OPTIONS[6]);
}
this.imageEventText.setDialogOption(OPTIONS[5]);
}
public void onEnterRoom() {
if (Settings.AMBIANCE_ON) {
CardCrawlGame.sound.play("EVENT_FORGE");
}
}
public void update() {
super.update();
if (this.pickCardForGemRemoval && !AbstractDungeon.isScreenUp && !AbstractDungeon.gridSelectScreen.selectedCards.isEmpty()) {
AbstractCard c = AbstractDungeon.gridSelectScreen.selectedCards.get(0);
((AbstractGuardianCard) c).sockets.clear();
((AbstractGuardianCard) c).updateDescription();
AbstractDungeon.effectsQueue.add(new ShowCardBrieflyEffect(c.makeStatEquivalentCopy()));
AbstractDungeon.gridSelectScreen.selectedCards.clear();
this.pickCardForGemRemoval = false;
cardsUpgraded.add(c.cardID);
updateEnhance();
} else if (this.pickCardForSalvageGems && !AbstractDungeon.isScreenUp && !AbstractDungeon.gridSelectScreen.selectedCards.isEmpty()) {
AbstractCard c = AbstractDungeon.gridSelectScreen.selectedCards.get(0);
AbstractGuardianCard cg = (AbstractGuardianCard) c;
ArrayList<AbstractCard> rewardGemCards = new ArrayList<>();
for (int i = 0; i < cg.sockets.size(); i++) {
switch (cg.sockets.get(i).toString()) {
case "RED":
rewardGemCards.add(new Gem_Red());
break;
case "GREEN":
rewardGemCards.add(new Gem_Green());
break;
case "ORANGE":
rewardGemCards.add(new Gem_Orange());
break;
case "CYAN":
rewardGemCards.add(new Gem_Cyan());
break;
case "WHITE":
rewardGemCards.add(new Gem_White());
break;
case "BLUE":
rewardGemCards.add(new Gem_Blue());
break;
case "CRIMSON":
rewardGemCards.add(new Gem_Crimson());
break;
case "FRAGMENTED":
rewardGemCards.add(new Gem_Fragmented());
break;
case "PURPLE":
rewardGemCards.add(new Gem_Purple());
break;
case "SYNTHETIC":
rewardGemCards.add(new Gem_Synthetic());
break;
case "YELLOW":
rewardGemCards.add(new Gem_Yellow());
break;
}
}
((AbstractGuardianCard) c).sockets.clear();
((AbstractGuardianCard) c).updateDescription();
for (int i = 0; i < rewardGemCards.size(); i++) {
AbstractCard c2 = rewardGemCards.get(i);
AbstractDungeon.effectList.add(new ShowCardAndObtainEffect(c2, (float) (Settings.WIDTH * (0.2 * (i + 1))), (float) (Settings.HEIGHT / 2)));
cardsAdded.add(c2.cardID);
}
AbstractDungeon.topLevelEffects.add(new PurgeCardEffect(c, (float) (Settings.WIDTH * 0.2), (float) (Settings.HEIGHT / 2)));
AbstractDungeon.player.masterDeck.removeCard(c);
cardsRemoved.add(c.cardID);
AbstractDungeon.gridSelectScreen.selectedCards.clear();
this.pickCardForSalvageGems = false;
updateEnhance();
} else if (this.pickCardForTransmute && !AbstractDungeon.isScreenUp && !AbstractDungeon.gridSelectScreen.selectedCards.isEmpty()) {
AbstractCard gem = GuardianMod.getRewardGemCards(false, 1).get(0);
AbstractDungeon.effectList.add(new ShowCardAndObtainEffect(gem, (float) (Settings.WIDTH * .3), (float) (Settings.HEIGHT / 2)));
AbstractCard removedCard = AbstractDungeon.gridSelectScreen.selectedCards.get(0);
AbstractDungeon.topLevelEffects.add(new PurgeCardEffect(removedCard, (float) (Settings.WIDTH * .7), (float) (Settings.HEIGHT / 2)));
AbstractDungeon.player.masterDeck.removeCard(removedCard);
cardsRemoved.add(removedCard.cardID);
cardsTransformed.add(gem.cardID);
AbstractDungeon.gridSelectScreen.selectedCards.clear();
this.pickCardForTransmute = false;
updateEnhance(1);
} else if (!AbstractDungeon.isScreenUp && !AbstractDungeon.gridSelectScreen.selectedCards.isEmpty() && GuardianMod.gridScreenForGems) {
this.gemChosen = (AbstractGuardianCard) AbstractDungeon.gridSelectScreen.selectedCards.get(0);
GuardianMod.gridScreenForGems = false;
GuardianMod.gridScreenForSockets = true;
AbstractDungeon.gridSelectScreen.selectedCards.clear();
AbstractDungeon.gridSelectScreen.open(GuardianMod.getSocketableCards(), 1, DESCRIPTIONS[9], false, false, true, false);
} else if (!AbstractDungeon.isScreenUp && !AbstractDungeon.gridSelectScreen.selectedCards.isEmpty() && GuardianMod.gridScreenForSockets) {
this.cardChosen = (AbstractGuardianCard) AbstractDungeon.gridSelectScreen.selectedCards.get(0);
cardChosen.addGemToSocket(gemChosen);
AbstractDungeon.effectList.add(new UpgradeShineEffect((float) Settings.WIDTH / 2.0F, (float) Settings.HEIGHT / 2.0F));
AbstractDungeon.effectList.add(new ShowCardBrieflyEffect(cardChosen.makeStatEquivalentCopy()));
this.imageEventText.updateBodyText(ENHANCE);
AbstractDungeon.gridSelectScreen.selectedCards.clear();
GuardianMod.gridScreenForSockets = false;
cardsUpgraded.add(cardChosen.cardID);
cardsRemoved.add(gemChosen.cardID);
updateEnhance();
}
}
private void updateEnhance() {
this.updateEnhance(0);
}
private void updateEnhance(int inflateGemCount) {
for (AbstractCard c : AbstractDungeon.player.masterDeck.group) {
c.update();
}
if (GuardianMod.getSocketableCards().size() == 0 || GuardianMod.getGemCards().size() + inflateGemCount == 0) {
this.imageEventText.updateDialogOption(3, OPTIONS[7], true);
} else {
this.imageEventText.updateDialogOption(3, OPTIONS[6], false);
}
}
protected void buttonEffect(int buttonPressed) {
switch (this.screenNum) {
case 0:
switch (buttonPressed) {
case 0:
this.pickCardForSalvageGems = true;
this.imageEventText.updateBodyText(SALVAGE);
this.imageEventText.updateDialogOption(0, OPTIONS[4], true);
AbstractDungeon.gridSelectScreen.open(GuardianMod.getCardsWithFilledSockets(), 1, false, DESCRIPTIONS[5]);
break;
case 1:
this.pickCardForGemRemoval = true;
AbstractDungeon.gridSelectScreen.open(GuardianMod.getCardsWithFilledSockets(), 1, DESCRIPTIONS[6], false, false, false, false);
this.imageEventText.updateBodyText(PRY);
this.imageEventText.updateDialogOption(1, OPTIONS[4], true);
break;
case 2:
this.pickCardForTransmute = true;
this.imageEventText.updateBodyText(TRANSMUTE);
AbstractDungeon.gridSelectScreen.open(CardGroup.getGroupWithoutBottledCards(AbstractDungeon.player.masterDeck.getPurgeableCards()), 1, DESCRIPTIONS[7], false, false, false, true);
this.imageEventText.updateDialogOption(2, OPTIONS[4], true);
break;
case 3:
GuardianMod.gridScreenForGems = true;
AbstractDungeon.gridSelectScreen.open(GuardianMod.getGemCards(), 1, DESCRIPTIONS[8], false, false, true, false);
break;
case 4:
this.screenNum = 2;
this.imageEventText.clearAllDialogs();
this.imageEventText.updateBodyText(LEAVE);
this.imageEventText.setDialogOption(OPTIONS[5]);
logMetric(ID, "Forged", cardsAdded, cardsRemoved, cardsTransformed, cardsUpgraded, null, null, null,
0, 0, 0, 0, 0, 0);
break;
}
break;
default:
this.openMap();
}
}
}
|
package io.palyvos.scheduler.policy.cgroup;
import io.palyvos.scheduler.adapters.SpeRuntimeInfo;
import io.palyvos.scheduler.metric.SchedulerMetricProvider;
import io.palyvos.scheduler.task.ExternalThread;
import io.palyvos.scheduler.task.Task;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.Validate;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* Assign each SPE to its own group with a custom priority.
*/
public class SpeCGroupPolicy implements CGroupPolicy {
public static final String NAME = "SPE";
private static final Logger LOG = LogManager.getLogger();
private static final int TOTAL_PRIORITY = 100;
private final Map<String, Double> weights;
private final Map<CGroup, Double> schedule = new HashMap<>();
private final Map<CGroup, Collection<ExternalThread>> assignment = new HashMap<>();
private int calls;
public SpeCGroupPolicy(Map<String, Double> weights) {
Validate.notEmpty(weights, "empty weights");
this.weights = weights;
}
@Override
public void init(Collection<Task> tasks, SpeRuntimeInfo speRuntimeInfo,
CGroupTranslator translator, SchedulerMetricProvider metricProvider) {
translator.init();
}
@Override
public void apply(Collection<Task> tasks,
SpeRuntimeInfo speRuntimeInfo, CGroupTranslator translator,
SchedulerMetricProvider metricProvider) {
final CGroup cgroup = CGroup.PARENT_CPU_CGROUP.newChild(speRuntimeInfo.spe());
Double speWeight = weights.get(speRuntimeInfo.spe());
Validate.validState(speWeight != null, "No weight for %s", speRuntimeInfo.spe());
schedule.put(cgroup, TOTAL_PRIORITY * speWeight);
List<ExternalThread> speProcesses = new ArrayList<>();
speRuntimeInfo.pids().forEach(pid -> speProcesses.add(new ExternalThread(pid, "SPE_PROCESS")));
assignment.put(cgroup, speProcesses);
LOG.info("Assigning SPE processes {} to cgroup {} with weight {}", speRuntimeInfo.pids(),
cgroup.path(), speWeight);
applyIfAllSpesReady(translator);
}
private void applyIfAllSpesReady(CGroupTranslator translator) {
if (++calls >= weights.size()) {
LOG.info("Applying for all SPEs...");
translator.assign(assignment);
translator.apply(schedule);
assignment.clear();
schedule.clear();
calls = 0;
}
}
}
|
/*
* Cloud Resource & Information Management System (CRIMSy)
* Copyright 2020 Leibniz-Institut f. Pflanzenbiochemie
*
* 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.ipb_halle.lbac.search.lang;
import de.ipb_halle.lbac.material.common.entity.MaterialEntity;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
/**
*
* @author fblocal
*/
public class SqlInsertBuilderTest {
@Test
public void testInsert() {
MaterialEntity mat = new MaterialEntity();
EntityGraph graph = new EntityGraph(mat.getClass());
SqlInsertBuilder builder = new SqlInsertBuilder(graph);
// assertEquals("Insert statement does not match", builder.getInsertSql(), "INSERT INTO materials (bla, blub) VALUES (?,?)");
String stmnt = builder.getInsertSql();
assertTrue("Insert statement starts ...", stmnt.startsWith("INSERT INTO materials ("));
assertTrue("Insert statement ends ...", stmnt.endsWith("?, ?, ?, ?)"));
}
}
|
package com.vmware.vim25;
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.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for HasUserPrivilegeOnEntitiesRequestType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="HasUserPrivilegeOnEntitiesRequestType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="_this" type="{urn:vim25}ManagedObjectReference"/>
* <element name="entities" type="{urn:vim25}ManagedObjectReference" maxOccurs="unbounded"/>
* <element name="userName" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="privId" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "HasUserPrivilegeOnEntitiesRequestType", propOrder = {
"_this",
"entities",
"userName",
"privId"
})
public class HasUserPrivilegeOnEntitiesRequestType {
@XmlElement(required = true)
protected ManagedObjectReference _this;
@XmlElement(required = true)
protected List<ManagedObjectReference> entities;
@XmlElement(required = true)
protected String userName;
protected List<String> privId;
/**
* Gets the value of the this property.
*
* @return
* possible object is
* {@link ManagedObjectReference }
*
*/
public ManagedObjectReference getThis() {
return _this;
}
/**
* Sets the value of the this property.
*
* @param value
* allowed object is
* {@link ManagedObjectReference }
*
*/
public void setThis(ManagedObjectReference value) {
this._this = value;
}
/**
* Gets the value of the entities 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 entities property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getEntities().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ManagedObjectReference }
*
*
*/
public List<ManagedObjectReference> getEntities() {
if (entities == null) {
entities = new ArrayList<ManagedObjectReference>();
}
return this.entities;
}
/**
* Gets the value of the userName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUserName() {
return userName;
}
/**
* Sets the value of the userName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUserName(String value) {
this.userName = value;
}
/**
* Gets the value of the privId 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 privId property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPrivId().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getPrivId() {
if (privId == null) {
privId = new ArrayList<String>();
}
return this.privId;
}
}
|
package test.priority;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
public abstract class SampleTestBase {
@BeforeClass
public void setUp() {}
@AfterClass
public void closeBrowser() {}
}
|
/*
* Licensed to Laurent Broudoux (the "Author") under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Author 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 io.github.microcks.util.openapi;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeType;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import io.github.microcks.domain.*;
import io.github.microcks.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;
/**
* An implementation of MockReopsitoryImporter that deals with OpenAPI v3.0.x specification
* file ; whether encoding into JSON or YAML documents.
* @author laurent
*/
public class OpenAPIImporter implements MockRepositoryImporter {
/** A simple logger for diagnostic messages. */
private static Logger log = LoggerFactory.getLogger(OpenAPIImporter.class);
private boolean isYaml = true;
private JsonNode spec;
private String specContent;
private static final List<String> VALID_VERBS = Arrays.asList("get", "put", "post", "delete", "options", "head", "patch", "trace");
/**
* Build a new importer.
* @param specificationFilePath The path to local OpenAPI spec file
* @throws IOException if project file cannot be found or read.
*/
public OpenAPIImporter(String specificationFilePath) throws IOException {
try {
// Analyse first lines of file content to guess repository type.
String line = null;
BufferedReader reader = Files.newBufferedReader(new File(specificationFilePath).toPath(), Charset.forName("UTF-8"));
while ((line = reader.readLine()) != null) {
line = line.trim();
// Check is we start with json object or array definition.
if (line.startsWith("{") || line.startsWith("[")) {
isYaml = false;
break;
}
else if (line.startsWith("---") || line.startsWith("openapi: ")) {
isYaml = true;
break;
}
}
reader.close();
// Read spec bytes.
byte[] bytes = Files.readAllBytes(Paths.get(specificationFilePath));
specContent = new String(bytes, Charset.forName("UTF-8"));
// Convert them to Node using Jackson object mapper.
ObjectMapper mapper = null;
if (isYaml) {
mapper = new ObjectMapper(new YAMLFactory());
} else {
mapper = new ObjectMapper();
}
spec = mapper.readTree(bytes);
} catch (Exception e) {
log.error("Exception while parsing OpenAPI specification file " + specificationFilePath, e);
throw new IOException("OpenAPI spec file parsing error");
}
}
@Override
public List<Service> getServiceDefinitions() throws MockRepositoryImportException {
List<Service> result = new ArrayList<>();
// Build a new service.
Service service = new Service();
service.setName(spec.path("info").path("title").asText());
service.setVersion(spec.path("info").path("version").asText());
service.setType(ServiceType.REST);
// Then build its operations.
service.setOperations(extractOperations());
result.add(service);
return result;
}
@Override
public List<Resource> getResourceDefinitions(Service service) {
List<Resource> results = new ArrayList<>();
// Build a suitable name.
String name = service.getName() + "-" + service.getVersion();
if (isYaml) {
name += ".yaml";
} else {
name += ".json";
}
// Build a brand new resource just with spec content.
Resource resource = new Resource();
resource.setName(name);
resource.setType(ResourceType.OPEN_API_SPEC);
resource.setContent(specContent);
results.add(resource);
return results;
}
@Override
public List<Exchange> getMessageDefinitions(Service service, Operation operation) throws MockRepositoryImportException {
Map<Request, Response> result = new HashMap<>();
// Iterate on specification "paths" nodes.
Iterator<Entry<String, JsonNode>> paths = spec.path("paths").fields();
while (paths.hasNext()) {
Entry<String, JsonNode> path = paths.next();
String pathName = path.getKey();
// Find examples fragments defined at the path level.
Map<String, Map<String, String>> pathPathParametersByExample = extractParametersByExample(path.getValue(), "path");
// Iterate on specification path, "verbs" nodes.
Iterator<Entry<String, JsonNode>> verbs = path.getValue().fields();
while (verbs.hasNext()) {
Entry<String, JsonNode> verb = verbs.next();
String verbName = verb.getKey();
// Find the correct operation.
if (operation.getName().equals(verbName.toUpperCase() + " " + pathName.trim())) {
// Find examples fragments defined at the verb level.
Map<String, Map<String, String>> pathParametersByExample = extractParametersByExample(verb.getValue(), "path");
pathParametersByExample.putAll(pathPathParametersByExample);
Map<String, Map<String, String>> queryParametersByExample = extractParametersByExample(verb.getValue(), "query");
Map<String, Map<String, String>> headerParametersByExample = extractParametersByExample(verb.getValue(), "header");
Map<String, Request> requestBodiesByExample = extractRequestBodies(verb.getValue());
// No need to go further if no examples.
if (verb.getValue().has("responses")) {
Iterator<Entry<String, JsonNode>> responseCodes = verb.getValue().path("responses").fields();
while (responseCodes.hasNext()) {
Entry<String, JsonNode> responseCode = responseCodes.next();
// Find here potential headers for output of this operation examples.
Map<String, List<Header>> headersByExample = extractHeadersByExample(responseCode.getValue());
Iterator<Entry<String, JsonNode>> contents = getResponseContent(responseCode.getValue()).fields();
while (contents.hasNext()) {
Entry<String, JsonNode> content = contents.next();
String contentValue = content.getKey();
Iterator<String> exampleNames = content.getValue().path("examples").fieldNames();
while (exampleNames.hasNext()) {
String exampleName = exampleNames.next();
JsonNode example = content.getValue().path("examples").path(exampleName);
// We should have everything at hand to build response here.
Response response = new Response();
response.setName(exampleName);
response.setMediaType(contentValue);
response.setStatus(responseCode.getKey());
response.setContent(getExampleValue(example));
if (!responseCode.getKey().startsWith("2")) {
response.setFault(true);
}
List<Header> responseHeaders = headersByExample.get(exampleName);
if (responseHeaders != null) {
responseHeaders.stream().forEach(header -> response.addHeader(header));
}
// Do we have a request for this example?
Request request = requestBodiesByExample.get(exampleName);
if (request == null) {
request = new Request();
request.setName(exampleName);
}
// Complete request accept-type with response content-type.
Header header = new Header();
header.setName("Accept");
HashSet<String> values = new HashSet<>();
values.add(contentValue);
header.setValues(values);
request.addHeader(header);
// Do we have to complete request with path parameters?
Map<String, String> pathParameters = pathParametersByExample.get(exampleName);
if (pathParameters != null) {
for (Entry<String, String> paramEntry : pathParameters.entrySet()) {
Parameter param = new Parameter();
param.setName(paramEntry.getKey());
param.setValue(paramEntry.getValue());
request.addQueryParameter(param);
}
} else if (DispatchStyles.URI_PARTS.equals(operation.getDispatcher())
|| DispatchStyles.URI_ELEMENTS.equals(operation.getDispatcher())) {
// We've must have at least one path parameters but none...
// Do not register this request / response pair.
break;
}
// Do we have to complete request with query parameters?
Map<String, String> queryParameters = queryParametersByExample.get(exampleName);
if (queryParameters != null) {
for (Entry<String, String> paramEntry : queryParameters.entrySet()) {
Parameter param = new Parameter();
param.setName(paramEntry.getKey());
param.setValue(paramEntry.getValue());
request.addQueryParameter(param);
}
}
// Do we have to complete request with header parameters?
Map<String, String> headerParameters = headerParametersByExample.get(exampleName);
if (headerParameters != null) {
for (Entry<String, String> headerEntry : headerParameters.entrySet()) {
header = new Header();
header.setName(headerEntry.getKey());
// Values may be multiple and CSV.
Set<String> headerValues = Arrays.stream(headerEntry.getValue().split(","))
.map(value -> value.trim())
.collect(Collectors.toSet());
header.setValues(headerValues);
request.addHeader(header);
}
}
// Finally, take care about dispatchCriteria and complete operation resourcePaths.
String dispatchCriteria = null;
String resourcePathPattern = operation.getName().split(" ")[1];
if (DispatchStyles.URI_PARAMS.equals(operation.getDispatcher())) {
Map<String, String> queryParams = queryParametersByExample.get(exampleName);
dispatchCriteria = DispatchCriteriaHelper
.buildFromParamsMap(operation.getDispatcherRules(), queryParams);
// We only need the pattern here.
operation.addResourcePath(resourcePathPattern);
} else if (DispatchStyles.URI_PARTS.equals(operation.getDispatcher())) {
Map<String, String> parts = pathParametersByExample.get(exampleName);
dispatchCriteria = DispatchCriteriaHelper.buildFromPartsMap(parts);
// We should complete resourcePath here.
String resourcePath = URIBuilder.buildURIFromPattern(resourcePathPattern, parts);
operation.addResourcePath(resourcePath);
} else if (DispatchStyles.URI_ELEMENTS.equals(operation.getDispatcher())) {
Map<String, String> parts = pathParametersByExample.get(exampleName);
Map<String, String> queryParams = queryParametersByExample.get(exampleName);
dispatchCriteria = DispatchCriteriaHelper.buildFromPartsMap(parts);
dispatchCriteria += DispatchCriteriaHelper
.buildFromParamsMap(operation.getDispatcherRules(), queryParams);
// We should complete resourcePath here.
String resourcePath = URIBuilder.buildURIFromPattern(resourcePathPattern, parts);
operation.addResourcePath(resourcePath);
}
response.setDispatchCriteria(dispatchCriteria);
result.put(request, response);
}
}
}
}
}
}
}
// Adapt map to list of Exchanges.
return result.entrySet().stream()
.map(entry -> new RequestResponsePair(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());
}
/**
* Extract the list of operations from Specification.
*/
private List<Operation> extractOperations() throws MockRepositoryImportException {
List<Operation> results = new ArrayList<>();
// Iterate on specification "paths" nodes.
Iterator<Entry<String, JsonNode>> paths = spec.path("paths").fields();
while (paths.hasNext()) {
Entry<String, JsonNode> path = paths.next();
String pathName = path.getKey();
// Iterate on specification path, "verbs" nodes.
Iterator<Entry<String, JsonNode>> verbs = path.getValue().fields();
while (verbs.hasNext()) {
Entry<String, JsonNode> verb = verbs.next();
String verbName = verb.getKey();
// Only deal with real verbs for now.
if (VALID_VERBS.contains(verbName)) {
String operationName = verbName.toUpperCase() + " " + pathName.trim();
Operation operation = new Operation();
operation.setName(operationName);
operation.setMethod(verbName.toUpperCase());
// Deal with dispatcher stuffs.
if (operationHasParameters(verb.getValue(), "query") && urlHasParts(pathName)) {
operation.setDispatcherRules(DispatchCriteriaHelper.extractPartsFromURIPattern(pathName)
+ " ?? " + extractOperationParams(verb.getValue()));
operation.setDispatcher(DispatchStyles.URI_ELEMENTS);
} else if (operationHasParameters(verb.getValue(), "query")) {
operation.setDispatcherRules(extractOperationParams(verb.getValue()));
operation.setDispatcher(DispatchStyles.URI_PARAMS);
} else if (urlHasParts(pathName)) {
operation.setDispatcherRules(DispatchCriteriaHelper.extractPartsFromURIPattern(pathName));
operation.setDispatcher(DispatchStyles.URI_PARTS);
} else {
operation.addResourcePath(pathName);
}
results.add(operation);
}
}
}
return results;
}
/**
* Extract parameters within a specification node and organize them by example. Parameter can be of type 'path',
* 'query', 'header' or 'cookie'. Allow to filter them using parameterType. Key of returned map is example name.
* Key of value map is param name. Value of value map is param value ;-)
*/
private Map<String, Map<String, String>> extractParametersByExample(JsonNode node, String parameterType) {
Map<String, Map<String, String>> results = new HashMap<>();
Iterator<JsonNode> parameters = node.path("parameters").elements();
while (parameters.hasNext()) {
JsonNode parameter = parameters.next();
// If parameter is a $ref, navigate to it first.
if (parameter.has("$ref")) {
// $ref: '#/components/parameters/accountId'
String ref = parameter.path("$ref").asText();
parameter = spec.at(ref.substring(1));
}
String parameterName = parameter.path("name").asText();
if (parameter.has("in") && parameter.path("in").asText().equals(parameterType)
&& parameter.has("examples")) {
Iterator<String> exampleNames = parameter.path("examples").fieldNames();
while (exampleNames.hasNext()) {
String exampleName = exampleNames.next();
JsonNode example = parameter.path("examples").path(exampleName);
String exampleValue = getExampleValue(example);
Map<String, String> exampleParams = results.get(exampleName);
if (exampleParams == null) {
exampleParams = new HashMap<>();
results.put(exampleName, exampleParams);
}
exampleParams.put(parameterName, exampleValue);
}
}
}
return results;
}
/**
* Extract request bodies within verb specification and organize them by example.
* Key of returned map is example name. Value is basic Microcks Request object (no query params, no headers)
*/
private Map<String, Request> extractRequestBodies(JsonNode verbNode) {
Map<String, Request> results = new HashMap<>();
JsonNode requestBody = verbNode.path("requestBody");
Iterator<String> contentTypeNames = requestBody.path("content").fieldNames();
while (contentTypeNames.hasNext()) {
String contentTypeName = contentTypeNames.next();
JsonNode contentType = requestBody.path("content").path(contentTypeName);
if (contentType.has("examples")) {
Iterator<String> exampleNames = contentType.path("examples").fieldNames();
while (exampleNames.hasNext()) {
String exampleName = exampleNames.next();
JsonNode example = contentType.path("examples").path(exampleName);
String exampleValue = getExampleValue(example);
// Build and store a request object.
Request request = new Request();
request.setName(exampleName);
request.setContent(exampleValue);
// We should add a Content-type header here for request body.
Header header = new Header();
header.setName("Content-Type");
HashSet<String> values = new HashSet<>();
values.add(contentTypeName);
header.setValues(values);
request.addHeader(header);
results.put(exampleName, request);
}
}
}
return results;
}
/**
* Extract headers within a header specification node and organize them by example.
* Key of returned map is example name. Value is a list of Microcks Header objects.
*/
private Map<String, List<Header>> extractHeadersByExample(JsonNode responseNode) {
Map<String, List<Header>> results = new HashMap<>();
if (responseNode.has("headers")) {
JsonNode headersNode = responseNode.path("headers");
Iterator<String> headerNames = headersNode.fieldNames();
while (headerNames.hasNext()) {
String headerName = headerNames.next();
JsonNode headerNode = headersNode.path(headerName);
if (headerNode.has("examples")) {
Iterator<String> exampleNames = headerNode.path("examples").fieldNames();
while (exampleNames.hasNext()) {
String exampleName = exampleNames.next();
JsonNode example = headerNode.path("examples").path(exampleName);
String exampleValue = getExampleValue(example);
// Example may be multiple CSV.
Set<String> values = Arrays.stream(
exampleValue.split(",")).map(value -> value.trim())
.collect(Collectors.toSet());
Header header = new Header();
header.setName(headerName);
header.setValues(values);
List<Header> headersForExample = results.get(exampleName);
if (headersForExample == null) {
headersForExample = new ArrayList<>();
}
headersForExample.add(header);
results.put(exampleName, headersForExample);
}
}
}
}
if (responseNode.has("$ref")) {
// $ref: '#/components/responses/unknown'
String ref = responseNode.path("$ref").asText();
JsonNode component = spec.at(ref.substring(1));
return extractHeadersByExample(component);
}
return results;
}
/** Get the value of an example. This can be direct value field or those of followed $ref */
private String getExampleValue(JsonNode example) {
if (example.has("value")) {
if (example.path("value").getNodeType() == JsonNodeType.ARRAY ||
example.path("value").getNodeType() == JsonNodeType.OBJECT ) {
return example.path("value").toString();
}
return example.path("value").asText();
}
if (example.has("$ref")) {
// $ref: '#/components/examples/param_laurent'
String ref = example.path("$ref").asText();
JsonNode component = spec.at(ref.substring(1));
return getExampleValue(component);
}
return null;
}
/** Get the content of a response. This can be direct content field or those of followed $ref */
private JsonNode getResponseContent(JsonNode response) {
if (response.has("$ref")) {
// $ref: '#/components/responses/unknown'
String ref = response.path("$ref").asText();
JsonNode component = spec.at(ref.substring(1));
return getResponseContent(component);
}
return response.path("content");
}
/** Build a string representing operation parameters as used in dispatcher rules (param1 && param2)*/
private String extractOperationParams(JsonNode operation) {
StringBuilder params = new StringBuilder();
Iterator<JsonNode> parameters = operation.path("parameters").elements();
while (parameters.hasNext()) {
JsonNode parameter = parameters.next();
// If parameter is a $ref, navigate to it first.
if (parameter.has("$ref")) {
// $ref: '#/components/parameters/accountId'
String ref = parameter.path("$ref").asText();
parameter = spec.at(ref.substring(1));
}
String parameterIn = parameter.path("in").asText();
if (!"path".equals(parameterIn)) {
if (params.length() > 0) {
params.append(" && ");
}
params.append(parameter.path("name").asText());
}
}
return params.toString();
}
/** Check parameters presence into given operation node. */
private boolean operationHasParameters(JsonNode operation, String parameterType) {
if (!operation.has("parameters")) {
return false;
}
Iterator<JsonNode> parameters = operation.path("parameters").elements();
while (parameters.hasNext()) {
JsonNode parameter = parameters.next();
// If parameter is a $ref, navigate to it first.
if (parameter.has("$ref")) {
// $ref: '#/components/parameters/accountId'
String ref = parameter.path("$ref").asText();
parameter = spec.at(ref.substring(1));
}
String parameterIn = parameter.path("in").asText();
if (parameterIn.equals(parameterType)) {
return true;
}
}
return false;
}
/** Check variables parts presence into given url. */
private static boolean urlHasParts(String url) {
return (url.indexOf("/:") != -1 || url.indexOf("/{") != -1);
}
}
|
package com.refinedmods.refinedstorage.screen.widget.sidebutton;
import com.mojang.blaze3d.vertex.PoseStack;
import com.refinedmods.refinedstorage.api.network.grid.IGrid;
import com.refinedmods.refinedstorage.container.GridContainerMenu;
import com.refinedmods.refinedstorage.screen.BaseScreen;
import net.minecraft.ChatFormatting;
import net.minecraft.client.resources.language.I18n;
public class GridViewTypeSideButton extends SideButton {
private final IGrid grid;
public GridViewTypeSideButton(BaseScreen<GridContainerMenu> screen, IGrid grid) {
super(screen);
this.grid = grid;
}
@Override
protected String getTooltip() {
return I18n.get("sidebutton.refinedstorage.grid.view_type") + "\n" + ChatFormatting.GRAY + I18n.get("sidebutton.refinedstorage.grid.view_type." + grid.getViewType());
}
@Override
protected void renderButtonIcon(PoseStack poseStack, int x, int y) {
screen.blit(poseStack, x, y, (grid.getViewType() - (grid.getViewType() >= 3 ? 3 : 0)) * 16, 112, 16, 16);
}
@Override
public void onPress() {
int type = grid.getViewType();
if (type == IGrid.VIEW_TYPE_NORMAL) {
type = IGrid.VIEW_TYPE_NON_CRAFTABLES;
} else if (type == IGrid.VIEW_TYPE_NON_CRAFTABLES) {
type = IGrid.VIEW_TYPE_CRAFTABLES;
} else if (type == IGrid.VIEW_TYPE_CRAFTABLES) {
type = IGrid.VIEW_TYPE_NORMAL;
}
grid.onViewTypeChanged(type);
}
}
|
package com.simibubi.create.content.contraptions.components.fan;
import com.simibubi.create.AllTileEntities;
import com.simibubi.create.content.contraptions.base.DirectionalKineticBlock;
import com.simibubi.create.foundation.block.ITE;
import com.simibubi.create.foundation.utility.worldWrappers.WrappedWorld;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.item.BlockItemUseContext;
import net.minecraft.item.ItemUseContext;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Direction;
import net.minecraft.util.Direction.Axis;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockReader;
import net.minecraft.world.IWorld;
import net.minecraft.world.IWorldReader;
import net.minecraft.world.World;
public class EncasedFanBlock extends DirectionalKineticBlock implements ITE<EncasedFanTileEntity> {
public EncasedFanBlock(Properties properties) {
super(properties);
}
@Override
public TileEntity createTileEntity(BlockState state, IBlockReader world) {
return AllTileEntities.ENCASED_FAN.create();
}
@Override
public void onBlockAdded(BlockState state, World worldIn, BlockPos pos, BlockState oldState, boolean isMoving) {
blockUpdate(state, worldIn, pos);
}
@Override
public void neighborChanged(BlockState state, World worldIn, BlockPos pos, Block blockIn, BlockPos fromPos,
boolean isMoving) {
blockUpdate(state, worldIn, pos);
}
@Override
public BlockState getStateForPlacement(BlockItemUseContext context) {
Direction preferredFacing = getPreferredFacing(context);
if (preferredFacing == null)
preferredFacing = context.getNearestLookingDirection();
return getDefaultState().with(FACING,
context.getPlayer().isSneaking() ? preferredFacing : preferredFacing.getOpposite());
}
protected void blockUpdate(BlockState state, World worldIn, BlockPos pos) {
if (worldIn instanceof WrappedWorld)
return;
notifyFanTile(worldIn, pos);
if (worldIn.isRemote)
return;
withTileEntityDo(worldIn, pos, te -> te.updateGenerator(state.get(FACING)));
}
protected void notifyFanTile(IWorld world, BlockPos pos) {
withTileEntityDo(world, pos, EncasedFanTileEntity::blockInFrontChanged);
}
@Override
public BlockState updateAfterWrenched(BlockState newState, ItemUseContext context) {
blockUpdate(newState, context.getWorld(), context.getPos());
return newState;
}
@Override
public Axis getRotationAxis(BlockState state) {
return state.get(FACING).getAxis();
}
@Override
public boolean hasShaftTowards(IWorldReader world, BlockPos pos, BlockState state, Direction face) {
return face == state.get(FACING).getOpposite();
}
@Override
public boolean showCapacityWithAnnotation() {
return true;
}
@Override
public Class<EncasedFanTileEntity> getTileEntityClass() {
return EncasedFanTileEntity.class;
}
}
|
package ru.myastrebov.demo.spring.cloud.contract.producer;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author m.yastrebov
*/
@Service
public class PriceService {
private static final Map<String, CarPrice> PRICES;
static {
PRICES = new ConcurrentHashMap<>();
PRICES.put("BMW", new CarPrice("BMW", 100, "RUB"));
PRICES.put("Mercedes", new CarPrice("Mercedes", 200, "RUB"));
PRICES.put("Audi", new CarPrice("Audi", 300, "RUB"));
}
Map<String, CarPrice> getAll() {
return PRICES;
}
CarPrice getPrice(String car) {
return PRICES.get(car);
}
CarPrice update(String car, CarPrice price) {
price.setUuid(UUID.randomUUID().toString());
return PRICES.put(car, price);
}
CarPrice remove(String car) {
return PRICES.remove(car);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.