text
stringlengths 7
1.01M
|
|---|
package com.ld.core.pack.utils;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ld.core.pack.DataSetException;
import com.ld.core.pack.LDDataType;
public class CastUtils {
static Logger logger = LoggerFactory.getLogger(CastUtils.class);
public static String toString(Object value) {
if (value == null) {
return null;
}
return value.toString();
}
public static Byte toByte(Object value) {
if (value == null) {
return null;
}
if (value instanceof Number) {
return ((Number) value).byteValue();
}
if (value instanceof String) {
String strVal = (String) value;
if (strVal.length() == 0) {
return null;
}
if ("null".equals(strVal) || "NULL".equals(strVal)) {
return null;
}
return Byte.parseByte(strVal);
}
throw new DataSetException("can not cast to byte, value : " + value);
}
public static Character toChar(Object value) {
if (value == null) {
return null;
}
if (value instanceof Character) {
return (Character) value;
}
if (value instanceof String) {
String strVal = (String) value;
if (strVal.length() == 0) {
return null;
}
if (strVal.length() != 1) {
throw new DataSetException("can not cast to byte, value : " + value);
}
return strVal.charAt(0);
}
throw new DataSetException("can not cast to byte, value : " + value);
}
public static Integer toInteger(Object value) {
if (value == null) {
return null;
}
if (value instanceof Integer) {
return (Integer) value;
}
if (value instanceof Number) {
return ((Number) value).intValue();
}
if (value instanceof String) {
String strVal = (String) value;
if (strVal.length() == 0) {
return null;
}
if ("null".equals(strVal)) {
return null;
}
if ("null".equals(strVal) || "NULL".equals(strVal)) {
return null;
}
return Integer.parseInt(strVal);
}
throw new DataSetException("can't cast to integer value:"+value);
}
public static Long toLong(Object value) {
if (value == null) {
return null;
}
if (value instanceof Number) {
return ((Number) value).longValue();
}
if (value instanceof String) {
String strVal = (String) value;
if (strVal.length() == 0) {
return null;
}
if ("null".equals(strVal) || "NULL".equals(strVal)) {
return null;
}
try {
return Long.parseLong(strVal);
} catch (NumberFormatException ex) {
//
}
}
throw new DataSetException("can not cast to long, value : " + value);
}
public static Double toDouble(Object value) {
if (value == null) {
return null;
}
if (value instanceof Number) {
return ((Number) value).doubleValue();
}
if (value instanceof String) {
String strVal = value.toString();
if (strVal.length() == 0) {
return null;
}
if ("null".equals(strVal) || "NULL".equals(strVal)) {
return null;
}
return Double.parseDouble(strVal);
}
throw new DataSetException("can not cast to double, value : " + value);
}
public static BigDecimal toBigDecimal(Object value) {
if (value == null) {
return null;
}
if (value instanceof BigDecimal) {
return (BigDecimal) value;
}
if (value instanceof BigInteger) {
return new BigDecimal((BigInteger) value);
}
String strVal = value.toString().trim();
if (strVal.length() == 0) {
return null;
}
return new BigDecimal(strVal);
}
public static byte[] toBytes(Object value) {
if (value instanceof byte[]) {
return (byte[]) value;
}
if (value instanceof String) {
return ((String) value).getBytes();
}
throw new DataSetException("can not cast to int, value : " + value);
}
public static <K,V> Map<K,V> toMap(Object value,Class<Map<K, V>> cls) {
Map<K, V> ret = new HashMap<K, V>();
if(value instanceof Map) {
ret.putAll((Map<? extends K, ? extends V>) value);
}
return ret;
}
public static Object cast(Object value,Character type) {
switch(type){
case LDDataType.BYTE_ARRAY:
return toBytes(value);
case LDDataType.CHAR:
return toChar(value);
case LDDataType.DOUBLE:
return toDouble(value);
case LDDataType.DECIMAL:
return toBigDecimal(value);
case LDDataType.INT:
return toInteger(value);
case LDDataType.LONG:
return toLong(value);
case LDDataType.STRING:
return toString(value);
}
return value;
}
public static <T> T cast(Object obj,Class<T> clazz) {
if(obj == null)
return null;
if(obj.getClass() == clazz) {
return (T)obj;
}
if (clazz == char.class || clazz == Character.class) {
return (T) toChar(obj);
}
if (clazz == int.class || clazz == Integer.class) {
return (T) toInteger(obj);
}
if (clazz == long.class || clazz == Long.class) {
return (T) toLong(obj);
}
if (clazz == double.class || clazz == Double.class) {
return (T) toDouble(obj);
}
if (clazz == String.class) {
return (T) toString(obj);
}
if (clazz == BigDecimal.class) {
return (T) toBigDecimal(obj);
}
logger.debug("cast to "+clazz.getName()+" failed,value="+obj);
return null;
}
}
|
package FunctionalCoreTests.ControllerTests.SubControllerTests;
import Factory.ServerFactory;
import FunctionalCore.Controller.SubControllers.RedirectionController;
import FunctionalCore.Request;
import Mocks.MockRequestDealer;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.LinkedHashMap;
import static org.junit.jupiter.api.Assertions.*;
class RedirectionControllerTest {
private int port = 5000;
private String directory = System.getProperty("user.dir") + "/src/test/java/Mocks";
private String configFile = directory + "/mock_routes.yml";
RedirectionController subject;
LinkedHashMap<String, String> properties;
LinkedHashMap<String, LinkedHashMap<String, String>> routes;
@BeforeEach
void setup() {
properties = new LinkedHashMap<>();
routes = new LinkedHashMap<>();
ServerFactory factory = new ServerFactory(port, directory, configFile);
subject = factory.buildRedirectionController();
}
@Test
void relevantReturnsTrueIfTheRouteHasARedirectionProperty() {
//Given
String uri = "/flagged-for-redirection";
properties.put("redirect-uri", "/redirect-to-here");
routes.put(uri, properties);
Request request = MockRequestDealer.getRequest(uri);
//When
boolean actual = subject.relevant(request, routes);
//Then
assertTrue(actual);
}
@Test
void relevantReturnsFalseIfTheRouteDoesNOtHaveARedirectProperty() {
//Given
String uri = "/not-flagged";
properties.put("allowed-methods", "OPTIONS,HEAD");
routes.put(uri, properties);
Request request = MockRequestDealer.getRequest(uri);
//When
boolean actual = subject.relevant(request, routes);
//Then
assertFalse(actual);
}
@Test
void generateReturnsA302Response() {
//Given
String uri = "/flagged-for-redirection";
properties.put("redirect-uri", "/redirect-to-here");
routes.put(uri, properties);
Request request = MockRequestDealer.getRequest(uri);
//When
byte[] actual = subject.generate(request, routes);
//Then
String expected = "302 Found";
assertTrue(new String(actual).contains(expected));
}
@Test
void generateReturnsTheRedirectUri() {
//Given
String uri = "/flagged-for-redirection";
String redirectUri = "/redirect-to-here";
properties.put("redirect-uri", redirectUri);
routes.put(uri, properties);
Request request = MockRequestDealer.getRequest(uri);
//When
byte[] actual = subject.generate(request, routes);
//Then
assertTrue(new String(actual).contains(redirectUri));
}
}
|
package com.zhike.blogpojo.DO;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* Copyright (C) 2022 智客工坊(52interview.com)
* The SpringBoot Super-blog Project.
* All rights reserved.
* <p>
* > Github地址: https://github.com/zhikecore/superblog.git
* > 教程地址: https://www.52interview.com/book/36
* > 智客工坊社区:https://www.52interview.com/
* <p>
* 智客工坊(52interview.com) - 经验创造价值,分享成就未来。
* <p>
* Article at 2022/1/16 21:04,code by JeffreyHu
* You can contact author with zhikecore@foxmail.com.
*/
@Data
@EqualsAndHashCode(callSuper = false)
public class Article implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "Id", type = IdType.AUTO)
private Integer Id;
@TableField("ArticleTypeId")
private Integer ArticleTypeId;
/**
* 文章类型名称
*/
@TableField("ArticleTypeName")
private String ArticleTypeName;
/**
* 所属用户ID
*/
@TableField("UserId")
private Integer UserId;
/**
* 标签,多个以逗号分隔
*/
@TableField("TagIds")
private String TagIds;
/**
* 标签,多个以逗号分隔
*/
@TableField("Tags")
private String Tags;
/**
* 标题
*/
@TableField("Title")
private String Title;
/**
* 链接
*/
@TableField("LinkUrl")
private String LinkUrl;
/**
* 封面
*/
@TableField("Cover")
private String Cover;
/**
* 导航
*/
@TableField("Navigation")
private String Navigation;
/**
* 摘要
*/
@TableField("Summary")
private String Summary;
@TableField("Content")
private String Content;
/**
* 是否置顶:0为否,1为是
*/
@TableField("IsUp")
private Boolean IsUp;
/**
* 是否编辑推荐:0为否,1为是
*/
@TableField("IsRecommend")
private Boolean IsRecommend;
/**
* 是否热点:0=否,1=是
*/
@TableField("IsHot")
private Boolean IsHot;
/**
* 开放状态:0=公开 1=会员可看 2=付费可看
*/
@TableField("OpenState")
private Integer OpenState;
/**
* 浏览次数
*/
@TableField("ScanNum")
private Integer ScanNum;
@TableField("LikeNum")
private Integer LikeNum;
@TableField("CommentNum")
private Integer CommentNum;
@TableField("ForwardNum")
private Integer ForwardNum;
/**
* 是否软删除
*/
@TableField("IsSoftDelete")
private Boolean IsSoftDelete;
@TableField("Description")
private String Description;
@TableField("CreateTime")
private LocalDateTime CreateTime;
@TableField("ModifyTime")
private LocalDateTime ModifyTime;
}
|
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.service.monitor.internal;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.vespa.applicationmodel.ClusterId;
import com.yahoo.vespa.applicationmodel.ServiceType;
import java.util.Objects;
/**
* @author hakon
*/
public class ZoneApplication {
private ZoneApplication() {}
static final ApplicationId ZONE_APPLICATION_ID =
ApplicationId.from("hosted-vespa", "routing", "default");
static boolean isNodeAdminService(ApplicationId applicationId,
ClusterId clusterId,
ServiceType serviceType) {
return Objects.equals(applicationId, ZONE_APPLICATION_ID) &&
Objects.equals(serviceType, ServiceType.CONTAINER) &&
Objects.equals(clusterId, ClusterId.NODE_ADMIN);
}
}
|
package uk.gov.dwp.queue.triage.core.classification.predicate;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import uk.gov.dwp.queue.triage.core.classification.classifier.Description;
import uk.gov.dwp.queue.triage.core.classification.classifier.FailedMessagePredicateWithResult;
import uk.gov.dwp.queue.triage.core.domain.FailedMessage;
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "_type"
)
@JsonSubTypes({
@Type(value = OrPredicate.class, name = "or"),
@Type(value = AndPredicate.class, name = "and"),
@Type(value = BrokerEqualsPredicate.class, name = "brokerEqualTo"),
@Type(value = ContentContainsJsonPath.class, name = "contentContainsJsonPath"),
@Type(value = ContentEqualToPredicate.class, name = "contentEqualTo"),
@Type(value = ContentMatchesJsonPath.class, name = "contentMatchesJsonPath"),
@Type(value = DestinationEqualsPredicate.class, name = "destinationEqualTo"),
@Type(value = PropertyEqualToPredicate.class, name = "propertyEqualTo"),
@Type(value = PropertyExistsPredicate.class, name = "propertyExists"),
@Type(value = PropertyMatchesPredicate.class, name = "propertyMatches"),
@Type(value = FailedMessagePredicateWithResult.class, name = "predicateWithResult")
})
public interface FailedMessagePredicate {
boolean test(FailedMessage failedMessage);
<T> Description<T> describe(Description<T> description);
}
|
package com.oz.ethereum.rpc.client;
import com.oz.utils.Constants;
import com.oz.utils.StringUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.apache.commons.codec.binary.Hex;
import org.spongycastle.util.BigIntegers;
import java.math.BigInteger;
/**
*
* Created at 8/16/16, 00:38.
* @author <a href="sock.sqt@gmail.com">sockosg</a>
* @since 1.0
*/
@Data
@AllArgsConstructor
public class Transaction {
private static final BigInteger DEFAULT_GAS_PRICE = new BigInteger("20000000000");
private static final BigInteger DEFAULT_GAS_LIMIT = new BigInteger("2000000");
private BigInteger from;
private BigInteger to;
private BigInteger gas;
private BigInteger gasPrice;
private BigInteger value;
private String data;
private BigInteger nonce;
private BigInteger hash;
private String input;
private BigInteger transactionIndex;
private BigInteger blockHash;
private BigInteger blockNumber;
private String encodedTransaction;
public Transaction() {
super();
this.gasPrice = DEFAULT_GAS_PRICE;
this.gas = DEFAULT_GAS_LIMIT;
}
public Transaction(final BigInteger gasPrice, final BigInteger gasLimit) {
super();
this.gasPrice = gasPrice;
this.gas = gasLimit;
}
public void sign(final BigInteger privKeyBytes) {
byte[] privateKey = BigIntegers.asUnsignedByteArray(privKeyBytes);
byte[] nonce = BigIntegers.asUnsignedByteArray(this.nonce);
byte[] gasPrice = BigIntegers.asUnsignedByteArray(this.gasPrice);
byte[] gasLimit = BigIntegers.asUnsignedByteArray(this.gas);
byte[] toAddress = BigIntegers.asUnsignedByteArray(this.to);
byte[] value = BigIntegers.asUnsignedByteArray(this.value);
byte[] data = org.spongycastle.util.encoders.Hex.decode(this.data.replaceFirst(Constants.HEX_PREFIX, StringUtils.EMPTY));
org.ethereum.core.Transaction rawTransaction = new org.ethereum.core.Transaction(
nonce,
gasPrice,
gasLimit,
toAddress,
value,
data);
rawTransaction.sign(privateKey);
this.encodedTransaction = Hex.encodeHexString(rawTransaction.getEncoded());
}
}
|
package bean;
public class Endereco {
private int fk_cidade;
private String rua;
private int numero;
private String complemento;
private String cep;
private String bairro;
public Endereco(String bairro,String cep,String complemento,int numero,String rua,int fk_cidade){
this.bairro=bairro;
this.cep = cep;
this.complemento = complemento;
this.fk_cidade = fk_cidade;
this.numero = numero;
this.rua = rua;
}
public int getFk_cidade() {
return fk_cidade;
}
public void setFk_cidade(int fk_cidade) {
this.fk_cidade = fk_cidade;
}
public String getRua() {
return rua;
}
public void setRua(String rua) {
this.rua = rua;
}
public int getNumero() {
return numero;
}
public void setNumero(int numero) {
this.numero = numero;
}
public String getComplemento() {
return complemento;
}
public void setComplemento(String complemento) {
this.complemento = complemento;
}
public String getCep() {
return cep;
}
public void setCep(String cep) {
this.cep = cep;
}
public String getBairro() {
return bairro;
}
public void setBairro(String bairro) {
this.bairro = bairro;
}
}
|
package ssd8.socket.ftp;
import java.io.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
/**
* @author Robin Hanxy
* @version 1.0.5
*/
public class FileClient {
private static final int tcp_PORT = 2021; // TCP连接端口
private static final String HOST = "127.0.0.1"; // 连接地址
private static final int udp_PORT = 2020; // UDP端口
private static final int SENDSIZE = 1024; // 一次传送文件的字节数
Socket socket = new Socket();
DatagramSocket dgsocket;
public FileClient() throws UnknownHostException, IOException {
socket = new Socket(HOST, tcp_PORT); //创建客户端套接字
}
public static void main(String[] args) throws UnknownHostException,
IOException {
new FileClient().send();
}
/**
* send implements
*/
public void send() {
try {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream()));// 客户端输出流,向服务器发消息
BufferedReader br = new BufferedReader(new InputStreamReader(
socket.getInputStream()));// 客户端输入流,接收服务器消息
PrintWriter pw = new PrintWriter(bw, true);//装饰输出流,及时刷新
System.out.println(br.readLine()); // 输出服务器返回连接成功的消息
Scanner in = new Scanner(System.in); // 接受用户信息
String cmd = null;
while ((cmd = in.next()) != null) {
pw.println(cmd); // 发送给服务器端
if (cmd.equals("cd") || cmd.equals("get")) {
String dir = in.next();
pw.println(dir);
if (cmd.equals("get")) {// 下载文件
long fileLength = Long.parseLong(br.readLine());
System.out.println("文件大小为:" + fileLength);
if (fileLength != -1) {
System.out.println("开始接收文件:" + dir);
getFile(dir, fileLength);
System.out.println("文件接收完毕");
} else {
System.out.println("Unknown file");
}
}
}
String msg = null;
while (null != (msg = br.readLine())) {
if (msg.equals("CmdEnd")) {
break;
}
System.out.println(msg); // 输出服务器返回的消息
}
if (cmd.equals("bye")) {
break; // 退出
}
}
in.close();
br.close();
bw.close();
pw.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != socket) {
try {
socket.close(); // 断开连接
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* Gets a file by name and length
*
* @param fileName the name of the file that wants getting.
* @param fileLength the length of the file that wants getting.
* @throws IOException
*/
private void getFile(String fileName, long fileLength) throws IOException {
DatagramPacket dp = new DatagramPacket(new byte[SENDSIZE], SENDSIZE);
dgsocket = new DatagramSocket(udp_PORT);// UDP连接
byte[] recInfo = new byte[SENDSIZE];
FileOutputStream fos = new FileOutputStream(new File(
("D:\\Download\\") + fileName));
int count = (int) (fileLength / SENDSIZE) + ((fileLength % SENDSIZE) == 0 ? 0 : 1);
while ((count--) > 0) {
dgsocket.receive(dp); // 接收文件信息
recInfo = dp.getData();
fos.write(recInfo, 0, dp.getLength());
fos.flush();
}
dgsocket.close();
fos.close();
}
}
|
package com.mvp.empty.Util;
import android.content.Context;
import android.util.TypedValue;
/**
* Date: 2016/8/30.
* Created by: v7428477
* email:764213580@qq.com
* 常用单位转换的辅助类
*/
public class ToolDensity {
private ToolDensity() {
/* cannot be instantiated */
throw new UnsupportedOperationException("cannot be instantiated");
}
/**
* dp转px
*
* @param context
* @param dpVal
* @return
*/
public static int dp2px(Context context, float dpVal) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
dpVal, context.getResources().getDisplayMetrics());
}
/**
* sp转px
*
* @param context
* @param spVal
* @return
*/
public static int sp2px(Context context, float spVal) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
spVal, context.getResources().getDisplayMetrics());
}
/**
* px转dp
*
* @param context
* @param pxVal
* @return
*/
public static float px2dp(Context context, float pxVal) {
final float scale = context.getResources().getDisplayMetrics().density;
return (pxVal / scale);
}
/**
* px转sp
*
* @param pxVal
* @return
*/
public static float px2sp(Context context, float pxVal) {
return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
}
}
|
package p07_FoodShortage;
public class Robot extends Indentifiable {
private String model;
public Robot(String model, String id) {
super(id);
this.model = model;
}
@Override
public boolean check(String fakeIdEnd) {
if (super.getId().endsWith(fakeIdEnd)) {
return true;
}
return false;
}
}
|
package Aula02;
/**
* Created by Gabriel on 01/03/2016.
*/
/*
4. Faca um programa que leia um vetor de 5 elementos,
apos a leitura os valores devem ser copiados para um novo vetor, na ordem inversa.
*/
public class Algoritmo4 {
static int[] vet = {1, 2, 3, 4, 5};
static int[] inverso = new int[5];
public static void main(String[] args) {
for(int i=0; i<vet.length; i++){
inverso[i] = vet[(vet.length-1)-i];
System.out.print(inverso[i] +" - ");
}
}
}
|
package com.wangwenjun.concurrent.chapter1;
/***************************************
* @author:Alex Wang
* @Date:2017/3/12 QQ:532500648
* QQ交流群:286081824
***************************************/
public class SingletonObject1 {
/**
* can't lazy load.
*/
private static final SingletonObject1 instance = new SingletonObject1();
private SingletonObject1() {
//empty
}
public static SingletonObject1 getInstance() {
return instance;
}
}
|
package com.tpa.videogames.services;
import com.tpa.videogames.entities.Videojuego;
import com.tpa.videogames.repositories.RepositorioVideojuego;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;
@Service
public class ServicioVideojuego implements ServicioBase<Videojuego>{
@Autowired
private RepositorioVideojuego repositorio;
@Override
@Transactional
public List<Videojuego> findAll() throws Exception {
try {
List<Videojuego> entities = this.repositorio.findAll();
return entities;
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
@Override
@Transactional
public Videojuego findById(long id) throws Exception {
try {
Optional<Videojuego> opt = this.repositorio.findById(id);
return opt.get();
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
@Override
@Transactional
public Videojuego saveOne(Videojuego entity) throws Exception {
try {
Videojuego videojuego = this.repositorio.save(entity);
return videojuego;
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
@Override
@Transactional
public Videojuego updateOne(Videojuego entity, long id) throws Exception {
try {
Optional<Videojuego> opt = this.repositorio.findById(id);
Videojuego videojuego = opt.get();
videojuego = this.repositorio.save(entity);
return videojuego;
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
@Override
@Transactional
public boolean deleteById(long id) throws Exception {
try {
Optional<Videojuego> opt = this.repositorio.findById(id);
if (!opt.isEmpty()) {
Videojuego videojuego = opt.get();
videojuego.setActivo(!videojuego.isActivo());
this.repositorio.save(videojuego);
} else {
throw new Exception();
}
return true;
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
/* Metodos nuevos */
@Transactional
public List<Videojuego> findAllByActivo() throws Exception{
try {
List<Videojuego> entities = this.repositorio.findAllByActivo();
return entities;
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
@Transactional
public Videojuego findByIdAndActivo(long id) throws Exception {
try {
Optional<Videojuego> opt = this.repositorio.findByIdAndActivo(id);
return opt.get();
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
@Transactional
public List<Videojuego> findByTitle(String q) throws Exception{
try{
List<Videojuego> entities = this.repositorio.findByTitle(q);
return entities;
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
@Transactional
public List<Videojuego> findByEverything(String q) throws Exception{
try{
List<Videojuego> entities = this.repositorio.findByTitle(q);
return entities;
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
}
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/container/v1/cluster_service.proto
package com.google.container.v1;
public interface SandboxConfigOrBuilder extends
// @@protoc_insertion_point(interface_extends:google.container.v1.SandboxConfig)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* Type of the sandbox to use for the node.
* </pre>
*
* <code>.google.container.v1.SandboxConfig.Type type = 2;</code>
* @return The enum numeric value on the wire for type.
*/
int getTypeValue();
/**
* <pre>
* Type of the sandbox to use for the node.
* </pre>
*
* <code>.google.container.v1.SandboxConfig.Type type = 2;</code>
* @return The type.
*/
com.google.container.v1.SandboxConfig.Type getType();
}
|
package net.dingzhaobo.PsyduckScript.AST.Expressions;
import lombok.NonNull;
import net.dingzhaobo.PsyduckScript.AST.Expression;
public class IntegerExpr extends Expression {
public IntegerExpr(int r, int c) {
super(r, c);
value = 0;
}
public IntegerExpr(int r, int c, int v) {
super(r, c);
value = v;
}
@NonNull
private int value;
@Override
public String toString() {
return "IntegerExpr(" + String.valueOf(value) + ")";
}
}
|
package com.mobiussoftware.iotbroker.mqtt.net;
/**
* Mobius Software LTD
* Copyright 2015-2018, Mobius Software LTD
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
import com.mobius.software.mqtt.parser.MQParser;
import com.mobius.software.mqtt.parser.header.api.MQMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
@Sharable
public class MQEncoder extends MessageToByteEncoder<MQMessage>
{
@Override
protected void encode(ChannelHandlerContext ctx, MQMessage message, ByteBuf out) throws Exception
{
ByteBuf buf = MQParser.encode(message);
out.writeBytes(buf);
}
}
|
package com.curisprofound.spring.reactivestackdemo.fixtures;
import javafx.application.Application;
import org.springframework.context.ApplicationContext;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerResponse;
import java.util.List;
import static org.hamcrest.Matchers.greaterThan;
import static org.junit.Assert.assertThat;
import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.springSecurity;
import static org.springframework.web.reactive.function.client.ExchangeFilterFunctions.basicAuthentication;
public class ReactiveRestFixture {
public static WebTestClient bindToRoutes(List<? extends RouterFunction<?>> routerFunctions){
assertThat(routerFunctions.size(), greaterThan(0));
RouterFunction<ServerResponse> router = routerFunctions.stream()
.map(r -> (RouterFunction<ServerResponse>) r)
.reduce((a, r) -> (RouterFunction<ServerResponse>) a.andOther(r))
.orElse(null);
return WebTestClient.bindToRouterFunction(router).build();
}
public static WebTestClient bindToApplicationContext(ApplicationContext context){
return WebTestClient.bindToApplicationContext(context)
.apply(springSecurity())
.configureClient()
.filter(basicAuthentication())
.build();
}
public static WebTestClient.ResponseSpec checkStatusCode(WebTestClient.ResponseSpec spec, String status) {
if (status.equalsIgnoreCase("ok"))
return spec.expectStatus().isOk();
if (status.equalsIgnoreCase("2xx"))
return spec.expectStatus().is2xxSuccessful();
if (status.equalsIgnoreCase("3xx"))
return spec.expectStatus().is3xxRedirection();
if (status.equalsIgnoreCase("4xx"))
return spec.expectStatus().is4xxClientError();
if (status.equalsIgnoreCase("5xx"))
return spec.expectStatus().is5xxServerError();
if (status.equalsIgnoreCase("1xx"))
return spec.expectStatus().is1xxInformational();
else
return spec.expectStatus().isEqualTo(Integer.valueOf(status));
}
}
|
package com.cms.exception;
import org.springframework.http.HttpStatus;
public class ResponseException {
private int status;
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public ResponseException message(String message) {
this.setMessage(message);
return this;
}
public ResponseException message(String message, HttpStatus httpStatus) {
this.setMessage(message);
this.setStatus(httpStatus);
return this;
}
public int getStatus() {
return status;
}
public void setStatus(HttpStatus status) {
this.status = status.value();
}
}
|
package imdb.bindingModel;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
public class FilmBindingModel {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
private String name;
private String genre;
private String director;
private int year;
}
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.common.settings;
import java.io.Closeable;
import java.security.GeneralSecurityException;
import java.util.Set;
/**
* An accessor for settings which are securely stored. See {@link SecureSetting}.
*/
public interface SecureSettings extends Closeable {
/** Returns true iff the settings are loaded and retrievable. */
boolean isLoaded();
/** Returns the names of all secure settings available. */
Set<String> getSettingNames();
/** Return a string setting. The {@link SecureString} should be closed once it is used. */
SecureString getString(String setting) throws GeneralSecurityException;
}
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.orc.writer;
import com.facebook.presto.common.block.Block;
import com.facebook.presto.common.type.Type;
import com.facebook.presto.orc.ColumnWriterOptions;
import com.facebook.presto.orc.DwrfDataEncryptor;
import com.facebook.presto.orc.OrcEncoding;
import com.facebook.presto.orc.checkpoint.BooleanStreamCheckpoint;
import com.facebook.presto.orc.checkpoint.ByteArrayStreamCheckpoint;
import com.facebook.presto.orc.checkpoint.LongStreamCheckpoint;
import com.facebook.presto.orc.metadata.ColumnEncoding;
import com.facebook.presto.orc.metadata.CompressedMetadataWriter;
import com.facebook.presto.orc.metadata.MetadataWriter;
import com.facebook.presto.orc.metadata.RowGroupIndex;
import com.facebook.presto.orc.metadata.Stream;
import com.facebook.presto.orc.metadata.Stream.StreamKind;
import com.facebook.presto.orc.metadata.statistics.ColumnStatistics;
import com.facebook.presto.orc.metadata.statistics.SliceColumnStatisticsBuilder;
import com.facebook.presto.orc.stream.ByteArrayOutputStream;
import com.facebook.presto.orc.stream.LongOutputStream;
import com.facebook.presto.orc.stream.PresentOutputStream;
import com.facebook.presto.orc.stream.StreamDataOutput;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import io.airlift.slice.Slice;
import org.openjdk.jol.info.ClassLayout;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;
import static com.facebook.presto.orc.OrcEncoding.DWRF;
import static com.facebook.presto.orc.metadata.ColumnEncoding.ColumnEncodingKind.DIRECT;
import static com.facebook.presto.orc.metadata.ColumnEncoding.ColumnEncodingKind.DIRECT_V2;
import static com.facebook.presto.orc.metadata.CompressionKind.NONE;
import static com.facebook.presto.orc.stream.LongOutputStream.createLengthOutputStream;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
public class SliceDirectColumnWriter
implements ColumnWriter
{
private static final int INSTANCE_SIZE = ClassLayout.parseClass(SliceDirectColumnWriter.class).instanceSize();
private final int column;
private final Type type;
private final boolean compressed;
private final ColumnEncoding columnEncoding;
private final LongOutputStream lengthStream;
private final ByteArrayOutputStream dataStream;
private final PresentOutputStream presentStream;
private final CompressedMetadataWriter metadataWriter;
private final List<ColumnStatistics> rowGroupColumnStatistics = new ArrayList<>();
private long columnStatisticsRetainedSizeInBytes;
private final Supplier<SliceColumnStatisticsBuilder> statisticsBuilderSupplier;
private SliceColumnStatisticsBuilder statisticsBuilder;
private boolean closed;
public SliceDirectColumnWriter(
int column,
Type type,
ColumnWriterOptions columnWriterOptions,
Optional<DwrfDataEncryptor> dwrfEncryptor,
OrcEncoding orcEncoding,
Supplier<SliceColumnStatisticsBuilder> statisticsBuilderSupplier,
MetadataWriter metadataWriter)
{
checkArgument(column >= 0, "column is negative");
requireNonNull(columnWriterOptions, "columnWriterOptions is null");
requireNonNull(dwrfEncryptor, "dwrfEncryptor is null");
requireNonNull(metadataWriter, "metadataWriter is null");
this.column = column;
this.type = requireNonNull(type, "type is null");
this.compressed = columnWriterOptions.getCompressionKind() != NONE;
this.columnEncoding = new ColumnEncoding(orcEncoding == DWRF ? DIRECT : DIRECT_V2, 0);
this.lengthStream = createLengthOutputStream(columnWriterOptions, dwrfEncryptor, orcEncoding);
this.dataStream = new ByteArrayOutputStream(columnWriterOptions, dwrfEncryptor);
this.presentStream = new PresentOutputStream(columnWriterOptions, dwrfEncryptor);
this.metadataWriter = new CompressedMetadataWriter(metadataWriter, columnWriterOptions, dwrfEncryptor);
this.statisticsBuilderSupplier = statisticsBuilderSupplier;
statisticsBuilder = statisticsBuilderSupplier.get();
}
@Override
public Map<Integer, ColumnEncoding> getColumnEncodings()
{
return ImmutableMap.of(column, columnEncoding);
}
@Override
public void beginRowGroup()
{
checkState(!closed);
presentStream.recordCheckpoint();
lengthStream.recordCheckpoint();
dataStream.recordCheckpoint();
}
@Override
public long writeBlock(Block block)
{
checkState(!closed);
checkArgument(block.getPositionCount() > 0, "Block is empty");
// record nulls
for (int position = 0; position < block.getPositionCount(); position++) {
writePresentValue(!block.isNull(position));
}
// record values
long elementSize = 0;
int nonNullValueCount = 0;
for (int position = 0; position < block.getPositionCount(); position++) {
if (!block.isNull(position)) {
Slice value = type.getSlice(block, position);
elementSize += value.length();
writeSlice(value, 0, value.length());
nonNullValueCount++;
}
}
return (block.getPositionCount() - nonNullValueCount) * NULL_SIZE + elementSize;
}
void writePresentValue(boolean value)
{
presentStream.writeBoolean(value);
}
void writeSlice(Slice slice, int sourceIndex, int length)
{
lengthStream.writeLong(length);
dataStream.writeSlice(slice, sourceIndex, length);
statisticsBuilder.addValue(slice, sourceIndex, length);
}
@Override
public Map<Integer, ColumnStatistics> finishRowGroup()
{
checkState(!closed);
ColumnStatistics statistics = statisticsBuilder.buildColumnStatistics();
rowGroupColumnStatistics.add(statistics);
columnStatisticsRetainedSizeInBytes += statistics.getRetainedSizeInBytes();
statisticsBuilder = statisticsBuilderSupplier.get();
return ImmutableMap.of(column, statistics);
}
@Override
public void close()
{
checkState(!closed);
closed = true;
lengthStream.close();
dataStream.close();
presentStream.close();
}
@Override
public Map<Integer, ColumnStatistics> getColumnStripeStatistics()
{
checkState(closed);
return ImmutableMap.of(column, ColumnStatistics.mergeColumnStatistics(rowGroupColumnStatistics));
}
@Override
public List<StreamDataOutput> getIndexStreams()
throws IOException
{
checkState(closed);
ImmutableList.Builder<RowGroupIndex> rowGroupIndexes = ImmutableList.builder();
List<LongStreamCheckpoint> lengthCheckpoints = lengthStream.getCheckpoints();
List<ByteArrayStreamCheckpoint> dataCheckpoints = dataStream.getCheckpoints();
Optional<List<BooleanStreamCheckpoint>> presentCheckpoints = presentStream.getCheckpoints();
for (int i = 0; i < rowGroupColumnStatistics.size(); i++) {
int groupId = i;
ColumnStatistics columnStatistics = rowGroupColumnStatistics.get(groupId);
LongStreamCheckpoint lengthCheckpoint = lengthCheckpoints.get(groupId);
ByteArrayStreamCheckpoint dataCheckpoint = dataCheckpoints.get(groupId);
Optional<BooleanStreamCheckpoint> presentCheckpoint = presentCheckpoints.map(checkpoints -> checkpoints.get(groupId));
List<Integer> positions = createSliceColumnPositionList(compressed, lengthCheckpoint, dataCheckpoint, presentCheckpoint);
rowGroupIndexes.add(new RowGroupIndex(positions, columnStatistics));
}
Slice slice = metadataWriter.writeRowIndexes(rowGroupIndexes.build());
Stream stream = new Stream(column, StreamKind.ROW_INDEX, slice.length(), false);
return ImmutableList.of(new StreamDataOutput(slice, stream));
}
private static List<Integer> createSliceColumnPositionList(
boolean compressed,
LongStreamCheckpoint lengthCheckpoint,
ByteArrayStreamCheckpoint dataCheckpoint,
Optional<BooleanStreamCheckpoint> presentCheckpoint)
{
ImmutableList.Builder<Integer> positionList = ImmutableList.builder();
presentCheckpoint.ifPresent(booleanStreamCheckpoint -> positionList.addAll(booleanStreamCheckpoint.toPositionList(compressed)));
positionList.addAll(dataCheckpoint.toPositionList(compressed));
positionList.addAll(lengthCheckpoint.toPositionList(compressed));
return positionList.build();
}
@Override
public List<StreamDataOutput> getDataStreams()
{
checkState(closed);
ImmutableList.Builder<StreamDataOutput> outputDataStreams = ImmutableList.builder();
presentStream.getStreamDataOutput(column).ifPresent(outputDataStreams::add);
outputDataStreams.add(lengthStream.getStreamDataOutput(column));
outputDataStreams.add(dataStream.getStreamDataOutput(column));
return outputDataStreams.build();
}
@Override
public long getBufferedBytes()
{
return lengthStream.getBufferedBytes() + dataStream.getBufferedBytes() + presentStream.getBufferedBytes();
}
@Override
public long getRetainedBytes()
{
return INSTANCE_SIZE + lengthStream.getRetainedBytes() + dataStream.getRetainedBytes() + presentStream.getRetainedBytes() + columnStatisticsRetainedSizeInBytes;
}
@Override
public void reset()
{
checkState(closed);
closed = false;
lengthStream.reset();
dataStream.reset();
presentStream.reset();
rowGroupColumnStatistics.clear();
columnStatisticsRetainedSizeInBytes = 0;
statisticsBuilder = statisticsBuilderSupplier.get();
}
}
|
package chefchallenge.backend.users;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping
public List<User> getListUser(){
return userService.getAllUser();
}
@GetMapping("/{id_user}")
public User getUserById(@PathVariable int id_user){
return userService.getUser(id_user);
}
@PutMapping
public User modifyUser(@RequestBody User user) {
return userService.modifyUser(user);
}
@PostMapping
public User addUser(@RequestBody User user) {
return userService.addUser(user);
}
@DeleteMapping("/{id_user}")
public String deleteUser(@PathVariable int id_user) {
return userService.deleteUser(id_user);
}
}
|
/*
* Copyright 2002-2015 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.test.context.junit4;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.transaction.PlatformTransactionManager;
/**
* Shared configuration for tests that need an embedded database pre-loaded
* with the schema for the 'person' table.
*
* @author Sam Brannen
* @since 4.2
*/
@Configuration
public class EmbeddedPersonDatabaseTestsConfig {
@Bean
public PlatformTransactionManager txMgr() {
return new DataSourceTransactionManager(dataSource());
}
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()//
.generateUniqueName(true)//
.addScript("classpath:/org/springframework/test/jdbc/schema.sql") //
.build();
}
}
|
package theHeart.cards;
import com.megacrit.cardcrawl.actions.common.ExhaustAction;
import com.megacrit.cardcrawl.actions.common.ExhaustSpecificCardAction;
import com.megacrit.cardcrawl.actions.common.GainBlockAction;
import com.megacrit.cardcrawl.actions.common.MakeTempCardInHandAction;
import com.megacrit.cardcrawl.cards.status.Wound;
import com.megacrit.cardcrawl.characters.AbstractPlayer;
import com.megacrit.cardcrawl.core.CardCrawlGame;
import com.megacrit.cardcrawl.dungeons.AbstractDungeon;
import com.megacrit.cardcrawl.localization.CardStrings;
import com.megacrit.cardcrawl.monsters.AbstractMonster;
import theHeart.DefaultMod;
import theHeart.actions.ExhaustDrawPileWounds;
import theHeart.actions.ExhaustingReprogramAction;
import theHeart.characters.TheDefault;
import static theHeart.DefaultMod.makeCardPath;
public class Embolectomy extends AbstractDynamicCard {
/*
* Wiki-page: https://github.com/daviscook477/BaseMod/wiki/Custom-Cards
*
* Big Slap Deal 10(15)) damage.
*/
// TEXT DECLARATION
public static final String ID = DefaultMod.makeID(Embolectomy.class.getSimpleName());
public static final String IMG = makeCardPath("Attack.png");
private static final CardStrings cardStrings = CardCrawlGame.languagePack.getCardStrings(ID);
public static final String UPGRADE_DESCRIPTION = cardStrings.UPGRADE_DESCRIPTION;
public static final String NAME = cardStrings.NAME;
public static final String DESCRIPTION = cardStrings.DESCRIPTION;
// /TEXT DECLARATION/
//This card is not added in yet and it does not work, it jsut freezes whenever it is used.
// STAT DECLARATION
private static final CardRarity RARITY = CardRarity.UNCOMMON;
private static final CardTarget TARGET = CardTarget.NONE;
private static final CardType TYPE = CardType.SKILL;
public static final CardColor COLOR = TheDefault.Enums.COLOR_GRAY;
private static final int COST = 1;
private static final int UPGRADED_PLUS_COST = 0;
// /STAT DECLARATION/
public Embolectomy() {
super(ID, IMG, COST, TYPE, COLOR, RARITY, TARGET);
exhaust = true;
}
// Actions the card should do.
@Override
public void use(AbstractPlayer p, AbstractMonster m) {
AbstractDungeon.actionManager.addToBottom( new ExhaustDrawPileWounds());
}
public AbstractDynamicCard makeCopy() {
return new Embolectomy();
}
//Upgraded stats.
@Override
public void upgrade() {
if (!this.upgraded) {
this.upgradeName();
upgradeBaseCost(UPGRADED_PLUS_COST);
rawDescription = UPGRADE_DESCRIPTION;
this.initializeDescription();
}
}
}
|
/**
* Copyright © 2016-2021 The Thingsboard Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.thingsboard.server.controller;
import com.google.common.util.concurrent.ListenableFuture;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.EntitySubtype;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.asset.Asset;
import org.thingsboard.server.common.data.asset.AssetInfo;
import org.thingsboard.server.common.data.asset.AssetSearchQuery;
import org.thingsboard.server.common.data.audit.ActionType;
import org.thingsboard.server.common.data.edge.Edge;
import org.thingsboard.server.common.data.edge.EdgeEventActionType;
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.AssetId;
import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.EdgeId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.page.PageLink;
import org.thingsboard.server.common.data.page.TimePageLink;
import org.thingsboard.server.dao.exception.IncorrectParameterException;
import org.thingsboard.server.dao.model.ModelConstants;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.asset.AssetBulkImportService;
import org.thingsboard.server.service.importing.BulkImportRequest;
import org.thingsboard.server.service.importing.BulkImportResult;
import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.security.permission.Operation;
import org.thingsboard.server.service.security.permission.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import static org.thingsboard.server.controller.ControllerConstants.ASSET_ID_PARAM_DESCRIPTION;
import static org.thingsboard.server.controller.ControllerConstants.ASSET_INFO_DESCRIPTION;
import static org.thingsboard.server.controller.ControllerConstants.ASSET_NAME_DESCRIPTION;
import static org.thingsboard.server.controller.ControllerConstants.ASSET_SORT_PROPERTY_ALLOWABLE_VALUES;
import static org.thingsboard.server.controller.ControllerConstants.ASSET_TEXT_SEARCH_DESCRIPTION;
import static org.thingsboard.server.controller.ControllerConstants.ASSET_TYPE_DESCRIPTION;
import static org.thingsboard.server.controller.ControllerConstants.CUSTOMER_ID_PARAM_DESCRIPTION;
import static org.thingsboard.server.controller.ControllerConstants.EDGE_ASSIGN_ASYNC_FIRST_STEP_DESCRIPTION;
import static org.thingsboard.server.controller.ControllerConstants.EDGE_ASSIGN_RECEIVE_STEP_DESCRIPTION;
import static org.thingsboard.server.controller.ControllerConstants.EDGE_ID_PARAM_DESCRIPTION;
import static org.thingsboard.server.controller.ControllerConstants.EDGE_UNASSIGN_ASYNC_FIRST_STEP_DESCRIPTION;
import static org.thingsboard.server.controller.ControllerConstants.EDGE_UNASSIGN_RECEIVE_STEP_DESCRIPTION;
import static org.thingsboard.server.controller.ControllerConstants.PAGE_DATA_PARAMETERS;
import static org.thingsboard.server.controller.ControllerConstants.PAGE_NUMBER_DESCRIPTION;
import static org.thingsboard.server.controller.ControllerConstants.PAGE_SIZE_DESCRIPTION;
import static org.thingsboard.server.controller.ControllerConstants.SORT_ORDER_ALLOWABLE_VALUES;
import static org.thingsboard.server.controller.ControllerConstants.SORT_ORDER_DESCRIPTION;
import static org.thingsboard.server.controller.ControllerConstants.SORT_PROPERTY_DESCRIPTION;
import static org.thingsboard.server.controller.ControllerConstants.TENANT_AUTHORITY_PARAGRAPH;
import static org.thingsboard.server.controller.ControllerConstants.TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH;
import static org.thingsboard.server.controller.EdgeController.EDGE_ID;
import static org.thingsboard.server.dao.asset.BaseAssetService.TB_SERVICE_QUEUE;
@RestController
@TbCoreComponent
@RequestMapping("/api")
@RequiredArgsConstructor
@Slf4j
public class AssetController extends BaseController {
private final AssetBulkImportService assetBulkImportService;
public static final String ASSET_ID = "assetId";
@ApiOperation(value = "Get Asset (getAssetById)",
notes = "Fetch the Asset object based on the provided Asset Id. " +
"If the user has the authority of 'Tenant Administrator', the server checks that the asset is owned by the same tenant. " +
"If the user has the authority of 'Customer User', the server checks that the asset is assigned to the same customer." + TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH
, produces = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/asset/{assetId}", method = RequestMethod.GET)
@ResponseBody
public Asset getAssetById(@ApiParam(value = ASSET_ID_PARAM_DESCRIPTION)
@PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException {
checkParameter(ASSET_ID, strAssetId);
try {
AssetId assetId = new AssetId(toUUID(strAssetId));
return checkAssetId(assetId, Operation.READ);
} catch (Exception e) {
throw handleException(e);
}
}
@ApiOperation(value = "Get Asset Info (getAssetInfoById)",
notes = "Fetch the Asset Info object based on the provided Asset Id. " +
"If the user has the authority of 'Tenant Administrator', the server checks that the asset is owned by the same tenant. " +
"If the user has the authority of 'Customer User', the server checks that the asset is assigned to the same customer. "
+ ASSET_INFO_DESCRIPTION + TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH, produces = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/asset/info/{assetId}", method = RequestMethod.GET)
@ResponseBody
public AssetInfo getAssetInfoById(@ApiParam(value = ASSET_ID_PARAM_DESCRIPTION)
@PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException {
checkParameter(ASSET_ID, strAssetId);
try {
AssetId assetId = new AssetId(toUUID(strAssetId));
return checkAssetInfoId(assetId, Operation.READ);
} catch (Exception e) {
throw handleException(e);
}
}
@ApiOperation(value = "Create Or Update Asset (saveAsset)",
notes = "Creates or Updates the Asset. When creating asset, platform generates Asset Id as [time-based UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_1_(date-time_and_MAC_address) " +
"The newly created Asset id will be present in the response. " +
"Specify existing Asset id to update the asset. " +
"Referencing non-existing Asset Id will cause 'Not Found' error." + TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH, produces = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/asset", method = RequestMethod.POST)
@ResponseBody
public Asset saveAsset(@ApiParam(value = "A JSON value representing the asset.") @RequestBody Asset asset) throws ThingsboardException {
try {
if (TB_SERVICE_QUEUE.equals(asset.getType())) {
throw new ThingsboardException("Unable to save asset with type " + TB_SERVICE_QUEUE, ThingsboardErrorCode.BAD_REQUEST_PARAMS);
}
asset.setTenantId(getCurrentUser().getTenantId());
checkEntity(asset.getId(), asset, Resource.ASSET);
Asset savedAsset = checkNotNull(assetService.saveAsset(asset));
onAssetCreatedOrUpdated(savedAsset, asset.getId() != null, getCurrentUser());
return savedAsset;
} catch (Exception e) {
logEntityAction(emptyId(EntityType.ASSET), asset,
null, asset.getId() == null ? ActionType.ADDED : ActionType.UPDATED, e);
throw handleException(e);
}
}
private void onAssetCreatedOrUpdated(Asset asset, boolean updated, SecurityUser user) {
try {
logEntityAction(user, asset.getId(), asset,
asset.getCustomerId(),
updated ? ActionType.UPDATED : ActionType.ADDED, null);
} catch (ThingsboardException e) {
log.error("Failed to log entity action", e);
}
if (updated) {
sendEntityNotificationMsg(asset.getTenantId(), asset.getId(), EdgeEventActionType.UPDATED);
}
}
@ApiOperation(value = "Delete asset (deleteAsset)",
notes = "Deletes the asset and all the relations (from and to the asset). Referencing non-existing asset Id will cause an error." + TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH)
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@RequestMapping(value = "/asset/{assetId}", method = RequestMethod.DELETE)
@ResponseStatus(value = HttpStatus.OK)
public void deleteAsset(@ApiParam(value = ASSET_ID_PARAM_DESCRIPTION) @PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException {
checkParameter(ASSET_ID, strAssetId);
try {
AssetId assetId = new AssetId(toUUID(strAssetId));
Asset asset = checkAssetId(assetId, Operation.DELETE);
List<EdgeId> relatedEdgeIds = findRelatedEdgeIds(getTenantId(), assetId);
assetService.deleteAsset(getTenantId(), assetId);
logEntityAction(assetId, asset,
asset.getCustomerId(),
ActionType.DELETED, null, strAssetId);
sendDeleteNotificationMsg(getTenantId(), assetId, relatedEdgeIds);
} catch (Exception e) {
logEntityAction(emptyId(EntityType.ASSET),
null,
null,
ActionType.DELETED, e, strAssetId);
throw handleException(e);
}
}
@ApiOperation(value = "Assign asset to customer (assignAssetToCustomer)",
notes = "Creates assignment of the asset to customer. Customer will be able to query asset afterwards." + TENANT_AUTHORITY_PARAGRAPH, produces = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@RequestMapping(value = "/customer/{customerId}/asset/{assetId}", method = RequestMethod.POST)
@ResponseBody
public Asset assignAssetToCustomer(@ApiParam(value = CUSTOMER_ID_PARAM_DESCRIPTION) @PathVariable("customerId") String strCustomerId,
@ApiParam(value = ASSET_ID_PARAM_DESCRIPTION) @PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException {
checkParameter("customerId", strCustomerId);
checkParameter(ASSET_ID, strAssetId);
try {
CustomerId customerId = new CustomerId(toUUID(strCustomerId));
Customer customer = checkCustomerId(customerId, Operation.READ);
AssetId assetId = new AssetId(toUUID(strAssetId));
checkAssetId(assetId, Operation.ASSIGN_TO_CUSTOMER);
Asset savedAsset = checkNotNull(assetService.assignAssetToCustomer(getTenantId(), assetId, customerId));
logEntityAction(assetId, savedAsset,
savedAsset.getCustomerId(),
ActionType.ASSIGNED_TO_CUSTOMER, null, strAssetId, strCustomerId, customer.getName());
sendEntityAssignToCustomerNotificationMsg(savedAsset.getTenantId(), savedAsset.getId(),
customerId, EdgeEventActionType.ASSIGNED_TO_CUSTOMER);
return savedAsset;
} catch (Exception e) {
logEntityAction(emptyId(EntityType.ASSET), null,
null,
ActionType.ASSIGNED_TO_CUSTOMER, e, strAssetId, strCustomerId);
throw handleException(e);
}
}
@ApiOperation(value = "Unassign asset from customer (unassignAssetFromCustomer)",
notes = "Clears assignment of the asset to customer. Customer will not be able to query asset afterwards." + TENANT_AUTHORITY_PARAGRAPH, produces = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@RequestMapping(value = "/customer/asset/{assetId}", method = RequestMethod.DELETE)
@ResponseBody
public Asset unassignAssetFromCustomer(@ApiParam(value = ASSET_ID_PARAM_DESCRIPTION) @PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException {
checkParameter(ASSET_ID, strAssetId);
try {
AssetId assetId = new AssetId(toUUID(strAssetId));
Asset asset = checkAssetId(assetId, Operation.UNASSIGN_FROM_CUSTOMER);
if (asset.getCustomerId() == null || asset.getCustomerId().getId().equals(ModelConstants.NULL_UUID)) {
throw new IncorrectParameterException("Asset isn't assigned to any customer!");
}
Customer customer = checkCustomerId(asset.getCustomerId(), Operation.READ);
Asset savedAsset = checkNotNull(assetService.unassignAssetFromCustomer(getTenantId(), assetId));
logEntityAction(assetId, asset,
asset.getCustomerId(),
ActionType.UNASSIGNED_FROM_CUSTOMER, null, strAssetId, customer.getId().toString(), customer.getName());
sendEntityAssignToCustomerNotificationMsg(savedAsset.getTenantId(), savedAsset.getId(),
customer.getId(), EdgeEventActionType.UNASSIGNED_FROM_CUSTOMER);
return savedAsset;
} catch (Exception e) {
logEntityAction(emptyId(EntityType.ASSET), null,
null,
ActionType.UNASSIGNED_FROM_CUSTOMER, e, strAssetId);
throw handleException(e);
}
}
@ApiOperation(value = "Make asset publicly available (assignAssetToPublicCustomer)",
notes = "Asset will be available for non-authorized (not logged-in) users. " +
"This is useful to create dashboards that you plan to share/embed on a publicly available website. " +
"However, users that are logged-in and belong to different tenant will not be able to access the asset." + TENANT_AUTHORITY_PARAGRAPH, produces = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@RequestMapping(value = "/customer/public/asset/{assetId}", method = RequestMethod.POST)
@ResponseBody
public Asset assignAssetToPublicCustomer(@ApiParam(value = ASSET_ID_PARAM_DESCRIPTION) @PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException {
checkParameter(ASSET_ID, strAssetId);
try {
AssetId assetId = new AssetId(toUUID(strAssetId));
Asset asset = checkAssetId(assetId, Operation.ASSIGN_TO_CUSTOMER);
Customer publicCustomer = customerService.findOrCreatePublicCustomer(asset.getTenantId());
Asset savedAsset = checkNotNull(assetService.assignAssetToCustomer(getTenantId(), assetId, publicCustomer.getId()));
logEntityAction(assetId, savedAsset,
savedAsset.getCustomerId(),
ActionType.ASSIGNED_TO_CUSTOMER, null, strAssetId, publicCustomer.getId().toString(), publicCustomer.getName());
return savedAsset;
} catch (Exception e) {
logEntityAction(emptyId(EntityType.ASSET), null,
null,
ActionType.ASSIGNED_TO_CUSTOMER, e, strAssetId);
throw handleException(e);
}
}
@ApiOperation(value = "Get Tenant Assets (getTenantAssets)",
notes = "Returns a page of assets owned by tenant. " +
PAGE_DATA_PARAMETERS + TENANT_AUTHORITY_PARAGRAPH, produces = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@RequestMapping(value = "/tenant/assets", params = {"pageSize", "page"}, method = RequestMethod.GET)
@ResponseBody
public PageData<Asset> getTenantAssets(
@ApiParam(value = PAGE_SIZE_DESCRIPTION)
@RequestParam int pageSize,
@ApiParam(value = PAGE_NUMBER_DESCRIPTION)
@RequestParam int page,
@ApiParam(value = ASSET_TYPE_DESCRIPTION)
@RequestParam(required = false) String type,
@ApiParam(value = ASSET_TEXT_SEARCH_DESCRIPTION)
@RequestParam(required = false) String textSearch,
@ApiParam(value = SORT_PROPERTY_DESCRIPTION, allowableValues = ASSET_SORT_PROPERTY_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortProperty,
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortOrder) throws ThingsboardException {
try {
TenantId tenantId = getCurrentUser().getTenantId();
PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
if (type != null && type.trim().length() > 0) {
return checkNotNull(assetService.findAssetsByTenantIdAndType(tenantId, type, pageLink));
} else {
return checkNotNull(assetService.findAssetsByTenantId(tenantId, pageLink));
}
} catch (Exception e) {
throw handleException(e);
}
}
@ApiOperation(value = "Get Tenant Asset Infos (getTenantAssetInfos)",
notes = "Returns a page of assets info objects owned by tenant. " +
PAGE_DATA_PARAMETERS + ASSET_INFO_DESCRIPTION + TENANT_AUTHORITY_PARAGRAPH, produces = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@RequestMapping(value = "/tenant/assetInfos", params = {"pageSize", "page"}, method = RequestMethod.GET)
@ResponseBody
public PageData<AssetInfo> getTenantAssetInfos(
@ApiParam(value = PAGE_SIZE_DESCRIPTION)
@RequestParam int pageSize,
@ApiParam(value = PAGE_NUMBER_DESCRIPTION)
@RequestParam int page,
@ApiParam(value = ASSET_TYPE_DESCRIPTION)
@RequestParam(required = false) String type,
@ApiParam(value = ASSET_TEXT_SEARCH_DESCRIPTION)
@RequestParam(required = false) String textSearch,
@ApiParam(value = SORT_PROPERTY_DESCRIPTION, allowableValues = ASSET_SORT_PROPERTY_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortProperty,
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortOrder) throws ThingsboardException {
try {
TenantId tenantId = getCurrentUser().getTenantId();
PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
if (type != null && type.trim().length() > 0) {
return checkNotNull(assetService.findAssetInfosByTenantIdAndType(tenantId, type, pageLink));
} else {
return checkNotNull(assetService.findAssetInfosByTenantId(tenantId, pageLink));
}
} catch (Exception e) {
throw handleException(e);
}
}
@ApiOperation(value = "Get Tenant Asset (getTenantAsset)",
notes = "Requested asset must be owned by tenant that the user belongs to. " +
"Asset name is an unique property of asset. So it can be used to identify the asset." + TENANT_AUTHORITY_PARAGRAPH, produces = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@RequestMapping(value = "/tenant/assets", params = {"assetName"}, method = RequestMethod.GET)
@ResponseBody
public Asset getTenantAsset(
@ApiParam(value = ASSET_NAME_DESCRIPTION)
@RequestParam String assetName) throws ThingsboardException {
try {
TenantId tenantId = getCurrentUser().getTenantId();
return checkNotNull(assetService.findAssetByTenantIdAndName(tenantId, assetName));
} catch (Exception e) {
throw handleException(e);
}
}
@ApiOperation(value = "Get Customer Assets (getCustomerAssets)",
notes = "Returns a page of assets objects assigned to customer. " +
PAGE_DATA_PARAMETERS, produces = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/customer/{customerId}/assets", params = {"pageSize", "page"}, method = RequestMethod.GET)
@ResponseBody
public PageData<Asset> getCustomerAssets(
@ApiParam(value = CUSTOMER_ID_PARAM_DESCRIPTION)
@PathVariable("customerId") String strCustomerId,
@ApiParam(value = PAGE_SIZE_DESCRIPTION)
@RequestParam int pageSize,
@ApiParam(value = PAGE_NUMBER_DESCRIPTION)
@RequestParam int page,
@ApiParam(value = ASSET_TYPE_DESCRIPTION)
@RequestParam(required = false) String type,
@ApiParam(value = ASSET_TEXT_SEARCH_DESCRIPTION)
@RequestParam(required = false) String textSearch,
@ApiParam(value = SORT_PROPERTY_DESCRIPTION, allowableValues = ASSET_SORT_PROPERTY_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortProperty,
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortOrder) throws ThingsboardException {
checkParameter("customerId", strCustomerId);
try {
TenantId tenantId = getCurrentUser().getTenantId();
CustomerId customerId = new CustomerId(toUUID(strCustomerId));
checkCustomerId(customerId, Operation.READ);
PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
if (type != null && type.trim().length() > 0) {
return checkNotNull(assetService.findAssetsByTenantIdAndCustomerIdAndType(tenantId, customerId, type, pageLink));
} else {
return checkNotNull(assetService.findAssetsByTenantIdAndCustomerId(tenantId, customerId, pageLink));
}
} catch (Exception e) {
throw handleException(e);
}
}
@ApiOperation(value = "Get Customer Asset Infos (getCustomerAssetInfos)",
notes = "Returns a page of assets info objects assigned to customer. " +
PAGE_DATA_PARAMETERS + ASSET_INFO_DESCRIPTION, produces = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/customer/{customerId}/assetInfos", params = {"pageSize", "page"}, method = RequestMethod.GET)
@ResponseBody
public PageData<AssetInfo> getCustomerAssetInfos(
@ApiParam(value = CUSTOMER_ID_PARAM_DESCRIPTION)
@PathVariable("customerId") String strCustomerId,
@ApiParam(value = PAGE_SIZE_DESCRIPTION)
@RequestParam int pageSize,
@ApiParam(value = PAGE_NUMBER_DESCRIPTION)
@RequestParam int page,
@ApiParam(value = ASSET_TYPE_DESCRIPTION)
@RequestParam(required = false) String type,
@ApiParam(value = ASSET_TEXT_SEARCH_DESCRIPTION)
@RequestParam(required = false) String textSearch,
@ApiParam(value = SORT_PROPERTY_DESCRIPTION, allowableValues = ASSET_SORT_PROPERTY_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortProperty,
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortOrder) throws ThingsboardException {
checkParameter("customerId", strCustomerId);
try {
TenantId tenantId = getCurrentUser().getTenantId();
CustomerId customerId = new CustomerId(toUUID(strCustomerId));
checkCustomerId(customerId, Operation.READ);
PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
if (type != null && type.trim().length() > 0) {
return checkNotNull(assetService.findAssetInfosByTenantIdAndCustomerIdAndType(tenantId, customerId, type, pageLink));
} else {
return checkNotNull(assetService.findAssetInfosByTenantIdAndCustomerId(tenantId, customerId, pageLink));
}
} catch (Exception e) {
throw handleException(e);
}
}
@ApiOperation(value = "Get Assets By Ids (getAssetsByIds)",
notes = "Requested assets must be owned by tenant or assigned to customer which user is performing the request. ", produces = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/assets", params = {"assetIds"}, method = RequestMethod.GET)
@ResponseBody
public List<Asset> getAssetsByIds(
@ApiParam(value = "A list of assets ids, separated by comma ','")
@RequestParam("assetIds") String[] strAssetIds) throws ThingsboardException {
checkArrayParameter("assetIds", strAssetIds);
try {
SecurityUser user = getCurrentUser();
TenantId tenantId = user.getTenantId();
CustomerId customerId = user.getCustomerId();
List<AssetId> assetIds = new ArrayList<>();
for (String strAssetId : strAssetIds) {
assetIds.add(new AssetId(toUUID(strAssetId)));
}
ListenableFuture<List<Asset>> assets;
if (customerId == null || customerId.isNullUid()) {
assets = assetService.findAssetsByTenantIdAndIdsAsync(tenantId, assetIds);
} else {
assets = assetService.findAssetsByTenantIdCustomerIdAndIdsAsync(tenantId, customerId, assetIds);
}
return checkNotNull(assets.get());
} catch (Exception e) {
throw handleException(e);
}
}
@ApiOperation(value = "Find related assets (findByQuery)",
notes = "Returns all assets that are related to the specific entity. " +
"The entity id, relation type, asset types, depth of the search, and other query parameters defined using complex 'AssetSearchQuery' object. " +
"See 'Model' tab of the Parameters for more info.", produces = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/assets", method = RequestMethod.POST)
@ResponseBody
public List<Asset> findByQuery(@RequestBody AssetSearchQuery query) throws ThingsboardException {
checkNotNull(query);
checkNotNull(query.getParameters());
checkNotNull(query.getAssetTypes());
checkEntityId(query.getParameters().getEntityId(), Operation.READ);
try {
List<Asset> assets = checkNotNull(assetService.findAssetsByQuery(getTenantId(), query).get());
assets = assets.stream().filter(asset -> {
try {
accessControlService.checkPermission(getCurrentUser(), Resource.ASSET, Operation.READ, asset.getId(), asset);
return true;
} catch (ThingsboardException e) {
return false;
}
}).collect(Collectors.toList());
return assets;
} catch (Exception e) {
throw handleException(e);
}
}
@ApiOperation(value = "Get Asset Types (getAssetTypes)",
notes = "Returns a set of unique asset types based on assets that are either owned by the tenant or assigned to the customer which user is performing the request.", produces = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/asset/types", method = RequestMethod.GET)
@ResponseBody
public List<EntitySubtype> getAssetTypes() throws ThingsboardException {
try {
SecurityUser user = getCurrentUser();
TenantId tenantId = user.getTenantId();
ListenableFuture<List<EntitySubtype>> assetTypes = assetService.findAssetTypesByTenantId(tenantId);
return checkNotNull(assetTypes.get());
} catch (Exception e) {
throw handleException(e);
}
}
@ApiOperation(value = "Assign asset to edge (assignAssetToEdge)",
notes = "Creates assignment of an existing asset to an instance of The Edge. " +
EDGE_ASSIGN_ASYNC_FIRST_STEP_DESCRIPTION +
"Second, remote edge service will receive a copy of assignment asset " +
EDGE_ASSIGN_RECEIVE_STEP_DESCRIPTION + ". " +
"Third, once asset will be delivered to edge service, it's going to be available for usage on remote edge instance.",
produces = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@RequestMapping(value = "/edge/{edgeId}/asset/{assetId}", method = RequestMethod.POST)
@ResponseBody
public Asset assignAssetToEdge(@ApiParam(value = EDGE_ID_PARAM_DESCRIPTION) @PathVariable(EDGE_ID) String strEdgeId,
@ApiParam(value = ASSET_ID_PARAM_DESCRIPTION) @PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException {
checkParameter(EDGE_ID, strEdgeId);
checkParameter(ASSET_ID, strAssetId);
try {
EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
Edge edge = checkEdgeId(edgeId, Operation.READ);
AssetId assetId = new AssetId(toUUID(strAssetId));
checkAssetId(assetId, Operation.READ);
Asset savedAsset = checkNotNull(assetService.assignAssetToEdge(getTenantId(), assetId, edgeId));
logEntityAction(assetId, savedAsset,
savedAsset.getCustomerId(),
ActionType.ASSIGNED_TO_EDGE, null, strAssetId, strEdgeId, edge.getName());
sendEntityAssignToEdgeNotificationMsg(getTenantId(), edgeId, savedAsset.getId(), EdgeEventActionType.ASSIGNED_TO_EDGE);
return savedAsset;
} catch (Exception e) {
logEntityAction(emptyId(EntityType.ASSET), null,
null,
ActionType.ASSIGNED_TO_EDGE, e, strAssetId, strEdgeId);
throw handleException(e);
}
}
@ApiOperation(value = "Unassign asset from edge (unassignAssetFromEdge)",
notes = "Clears assignment of the asset to the edge. " +
EDGE_UNASSIGN_ASYNC_FIRST_STEP_DESCRIPTION +
"Second, remote edge service will receive an 'unassign' command to remove asset " +
EDGE_UNASSIGN_RECEIVE_STEP_DESCRIPTION + ". " +
"Third, once 'unassign' command will be delivered to edge service, it's going to remove asset locally.",
produces = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@RequestMapping(value = "/edge/{edgeId}/asset/{assetId}", method = RequestMethod.DELETE)
@ResponseBody
public Asset unassignAssetFromEdge(@ApiParam(value = EDGE_ID_PARAM_DESCRIPTION) @PathVariable(EDGE_ID) String strEdgeId,
@ApiParam(value = ASSET_ID_PARAM_DESCRIPTION) @PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException {
checkParameter(EDGE_ID, strEdgeId);
checkParameter(ASSET_ID, strAssetId);
try {
EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
Edge edge = checkEdgeId(edgeId, Operation.READ);
AssetId assetId = new AssetId(toUUID(strAssetId));
Asset asset = checkAssetId(assetId, Operation.READ);
Asset savedAsset = checkNotNull(assetService.unassignAssetFromEdge(getTenantId(), assetId, edgeId));
logEntityAction(assetId, asset,
asset.getCustomerId(),
ActionType.UNASSIGNED_FROM_EDGE, null, strAssetId, strEdgeId, edge.getName());
sendEntityAssignToEdgeNotificationMsg(getTenantId(), edgeId, savedAsset.getId(), EdgeEventActionType.UNASSIGNED_FROM_EDGE);
return savedAsset;
} catch (Exception e) {
logEntityAction(emptyId(EntityType.ASSET), null,
null,
ActionType.UNASSIGNED_FROM_EDGE, e, strAssetId, strEdgeId);
throw handleException(e);
}
}
@ApiOperation(value = "Get assets assigned to edge (getEdgeAssets)",
notes = "Returns a page of assets assigned to edge. " +
PAGE_DATA_PARAMETERS, produces = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/edge/{edgeId}/assets", params = {"pageSize", "page"}, method = RequestMethod.GET)
@ResponseBody
public PageData<Asset> getEdgeAssets(
@ApiParam(value = EDGE_ID_PARAM_DESCRIPTION)
@PathVariable(EDGE_ID) String strEdgeId,
@ApiParam(value = PAGE_SIZE_DESCRIPTION)
@RequestParam int pageSize,
@ApiParam(value = PAGE_NUMBER_DESCRIPTION)
@RequestParam int page,
@ApiParam(value = ASSET_TYPE_DESCRIPTION)
@RequestParam(required = false) String type,
@ApiParam(value = ASSET_TEXT_SEARCH_DESCRIPTION)
@RequestParam(required = false) String textSearch,
@ApiParam(value = SORT_PROPERTY_DESCRIPTION, allowableValues = ASSET_SORT_PROPERTY_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortProperty,
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortOrder,
@ApiParam(value = "Timestamp. Assets with creation time before it won't be queried")
@RequestParam(required = false) Long startTime,
@ApiParam(value = "Timestamp. Assets with creation time after it won't be queried")
@RequestParam(required = false) Long endTime) throws ThingsboardException {
checkParameter(EDGE_ID, strEdgeId);
try {
TenantId tenantId = getCurrentUser().getTenantId();
EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
checkEdgeId(edgeId, Operation.READ);
TimePageLink pageLink = createTimePageLink(pageSize, page, textSearch, sortProperty, sortOrder, startTime, endTime);
PageData<Asset> nonFilteredResult;
if (type != null && type.trim().length() > 0) {
nonFilteredResult = assetService.findAssetsByTenantIdAndEdgeIdAndType(tenantId, edgeId, type, pageLink);
} else {
nonFilteredResult = assetService.findAssetsByTenantIdAndEdgeId(tenantId, edgeId, pageLink);
}
List<Asset> filteredAssets = nonFilteredResult.getData().stream().filter(asset -> {
try {
accessControlService.checkPermission(getCurrentUser(), Resource.ASSET, Operation.READ, asset.getId(), asset);
return true;
} catch (ThingsboardException e) {
return false;
}
}).collect(Collectors.toList());
PageData<Asset> filteredResult = new PageData<>(filteredAssets,
nonFilteredResult.getTotalPages(),
nonFilteredResult.getTotalElements(),
nonFilteredResult.hasNext());
return checkNotNull(filteredResult);
} catch (Exception e) {
throw handleException(e);
}
}
@ApiOperation(value = "Import the bulk of assets (processAssetsBulkImport)",
notes = "There's an ability to import the bulk of assets using the only .csv file.", produces = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN')")
@PostMapping("/asset/bulk_import")
public BulkImportResult<Asset> processAssetsBulkImport(@RequestBody BulkImportRequest request) throws Exception {
SecurityUser user = getCurrentUser();
return assetBulkImportService.processBulkImport(request, user, importedAssetInfo -> {
onAssetCreatedOrUpdated(importedAssetInfo.getEntity(), importedAssetInfo.isUpdated(), user);
});
}
}
|
package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
public class AlipayOpenAppServiceSchemaQueryModel
extends AlipayObject {
private static final long serialVersionUID = 6862586748722949163L;
@ApiField("category_id")
private String categoryId;
public String getCategoryId() {
return this.categoryId;
}
public void setCategoryId(String categoryId) {
this.categoryId = categoryId;
}
}
|
package pl.beda.springcourse_knightsgame.domain;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class KnightTest {
@Test
public void testIfQuestMarkedAsStarted() {
Knight knight = new Knight("Percival", 25);
Quest quest = new Quest(1, "Testowe zdanie");
knight.setQuest(quest);
assertTrue(knight.getQuest().isStarted());
}
}
|
/**
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig 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.openregistry.core.web;
import org.openregistry.core.domain.Name;
import org.openregistry.core.domain.Person;
import org.openregistry.core.service.MutableSearchCriteriaImpl;
import org.openregistry.core.service.PersonService;
import org.openregistry.core.service.reconciliation.PersonMatch;
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.RequestParam;
import javax.inject.Inject;
import java.io.IOException;
import java.io.Writer;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @version $Revision: 20336 $ $Date: 2010-03-23 14:16:10 -0700 (Tue, 23 Mar 2010) $
* @since 0.1-M1
*/
@Controller
public final class AjaxController {
@Inject
private PersonService personService;
@RequestMapping(value="/nameSearch.json", method = RequestMethod.GET)
public void nameSearch(@RequestParam("term") final String term, final Writer writer) throws IOException {
final MutableSearchCriteriaImpl searchCriteria = new MutableSearchCriteriaImpl();
searchCriteria.setName(term);
final Set<String> names = new HashSet<String>();
final List<PersonMatch> personMatches = this.personService.searchForPersonBy(searchCriteria);
for (final PersonMatch personMatch : personMatches) {
final Person person = personMatch.getPerson();
final Name name = person.getOfficialName();
names.add(name.getGiven() + " " + name.getFamily());
}
final StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("[");
boolean pastFirst = false;
for (final String name : names) {
if (pastFirst) {
stringBuilder.append(",");
}
pastFirst = true;
stringBuilder.append("\"");
stringBuilder.append(name);
stringBuilder.append("\"");
}
stringBuilder.append("]");
writer.write(stringBuilder.toString());
}
}
|
package com.zwf3lbs.stream;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.common.MapBuilder;
import com.facebook.react.uimanager.SimpleViewManager;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.annotations.ReactProp;
import java.util.Map;
import javax.annotation.Nullable;
public class StreamPlayerManager extends SimpleViewManager<ZWOpenGLView> {
private static final String REACT_CLASS = "ZWVideoView";//组件名称
private static final int COMMAND_PLAY_ID = 1;
private static final int COMMAND_STOP_ID = 2;
private static final int COMMAND_CAPTURE_ID = 3;
private static final String COMMAND_PLAY_NAME = "play";
private static final String COMMAND_STOP_NAME = "stop";
private static final String COMMAND_CAPTURE_NAME = "capture";
/**
设置引用名
*/
@Override
public String getName() {
return REACT_CLASS;
}
/**
创建ui组件实例
*/
protected ZWOpenGLView createViewInstance(ThemedReactContext reactContext) {
ZWOpenGLView openGLView = new ZWOpenGLView(reactContext);
System.out.println("ZWOpenGLView created.");
return openGLView;
}
/**
获取音视频uri
*/
@ReactProp(name="socketUrl")
public void setSocketUrl(ZWOpenGLView openGLView, String socketUrl){
System.out.println("socketUrl " + socketUrl);
openGLView.setSockUrl(socketUrl);
}
private void initPlayer(ZWOpenGLView openGLView) {
ZWStreamPlayer player = openGLView.getPlayer();
if (player != null) {
return;
}
player = new ZWStreamPlayer(openGLView,8000);
player.setZwContext((ThemedReactContext) openGLView.getContext());
player.initPlayer();
System.out.println("player: " + player);
}
/**
打开关闭音视频
*/
@ReactProp(name="ifOpenVideo")
public void setIfOpenVideo(ZWOpenGLView openGLView, Boolean ifOpenVideo){
if (ifOpenVideo) {
initPlayer(openGLView);
play(openGLView);
return;
}
stop(openGLView);
}
/**
打开关闭音频
*/
@ReactProp(name="ifOpenAudio")
public void setIfOpenAudio(ZWOpenGLView openGLView, Boolean ifOpenAudio){
if (ifOpenAudio) {
playAudio(openGLView);
return;
}
stopAudio(openGLView);
}
@Override
public @Nullable Map<String, Integer> getCommandsMap() {
return MapBuilder.of(
COMMAND_PLAY_NAME, COMMAND_PLAY_ID,
COMMAND_STOP_NAME, COMMAND_STOP_ID,
COMMAND_CAPTURE_NAME, COMMAND_CAPTURE_ID
);
}
@Override
public void receiveCommand(ZWOpenGLView root, int commandId, @Nullable ReadableArray args) {
switch (commandId) {
case COMMAND_PLAY_ID:
play(root);
break;
case COMMAND_STOP_ID:
stop(root);
break;
case COMMAND_CAPTURE_ID:
capture(root);
break;
default:
break;
}
}
private void play(ZWOpenGLView openGLView) {
ZWStreamPlayer player = openGLView.getPlayer();
if (player == null) {
return;
}
player.play();
}
private void stop(ZWOpenGLView openGLView) {
ZWStreamPlayer player = openGLView.getPlayer();
if (player == null) {
return;
}
player.stop();
}
private void playAudio(ZWOpenGLView openGLView) {
ZWStreamPlayer player = openGLView.getPlayer();
if (player == null) {
return;
}
player.playAudio();
}
private void stopAudio(ZWOpenGLView openGLView) {
ZWStreamPlayer player = openGLView.getPlayer();
if (player == null) {
return;
}
player.stopAudio();
}
private void capture(ZWOpenGLView openGLView) {
openGLView.capture();
}
}
|
/*
* Copyright 2016-2017 Crown Copyright
*
* 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 uk.gov.gchq.gaffer.rest;
import uk.gov.gchq.gaffer.rest.factory.UnknownUserFactory;
public class UserFactoryForTest extends UnknownUserFactory {
}
|
/**
* This code was auto-generated by a Codezu.
*
* Changes to this file may cause incorrect behavior and will be lost if
* the code is regenerated.
*/
package com.mozu.api.clients.commerce.catalog.storefront;
import java.util.List;
import java.util.ArrayList;
import com.mozu.api.MozuClient;
import com.mozu.api.MozuClientFactory;
import com.mozu.api.MozuUrl;
import com.mozu.api.Headers;
import com.mozu.api.AsyncCallback;
import com.mozu.api.security.AuthTicket;
import org.apache.commons.lang.StringUtils;
import java.util.concurrent.CountDownLatch;
/** <summary>
* Use the Storefront Categories resource to view the product category hierarchy as it appears to shoppers who are browsing the storefront. The hierarchy can be returned as a flat list or as a category tree.
* </summary>
*/
public class CategoryClient {
/**
* Retrieves a list of categories according to any specified filter criteria and sort options.
* <p><pre><code>
* MozuClient<com.mozu.api.contracts.productruntime.CategoryPagedCollection> mozuClient=GetCategoriesClient();
* client.setBaseAddress(url);
* client.executeRequest();
* CategoryPagedCollection categoryPagedCollection = client.Result();
* </code></pre></p>
* @return Mozu.Api.MozuClient <com.mozu.api.contracts.productruntime.CategoryPagedCollection>
* @see com.mozu.api.contracts.productruntime.CategoryPagedCollection
*/
public static MozuClient<com.mozu.api.contracts.productruntime.CategoryPagedCollection> getCategoriesClient() throws Exception
{
return getCategoriesClient( null, null, null, null, null);
}
/**
* Retrieves a list of categories according to any specified filter criteria and sort options.
* <p><pre><code>
* MozuClient<com.mozu.api.contracts.productruntime.CategoryPagedCollection> mozuClient=GetCategoriesClient( filter, startIndex, pageSize, sortBy, responseFields);
* client.setBaseAddress(url);
* client.executeRequest();
* CategoryPagedCollection categoryPagedCollection = client.Result();
* </code></pre></p>
* @param filter A set of filter expressions representing the search parameters for a query: eq=equals, ne=not equals, gt=greater than, lt = less than or equals, gt = greater than or equals, lt = less than or equals, sw = starts with, or cont = contains. Optional.
* @param pageSize The number of results to display on each page when creating paged results from a query. The maximum value is 200.
* @param responseFields A list or array of fields returned for a call. These fields may be customized and may be used for various types of data calls in Mozu. For example, responseFields are returned for retrieving or updating attributes, carts, and messages in Mozu.
* @param sortBy
* @param startIndex
* @return Mozu.Api.MozuClient <com.mozu.api.contracts.productruntime.CategoryPagedCollection>
* @see com.mozu.api.contracts.productruntime.CategoryPagedCollection
*/
public static MozuClient<com.mozu.api.contracts.productruntime.CategoryPagedCollection> getCategoriesClient(String filter, Integer startIndex, Integer pageSize, String sortBy, String responseFields) throws Exception
{
MozuUrl url = com.mozu.api.urls.commerce.catalog.storefront.CategoryUrl.getCategoriesUrl(filter, pageSize, responseFields, sortBy, startIndex);
String verb = "GET";
Class<?> clz = com.mozu.api.contracts.productruntime.CategoryPagedCollection.class;
MozuClient<com.mozu.api.contracts.productruntime.CategoryPagedCollection> mozuClient = (MozuClient<com.mozu.api.contracts.productruntime.CategoryPagedCollection>) MozuClientFactory.getInstance(clz);
mozuClient.setVerb(verb);
mozuClient.setResourceUrl(url);
return mozuClient;
}
/**
* Retrieves the details of a single category.
* <p><pre><code>
* MozuClient<com.mozu.api.contracts.productruntime.Category> mozuClient=GetCategoryClient( categoryId);
* client.setBaseAddress(url);
* client.executeRequest();
* Category category = client.Result();
* </code></pre></p>
* @param categoryId Unique identifier for the storefront container used to organize products.
* @return Mozu.Api.MozuClient <com.mozu.api.contracts.productruntime.Category>
* @see com.mozu.api.contracts.productruntime.Category
*/
public static MozuClient<com.mozu.api.contracts.productruntime.Category> getCategoryClient(Integer categoryId) throws Exception
{
return getCategoryClient( categoryId, null, null);
}
/**
* Retrieves the details of a single category.
* <p><pre><code>
* MozuClient<com.mozu.api.contracts.productruntime.Category> mozuClient=GetCategoryClient( categoryId, allowInactive, responseFields);
* client.setBaseAddress(url);
* client.executeRequest();
* Category category = client.Result();
* </code></pre></p>
* @param allowInactive If true, allow inactive categories to be retrieved in the category list response. If false, the categories retrieved will not include ones marked inactive.
* @param categoryId Unique identifier for the storefront container used to organize products.
* @param responseFields A list or array of fields returned for a call. These fields may be customized and may be used for various types of data calls in Mozu. For example, responseFields are returned for retrieving or updating attributes, carts, and messages in Mozu.
* @return Mozu.Api.MozuClient <com.mozu.api.contracts.productruntime.Category>
* @see com.mozu.api.contracts.productruntime.Category
*/
public static MozuClient<com.mozu.api.contracts.productruntime.Category> getCategoryClient(Integer categoryId, Boolean allowInactive, String responseFields) throws Exception
{
MozuUrl url = com.mozu.api.urls.commerce.catalog.storefront.CategoryUrl.getCategoryUrl(allowInactive, categoryId, responseFields);
String verb = "GET";
Class<?> clz = com.mozu.api.contracts.productruntime.Category.class;
MozuClient<com.mozu.api.contracts.productruntime.Category> mozuClient = (MozuClient<com.mozu.api.contracts.productruntime.Category>) MozuClientFactory.getInstance(clz);
mozuClient.setVerb(verb);
mozuClient.setResourceUrl(url);
return mozuClient;
}
/**
* Retrieves the list of product categories that appear on the storefront organized in a hierarchical format. Hidden categories do not appear in the list.
* <p><pre><code>
* MozuClient<com.mozu.api.contracts.productruntime.CategoryCollection> mozuClient=GetCategoryTreeClient();
* client.setBaseAddress(url);
* client.executeRequest();
* CategoryCollection categoryCollection = client.Result();
* </code></pre></p>
* @return Mozu.Api.MozuClient <com.mozu.api.contracts.productruntime.CategoryCollection>
* @see com.mozu.api.contracts.productruntime.CategoryCollection
*/
public static MozuClient<com.mozu.api.contracts.productruntime.CategoryCollection> getCategoryTreeClient() throws Exception
{
return getCategoryTreeClient( null);
}
/**
* Retrieves the list of product categories that appear on the storefront organized in a hierarchical format. Hidden categories do not appear in the list.
* <p><pre><code>
* MozuClient<com.mozu.api.contracts.productruntime.CategoryCollection> mozuClient=GetCategoryTreeClient( responseFields);
* client.setBaseAddress(url);
* client.executeRequest();
* CategoryCollection categoryCollection = client.Result();
* </code></pre></p>
* @param responseFields A list or array of fields returned for a call. These fields may be customized and may be used for various types of data calls in Mozu. For example, responseFields are returned for retrieving or updating attributes, carts, and messages in Mozu.
* @return Mozu.Api.MozuClient <com.mozu.api.contracts.productruntime.CategoryCollection>
* @see com.mozu.api.contracts.productruntime.CategoryCollection
*/
public static MozuClient<com.mozu.api.contracts.productruntime.CategoryCollection> getCategoryTreeClient(String responseFields) throws Exception
{
MozuUrl url = com.mozu.api.urls.commerce.catalog.storefront.CategoryUrl.getCategoryTreeUrl(responseFields);
String verb = "GET";
Class<?> clz = com.mozu.api.contracts.productruntime.CategoryCollection.class;
MozuClient<com.mozu.api.contracts.productruntime.CategoryCollection> mozuClient = (MozuClient<com.mozu.api.contracts.productruntime.CategoryCollection>) MozuClientFactory.getInstance(clz);
mozuClient.setVerb(verb);
mozuClient.setResourceUrl(url);
return mozuClient;
}
}
|
package usersdatabase.models;
/**
* @author Evgeny Khodzitskiy (evgeny.hodz@gmail.com)
* @since 07.07.2017
*/
public class Role {
/**
* To avoid magic number mistake.
*/
private static final int THIRTYONE = 31;
/**
* Role id.
*/
private int id;
/**
* Role name.
*/
private String name;
/**
* Constructor.
*
* @param roleId role id.
* @param roleName role name.
*/
public Role(int roleId, String roleName) {
this.id = roleId;
this.name = roleName;
}
/**
* Getter.
*
* @return id.
*/
public int getId() {
return id;
}
/**
* Getter.
*
* @return role name.
*/
public String getName() {
return name;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Role role = (Role) o;
return id == role.id && (name != null && name.equals(role.name)
|| name == null && role.name == null);
}
@Override
public int hashCode() {
int result = id;
if (name != null) {
result = THIRTYONE * result + name.hashCode();
} else {
result = THIRTYONE * result;
}
return result;
}
}
|
package OOFramework.Collision2D.Colliders;
import OOFramework.Collision2D.CollisionCallback;
import OOFramework.Collision2D.CollisionSystem;
import OOFramework.Collision2D.Enums.ColliderTag;
import OOFramework.Collision2D.Enums.ColliderType;
import OOFramework.Maths.Vector2;
import OOFramework.Modules.ASSERT_MSG;
import OOFramework.Modules.Callback;
public abstract class Collider2D {
public Callback preCollisionCallback;
public CollisionCallback collisionCallback;
protected Object ownerObject = null;
protected ColliderTag colliderTag = ColliderTag.DEFAULT;
protected ColliderType colliderType;
protected boolean isColliding;
protected Vector2 pos;
protected Collider2D() {
CollisionSystem.getInstance().setShouldAddToColliders(true);
CollisionSystem.getInstance().getCollidersToBeAdded().add(this);
}
//check for collision
public boolean Collide(ColliderType collideWith, Collider2D other) {
return false;
}
//collisionChecks
protected boolean CircleCollision(CircleCollider other) {
ASSERT_MSG.ASSERT_MSG(true, "the collision checks should not call the parent class");
return false;
}
protected boolean BoxCollision(BoxCollider other) {
ASSERT_MSG.ASSERT_MSG(true, "the collision checks should not call the parent class");
return false;
}
protected boolean RayIntersection(Object other) {
ASSERT_MSG.ASSERT_MSG(true, "the collision checks should not call the parent class");
return false;
}
public boolean ContainsPoint(Vector2 point) {
ASSERT_MSG.ASSERT_MSG(true, "the collision checks should not call the parent class");
return false;
}
/////////////////
public void OnDestroy() {
CollisionSystem.getInstance().setShouldRemoveFromColliders(true);
CollisionSystem.getInstance().getCollidersToBeRemoved().add(this);
}
public void PreCollisons() {
}
public void UpdateCollisons(Collider2D other) {
}
public Object getOwnerObject() {
return ownerObject;
}
public void setOwnerObject(Object ownerObject) {
this.ownerObject = ownerObject;
}
public ColliderType getColliderType() {
return colliderType;
}
public CollisionCallback getCollisionCallback() {
return collisionCallback;
}
public Callback getPreCollisionCallback() {
return preCollisionCallback;
}
public boolean getIsColliding() {
return isColliding;
}
public void setIsColliding(boolean isColl) {
this.isColliding = isColl;
}
public ColliderTag getColliderTag() {
return colliderTag;
}
public void setColliderTag(ColliderTag colliderTag) {
this.colliderTag = colliderTag;
}
public Vector2 getPos() {
return pos;
}
public void setPos(Vector2 pos) {
this.pos = pos;
}
}
|
/**
*
*/
package com.tangdao.scheduler.web.controller;
/**
* <p>
* TODO 描述
* </p>
*
* @author ruyang
* @since 2021年4月13日
*/
public class SchedulerJobLogController {
}
|
/**
* 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.ozone.security.acl;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.ozone.OzoneConsts;
import org.apache.hadoop.ozone.om.exceptions.OMException;
import java.util.BitSet;
/**
* Public API for Ozone ACLs. Security providers providing support for Ozone
* ACLs should implement this.
*/
@InterfaceAudience.LimitedPrivate({"HDFS", "Yarn", "Ranger", "Hive", "HBase"})
@InterfaceStability.Evolving
public interface IAccessAuthorizer {
/**
* Check access for given ozoneObject.
*
* @param ozoneObject object for which access needs to be checked.
* @param context Context object encapsulating all user related information.
* @throws org.apache.hadoop.ozone.om.exceptions.OMException
* @return true if user has access else false.
*/
boolean checkAccess(IOzoneObj ozoneObject, RequestContext context)
throws OMException;
/**
* ACL rights.
*/
enum ACLType {
READ,
WRITE,
CREATE,
LIST,
DELETE,
READ_ACL,
WRITE_ACL,
ALL,
NONE;
private static int length = ACLType.values().length;
public static int getNoOfAcls() {
return length;
}
/**
* Returns the ACL rights based on passed in String.
*
* @param type ACL right string
* @return ACLType
*/
public static ACLType getACLRight(String type) {
if (type == null || type.isEmpty()) {
throw new IllegalArgumentException("ACL right cannot be empty");
}
switch (type) {
case OzoneConsts.OZONE_ACL_READ:
return ACLType.READ;
case OzoneConsts.OZONE_ACL_WRITE:
return ACLType.WRITE;
case OzoneConsts.OZONE_ACL_CREATE:
return ACLType.CREATE;
case OzoneConsts.OZONE_ACL_DELETE:
return ACLType.DELETE;
case OzoneConsts.OZONE_ACL_LIST:
return ACLType.LIST;
case OzoneConsts.OZONE_ACL_READ_ACL:
return ACLType.READ_ACL;
case OzoneConsts.OZONE_ACL_WRITE_ACL:
return ACLType.WRITE_ACL;
case OzoneConsts.OZONE_ACL_ALL:
return ACLType.ALL;
case OzoneConsts.OZONE_ACL_NONE:
return ACLType.NONE;
default:
throw new IllegalArgumentException("[" + type + "] ACL right is not " +
"recognized");
}
}
/**
* Returns String representation of ACL rights.
*
* @param acls ACLType
* @return String representation of acl
*/
public static String getACLString(BitSet acls) {
StringBuffer sb = new StringBuffer();
acls.stream().forEach(acl -> {
sb.append(getAclString(ACLType.values()[acl]));
});
return sb.toString();
}
public static String getAclString(ACLType acl) {
switch (acl) {
case READ:
return OzoneConsts.OZONE_ACL_READ;
case WRITE:
return OzoneConsts.OZONE_ACL_WRITE;
case CREATE:
return OzoneConsts.OZONE_ACL_CREATE;
case DELETE:
return OzoneConsts.OZONE_ACL_DELETE;
case LIST:
return OzoneConsts.OZONE_ACL_LIST;
case READ_ACL:
return OzoneConsts.OZONE_ACL_READ_ACL;
case WRITE_ACL:
return OzoneConsts.OZONE_ACL_WRITE_ACL;
case ALL:
return OzoneConsts.OZONE_ACL_ALL;
case NONE:
return OzoneConsts.OZONE_ACL_NONE;
default:
throw new IllegalArgumentException("ACL right is not recognized");
}
}
}
/**
* Type of acl identity.
*/
enum ACLIdentityType {
USER(OzoneConsts.OZONE_ACL_USER_TYPE),
GROUP(OzoneConsts.OZONE_ACL_GROUP_TYPE),
CLIENT_IP(OzoneConsts.OZONE_ACL_IP_TYPE),
WORLD(OzoneConsts.OZONE_ACL_WORLD_TYPE),
ANONYMOUS(OzoneConsts.OZONE_ACL_ANONYMOUS_TYPE);
@Override
public String toString() {
return value;
}
/**
* String value for this Enum.
*/
private final String value;
/**
* Init OzoneACLtypes enum.
*
* @param val String type for this enum.
*/
ACLIdentityType(String val) {
value = val;
}
}
}
|
package io.testoftiramisu.spring.aop;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AroundLoggingModule implements MethodInterceptor {
private static final Logger log = LoggerFactory.getLogger(AroundLoggingModule.class);
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
Object result = null;
if (log.isDebugEnabled()) {
log.debug("@@@(AROUND-BEFORE) Method called: " + invocation.getMethod().getName());
}
if (invocation.getArguments().length == 0) {
log.debug("@@@(AROUND-BEFORE) No arguments passed.");
}
for (Object arg : invocation.getArguments()) {
log.debug("@@@(AROUND-BEFORE) Argument passed: " + arg);
}
try {
if (log.isDebugEnabled()) {
log.debug("@@@(AROUND) Processing...");
}
result = invocation.proceed();
if (log.isDebugEnabled()) {
log.debug("@@@(AROUND-AFTER) Result: " + result);
}
return result;
} catch (IllegalArgumentException ex) {
log.error("@@@(AROUND) Throws an exception: " + ex.getMessage());
throw ex;
}
}
}
|
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.webkit;
import androidx.annotation.NonNull;
import org.junit.Assert;
import java.util.concurrent.Callable;
/**
* A class for checking a specific statement {@link #check()} through polling, either until the
* statement is true, or until timing out.
*
* This should remain functionally equivalent to
* com.android.compatibility.common.util.PollingCheck. Modifications to this class should be
* reflected in that class as necessary. See http://go/modifying-webview-cts.
*/
public abstract class PollingCheck {
private static final long TIME_SLICE = 50;
private long mTimeout;
public PollingCheck(long timeout) {
mTimeout = timeout;
}
protected abstract boolean check();
public void run() {
if (check()) {
return;
}
long timeout = mTimeout;
while (timeout > 0) {
try {
Thread.sleep(TIME_SLICE);
} catch (InterruptedException e) {
Assert.fail("unexpected InterruptedException");
}
if (check()) {
return;
}
timeout -= TIME_SLICE;
}
Assert.fail("unexpected timeout");
}
public static void check(@NonNull CharSequence message, long timeout,
@NonNull Callable<Boolean> condition)
throws Exception {
while (timeout > 0) {
if (condition.call()) {
return;
}
Thread.sleep(TIME_SLICE);
timeout -= TIME_SLICE;
}
Assert.fail(message.toString());
}
}
|
package com.xcvgsystems.hypergiant.thinkers;
import java.util.EnumSet;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.xcvgsystems.hypergiant.managers.SoundManager;
import com.xcvgsystems.hypergiant.managers.StateManager;
import com.xcvgsystems.hypergiant.managers.TextureManager;
import com.xcvgsystems.hypergiant.scenes.ScrollScene;
public class TreeBranch extends ActorThinker {
final protected ScrollScene CONTEXT;
final String GRAPHIC_NAME = "Branch";
final int RADIUS = 32;
final int DRAW_WIDTH = 96;
final int DRAW_HEIGHT = 96;
Sprite currentSprite;
boolean alreadyHit = false;
public TreeBranch(int x, int y, ScrollScene context) {
CONTEXT = context;
this.x = x;
this.y = y;
this.facing = 0;
this.solid = true;
flags = EnumSet.of(ActorFlag.NOGRAVITY, ActorFlag.HURTSPLAYER);
currentSprite = new Sprite(TextureManager.get(GRAPHIC_NAME+"A0"));
velocityX = (CONTEXT.getSCROLL_RATE()) * -1;
}
@Override
public void tick() {
x += velocityX;
y += velocityY;
//draw sprite
currentSprite.setSize(DRAW_WIDTH, DRAW_HEIGHT);
currentSprite.setCenter(x, y);
CONTEXT.drawSprite(currentSprite, 1);
}
@Override
public void hit(Thinker other) {
if(!alreadyHit && other instanceof PlayerPawn)
{
//damage player, play sound, make this not solid
StateManager.getPlayer().changeHP(-1);
SoundManager.play("GENHIT");
//this.solid = false;
//if player is moving, slow them down!
//if(other.getVelocityX() > 0.1f)
alreadyHit = true;
}
//slowdown effect because the other one makes the game
if(other instanceof PlayerPawn)
{
other.setVelocityX(other.getVelocityX() / 5f);
other.setVelocityY(other.getVelocityY() / 5f);
}
}
@Override
public int getRADIUS() {
// TODO Auto-generated method stub
return RADIUS;
}
}
|
/*
* MIT License
*
* Copyright (c) 2020 Jannis Weis
*
* 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.github.weisj.darklaf.ui.taskpane;
import com.github.weisj.darklaf.util.DarkUIUtil;
import org.jdesktop.swingx.JXCollapsiblePane;
import org.jdesktop.swingx.JXHyperlink;
import org.jdesktop.swingx.JXTaskPane;
import org.jdesktop.swingx.plaf.metal.MetalTaskPaneUI;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.UIResource;
import java.awt.*;
public class DarkTaskPaneUI extends MetalTaskPaneUI {
protected boolean isCollapsed;
protected Color borderColor;
protected Icon collapsedIcon;
protected Icon openIcon;
protected int arc;
public static ComponentUI createUI(final JComponent c) {
return new DarkTaskPaneUI();
}
@Override
protected void installDefaults() {
borderColor = UIManager.getColor("TaskPane.borderColor");
arc = UIManager.getInt("TaskPane.arc");
collapsedIcon = UIManager.getIcon("TaskPane.collapsed.icon");
openIcon = UIManager.getIcon("TaskPane.open.icon");
super.installDefaults();
}
@Override
protected Border createPaneBorder() {
return new DarkPaneBorder();
}
@Override
protected void installListeners() {
super.installListeners();
group.addPropertyChangeListener(JXCollapsiblePane.ANIMATION_STATE_KEY, e -> isCollapsed = "collapsed".equals(e.getNewValue()));
}
@Override
protected Border createContentPaneBorder() {
return new CompoundBorder(new DarkContentPaneBorder(borderColor, arc),
BorderFactory.createEmptyBorder(10, 10, 10, 10));
}
@Override
protected void configure(final JXHyperlink link) {
super.configure(link);
link.setFocusPainted(false);
}
@Override
protected int getRoundHeight() {
return arc;
}
protected boolean isCollapsed() {
if (!group.isAnimated()) return group.isCollapsed();
return isCollapsed;
}
protected static class DarkContentPaneBorder implements Border, UIResource {
protected Color color;
protected int arc;
public DarkContentPaneBorder(final Color color, final int arc) {
this.arc = arc;
this.color = color;
}
public void paintBorder(final Component c, final Graphics g, final int x, final int y,
final int width, final int height) {
Rectangle clip = g.getClip().getBounds();
int h = height + arc;
g.setClip(clip.x, clip.y, width, h / 2 + 1);
g.setColor(color);
DarkUIUtil.drawRect(g, x, y - 1, width, h, 1);
if (c.isOpaque()) {
g.setColor(c.getBackground());
g.setClip(clip.x, clip.x + h - arc, width, arc);
DarkUIUtil.fillRoundRect((Graphics2D) g, x, y, width - 1, h - 1, arc);
}
g.setClip(clip.x, clip.y + h / 2 - 1, width, h / 2 + 2);
g.setColor(color);
DarkUIUtil.paintLineBorder((Graphics2D) g, x, y, width - 1, h - 1, arc);
g.setClip(clip);
}
public Insets getBorderInsets(final Component c) {
return new Insets(0, 1, 1, 1);
}
public boolean isBorderOpaque() {
return true;
}
}
protected class DarkPaneBorder extends PaneBorder {
@Override
protected void paintTitleBackground(final JXTaskPane group, final Graphics g2) {
Graphics2D g = (Graphics2D) g2;
int w = group.getWidth();
int h = getTitleHeight(group);
if (group.isSpecial()) {
g.setColor(specialTitleBackground);
} else {
g.setColor(titleBackgroundGradientStart);
}
if (isCollapsed()) {
DarkUIUtil.fillRoundRect(g, 0, 0, w - 1, h - 1, getRoundHeight());
g.setColor(borderColor);
DarkUIUtil.paintLineBorder(g, 0, 0, w - 1, h - 1, getRoundHeight());
} else {
Rectangle clip = g.getClip().getBounds();
g.setClip(0, 0, w, h / 2 + 1);
DarkUIUtil.fillRoundRect(g, 0, 0, w - 1, h - 1, getRoundHeight());
g.setClip(0, h / 2 - 1, w, h / 2 + 2);
g.fillRect(0, 0, w, h);
g.setColor(borderColor);
g.setClip(0, 0, w, h / 2 + 1);
DarkUIUtil.paintLineBorder(g, 0, 0, w - 1, h - 1, getRoundHeight());
g.setClip(0, h / 2 - 1, w, h / 2 + 2);
DarkUIUtil.drawRect(g, 0, 0, w, h, 1);
g.setClip(clip);
}
}
@Override
protected void configureLabel(final JXTaskPane group) {
super.configureLabel(group);
label.setFont(label.getFont().deriveFont(Font.PLAIN));
}
@Override
protected void paintExpandedControls(final JXTaskPane group, final Graphics g, final int x,
final int y, final int width, final int height) {
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(getPaintColor(group));
if (group.isCollapsed()) {
collapsedIcon.paintIcon(group, g, x, y);
} else {
openIcon.paintIcon(group, g, x, y);
}
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
}
@Override
protected boolean isMouseOverBorder() {
return true;
}
}
}
|
package org.jeecg;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.Context;
import org.apache.tomcat.util.scan.StandardJarScanner;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.boot.SpringApplication;
//import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* 单体启动类(采用此类启动为单体模式)
*/
@Slf4j
@SpringBootApplication
@EnableAutoConfiguration(exclude={MongoAutoConfiguration.class})
public class JeecgSystemApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(JeecgSystemApplication.class);
}
public static void main(String[] args) throws UnknownHostException {
ConfigurableApplicationContext application = SpringApplication.run(JeecgSystemApplication.class, args);
Environment env = application.getEnvironment();
String ip = InetAddress.getLocalHost().getHostAddress();
String port = env.getProperty("server.port");
String path = oConvertUtils.getString(env.getProperty("server.servlet.context-path"));
log.info("\n----------------------------------------------------------\n\t" +
"Application Jeecg-Boot is running! Access URLs:\n\t" +
"Local: \t\thttp://localhost:" + port + path + "/\n\t" +
"External: \thttp://" + ip + ":" + port + path + "/\n\t" +
"Swagger文档: \thttp://" + ip + ":" + port + path + "/doc.html\n" +
"----------------------------------------------------------");
}
}
|
package com.zjzy.morebit.goods.shopping.model;
import android.text.TextUtils;
import com.zjzy.morebit.LocalData.UserLocalData;
import com.zjzy.morebit.Module.common.Activity.BaseActivity;
import com.zjzy.morebit.Module.common.Utils.LoadingView;
import com.zjzy.morebit.R;
import com.zjzy.morebit.mvp.base.frame.MvpModel;
import com.zjzy.morebit.network.BaseResponse;
import com.zjzy.morebit.network.RxHttp;
import com.zjzy.morebit.network.RxUtils;
import com.zjzy.morebit.network.RxWXHttp;
import com.zjzy.morebit.pojo.ProgramGetGoodsDetailBean;
import com.zjzy.morebit.pojo.ReleaseGoodsPermission;
import com.zjzy.morebit.pojo.ShopGoodInfo;
import com.zjzy.morebit.pojo.request.RequestGoodsCollectBean;
import com.zjzy.morebit.pojo.request.RequestMaterialLink;
import com.zjzy.morebit.pojo.request.RequestReleaseGoods;
import com.zjzy.morebit.pojo.requestbodybean.RequestItemSourceId;
import com.zjzy.morebit.pojo.requestbodybean.RequestShopId;
import com.zjzy.morebit.utils.C;
import com.zjzy.morebit.utils.encrypt.EncryptUtlis;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;
import java.util.List;
import io.reactivex.Observable;
import io.reactivex.functions.Action;
import okhttp3.RequestBody;
/**
* Created by fengrs
* Data: 2018/12/15.
* 返现 model
*/
public class GoodsDetailModel extends MvpModel {
public Observable<BaseResponse<Integer>> getGoodsCollect(BaseActivity rxActivity, ShopGoodInfo goodsInfo) {
RequestGoodsCollectBean requestBean = new RequestGoodsCollectBean();
requestBean.setItemSourceId(goodsInfo.getItemSourceId());
requestBean.setItemTitle(goodsInfo.getTitle());
requestBean.setItemPicture(goodsInfo.getPicture());
requestBean.setItemPrice(goodsInfo.getPrice());
requestBean.setCouponPrice(goodsInfo.getCouponPrice());
requestBean.setItemVoucherPrice(goodsInfo.getVoucherPrice());
requestBean.setCouponUrl(goodsInfo.getCouponUrl());
requestBean.setCouponEndTime(goodsInfo.getCouponEndTime());
requestBean.setCommission(goodsInfo.getCommission());
requestBean.setShopType(goodsInfo.getShopType()+"");
requestBean.setShopName(goodsInfo.getShopName());
requestBean.setSaleMonth(TextUtils.isEmpty(goodsInfo.getSaleMonth())?"0":goodsInfo.getSaleMonth());
requestBean.setSign(EncryptUtlis.getSign2(requestBean));
return RxHttp.getInstance().getCommonService().getGoodsCollect(
requestBean
)
.compose(RxUtils.<BaseResponse<Integer>>switchSchedulers())
.compose(rxActivity.<BaseResponse<Integer>>bindToLifecycle())
.doFinally(new Action() {
@Override
public void run() throws Exception {
LoadingView.dismissDialog();
}
});
}
public Observable<BaseResponse<List<ShopGoodInfo>>> getShopList(final BaseActivity rxActivity, final ShopGoodInfo goodsInfo) {
// return RxHttp.getInstance().getGoodsService().getIdentical(goodsInfo.getShopId())
return RxHttp.getInstance().getGoodsService().getIdentical(new RequestShopId().setShopId(goodsInfo.getShopId()))
.compose(RxUtils.<BaseResponse<List<ShopGoodInfo>>>switchSchedulers())
.compose(rxActivity.<BaseResponse<List<ShopGoodInfo>>>bindToLifecycle())
.doFinally(new Action() {
@Override
public void run() throws Exception {
LoadingView.dismissDialog();
}
});
}
public Observable<BaseResponse<ShopGoodInfo>> getBaseResponseObservable(BaseActivity rxActivity, ShopGoodInfo goodsInfo) {
return RxHttp.getInstance().getCommonService().getDetailData(new RequestItemSourceId().setItemSourceId(goodsInfo.getItemSourceId()).setItemFrom(goodsInfo.getItemFrom()))
.compose(RxUtils.<BaseResponse<ShopGoodInfo>>switchSchedulers())
.compose(rxActivity.<BaseResponse<ShopGoodInfo>>bindToLifecycle());
}
/**
* 拼多多
* @param rxActivity
* @param goodsInfo
* @return
*/
public Observable<BaseResponse<ShopGoodInfo>> getBaseResponseObservableForPdd(BaseActivity rxActivity, ShopGoodInfo goodsInfo) {
return RxHttp.getInstance().getCommonService().getJdPddGoodsDetail(new ProgramGetGoodsDetailBean().setType(2)
.setGoodsId(goodsInfo.getGoodsId()))
.compose(RxUtils.<BaseResponse<ShopGoodInfo>>switchSchedulers())
.compose(rxActivity.<BaseResponse<ShopGoodInfo>>bindToLifecycle());
}
public Observable<String> getprofileUrlObservable(BaseActivity rxActivity, String url) {
return RxWXHttp.getInstance().getService(C.getInstance().getGoodsIp()).profilePicture(url)
.compose(RxUtils.<String>switchSchedulers())
.compose(rxActivity.<String>bindToLifecycle());
}
public Observable<BaseResponse<ShopGoodInfo>> putTaobaoData(BaseActivity rxActivity, String data) {
RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), data );
return RxHttp.getInstance().getGoodsService().postTaobaoData(body)
.compose(RxUtils.<BaseResponse<ShopGoodInfo>>switchSchedulers())
.compose(rxActivity.<BaseResponse<ShopGoodInfo>>bindToLifecycle());
}
public Observable<BaseResponse<ReleaseGoodsPermission>> checkPermission(RxAppCompatActivity rxActivity, RequestReleaseGoods body) {
return RxHttp.getInstance().getGoodsService().checkPermission(body)
.compose(RxUtils.<BaseResponse<ReleaseGoodsPermission>>switchSchedulers())
.compose(rxActivity.<BaseResponse<ReleaseGoodsPermission>>bindToLifecycle());
}
public Observable<BaseResponse<String>> materialLinkList(RxAppCompatActivity rxActivity, String itemSourceId, String material) {
RequestMaterialLink link = new RequestMaterialLink();
link.setInvedeCode(UserLocalData.getUser().getInviteCode());
link.setItemId(itemSourceId);
link.setMaterial(material);
return RxHttp.getInstance().getGoodsService().materialLinkList(link )
.compose(RxUtils.<BaseResponse<String>>switchSchedulers())
.compose(rxActivity.<BaseResponse<String>>bindToLifecycle());
}
}
|
/**
* Copyright (c) 2015, Intel Corporation
*
* 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 Intel Corporation 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 com.intel.stl.fecdriver.messages.response.sa;
import com.intel.stl.api.subnet.SC2SLMTRecordBean;
import com.intel.stl.fecdriver.messages.adapter.sa.SC2SLMTRecord;
/**
*/
public class FVRspGetSC2SLMT extends
SAResponse<SC2SLMTRecordBean, SC2SLMTRecord> {
/*
* (non-Javadoc)
*
* @see com.intel.hpc.stl.message.response.sa.SAResponse#createRecord()
*/
@Override
protected SC2SLMTRecord createRecord() {
return new SC2SLMTRecord();
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.shardingsphere.scaling.core.job.preparer.splitter;
import org.apache.shardingsphere.scaling.core.config.DataSourceConfiguration;
import org.apache.shardingsphere.scaling.core.config.JDBCDataSourceConfiguration;
import org.apache.shardingsphere.scaling.core.config.RdbmsConfiguration;
import org.apache.shardingsphere.scaling.core.config.SyncConfiguration;
import org.apache.shardingsphere.scaling.core.datasource.DataSourceManager;
import org.apache.shardingsphere.scaling.core.job.task.ScalingTask;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
public class InventoryDataTaskSplitterTest {
private static final String DATA_SOURCE_URL = "jdbc:h2:mem:test_db;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MySQL";
private static final String USERNAME = "root";
private static final String PASSWORD = "password";
private SyncConfiguration syncConfiguration;
private DataSourceManager dataSourceManager;
private InventoryDataTaskSplitter inventoryDataTaskSplitter;
@Before
public void setUp() {
RdbmsConfiguration dumperConfig = mockDumperConfig();
RdbmsConfiguration importerConfig = new RdbmsConfiguration();
Map<String, String> tableMap = new HashMap<>();
tableMap.put("t_order", "t_order");
syncConfiguration = new SyncConfiguration(3, tableMap,
dumperConfig, importerConfig);
dataSourceManager = new DataSourceManager();
inventoryDataTaskSplitter = new InventoryDataTaskSplitter();
}
@After
public void tearDown() {
dataSourceManager.close();
}
@Test
public void assertSplitInventoryDataWithIntPrimary() throws SQLException {
initIntPrimaryEnvironment(syncConfiguration.getDumperConfiguration());
Collection<ScalingTask> actual = inventoryDataTaskSplitter.splitInventoryData(syncConfiguration, dataSourceManager);
assertNotNull(actual);
assertThat(actual.size(), is(3));
}
@Test
public void assertSplitInventoryDataWithCharPrimary() throws SQLException {
initCharPrimaryEnvironment(syncConfiguration.getDumperConfiguration());
Collection<ScalingTask> actual = inventoryDataTaskSplitter.splitInventoryData(syncConfiguration, dataSourceManager);
assertNotNull(actual);
assertThat(actual.size(), is(1));
}
@Test
public void assertSplitInventoryDataWithUnionPrimary() throws SQLException {
initUnionPrimaryEnvironment(syncConfiguration.getDumperConfiguration());
Collection<ScalingTask> actual = inventoryDataTaskSplitter.splitInventoryData(syncConfiguration, dataSourceManager);
assertNotNull(actual);
assertThat(actual.size(), is(1));
}
@Test
public void assertSplitInventoryDataWithoutPrimary() throws SQLException {
initNoPrimaryEnvironment(syncConfiguration.getDumperConfiguration());
Collection<ScalingTask> actual = inventoryDataTaskSplitter.splitInventoryData(syncConfiguration, dataSourceManager);
assertNotNull(actual);
assertThat(actual.size(), is(1));
}
private void initIntPrimaryEnvironment(final RdbmsConfiguration dumperConfig) throws SQLException {
DataSource dataSource = dataSourceManager.getDataSource(dumperConfig.getDataSourceConfiguration());
try (Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement()) {
statement.execute("DROP TABLE IF EXISTS t_order");
statement.execute("CREATE TABLE t_order (id INT PRIMARY KEY, user_id VARCHAR(12))");
statement.execute("INSERT INTO t_order (id, user_id) VALUES (1, 'xxx'), (999, 'yyy')");
}
}
private void initCharPrimaryEnvironment(final RdbmsConfiguration dumperConfig) throws SQLException {
DataSource dataSource = dataSourceManager.getDataSource(dumperConfig.getDataSourceConfiguration());
try (Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement()) {
statement.execute("DROP TABLE IF EXISTS t_order");
statement.execute("CREATE TABLE t_order (id CHAR(3) PRIMARY KEY, user_id VARCHAR(12))");
statement.execute("INSERT INTO t_order (id, user_id) VALUES ('1', 'xxx'), ('999', 'yyy')");
}
}
private void initUnionPrimaryEnvironment(final RdbmsConfiguration dumperConfig) throws SQLException {
DataSource dataSource = dataSourceManager.getDataSource(dumperConfig.getDataSourceConfiguration());
try (Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement()) {
statement.execute("DROP TABLE IF EXISTS t_order");
statement.execute("CREATE TABLE t_order (id INT, user_id VARCHAR(12), PRIMARY KEY (id, user_id))");
statement.execute("INSERT INTO t_order (id, user_id) VALUES (1, 'xxx'), (999, 'yyy')");
}
}
private void initNoPrimaryEnvironment(final RdbmsConfiguration dumperConfig) throws SQLException {
DataSource dataSource = dataSourceManager.getDataSource(dumperConfig.getDataSourceConfiguration());
try (Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement()) {
statement.execute("DROP TABLE IF EXISTS t_order");
statement.execute("CREATE TABLE t_order (id INT, user_id VARCHAR(12))");
statement.execute("INSERT INTO t_order (id, user_id) VALUES (1, 'xxx'), (999, 'yyy')");
}
}
private RdbmsConfiguration mockDumperConfig() {
DataSourceConfiguration dataSourceConfiguration = new JDBCDataSourceConfiguration(DATA_SOURCE_URL, USERNAME, PASSWORD);
RdbmsConfiguration result = new RdbmsConfiguration();
result.setDataSourceConfiguration(dataSourceConfiguration);
return result;
}
}
|
package com.mrntlu.toastie;
import android.content.Context;
import android.graphics.Typeface;
import android.os.Build;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.cardview.widget.CardView;
/**
* Created by MrNtlu on 19.05.2019.
*/
public class Toastie {
private Context context;
private int icon=R.drawable.ic_warning_white_24dp;
private String message="No text!";
private int cardBackgroundColor=android.R.color.black;
private float cardElevation=4;
private float cardCornerRadius=8;
private float textSize=16;
private Typeface typeface=Typeface.DEFAULT;
private int gravity=-91;
private int xOffset;
private int yOffset;
public Toastie() {
}
public Toastie(Context context){
this.context=context;
}
public Toastie setIcon(int icon) {
this.icon = icon;
return this;
}
public Toastie setMessage(String message) {
this.message = message;
return this;
}
public Toastie setCardBackgroundColor(int cardBackgroundColor) {
this.cardBackgroundColor = cardBackgroundColor;
return this;
}
public Toastie setCardElevation(float elevation){
this.cardElevation=elevation;
return this;
}
public Toastie setCardRadius(float radius){
this.cardCornerRadius=radius;
return this;
}
public Toastie setTextSize(float textSize){
this.textSize=textSize;
return this;
}
public Toastie setTypeFace(Typeface typeface){
this.typeface=typeface;
return this;
}
public Toastie setGravity(int gravity, int xOffset, int yOffset){
this.gravity=gravity;
this.xOffset=xOffset;
this.yOffset=yOffset;
return this;
}
/**
* Creates the toast with initialized variables. And returns the custom toast.
* @param duration Duration of the toast message.
* @return Toast object.
*/
public Toast createToast(int duration){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view=inflater.inflate(R.layout.toast_layout,null);
CardView cardView=view.findViewById(R.id.cardView);
ImageView toastIcon=view.findViewById(R.id.toastIcon);
TextView toastMessage=view.findViewById(R.id.toastMessage);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
cardView.setCardBackgroundColor(context.getColor(cardBackgroundColor));
}else{
cardView.setBackgroundColor(context.getResources().getColor(cardBackgroundColor));
}
cardView.setCardElevation(cardElevation);
cardView.setRadius(cardCornerRadius);
toastIcon.setImageDrawable(context.getDrawable(icon));
toastMessage.setTextSize(textSize);
toastMessage.setText(message);
toastMessage.setTypeface(typeface);
Toast toast=new Toast(context);
toast.setView(view);
toast.setDuration(duration);
if (gravity!=-91) toast.setGravity(gravity,xOffset,yOffset);
return toast;
}
/**
* Pre-Set Info toast
* @param context Context
* @param message Message that will be on the toast.
* @param duration Duration of the toast message.
* @return Toast
*/
public static Toast info(Context context, String message, int duration){
return new Toastie(context)
.setIcon(R.drawable.ic_info_black_24dp)
.setMessage(message)
.setCardBackgroundColor(R.color.infoColor)
.createToast(duration);
}
/**
* Pre-Set Centered Info toast
* @param context Context
* @param message Message that will be on the toast.
* @param duration Duration of the toast message.
* @return Toast.
*/
public static Toast centerInfo(Context context, String message, int duration){
Toast toast= warning(context,message,duration);
toast.setGravity(Gravity.CENTER,0,0);
return toast;
}
/**
* Pre-Set Top Info toast
* @param context Context
* @param message Message that will be on the toast.
* @param duration Duration of the toast message.
* @return Toast.
*/
public static Toast topInfo(Context context, String message, int duration){
Toast toast= warning(context,message,duration);
toast.setGravity(Gravity.TOP,0,64);
return toast;
}
/**
* Pre-Set Warning toast
* @param context Context
* @param message Message that will be on the toast.
* @param duration Duration of the toast message.
* @return Toast.
*/
public static Toast warning(Context context, String message, int duration){
return new Toastie(context)
.setIcon(R.drawable.ic_warning_white_24dp)
.setMessage(message)
.setCardBackgroundColor(R.color.warningColor)
.createToast(duration);
}
/**
* Pre-Set Centered Warning toast
* @param context Context
* @param message Message that will be on the toast.
* @param duration Duration of the toast message.
* @return Toast.
*/
public static Toast centerWarning(Context context, String message, int duration){
Toast toast= warning(context,message,duration);
toast.setGravity(Gravity.CENTER,0,0);
return toast;
}
/**
* Pre-Set Top Warning toast
* @param context Context
* @param message Message that will be on the toast.
* @param duration Duration of the toast message.
* @return Toast.
*/
public static Toast topWarning(Context context, String message, int duration){
Toast toast= warning(context,message,duration);
toast.setGravity(Gravity.TOP,0,64);
return toast;
}
/**
* Pre-Set Error toast
* @param context Context
* @param message Message that will be on the toast.
* @param duration Duration of the toast message.
* @return Toast.
*/
public static Toast error(Context context, String message, int duration){
return new Toastie(context)
.setIcon(R.drawable.ic_error_black_24dp)
.setMessage(message)
.setCardBackgroundColor(R.color.errorColor)
.createToast(duration);
}
/**
* Pre-Set Centered Error toast
* @param context Context
* @param message Message that will be on the toast.
* @param duration Duration of the toast message.
* @return Toast.
*/
public static Toast centerError(Context context, String message, int duration){
Toast toast= error(context,message,duration);
toast.setGravity(Gravity.CENTER,0,0);
return toast;
}
/**
* Pre-Set Top Error toast
* @param context Context
* @param message Message that will be on the toast.
* @param duration Duration of the toast message.
* @return Toast.
*/
public static Toast topError(Context context, String message, int duration){
Toast toast= error(context,message,duration);
toast.setGravity(Gravity.TOP,0,64);
return toast;
}
/**
* Pre-Set Success toast
* @param context Context
* @param message Message that will be on the toast.
* @param duration Duration of the toast message.
* @return Toast.
*/
public static Toast success(Context context, String message, int duration){
return new Toastie(context)
.setIcon(R.drawable.ic_check_circle_black_24dp)
.setMessage(message)
.setCardBackgroundColor(R.color.successColor)
.createToast(duration);
}
/**
* Pre-Set Centered Success toast
* @param context Context
* @param message Message that will be on the toast.
* @param duration Duration of the toast message.
* @return Toast.
*/
public static Toast centerSuccess(Context context, String message, int duration){
Toast toast= success(context,message,duration);
toast.setGravity(Gravity.CENTER,0,0);
return toast;
}
/**
* Pre-Set Top Success toast
* @param context Context
* @param message Message that will be on the toast.
* @param duration Duration of the toast message.
* @return Toast.
*/
public static Toast topSuccess(Context context,String message,int duration){
Toast toast= success(context,message,duration);
toast.setGravity(Gravity.TOP,0,64);
return toast;
}
/**
* Customizable toast
* @param context Context
* @param message Message that will be on the toast.
* @param icon Icon that will be on the left side of the toast message.
* @param cardBackgroundColor Background color of toast.
* @param duration Duration of the toast message.
* @return Toast.
*/
public static Toast custom(Context context, String message, int icon, int cardBackgroundColor, int duration){
return new Toastie(context)
.setIcon(icon)
.setMessage(message)
.setCardBackgroundColor(cardBackgroundColor)
.createToast(duration);
}
/**
* Customizable centered toast
* @param context Context
* @param message Message that will be on the toast.
* @param icon Icon that will be on the left side of the toast message.
* @param cardBackgroundColor Background color of toast.
* @param duration Duration of the toast message.
* @return Toast.
*/
public static Toast customCenter(Context context, String message, int icon, int cardBackgroundColor, int duration){
Toast toast= custom(context,message,icon,cardBackgroundColor,duration);
toast.setGravity(Gravity.CENTER,0,0);
return toast;
}
/**
* Customizable top toast
* @param context Context
* @param message Message that will be on the toast.
* @param icon Icon that will be on the left side of the toast message.
* @param cardBackgroundColor Background color of toast.
* @param duration Duration of the toast message.
* @return Toast.
*/
public static Toast customTop(Context context, String message, int icon, int cardBackgroundColor, int duration){
Toast toast= custom(context,message,icon,cardBackgroundColor,duration);
toast.setGravity(Gravity.TOP,0,64);
return toast;
}
/**
* Fully customizable toast
* @param context Context
* @param message Message that will be on the toast.
* @param icon Icon that will be on the left side of the toast message.
* @param cardBackgroundColor Background color of toast.
* @param cornerRadius Corner radius of the toast.
* @param elevation Elevation of the toast.
* @param textSize Text size of the toast message.
* @param typeface Typeface of the toast message.
* @param gravity Gravity of the toast.
* @param xOffset X axis offset for toast gravity.
* @param yOffset Y axis offset for toast gravity.
* @param duration Duration of the toast message.
* @return Toast.
*/
public static Toast allCustom(Context context, String message, int icon, int cardBackgroundColor, float cornerRadius, float elevation,
float textSize, Typeface typeface, int gravity, int xOffset, int yOffset, int duration){
Toast toast=new Toastie(context)
.setIcon(icon)
.setMessage(message)
.setCardBackgroundColor(cardBackgroundColor)
.setCardElevation(elevation)
.setCardRadius(cornerRadius)
.setTextSize(textSize)
.setTypeFace(typeface)
.createToast(duration);
if (gravity!=-1) toast.setGravity(gravity,xOffset,yOffset);
return toast;
}
/**
* Simple way to create Toastie. You can use it to fully customize toast.
* @param context Context
* @return Toastie object
*/
public static Toastie allCustom(Context context){
return new Toastie(context);
}
}
|
package com.vaka.model;
import java.io.Serializable;
import javax.persistence.*;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import java.sql.Timestamp;
import java.util.List;
/**
* The persistent class for the events database table.
*
*/
@Entity
@XmlRootElement(name = "Event", namespace="")
@XmlAccessorType(XmlAccessType.FIELD)
@Table(name="events")
@NamedQuery(name="Event.findAll", query="SELECT e FROM Event e")
public class Event implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="event_id", unique=true, nullable=false)
private Integer eventId;
@Column(name="event_acronym", length=10)
private String eventAcronym;
@Column(name="event_date")
private Timestamp eventDate;
@Column(name="event_description", length=2147483647)
private String eventDescription;
@Column(name="event_end_date", length=20)
private String eventEndDate;
@Column(name="event_image", length=50)
private String eventImage;
@Column(name="event_location", length=100)
private String eventLocation;
@Column(name="event_name", length=100)
private String eventName;
@Column(name="event_start_date", length=20)
private String eventStartDate;
//bi-directional many-to-one association to User cascadeOneToOne.cascadeannotation element(Optional) The operations that must be cascaded to the target of the association.
//See JavaDoc Reference Page...=CascadeType.PERSIST) cascade=CascadeType.PERSIST
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="event_user_id", nullable=false)
private User user;
//bi-directional many-to-one association to InvitedUser
@OneToMany(mappedBy="event")
private List<InvitedUser> invitedUsers;
//bi-directional many-to-one association to Post
@OneToMany(mappedBy="event")
private List<Post> posts;
public Event() {
}
public Integer getEventId() {
return this.eventId;
}
public void setEventId(Integer eventId) {
this.eventId = eventId;
}
public String getEventAcronym() {
return this.eventAcronym;
}
public void setEventAcronym(String eventAcronym) {
this.eventAcronym = eventAcronym;
}
public Timestamp getEventDate() {
return this.eventDate;
}
public void setEventDate(Timestamp eventDate) {
this.eventDate = eventDate;
}
public String getEventDescription() {
return this.eventDescription;
}
public void setEventDescription(String eventDescription) {
this.eventDescription = eventDescription;
}
public String getEventEndDate() {
return this.eventEndDate;
}
public void setEventEndDate(String eventEndDate) {
this.eventEndDate = eventEndDate;
}
public String getEventImage() {
return this.eventImage;
}
public void setEventImage(String eventImage) {
this.eventImage = eventImage;
}
public String getEventLocation() {
return this.eventLocation;
}
public void setEventLocation(String eventLocation) {
this.eventLocation = eventLocation;
}
public String getEventName() {
return this.eventName;
}
public void setEventName(String eventName) {
this.eventName = eventName;
}
public String getEventStartDate() {
return this.eventStartDate;
}
public void setEventStartDate(String eventStartDate) {
this.eventStartDate = eventStartDate;
}
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
public List<InvitedUser> getInvitedUsers() {
return this.invitedUsers;
}
public void setInvitedUsers(List<InvitedUser> invitedUsers) {
this.invitedUsers = invitedUsers;
}
public InvitedUser addInvitedUser(InvitedUser invitedUser) {
getInvitedUsers().add(invitedUser);
invitedUser.setEvent(this);
return invitedUser;
}
public InvitedUser removeInvitedUser(InvitedUser invitedUser) {
getInvitedUsers().remove(invitedUser);
invitedUser.setEvent(null);
return invitedUser;
}
public List<Post> getPosts() {
return this.posts;
}
public void setPosts(List<Post> posts) {
this.posts = posts;
}
public Post addPost(Post post) {
getPosts().add(post);
post.setEvent(this);
return post;
}
public Post removePost(Post post) {
getPosts().remove(post);
post.setEvent(null);
return post;
}
@Override
public String toString() {
return "Event [eventId=" + eventId + ", eventAcronym=" + eventAcronym
+ ", eventDate=" + eventDate + ", eventDescription="
+ eventDescription + ", eventEndDate=" + eventEndDate
+ ", eventImage=" + eventImage + ", eventLocation="
+ eventLocation + ", eventName=" + eventName
+ ", eventStartDate=" + eventStartDate + ", user=" + user
+ ", invitedUsers=" + invitedUsers + ", posts=" + posts + "]";
}
}
|
package com.slack.kaldb.metadata.recovery;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.util.JsonFormat;
import com.slack.kaldb.metadata.core.MetadataSerializer;
import com.slack.kaldb.proto.metadata.Metadata;
public class RecoveryTaskMetadataSerializer implements MetadataSerializer<RecoveryTaskMetadata> {
private static RecoveryTaskMetadata fromRecoveryTaskMetadataProto(
Metadata.RecoveryTaskMetadata recoveryTaskMetadataProto) {
return new RecoveryTaskMetadata(
recoveryTaskMetadataProto.getName(),
recoveryTaskMetadataProto.getPartitionId(),
recoveryTaskMetadataProto.getStartOffset(),
recoveryTaskMetadataProto.getEndOffset(),
recoveryTaskMetadataProto.getCreatedTimeUtc());
}
private static Metadata.RecoveryTaskMetadata toRecoveryTaskMetadataProto(
RecoveryTaskMetadata metadata) {
return Metadata.RecoveryTaskMetadata.newBuilder()
.setName(metadata.name)
.setPartitionId(metadata.partitionId)
.setStartOffset(metadata.startOffset)
.setEndOffset(metadata.endOffset)
.setCreatedTimeUtc(metadata.createdTimeUtc)
.build();
}
@Override
public String toJsonStr(RecoveryTaskMetadata metadata) throws InvalidProtocolBufferException {
if (metadata == null) throw new IllegalArgumentException("metadata object can't be null");
return printer.print(toRecoveryTaskMetadataProto(metadata));
}
@Override
public RecoveryTaskMetadata fromJsonStr(String data) throws InvalidProtocolBufferException {
Metadata.RecoveryTaskMetadata.Builder recoveryTaskMetadataBuilder =
Metadata.RecoveryTaskMetadata.newBuilder();
JsonFormat.parser().ignoringUnknownFields().merge(data, recoveryTaskMetadataBuilder);
return fromRecoveryTaskMetadataProto(recoveryTaskMetadataBuilder.build());
}
}
|
/*
* Copyright (c) 2016. Axon Framework
*
* 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.axonframework.samples.bank.command;
import org.axonframework.samples.bank.api.banktransfer.BankTransferCompletedEvent;
import org.axonframework.samples.bank.api.banktransfer.BankTransferCreatedEvent;
import org.axonframework.samples.bank.api.banktransfer.BankTransferFailedEvent;
import org.axonframework.samples.bank.api.banktransfer.CreateBankTransferCommand;
import org.axonframework.samples.bank.api.banktransfer.MarkBankTransferCompletedCommand;
import org.axonframework.samples.bank.api.banktransfer.MarkBankTransferFailedCommand;
import org.axonframework.test.aggregate.AggregateTestFixture;
import org.axonframework.test.aggregate.FixtureConfiguration;
import org.junit.*;
public class BankTransferTest {
private FixtureConfiguration<BankTransfer> fixture;
@Before
public void setUp() throws Exception {
fixture = new AggregateTestFixture<>(BankTransfer.class);
}
@Test
public void testCreateBankTransfer() throws Exception {
String bankTransferId = "bankTransferId";
String sourceBankAccountId = "sourceBankAccountId";
String destinationBankAccountId = "destinationBankAccountId";
fixture.givenNoPriorActivity()
.when(new CreateBankTransferCommand(bankTransferId, sourceBankAccountId, destinationBankAccountId, 20))
.expectEvents(new BankTransferCreatedEvent(bankTransferId,
sourceBankAccountId,
destinationBankAccountId,
20));
}
@Test
public void testMarkBankTransferCompleted() throws Exception {
String bankTransferId = "bankTransferId";
String sourceBankAccountId = "sourceBankAccountId";
String destinationBankAccountId = "destinationBankAccountId";
fixture.given(new BankTransferCreatedEvent(bankTransferId, sourceBankAccountId, destinationBankAccountId, 20))
.when(new MarkBankTransferCompletedCommand(bankTransferId))
.expectEvents(new BankTransferCompletedEvent(bankTransferId));
}
@Test
public void testMarkBankTransferFailed() throws Exception {
String bankTransferId = "bankTransferId";
String sourceBankAccountId = "sourceBankAccountId";
String destinationBankAccountId = "destinationBankAccountId";
fixture.given(new BankTransferCreatedEvent(bankTransferId, sourceBankAccountId, destinationBankAccountId, 20))
.when(new MarkBankTransferFailedCommand(bankTransferId))
.expectEvents(new BankTransferFailedEvent(bankTransferId));
}
}
|
package org.apache.spark.sql.execution.arrow;
public class ArrowWriter {
static public org.apache.spark.sql.execution.arrow.ArrowWriter create (org.apache.spark.sql.types.StructType schema, java.lang.String timeZoneId) { throw new RuntimeException(); }
static public org.apache.spark.sql.execution.arrow.ArrowWriter create (org.apache.arrow.vector.VectorSchemaRoot root) { throw new RuntimeException(); }
public org.apache.arrow.vector.VectorSchemaRoot root () { throw new RuntimeException(); }
// not preceding
public ArrowWriter (org.apache.arrow.vector.VectorSchemaRoot root, org.apache.spark.sql.execution.arrow.ArrowFieldWriter[] fields) { throw new RuntimeException(); }
public org.apache.spark.sql.types.StructType schema () { throw new RuntimeException(); }
public void write (org.apache.spark.sql.catalyst.InternalRow row) { throw new RuntimeException(); }
public void finish () { throw new RuntimeException(); }
public void reset () { throw new RuntimeException(); }
}
|
package com.twa.flights.api.clusters.controller;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.twa.flights.api.clusters.controller.documentation.ClustersResources;
import com.twa.flights.api.clusters.service.ClustersService;
import com.twa.flights.api.clusters.validator.AvailabilityRequestValidator;
import com.twa.flights.common.dto.itinerary.ItineraryDTO;
import com.twa.flights.common.dto.request.AvailabilityRequestDTO;
@RestController
@RequestMapping("/")
public class ClustersController implements ClustersResources {
private static final Logger LOGGER = LoggerFactory.getLogger(ClustersController.class);
private final ClustersService clustersService;
private final AvailabilityRequestValidator requestValidator;
@Autowired
public ClustersController(ClustersService clustersService, AvailabilityRequestValidator requestValidator) {
this.clustersService = clustersService;
this.requestValidator = requestValidator;
}
@Override
public ResponseEntity<List<ItineraryDTO>> availability(AvailabilityRequestDTO request) {
LOGGER.debug("Obtain all the itineraries with price");
requestValidator.validate(request);
List<ItineraryDTO> response = clustersService.availability(request);
return new ResponseEntity<>(response, HttpStatus.OK);
}
}
|
package dll.struct;
import com.sun.jna.NativeLong;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
import java.util.Arrays;
import java.util.List;
/**
* <i>native declaration : D:\HWPuSDK.h</i><br>
* This file was autogenerated by <a href="http://jnaerator.googlecode.com/">JNAerator</a>,<br>
* a tool written by <a href="http://ochafik.com/">Olivier Chafik</a> that <a href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few opensource projects.</a>.<br>
* For help, please visit <a href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> , <a href="http://rococoa.dev.java.net/">Rococoa</a>, or <a href="http://jna.dev.java.net/">JNA</a>.
*/
public class PU_VOICE_INFO extends Structure {
/** \u901a\u9053ID */
public NativeLong ulChannelId;
/**
* \u672c\u5730\u97f3\u9891IP<br>
* C type : CHAR[16]
*/
public byte[] szLocalAudioIp = new byte[16];
/** \u662f\u5426\u5582\u6570\u636e(\u8bed\u97f3\u5bf9\u8bb2\uff1aTRUE\u65f6\u56de\u8c03\u51fd\u6570\u4e0d\u80fd\u4e3a\u7a7a\uff0cFLASE\u65f6\u56de\u8c03\u51fd\u6570\u5fc5\u987b\u4e3a\u7a7a) */
public boolean bFeedAudioData;
/** C type : CHAR[32] */
public byte[] szReserve = new byte[32];
public PU_VOICE_INFO() {
super();
}
protected List<String> getFieldOrder() {
return Arrays.asList("ulChannelId", "szLocalAudioIp", "bFeedAudioData", "szReserve");
}
/**
* @param ulChannelId \u901a\u9053ID<br>
* @param szLocalAudioIp \u672c\u5730\u97f3\u9891IP<br>
* C type : CHAR[16]<br>
* @param bFeedAudioData \u662f\u5426\u5582\u6570\u636e(\u8bed\u97f3\u5bf9\u8bb2\uff1aTRUE\u65f6\u56de\u8c03\u51fd\u6570\u4e0d\u80fd\u4e3a\u7a7a\uff0cFLASE\u65f6\u56de\u8c03\u51fd\u6570\u5fc5\u987b\u4e3a\u7a7a)<br>
* @param szReserve C type : CHAR[32]
*/
public PU_VOICE_INFO(NativeLong ulChannelId, byte szLocalAudioIp[], boolean bFeedAudioData, byte szReserve[]) {
super();
this.ulChannelId = ulChannelId;
if ((szLocalAudioIp.length != this.szLocalAudioIp.length))
throw new IllegalArgumentException("Wrong array size !");
this.szLocalAudioIp = szLocalAudioIp;
this.bFeedAudioData = bFeedAudioData;
if ((szReserve.length != this.szReserve.length))
throw new IllegalArgumentException("Wrong array size !");
this.szReserve = szReserve;
}
public PU_VOICE_INFO(Pointer peer) {
super(peer);
}
public static class ByReference extends PU_VOICE_INFO implements Structure.ByReference {
};
public static class ByValue extends PU_VOICE_INFO implements Structure.ByValue {
};
}
|
/*
* Copyright 2002-2016 jamod & j2mod development teams
*
* 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.ghgande.j2mod.modbus.procimg;
/**
* @author Julie
*
* File -- an abstraction of a Modbus Record, as supported by the
* READ FILE RECORD and WRITE FILE RECORD commands.
* @author Steve O'Hara (4NG)
* @version 2.0 (March 2016)
*/
public class Record {
private int recordNumber;
private int registerCount;
private Register[] registers;
public Record(int recordNumber, int registers) {
this.recordNumber = recordNumber;
registerCount = registers;
this.registers = new Register[registers];
for (int i = 0; i < registerCount; i++) {
this.registers[i] = new SimpleRegister(0);
}
}
public int getRecordNumber() {
return recordNumber;
}
public int getRegisterCount() {
return registerCount;
}
public Register getRegister(int register) {
if (register < 0 || register >= registerCount) {
throw new IllegalAddressException();
}
return registers[register];
}
public Record setRegister(int ref, Register register) {
if (ref < 0 || ref >= registerCount) {
throw new IllegalAddressException();
}
registers[ref] = register;
return this;
}
}
|
package precisionFDA.model;
public class FileProfile {
private String fileName;
private String fileDescription;
private String fileComment;
public FileProfile(final String fileName,
final String fileDescription,
final String fileComment) {
this.fileName = fileName;
this.fileDescription = fileDescription;
this.fileComment = fileComment;
}
public String getFileName() {
return fileName;
}
public String getFileDescription() {
return fileDescription;
}
public String getFileComment() {
return fileComment;
}
public void setFileName(String newName) {
this.fileName = newName;
}
public void setFileDescription(String newDescr) {
this.fileDescription = newDescr;
}
}
|
/**
* Copyright (C) 2015 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.fabric8.volcano.test.request;
import io.fabric8.volcano.client.VolcanoClient;
import io.fabric8.volcano.scheduling.v1beta1.Queue;
import io.fabric8.volcano.scheduling.v1beta1.QueueBuilder;
import io.fabric8.volcano.server.mock.EnableVolcanoMockClient;
import io.fabric8.volcano.server.mock.VolcanoMockServer;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.net.HttpURLConnection;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@EnableVolcanoMockClient
class QueueTest {
VolcanoClient client;
VolcanoMockServer server;
@Test
@DisplayName("Should get a queue")
void testGet() {
server.expect().get().withPath("/apis/scheduling.volcano.sh/v1beta1/namespaces/ns1/queues/q1")
.andReturn(HttpURLConnection.HTTP_OK, createQueue()).once();
Queue queue = client.v1beta1().queues().inNamespace("ns1").withName("q1").get();
assertNotNull(queue);
}
@Test
@DisplayName("Should create a queue")
void testCreate() {
Queue queue = createQueue();
server.expect().post().withPath("/apis/scheduling.volcano.sh/v1beta1/namespaces/ns1/queues")
.andReturn(HttpURLConnection.HTTP_CREATED, queue).once();
queue = client.v1beta1().queues().inNamespace("ns1").create(queue);
assertNotNull(queue);
assertEquals("q1", queue.getMetadata().getName());
}
private Queue createQueue() {
return new QueueBuilder()
.withNewMetadata().withName("q1").endMetadata()
.build();
}
}
|
/*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.ayou.netty.frame.fixedLen;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
/**
* @author lilinfeng
* @date 2014年2月14日
* @version 1.0
*/
@Sharable
public class EchoServerHandler extends ChannelHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("Receive client : [" + msg + "]");
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();// 发生异常,关闭链路
}
}
|
package me.ahoo.cosid.shardingsphere.sharding.mod;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* @author : Rocher Kong
*/
class NotSupportModShardingTypeExceptionTest {
@Test
void NotSupportModShardingTypeExceptionTest(){
NotSupportModShardingTypeException NotSupportModShardingTypeException=new NotSupportModShardingTypeException("not support interval exception");
Assertions.assertEquals(NotSupportModShardingTypeException.getMessage(),"not support interval exception");
}
@Test
void NotSupportModShardingTypeExceptionTest2(){
NotSupportModShardingTypeException NotSupportModShardingTypeException=new NotSupportModShardingTypeException("not support interval exception",new Throwable());
Assertions.assertEquals(NotSupportModShardingTypeException.getMessage(),"not support interval exception");
}
@Test
void NotSupportModShardingTypeExceptionTest3(){
Throwable throwable=new Throwable();
NotSupportModShardingTypeException NotSupportModShardingTypeException=new NotSupportModShardingTypeException(throwable);
Assertions.assertEquals(NotSupportModShardingTypeException.getCause(),throwable);
}
@Test
void NotSupportModShardingTypeExceptionTest4(){
NotSupportModShardingTypeException NotSupportModShardingTypeException=new NotSupportModShardingTypeException("not support interval exception",new Throwable(),true,true);
Assertions.assertEquals(NotSupportModShardingTypeException.getMessage(),"not support interval exception");
}
}
|
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
end_comment
begin_package
DECL|package|org.apache.camel.spring.example
package|package
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|spring
operator|.
name|example
package|;
end_package
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|Consume
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|EndpointInject
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|ProducerTemplate
import|;
end_import
begin_comment
comment|// START SNIPPET: e1
end_comment
begin_class
DECL|class|FooEventConsumer
specifier|public
class|class
name|FooEventConsumer
block|{
annotation|@
name|EndpointInject
argument_list|(
literal|"mock:result"
argument_list|)
DECL|field|destination
specifier|private
name|ProducerTemplate
name|destination
decl_stmt|;
annotation|@
name|Consume
argument_list|(
literal|"ref:foo"
argument_list|)
DECL|method|doSomething (String body)
specifier|public
name|void
name|doSomething
parameter_list|(
name|String
name|body
parameter_list|)
block|{
name|destination
operator|.
name|sendBody
argument_list|(
literal|"foo"
operator|+
name|body
argument_list|)
expr_stmt|;
block|}
block|}
end_class
begin_comment
comment|// END SNIPPET: e1
end_comment
end_unit
|
package com.verifone.swordfish.manualtransaction;
import android.support.annotation.NonNull;
import com.verifone.commerce.entities.Payment;
import java.math.BigDecimal;
/**
* Copyright (C) 2016,2017,2018 Verifone, Inc.
* <p>
* 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:
* <p>
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
* <p>
* 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
* VERIFONE, INC. 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.
* <p>
* Except as contained in this notice, the name of Verifone, Inc. shall not be
* used in advertising or otherwise to promote the sale, use or other dealings
* in this Software without prior written authorization from Verifone, Inc.
* <p>
* <p>
* Created by romans1 on 01/24/2018.
*/
public interface IBridgeListener {
void sessionStarted();
void sessionStopped();
void merchandiseAdded();
void merchandiseUpdated();
void merchandiseDeleted();
void basketAdjusted();
void basketFinalized();
void onPaymentSuccess(Payment payment);
void onPaymentDecline();
void onPaymentFailure();
void onPaymentCanceled();
void onReceiptMethodSelected(int methodId, String recipient);
void onTransactionCanceled();
void onAmountAdded(@NonNull BigDecimal addedAmount);
void onTransactionEnded(boolean isSuccessful);
void sessionStartFailed();
void reconcileSuccess();
void reconcileFailed(String message);
}
|
package ua.com.fielden.platform.web.resources.webui;
import java.io.ByteArrayInputStream;
import org.restlet.Context;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.data.Encoding;
import org.restlet.data.MediaType;
import org.restlet.engine.application.EncodeRepresentation;
import org.restlet.representation.InputRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
import com.google.common.base.Charsets;
import ua.com.fielden.platform.entity.AbstractEntity;
import ua.com.fielden.platform.utils.IDates;
import ua.com.fielden.platform.web.interfaces.IDeviceProvider;
import ua.com.fielden.platform.web.view.master.EntityMaster;
/**
* Represents web server resource that returns entity master component for specified entity type to the client (for testing).
*
* @author TG Team
*
*/
public class MasterTestsComponentResource extends AbstractWebResource {
private final EntityMaster<? extends AbstractEntity<?>> master;
/**
* Creates {@link MasterTestsComponentResource} and initialises it with master instance.
*
* @param centre
* @param context
* @param request
* @param response
*/
public MasterTestsComponentResource(
final EntityMaster<? extends AbstractEntity<?>> master,
final IDeviceProvider deviceProvider,
final IDates dates,
final Context context,
final Request request,
final Response response //
) {
super(context, request, response, deviceProvider, dates);
this.master = master;
}
@Get
@Override
public Representation get() {
return new EncodeRepresentation(Encoding.GZIP, new InputRepresentation(new ByteArrayInputStream(master.render().toString().getBytes(Charsets.UTF_8)), MediaType.TEXT_HTML));
}
}
|
/*
* Copyright (c) 2010-2017 Evolveum
*
* 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.evolveum.midpoint.prism;
import org.apache.commons.io.IOUtils;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.io.InputStream;
/**
* @author mederly
*/
public class ParserStringSource implements ParserSource {
@NotNull private final String data;
public ParserStringSource(@NotNull String data) {
this.data = data;
}
@NotNull
public String getData() {
return data;
}
@NotNull
@Override
public InputStream getInputStream() throws IOException {
return IOUtils.toInputStream(data, "utf-8");
}
@Override
public boolean closeStreamAfterParsing() {
return true;
}
@Override
public boolean throwsIOException() {
return false;
}
}
|
package org.example.demo.link;
import org.junit.Test;
public class SolutionTest {
@Test
public void reverseList() {
Solution solution = new Solution();
ListNode node = new ListNode(-1);
ListNode n1 = new ListNode(2);
ListNode n2 = new ListNode(3);
ListNode n3 = new ListNode(4);
node.next = n1;
n1.next = n2;
n2.next = n3;
Helper.printList(node);
// 测试递归的
System.out.println("递归版翻转链表:");
ListNode listNode = solution.reverseListRecur(node);
Helper.printList(listNode);
// 测试非递归的
System.out.println("非递归版翻转链表:");
listNode = solution.reverseList(listNode);
Helper.printList(listNode);
}
}
|
/*
* 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.vinci.transport.util;
/**
* Provides utility methods for Binary <=> Base64 conversion.
*/
public class Base64Converter {
/**
* If you ask for line-breaks, this is the maximum line length used.
*/
static public final int LINE_LENGTH = 70;
static private final byte[] B64_CODE = { (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D',
//IC see: https://issues.apache.org/jira/browse/UIMA-48
(byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K',
(byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R',
(byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y',
(byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f',
(byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm',
(byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't',
(byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0',
(byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7',
(byte) '8', (byte) '9', (byte) '+', (byte) '/' };
/**
* Utility class not meant to be instantiated.
*/
private Base64Converter() {
}
/**
* @pre from != null
* @param from -
* @return -
*/
static public byte[] convertBinaryToBase64(byte[] from) {
return convertBinaryToBase64(from, from.length, true);
}
/**
* @pre convert_me != null
* @param convert_me -
* @return -
*/
static public String convertStringToBase64String(String convert_me) {
return new String(convertBinaryToBase64(convert_me.getBytes()));
}
/**
* @pre base64 != null
* @param base64 -
* @return -
* @throws Base64FormatException -
*/
static public String convertBase64StringToString(String base64) throws Base64FormatException {
return new String(convertBase64ToBinary(base64.getBytes()));
}
/**
* @pre count ≤ from.length
* @param from -
* @param count -
* @param line_breaks -
* @return -
*/
static public byte[] convertBinaryToBase64(byte[] from, final int count, boolean line_breaks) {
int size = calculateBase64OutputSize(count, line_breaks);
byte[] tmp = new byte[size];
int used = 0;
for (int done = 0; done < count; done += 3) {
b64encodeOctet(tmp, used, from, done, count - done);
used += 4;
}
if (line_breaks) {
byte[] to = new byte[size];
int pos = 0;
for (int breaks = 0; breaks < used; breaks += LINE_LENGTH) {
int length = used - breaks;
if (length > LINE_LENGTH) {
length = LINE_LENGTH;
}
System.arraycopy(tmp, breaks, to, pos, length);
pos += length;
to[pos++] = (byte) '\n';
}
// Debug.Assert(pos == to.length);
return to;
} else {
// Debug.Assert(used == tmp.length);
return tmp;
}
}
/**
* Calculates the size of the resulting Base64 string returned by this class for a binary byte
* array of the specified length. Includes carriage returns and all.
* @param input_size -
* @param line_breaks -
* @return -
*/
static public int calculateBase64OutputSize(int input_size, boolean line_breaks) {
int q = input_size / 3;
if (input_size % 3 != 0) {
q += 1;
}
// Output is always a multiple of 4 characters.
q *= 4;
// Factor in the extra length needed for line breaks.
if (line_breaks) {
q += (q / LINE_LENGTH) + (q % LINE_LENGTH == 0 ? 0 : 1);
}
return q;
}
/**
* @pre input != null
* @param input -
* @return -
* @throws Base64FormatException -
*/
static public byte[] convertBase64ToBinary(byte[] input) throws Base64FormatException {
return convertBase64ToBinary(input, input.length);
}
/**
* @pre input != null
* @pre input_size ≤ input.length
* @param input -
* @param input_size -
* @return -
* @throws Base64FormatException -
*/
static public byte[] convertBase64ToBinary(byte[] input, final int input_size)
//IC see: https://issues.apache.org/jira/browse/UIMA-48
throws Base64FormatException {
int output_size = calculateBinaryOutputSize(input, input_size);
byte[] output = new byte[output_size];
int pos = 0;
int i = 0;
while (pos + 4 <= input_size) {
pos = b64decodeOctet(input, pos, output, 3 * i, input_size);
i++;
}
return output;
}
/**
* Calculate the number of bytes encoded by a given Base64 input.
*
* @pre input != null
* @pre input_size ≤ input.length
* @param input -
* @param input_size -
* @return -
* @throws Base64FormatException -
*/
static public int calculateBinaryOutputSize(byte[] input, final int input_size)
//IC see: https://issues.apache.org/jira/browse/UIMA-48
throws Base64FormatException {
int output_size = 0;
for (int i = 0; i + 4 <= input_size;) {
i = consumeInvalidDigits(input, i, input_size);
i++;
i = consumeInvalidDigits(input, i, input_size);
i++;
i = consumeInvalidDigits(input, i, input_size);
if (input[i] == (byte) '=') {
output_size += 1;
break;
}
i++;
i = consumeInvalidDigits(input, i, input_size);
if (input[i] == (byte) '=') {
output_size += 2;
break;
}
i++;
output_size += 3;
}
return output_size;
}
static private int consumeInvalidDigits(byte[] in, int off, int max_offset)
//IC see: https://issues.apache.org/jira/browse/UIMA-48
throws Base64FormatException {
if (off >= max_offset) {
throw new Base64FormatException("short read");
}
while (!b64validDigit(in[off])) {
off++;
if (off >= max_offset) {
throw new Base64FormatException("short read");
}
}
return off;
}
/**
* @pre in != null
* @pre out != null
*/
static private int b64decodeOctet(byte[] in, int in_offset, byte[] out, int out_offset,
int max_offset) throws Base64FormatException {
int A;
int B;
int C;
int D;
in_offset = consumeInvalidDigits(in, in_offset, max_offset);
A = in[in_offset++];
if (A < 0) {
throw new Base64FormatException();
}
in_offset = consumeInvalidDigits(in, in_offset, max_offset);
B = in[in_offset++];
if (B < 0) {
throw new Base64FormatException();
}
in_offset = consumeInvalidDigits(in, in_offset, max_offset);
C = in[in_offset++];
in_offset = consumeInvalidDigits(in, in_offset, max_offset);
D = in[in_offset++];
A = b64decodeDigit(A);
A <<= 2;
B = b64decodeDigit(B);
A |= (B >> 4);
out[out_offset] = (byte) A;
B <<= 4;
C = b64decodeDigit(C);
if (C < 0) {
return max_offset; // we are done
}
B |= C >> 2;
out[out_offset + 1] = (byte) B;
C <<= 6;
D = b64decodeDigit(D);
if (D < 0) {
return max_offset; // we are done
}
C |= D;
out[out_offset + 2] = (byte) C;
return in_offset;
}
static private int b64decodeDigit(int c) {
if (c >= (byte) 'A' && c <= (byte) 'Z') {
return c - (byte) 'A';
} else if (c >= (byte) 'a' && c <= (byte) 'z') {
return c - (byte) 'a' + 26;
} else if (c >= (byte) '0' && c <= (byte) '9') {
return c - (byte) '0' + 52;
} else if (c == (byte) '+') {
return 62;
} else if (c == (byte) '/') {
return 63;
} else if (c == (byte) '=') {
return -2;
}
return -1;
}
static private boolean b64validDigit(byte a) {
if (a >= (byte) 'A' && a <= (byte) 'Z') {
return true;
}
if (a >= (byte) 'a' && a <= (byte) 'z') {
return true;
}
if (a >= (byte) '0' && a <= (byte) '9') {
return true;
}
if (a == (byte) '/' || a == (byte) '+' || a == (byte) '=') {
return true;
}
return false;
}
static private void b64encodeOctet(byte[] to, int to_offset, byte[] from, int from_offset,
int count) {
int A = 0;
int B = 0;
int C = 0;
int D = 0;
int tmp = 0;
A = from[from_offset];
if (A < 0) {
A += 256;
}
A >>= 2;
B = from[from_offset];
if (B < 0) {
B += 256;
}
B &= 3;
B <<= 4;
if (count > 1) {
tmp = from[from_offset + 1] < 0 ? (from[from_offset + 1]) + 256 : from[from_offset + 1];
B |= tmp >> 4;
C = from[from_offset + 1];
if (C < 0) {
C += 256;
}
C &= 15;
C <<= 2;
}
if (count > 2) {
tmp = from[from_offset + 2] < 0 ? (from[from_offset + 2]) + 256 : from[from_offset + 2];
C |= tmp >> 6;
D = from[from_offset + 2];
if (D < 0) {
D += 256;
}
D &= 0x3F;
}
to[to_offset] = b64codes(A);
to[to_offset + 1] = b64codes(B);
if (count > 1) {
to[to_offset + 2] = b64codes(C);
} else {
to[to_offset + 2] = (byte) '=';
}
if (count > 2) {
to[to_offset + 3] = b64codes(D);
} else {
to[to_offset + 3] = (byte) '=';
}
}
static private byte b64codes(int which) {
if (which < 0) {
which += 256;
}
return B64_CODE[which];
}
/*
* public static void main(String[] args) throws Base64FormatException { int to = 256; if
* (args.length > 0) { to = Integer.parseInt(args[0]); } System.out.println("TESTING case: " +
* to); byte[] input = new byte[to]; for (int i=0; i<to; i++) { input[i] = (byte)i; } byte[]
* output = convertBinaryToBase64(input); String output_me = new String(output, 0, output.length);
* System.out.println("Encoded string:\n" + output_me); input = convertBase64ToBinary(output); for
* (int i=0; i<to; i++) { if (input[i] ≥ 0) { Debug.Assert(i == (int)input[i]); } else {
* Debug.Assert(i == ((int)input[i]) + 256); } } if (to != 0 && args.length > 0) { // Test all
* cases all the way down to 0 length arrays args[0] = Integer.toString(to-1); main(args); } }
*/
} // class
|
package com.company;
import java.io.*;
public class ScoreManager {
// Current scores
private int currentScore;
private int currentTopScore;
private long time;
private long startingTime;
private long bestTime;
private int[] board = new int[GameBoard.ROWS * GameBoard.COLS];
// File
private String filePath;
private String temp = "TEMP.tmp";
private GameBoard gBoard;
//Boolean
private boolean newGame;
public ScoreManager (GameBoard gBoard){
this.gBoard = gBoard;
// filePath = System.getProperty("user.home");
filePath = new File("").getAbsolutePath();
}
public void reset(){
File f = new File(filePath, temp );
if (f.isFile()){
f.delete();
}
newGame = true;
startingTime = 0;
currentScore = 0;
time = 0;
}
private void createFile(){
FileWriter output = null;
newGame = true;
try {
File f = new File(filePath, temp);
output = new FileWriter(f);
BufferedWriter writer = new BufferedWriter(output);
writer.write("" + 0);
writer.newLine();
writer.write("" + 0);
writer.newLine();
writer.write("" + 0);
writer.newLine();
writer.write("" + 0);
writer.newLine();
// For saving the GameBoard
for (int row = 0; row < GameBoard.ROWS; row++){
for (int col = 0; col < GameBoard.COLS; col++){
if (row == GameBoard.ROWS - 1 && col == GameBoard.COLS - 1){
writer.write("" + 0);
} else {
writer.write(0 + "-");
}
}
}
writer.close();
} catch(Exception e){
e.printStackTrace();
}
}
public void saveGame() {
FileWriter output = null;
if (newGame){
newGame = false;
}
try {
File f = new File(filePath, temp);
output = new FileWriter(f);
BufferedWriter writer = new BufferedWriter(output);
writer.write("" + currentScore);
writer.newLine();
writer.write("" + currentTopScore);
writer.newLine();
writer.write("" + time);
writer.newLine();
writer.write("" + bestTime);
writer.newLine();
// For saving the GameBoard
for (int row = 0; row < GameBoard.ROWS; row++){
for (int col = 0; col < GameBoard.COLS; col++){
// transforming 2D location into 1D location
// row = 3 col = 2 --> 4 * 3 + 2 = 14
int location = row * GameBoard.COLS + col;
Tile tile = gBoard.getBoard()[row][col];
this.board[location] = tile != null ? tile.getValue() : 0;
if (row == GameBoard.ROWS - 1 && col == GameBoard.COLS - 1){
writer.write("" + board[location]);
} else {
writer.write(board[location] + "-");
}
}
}
writer.close();
} catch (Exception e){
e.printStackTrace();
}
}
public void loadGame() {
try {
File f = new File(filePath, temp);
if (!f.isFile()){
createFile();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
currentScore = Integer.parseInt(reader.readLine());
currentTopScore = Integer.parseInt(reader.readLine());
time = Long.parseLong(reader.readLine());
startingTime = time;
bestTime = Long.parseLong(reader.readLine());
String[] board = reader.readLine().split("-");
for (int i = 0; i < board.length; i++){
this.board[i] = Integer.parseInt(board[i]);
}
reader.close();
} catch (Exception e){
e.printStackTrace();
}
}
public int getCurrentScore() {
return currentScore;
}
public void setCurrentScore(int currentScore) {
this.currentScore = currentScore;
}
public int getCurrentTopScore() {
return currentTopScore;
}
public void setCurrentTopScore(int currentTopScore) {
this.currentTopScore = currentTopScore;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time + startingTime;
}
public long getBestTime() {
return bestTime;
}
public void setBestTime(long bestTime) {
this.bestTime = bestTime;
}
public int[] getBoard() {
return board;
}
public boolean newGame() {
return newGame;
}
}
|
/*
* Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) 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 org.wso2.developerstudio.eclipse.capp.core.artifacts.manager;
import org.wso2.developerstudio.eclipse.capp.core.model.ServerRole;
import org.wso2.developerstudio.eclipse.greg.core.interfaces.IRegistryHandler;
public class CAppEnvironment {
private static ICAppArtifactManager cAppManager;
private static ServerRole defaultServerRole=new ServerRole("Default","Default Server Role");
private static IRegistryHandler registryHandler;
public static void setcAppManager(ICAppArtifactManager cAppManager) {
CAppEnvironment.cAppManager = cAppManager;
}
public static ICAppArtifactManager getcAppManager() {
return cAppManager;
}
public static ServerRole getDefaultServerRole() {
return defaultServerRole;
}
public static void setRegistryHandler(IRegistryHandler registryHandler) {
CAppEnvironment.registryHandler = registryHandler;
}
public static IRegistryHandler getRegistryHandler() {
return registryHandler;
}
public static boolean isRegistryHandlerPresent(){
return (getRegistryHandler()!=null);
}
public static IServerRole createServerRole(String serverRoleName,String serverRoleDescription){
return new ServerRole(serverRoleName, serverRoleDescription);
}
public static IServerRole createServerRole(String serverRoleName){
return createServerRole(serverRoleName,"");
}
}
|
/**
* Copyright 2018 Dingfan Zhao
*
* 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.
*/
/*
* Apache Fineract API Documentation
* Apache Fineract is a secure, multi-tenanted microfinance platform. <br /> The goal of the Apache Fineract API is to empower developers to build apps on top of the Apache Fineract Platform. The reference app [ https://demo.openmf.org ] (username: mifos, password: password) works on the same demo tenant as the interactive links in this documentation. <br/>The API is organized around REST [ https://en.wikipedia.org/wiki/Representational_state_transfer ] <br/> Find out more about Apache Fineract on [ https://demo.openmf.org/api-docs/apiLive.htm#top ] <br/> You can Try The API From Your Browser itself at [ https://demo.openmf.org/api-docs/apiLive.htm#interact ] <br/> The Generic Options are available at [ https://demo.openmf.org/api-docs/apiLive.htm#genopts ] <br/> Find out more about Updating Dates and Numbers at [ https://demo.openmf.org/api-docs/apiLive.htm#dates_and_numbers ] <br/> For the Authentication and the Basic of HTTP and HTTPS refer [ https://demo.openmf.org/api-docs/apiLive.htm#authentication_overview ] <br/> Check about ERROR codes at [ https://demo.openmf.org/api-docs/apiLive.htm#errors ] <br/> <br/> Please refer to the old documentation for any documentation queries [ https://demo.openmf.org/api-docs/apiLive.htm ] <br/> ______________________________________________________________________________________________________________________________
*
* OpenAPI spec version: 1.0.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package org.mifos.chatbot.client.model;
import java.util.Objects;
import com.google.gson.annotations.SerializedName;
import io.swagger.annotations.ApiModelProperty;
import org.mifos.chatbot.client.model.LoanProduct;
import org.mifos.chatbot.client.model.LoanProduct;
/**
* LoanProductConfigurableAttributes
*/
public class LoanProductConfigurableAttributes {
@SerializedName("id")
private Long id = null;
@SerializedName("loanproduct")
private LoanProduct loanProduct = null;
@SerializedName("amortizationBoolean")
private Boolean amortizationBoolean = null;
@SerializedName("arrearsToleranceBoolean")
private Boolean arrearsToleranceBoolean = null;
@SerializedName("graceOnArrearsAgingBoolean")
private Boolean graceOnArrearsAgingBoolean = null;
@SerializedName("interestCalcPeriodBoolean")
private Boolean interestCalcPeriodBoolean = null;
@SerializedName("interestMethodBoolean")
private Boolean interestMethodBoolean = null;
@SerializedName("graceOnPrincipalAndInterestPaymentBoolean")
private Boolean graceOnPrincipalAndInterestPaymentBoolean = null;
@SerializedName("repaymentEveryBoolean")
private Boolean repaymentEveryBoolean = null;
@SerializedName("transactionProcessingStrategyBoolean")
private Boolean transactionProcessingStrategyBoolean = null;
@SerializedName("new")
private Boolean _new = null;
public LoanProductConfigurableAttributes id(Long id) {
this.id = id;
return this;
}
/**
* Get id
* @return id
**/
@ApiModelProperty(value = "")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public LoanProductConfigurableAttributes loanProduct(LoanProduct loanProduct) {
this.loanProduct = loanProduct;
return this;
}
/**
* Get loanproduct
* @return loanproduct
**/
@ApiModelProperty(value = "")
public LoanProduct getLoanProduct() {
return loanProduct;
}
public void setLoanProduct(LoanProduct loanProduct) {
this.loanProduct = loanProduct;
}
public LoanProductConfigurableAttributes amortizationBoolean(Boolean amortizationBoolean) {
this.amortizationBoolean = amortizationBoolean;
return this;
}
/**
* Get amortizationBoolean
* @return amortizationBoolean
**/
@ApiModelProperty(value = "")
public Boolean isAmortizationBoolean() {
return amortizationBoolean;
}
public void setAmortizationBoolean(Boolean amortizationBoolean) {
this.amortizationBoolean = amortizationBoolean;
}
public LoanProductConfigurableAttributes arrearsToleranceBoolean(Boolean arrearsToleranceBoolean) {
this.arrearsToleranceBoolean = arrearsToleranceBoolean;
return this;
}
/**
* Get arrearsToleranceBoolean
* @return arrearsToleranceBoolean
**/
@ApiModelProperty(value = "")
public Boolean isArrearsToleranceBoolean() {
return arrearsToleranceBoolean;
}
public void setArrearsToleranceBoolean(Boolean arrearsToleranceBoolean) {
this.arrearsToleranceBoolean = arrearsToleranceBoolean;
}
public LoanProductConfigurableAttributes graceOnArrearsAgingBoolean(Boolean graceOnArrearsAgingBoolean) {
this.graceOnArrearsAgingBoolean = graceOnArrearsAgingBoolean;
return this;
}
/**
* Get graceOnArrearsAgingBoolean
* @return graceOnArrearsAgingBoolean
**/
@ApiModelProperty(value = "")
public Boolean isGraceOnArrearsAgingBoolean() {
return graceOnArrearsAgingBoolean;
}
public void setGraceOnArrearsAgingBoolean(Boolean graceOnArrearsAgingBoolean) {
this.graceOnArrearsAgingBoolean = graceOnArrearsAgingBoolean;
}
public LoanProductConfigurableAttributes interestCalcPeriodBoolean(Boolean interestCalcPeriodBoolean) {
this.interestCalcPeriodBoolean = interestCalcPeriodBoolean;
return this;
}
/**
* Get interestCalcPeriodBoolean
* @return interestCalcPeriodBoolean
**/
@ApiModelProperty(value = "")
public Boolean isInterestCalcPeriodBoolean() {
return interestCalcPeriodBoolean;
}
public void setInterestCalcPeriodBoolean(Boolean interestCalcPeriodBoolean) {
this.interestCalcPeriodBoolean = interestCalcPeriodBoolean;
}
public LoanProductConfigurableAttributes interestMethodBoolean(Boolean interestMethodBoolean) {
this.interestMethodBoolean = interestMethodBoolean;
return this;
}
/**
* Get interestMethodBoolean
* @return interestMethodBoolean
**/
@ApiModelProperty(value = "")
public Boolean isInterestMethodBoolean() {
return interestMethodBoolean;
}
public void setInterestMethodBoolean(Boolean interestMethodBoolean) {
this.interestMethodBoolean = interestMethodBoolean;
}
public LoanProductConfigurableAttributes graceOnPrincipalAndInterestPaymentBoolean(Boolean graceOnPrincipalAndInterestPaymentBoolean) {
this.graceOnPrincipalAndInterestPaymentBoolean = graceOnPrincipalAndInterestPaymentBoolean;
return this;
}
/**
* Get graceOnPrincipalAndInterestPaymentBoolean
* @return graceOnPrincipalAndInterestPaymentBoolean
**/
@ApiModelProperty(value = "")
public Boolean isGraceOnPrincipalAndInterestPaymentBoolean() {
return graceOnPrincipalAndInterestPaymentBoolean;
}
public void setGraceOnPrincipalAndInterestPaymentBoolean(Boolean graceOnPrincipalAndInterestPaymentBoolean) {
this.graceOnPrincipalAndInterestPaymentBoolean = graceOnPrincipalAndInterestPaymentBoolean;
}
public LoanProductConfigurableAttributes repaymentEveryBoolean(Boolean repaymentEveryBoolean) {
this.repaymentEveryBoolean = repaymentEveryBoolean;
return this;
}
/**
* Get repaymentEveryBoolean
* @return repaymentEveryBoolean
**/
@ApiModelProperty(value = "")
public Boolean isRepaymentEveryBoolean() {
return repaymentEveryBoolean;
}
public void setRepaymentEveryBoolean(Boolean repaymentEveryBoolean) {
this.repaymentEveryBoolean = repaymentEveryBoolean;
}
public LoanProductConfigurableAttributes transactionProcessingStrategyBoolean(Boolean transactionProcessingStrategyBoolean) {
this.transactionProcessingStrategyBoolean = transactionProcessingStrategyBoolean;
return this;
}
/**
* Get transactionProcessingStrategyBoolean
* @return transactionProcessingStrategyBoolean
**/
@ApiModelProperty(value = "")
public Boolean isTransactionProcessingStrategyBoolean() {
return transactionProcessingStrategyBoolean;
}
public void setTransactionProcessingStrategyBoolean(Boolean transactionProcessingStrategyBoolean) {
this.transactionProcessingStrategyBoolean = transactionProcessingStrategyBoolean;
}
public LoanProductConfigurableAttributes _new(Boolean _new) {
this._new = _new;
return this;
}
/**
* Get _new
* @return _new
**/
@ApiModelProperty(value = "")
public Boolean isNew() {
return _new;
}
public void setNew(Boolean _new) {
this._new = _new;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
LoanProductConfigurableAttributes loanProductConfigurableAttributes = (LoanProductConfigurableAttributes) o;
return Objects.equals(this.id, loanProductConfigurableAttributes.id) &&
Objects.equals(this.loanProduct, loanProductConfigurableAttributes.loanProduct) &&
Objects.equals(this.amortizationBoolean, loanProductConfigurableAttributes.amortizationBoolean) &&
Objects.equals(this.arrearsToleranceBoolean, loanProductConfigurableAttributes.arrearsToleranceBoolean) &&
Objects.equals(this.graceOnArrearsAgingBoolean, loanProductConfigurableAttributes.graceOnArrearsAgingBoolean) &&
Objects.equals(this.interestCalcPeriodBoolean, loanProductConfigurableAttributes.interestCalcPeriodBoolean) &&
Objects.equals(this.interestMethodBoolean, loanProductConfigurableAttributes.interestMethodBoolean) &&
Objects.equals(this.graceOnPrincipalAndInterestPaymentBoolean, loanProductConfigurableAttributes.graceOnPrincipalAndInterestPaymentBoolean) &&
Objects.equals(this.repaymentEveryBoolean, loanProductConfigurableAttributes.repaymentEveryBoolean) &&
Objects.equals(this.transactionProcessingStrategyBoolean, loanProductConfigurableAttributes.transactionProcessingStrategyBoolean) &&
Objects.equals(this._new, loanProductConfigurableAttributes._new);
}
@Override
public int hashCode() {
return Objects.hash(id, loanProduct, amortizationBoolean, arrearsToleranceBoolean, graceOnArrearsAgingBoolean, interestCalcPeriodBoolean, interestMethodBoolean, graceOnPrincipalAndInterestPaymentBoolean, repaymentEveryBoolean, transactionProcessingStrategyBoolean, _new);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class LoanProductConfigurableAttributes {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" loanproduct: ").append(toIndentedString(loanProduct)).append("\n");
sb.append(" amortizationBoolean: ").append(toIndentedString(amortizationBoolean)).append("\n");
sb.append(" arrearsToleranceBoolean: ").append(toIndentedString(arrearsToleranceBoolean)).append("\n");
sb.append(" graceOnArrearsAgingBoolean: ").append(toIndentedString(graceOnArrearsAgingBoolean)).append("\n");
sb.append(" interestCalcPeriodBoolean: ").append(toIndentedString(interestCalcPeriodBoolean)).append("\n");
sb.append(" interestMethodBoolean: ").append(toIndentedString(interestMethodBoolean)).append("\n");
sb.append(" graceOnPrincipalAndInterestPaymentBoolean: ").append(toIndentedString(graceOnPrincipalAndInterestPaymentBoolean)).append("\n");
sb.append(" repaymentEveryBoolean: ").append(toIndentedString(repaymentEveryBoolean)).append("\n");
sb.append(" transactionProcessingStrategyBoolean: ").append(toIndentedString(transactionProcessingStrategyBoolean)).append("\n");
sb.append(" _new: ").append(toIndentedString(_new)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
package ru.job4j.model.email;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.is;
/**
* Test class for class "Email"
* @author Geraskin Yegor(yegeraskin13@gmail.com)
*/
public class EmailTest {
@Test
public void testToString1() {
String value = "yegeraskin13@gmail.com";
Email email = new Email(value);
String result = email.toString();
String expected = "Email{" + value + "}";
assertThat(result, is(expected));
}
@Test
public void testToString2() {
String value = "";
Email email = new Email(value);
String result = email.toString();
String expected = "Email{" + value + "}";
assertThat(result, is(expected));
}
@Test
public void testToString3() {
String value = "yegeraskin13@rambler.com";
Email email = new Email(value);
String result = email.toString();
String expected = "Email{" + value + "}";
assertThat(result, is(expected));
}
@Test
public void testToString4() {
String value = "xxx@yyy.org";
Email email = new Email(value);
String result = email.toString();
String expected = "Email{" + value + "}";
assertThat(result, is(expected));
}
@Test
public void testToString5() {
String value = "xxx@yyy.edu";
Email email = new Email(value);
String result = email.toString();
String expected = "Email{" + value + "}";
assertThat(result, is(expected));
}
@Test
public void testToString6() {
String value = "qw@po.net";
Email email = new Email(value);
String result = email.toString();
String expected = "Email{" + value + "}";
assertThat(result, is(expected));
}
@Test
public void testToString7() {
String value = "eg@mipt.ru";
Email email = new Email(value);
String result = email.toString();
String expected = "Email{" + value + "}";
assertThat(result, is(expected));
}
@Test
public void testToString8() {
String value = "@serv.";
Email email = new Email(value);
String result = email.toString();
String expected = "Email{" + value + "}";
assertThat(result, is(expected));
}
@Test
public void testToString9() {
String value = "@";
Email email = new Email(value);
String result = email.toString();
String expected = "Email{" + value + "}";
assertThat(result, is(expected));
}
@Test
public void testToString10() {
String value = "fglsfgj ;lskj erioj reigj aeropi _";
Email email = new Email(value);
String result = email.toString();
String expected = "Email{" + value + "}";
assertThat(result, is(expected));
}
@Test
public void testHashCode1() {
String value = "yegeraskin13@gmail.com";
Email email = new Email(value);
int result = email.hashCode();
int expected = value.hashCode();
assertThat(result, is(expected));
}
@Test
public void testHashCode2() {
String value = "";
Email email = new Email(value + "");
int result = email.hashCode();
int expected = value.hashCode();
assertThat(result, is(expected));
}
@Test
public void testHashCode3() {
String value = "yegeraskin13@rambler.com";
Email email = new Email(value + "");
int result = email.hashCode();
int expected = value.hashCode();
assertThat(result, is(expected));
}
@Test
public void testHashCode4() {
String value = "xxx@yyy.org";
Email email = new Email(value + "");
int result = email.hashCode();
int expected = value.hashCode();
assertThat(result, is(expected));
}
@Test
public void testHashCode5() {
String value = "xxx@yyy.edu";
Email email = new Email(value + "");
int result = email.hashCode();
int expected = value.hashCode();
assertThat(result, is(expected));
}
@Test
public void testHashCode6() {
String value = "qw@po.net";
Email email = new Email("" + value);
int result = email.hashCode();
int expected = value.hashCode();
assertThat(result, is(expected));
}
@Test
public void testHashCode7() {
String value = "eg@mipt.ru";
Email email = new Email("" + value);
int result = email.hashCode();
int expected = value.hashCode();
assertThat(result, is(expected));
}
@Test
public void testHashCode8() {
String value = "@serv.";
Email email = new Email("" + value);
int result = email.hashCode();
int expected = value.hashCode();
assertThat(result, is(expected));
}
@Test
public void testHashCode9() {
String value = "@";
Email email = new Email("" + value);
int result = email.hashCode();
int expected = value.hashCode();
assertThat(result, is(expected));
}
@Test
public void testHashCode10() {
String value = "fglsfgj ;lskj erioj reigj aeropi _";
Email email = new Email(value);
int result = email.hashCode();
int expected = value.hashCode();
assertThat(result, is(expected));
}
@Test
public void testEquals1() {
String value = "yegeraskin13@gmail.com";
Email email1 = new Email(value);
Email email2 = new Email("" + value);
boolean result = email1.equals(email2);
boolean expected = true;
assertThat(result, is(expected));
}
@Test
public void testEquals2() {
String value = "";
Email email1 = new Email(value);
Email email2 = new Email("" + value);
boolean result = email1.equals(email2);
boolean expected = true;
assertThat(result, is(expected));
}
@Test
public void testEquals3() {
String value = "yegeraskin13@rambler.com";
Email email1 = new Email(value);
Email email2 = new Email("" + value);
boolean result = email1.equals(email2);
boolean expected = true;
assertThat(result, is(expected));
}
@Test
public void testEquals4() {
String value = "xxx@yyy.org";
Email email1 = new Email("" + value);
Email email2 = new Email(value);
boolean result = email1.equals(email2);
boolean expected = true;
assertThat(result, is(expected));
}
@Test
public void testEquals5() {
String value = "xxx@yyy.edu";
Email email1 = new Email("" + value);
Email email2 = new Email(value);
boolean result = email1.equals(email2);
boolean expected = true;
assertThat(result, is(expected));
}
@Test
public void testEquals6() {
String value = "qw@po.net";
Email email1 = new Email(value);
Email email2 = new Email("" + value);
boolean result = email1.equals(email2);
boolean expected = true;
assertThat(result, is(expected));
}
@Test
public void testEquals7() {
String value = "eg@mipt.ru";
Email email1 = new Email("" + value);
Email email2 = new Email(value);
boolean result = email1.equals(email2);
boolean expected = true;
assertThat(result, is(expected));
}
@Test
public void testEquals8() {
String value = "@serv.";
Email email1 = new Email("" + value);
Email email2 = new Email(value);
boolean result = email1.equals(email2);
boolean expected = true;
assertThat(result, is(expected));
}
@Test
public void testEquals9() {
String value = "@";
Email email1 = new Email(value);
Email email2 = new Email(value);
boolean result = email1.equals(email2);
boolean expected = true;
assertThat(result, is(expected));
}
@Test
public void testEquals10() {
String value = "fglsfgj ;lskj erioj reigj aeropi _";
Email email1 = new Email(value);
Email email2 = new Email(value);
boolean result = email1.equals(email2);
boolean expected = true;
assertThat(result, is(expected));
}
@Test
public void testEquals11() {
String value = "yegeraskin13@gmail.com";
Email email1 = new Email(value);
Email email2 = new Email("");
boolean result = email1.equals(email2);
boolean expected = false;
assertThat(result, is(expected));
}
@Test
public void testEquals12() {
String value = "";
Email email1 = new Email(value);
Email email2 = new Email(value + ".");
boolean result = email1.equals(email2);
boolean expected = false;
assertThat(result, is(expected));
}
@Test
public void testEquals13() {
String value = "yegeraskin13@rambler.com";
Email email1 = new Email(value + ".");
Email email2 = new Email(value);
boolean result = email1.equals(email2);
boolean expected = false;
assertThat(result, is(expected));
}
@Test
public void testEquals14() {
String value = "xxx@yyy.org";
Email email1 = new Email(value);
Email email2 = new Email("xxx@yxy.org");
boolean result = email1.equals(email2);
boolean expected = false;
assertThat(result, is(expected));
}
@Test
public void testEquals15() {
String value = "xxx@yyy.edu";
Email email1 = new Email("yxx@yyy.edu");
Email email2 = new Email(value);
boolean result = email1.equals(email2);
boolean expected = false;
assertThat(result, is(expected));
}
@Test
public void testEquals16() {
String value = "qw@po.net";
Email email1 = new Email(value);
Email email2 = new Email("qw@po.edu");
boolean result = email1.equals(email2);
boolean expected = false;
assertThat(result, is(expected));
}
@Test
public void testEquals17() {
String value = "eg@mipt.ru";
Email email1 = new Email("eg@diht.ru");
Email email2 = new Email(value);
boolean result = email1.equals(email2);
boolean expected = false;
assertThat(result, is(expected));
}
@Test
public void testEquals18() {
String value = "@serv.";
Email email1 = new Email(value);
Email email2 = new Email("@serv");
boolean result = email1.equals(email2);
boolean expected = false;
assertThat(result, is(expected));
}
@Test
public void testEquals19() {
String value = "@";
Email email1 = new Email(value);
Email email2 = new Email(".");
boolean result = email1.equals(email2);
boolean expected = false;
assertThat(result, is(expected));
}
@Test
public void testEquals20() {
String value = "fglsfgj ;lskj erioj reigj aeropi _";
Email email1 = new Email(value);
Email email2 = new Email("fglsfgj ;lskj erioj reigj aropi _");
boolean result = email1.equals(email2);
boolean expected = false;
assertThat(result, is(expected));
}
@Test
public void getValue1() {
String value = "";
Email email = new Email(value);
String result = email.getValue();
String expected = "" + value;
assertThat(result, is(expected));
}
@Test
public void getValue2() {
String value = "31123132";
Email email = new Email(value);
String result = email.getValue();
String expected = "" + value;
assertThat(result, is(expected));
}
@Test
public void getValue3() {
String value = "asadsd@";
Email email = new Email(value);
String result = email.getValue();
String expected = "" + value;
assertThat(result, is(expected));
}
@Test
public void getValue4() {
String value = "yegeraskin13@gmail.com";
Email email = new Email(value);
String result = email.getValue();
String expected = "" + value;
assertThat(result, is(expected));
}
@Test
public void getValue5() {
String value = "@@@";
Email email = new Email(value);
String result = email.getValue();
String expected = "" + value;
assertThat(result, is(expected));
}
@Test
public void getValue6() {
String value = "dllffg j;seo jpeigj ek....";
Email email = new Email(value);
String result = email.getValue();
String expected = "" + value;
assertThat(result, is(expected));
}
@Test
public void getValue7() {
String value = "geraskin@phystech.edu";
Email email = new Email(value);
String result = email.getValue();
String expected = "" + value;
assertThat(result, is(expected));
}
@Test
public void getValue8() {
String value = "ya@.org";
Email email = new Email(value);
String result = email.getValue();
String expected = "" + value;
assertThat(result, is(expected));
}
@Test
public void getValue9() {
String value = "kuzen.net";
Email email = new Email(value);
String result = email.getValue();
String expected = "" + value;
assertThat(result, is(expected));
}
@Test
public void getValue10() {
String value = "@@egor@@@@@@77777";
Email email = new Email(value);
String result = email.getValue();
String expected = "" + value;
assertThat(result, is(expected));
}
@Test
public void getName1() {
String value = "@yandex.ru";
Email email = new Email(value);
String result = email.getName();
String expected = "";
assertThat(result, is(expected));
}
@Test
public void getName2() {
String value = "dvsfsdfasdfasdffad";
Email email = new Email(value);
String result = email.getName();
String expected = "";
assertThat(result, is(expected));
}
@Test
public void getName3() {
String value = "egoryandex.ru";
Email email = new Email(value);
String result = email.getName();
String expected = "";
assertThat(result, is(expected));
}
@Test
public void getName4() {
String value = "yegeraskin13@gmail.com";
Email email = new Email(value);
String result = email.getName();
String expected = "yegeraskin13";
assertThat(result, is(expected));
}
@Test
public void getName5() {
String value = "geraskin@phystech.edu";
Email email = new Email(value);
String result = email.getName();
String expected = "geraskin";
assertThat(result, is(expected));
}
@Test
public void getName6() {
String value = "......@";
Email email = new Email(value);
String result = email.getName();
String expected = "......";
assertThat(result, is(expected));
}
@Test
public void getName7() {
String value = "xxx_qweqwe092284983247...@gmail.com";
Email email = new Email(value);
String result = email.getName();
String expected = "xxx_qweqwe092284983247...";
assertThat(result, is(expected));
}
@Test
public void getName8() {
String value = ".@";
Email email = new Email(value);
String result = email.getName();
String expected = ".";
assertThat(result, is(expected));
}
@Test
public void getName9() {
String value = "ivan@ivanov.com";
Email email = new Email(value);
String result = email.getName();
String expected = "ivan";
assertThat(result, is(expected));
}
@Test
public void getName10() {
String value = "@";
Email email = new Email(value);
String result = email.getName();
String expected = "";
assertThat(result, is(expected));
}
@Test
public void getService1() {
String value = "dfasdfasdfsafsdaf";
Email email = new Email(value);
String result = email.getService();
String expected = "";
assertThat(result, is(expected));
}
@Test
public void getService2() {
String value = "asdasdasd.ru";
Email email = new Email(value);
String result = email.getService();
String expected = "";
assertThat(result, is(expected));
}
@Test
public void getService3() {
String value = "";
Email email = new Email(value);
String result = email.getService();
String expected = "";
assertThat(result, is(expected));
}
@Test
public void getService4() {
String value = "egor@yandexru";
Email email = new Email(value);
String result = email.getService();
String expected = "";
assertThat(result, is(expected));
}
@Test
public void getService5() {
String value = "egor@";
Email email = new Email(value);
String result = email.getService();
String expected = "";
assertThat(result, is(expected));
}
@Test
public void getService6() {
String value = "yegeraskin13@gmail.com";
Email email = new Email(value);
String result = email.getService();
String expected = "gmail";
assertThat(result, is(expected));
}
@Test
public void getService7() {
String value = "geraskin@phystech.edu";
Email email = new Email(value);
String result = email.getService();
String expected = "phystech";
assertThat(result, is(expected));
}
@Test
public void getService8() {
String value = "egor@pa@ram.pam.pam.net";
Email email = new Email(value);
String result = email.getService();
String expected = "pa@ram";
assertThat(result, is(expected));
}
@Test
public void getService9() {
String value = "egor...asdaef.qweq@lkjlK@jkj@Lj@LKjL@KJ.asd.@Q@.asdf@..net.@aewrrwe.ru";
Email email = new Email(value);
String result = email.getService();
String expected = "lkjlK@jkj@Lj@LKjL@KJ";
assertThat(result, is(expected));
}
@Test
public void getService10() {
String value = "eg.@or@yandex.ru";
Email email = new Email(value);
String result = email.getService();
String expected = "or@yandex";
assertThat(result, is(expected));
}
@Test
public void getDomain1() {
String value = "";
Email email = new Email(value);
String result = email.getDomain();
String expected = "";
assertThat(result, is(expected));
}
@Test
public void getDomain2() {
String value = "egor@yandexru";
Email email = new Email(value);
String result = email.getDomain();
String expected = "";
assertThat(result, is(expected));
}
@Test
public void getDomain3() {
String value = "eg.or@yandexru";
Email email = new Email(value);
String result = email.getDomain();
String expected = "";
assertThat(result, is(expected));
}
@Test
public void getDomain4() {
String value = "eg.or@yandex.ru";
Email email = new Email(value);
String result = email.getDomain();
String expected = "ru";
assertThat(result, is(expected));
}
@Test
public void getDomain5() {
String value = "@@@@@";
Email email = new Email(value);
String result = email.getDomain();
String expected = "";
assertThat(result, is(expected));
}
@Test
public void getDomain6() {
String value = "..@@asd@asd@com";
Email email = new Email(value);
String result = email.getDomain();
String expected = "";
assertThat(result, is(expected));
}
@Test
public void getDomain7() {
String value = "egoryandex.ru";
Email email = new Email(value);
String result = email.getDomain();
String expected = "";
assertThat(result, is(expected));
}
@Test
public void getDomain8() {
String value = "yegeraskin13@gmail.com";
Email email = new Email(value);
String result = email.getDomain();
String expected = "com";
assertThat(result, is(expected));
}
@Test
public void getDomain9() {
String value = "geraskin@phystech.edu";
Email email = new Email(value);
String result = email.getDomain();
String expected = "edu";
assertThat(result, is(expected));
}
@Test
public void getDomain10() {
String value = "geraskin@phys.tech.edu";
Email email = new Email(value);
String result = email.getDomain();
String expected = "tech.edu";
assertThat(result, is(expected));
}
@Test
public void getDomain11() {
String value = ".ge.ra.skin@p@@@@hys.tech.edu";
Email email = new Email(value);
String result = email.getDomain();
String expected = "tech.edu";
assertThat(result, is(expected));
}
@Test
public void getDomain12() {
String value = "......@@@sadasdasdasd___@@.@a;sdfl;.@rucom@yandex.org";
Email email = new Email(value);
String result = email.getDomain();
String expected = "@a;sdfl;.@rucom@yandex.org";
assertThat(result, is(expected));
}
@Test
public void getDomain13() {
String value = "autocity222@krasnoyarsk77.net";
Email email = new Email(value);
String result = email.getDomain();
String expected = "net";
assertThat(result, is(expected));
}
@Test
public void getDomain14() {
String value = "paraplan1@tyktyk.org";
Email email = new Email(value);
String result = email.getDomain();
String expected = "org";
assertThat(result, is(expected));
}
@Test
public void getDomain15() {
String value = "karkasi@saratov.net";
Email email = new Email(value);
String result = email.getDomain();
String expected = "net";
assertThat(result, is(expected));
}
@Test
public void getDomain16() {
String value = "traktori@moscow.com";
Email email = new Email(value);
String result = email.getDomain();
String expected = "com";
assertThat(result, is(expected));
}
@Test
public void getDomain17() {
String value = "vasiliipupkin@rambler.net";
Email email = new Email(value);
String result = email.getDomain();
String expected = "net";
assertThat(result, is(expected));
}
}
|
/*
* Copyright 2017 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 com.github.liaochong.myexcel.core.annotation;
import com.github.liaochong.myexcel.core.WorkbookType;
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;
/**
* @author liaochong
* @version 1.0
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
public @interface ExcelTable {
/**
* 创建的excel包含所有字段
*
* @return true/false
*/
boolean includeAllField() default true;
/**
* 是否忽略父类属性
*
* @return true/false
*/
boolean excludeParent() default false;
/**
* 工作簿类型,.xls、.xlsx
*
* @return WorkbookType
*/
WorkbookType workbookType() default WorkbookType.SXLSX;
/**
* sheeName
*
* @return sheeName
*/
String sheetName() default "";
/**
* 内存行数保有量,只在WorkbookType.SXLSX有效
*
* @return 行数
*/
int rowAccessWindowSize() default -1;
/**
* 是否使用字段名称作为标题
*
* @return true/false
*/
boolean useFieldNameAsTitle() default false;
/**
* 为null时默认值
*
* @return 默认值
*/
String defaultValue() default "";
/**
* 是否自动换行
*
* @return true/false
*/
boolean wrapText() default true;
/**
* 是否过滤静态字段
*
* @return true/false
*/
boolean ignoreStaticFields() default true;
/**
* 标题分离器
*
* @return 分离器
*/
String titleSeparator() default "->";
}
|
/*
* Copyright (c) 2018-2021 Hugo Dupanloup (Yeregorix)
*
* 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 net.smoofyuniverse.mirage.util;
import net.smoofyuniverse.mirage.impl.internal.InternalBlockState;
import org.spongepowered.api.block.BlockState;
public class BlockUtil {
public static boolean isOpaque(BlockState state) {
return ((InternalBlockState) state).isOpaque();
}
}
|
/****************************************************************
* 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.james.transport.mailets.jsieve.delivery;
import java.util.Locale;
import javax.mail.MessagingException;
import org.apache.james.core.MailAddress;
import org.apache.james.transport.mailets.delivery.MailStore;
import org.apache.james.transport.mailets.jsieve.Poster;
import org.apache.james.user.api.UsersRepository;
import org.apache.james.user.api.UsersRepositoryException;
import org.apache.mailet.Mail;
public class SievePoster implements Poster {
private final String folder;
private final UsersRepository usersRepository;
public SievePoster(UsersRepository usersRepository, String folder) {
this.usersRepository = usersRepository;
this.folder = folder;
}
@Override
public void post(String url, Mail mail) throws MessagingException {
int endOfScheme = url.indexOf(':');
if (endOfScheme < 0) {
throw new MessagingException("Malformed URI");
} else {
String scheme = url.substring(0, endOfScheme);
if (scheme.equals("mailbox")) {
UserAndPath userAndPath = retrieveUserAndPath(url, endOfScheme);
mail.setAttribute(MailStore.DELIVERY_PATH_PREFIX + userAndPath.user, userAndPath.path);
} else {
throw new MessagingException("Unsupported protocol");
}
}
}
private UserAndPath retrieveUserAndPath(String url, int endOfScheme) throws MessagingException {
int startOfUser = endOfScheme + 3;
int endOfUser = url.indexOf('@', startOfUser);
int startOfHost = endOfUser + 1;
int endOfHost = url.indexOf('/', startOfHost);
if (endOfUser < 0) {
// TODO: When user missing, append to a default location
throw new MessagingException("Shared mailbox is not supported");
} else {
String host = url.substring(startOfHost, endOfHost);
String user = retrieveUser(url, startOfUser, endOfUser, host);
String urlPath = parseUrlPath(url, endOfHost);
return new UserAndPath(user, urlPath);
}
}
private String parseUrlPath(String url, int endOfHost) {
int length = url.length();
if (endOfHost + 1 == length) {
return this.folder;
} else {
return url.substring(endOfHost, length);
}
}
private String retrieveUser(String url, int startOfUser, int endOfUser, String host) throws MessagingException {
// lowerCase the user - see
// https://issues.apache.org/jira/browse/JAMES-1369
String user = url.substring(startOfUser, endOfUser).toLowerCase(Locale.US);
// Check if we should use the full email address as username
try {
return usersRepository.getUser(new MailAddress(user, host));
} catch (UsersRepositoryException e) {
throw new MessagingException("Unable to accessUsersRepository", e);
}
}
private static class UserAndPath {
private final String user;
private final String path;
public UserAndPath(String user, String path) {
this.user = user;
this.path = path;
}
}
}
|
package io.apptik.json.generator.generators.formats;
import io.apptik.json.JsonElement;
import io.apptik.json.JsonString;
import io.apptik.json.generator.JsonGenerator;
import io.apptik.json.generator.JsonGeneratorConfig;
import io.apptik.json.schema.Schema;
import java.util.ArrayList;
/**
* Created by sandy on 6/11/2016.
*/
public class EmailGenerator extends JsonGenerator {
public EmailGenerator(Schema schema, JsonGeneratorConfig configuration) {
super(schema, configuration);
}
public EmailGenerator(Schema schema, JsonGeneratorConfig configuration, String propertyName) {
super(schema, configuration, propertyName);
}
// This api is here but preferably should be in some util
private String generateRandomString(int minChars, int maxChars) {
int cnt = minChars;
if(maxChars>minChars) {
cnt += rnd.nextInt(maxChars - minChars);
}
String res = "";
for (int i = 0; i < cnt; i++)
res += (rnd.nextBoolean()) ? (char) (65 + rnd.nextInt(25)) : (char) (97 + rnd.nextInt(25));
return res;
}
@Override
public JsonElement generate() {
ArrayList<String> hosts;
ArrayList<String> locals;
if (configuration != null && propertyName != null && configuration.emailHosts.get(propertyName) != null
&& configuration.emailHosts.get(propertyName).size() > 0) {
hosts = configuration.emailHosts.get(propertyName);
} else if (configuration != null && configuration.globalEmailHosts != null & configuration.globalEmailHosts.size() > 0) {
hosts = configuration.globalEmailHosts;
} else {
//random host
hosts = new ArrayList<String>();
int minHostLen = 3;
int maxHostLen = 10;
if (configuration != null) {
if (configuration.globalEmailHostLengthMin != null) {
minHostLen = configuration.globalEmailHostLengthMin;
}
if (configuration.globalEmailHostLengthMax != null) {
maxHostLen = configuration.globalEmailHostLengthMax;
}
if (propertyName != null) {
if (configuration.emailHostLengthMin.get(propertyName) != null) {
minHostLen = configuration.emailHostLengthMin.get(propertyName);
}
if (configuration.emailHostLengthMax.get(propertyName) != null) {
maxHostLen = configuration.emailHostLengthMax.get(propertyName);
}
}
}
if (maxHostLen < 3) maxHostLen = 3;
String sld = generateRandomString(Math.max(1, minHostLen - 2), maxHostLen - 2);
String tld = generateRandomString(1, maxHostLen - sld.length() - 1);
hosts.add(sld + "." + tld);
}
if (configuration != null && propertyName != null && configuration.emailLocalParts.get(propertyName) != null
&& configuration.emailLocalParts.get(propertyName).size() > 0) {
locals = configuration.emailLocalParts.get(propertyName);
} else if (configuration != null && configuration.globalEmailLocalParts != null & configuration.globalEmailLocalParts.size() > 0) {
locals = configuration.globalEmailLocalParts;
} else {
//random local
locals = new ArrayList<String>();
int minlocalLen = 1;
int maxlocalLen = 10;
if (configuration != null) {
if (configuration.globalEmailLocalPartLengthMin != null) {
minlocalLen = configuration.globalEmailLocalPartLengthMin;
}
if (configuration.globalEmailLocalPartLengthMax != null) {
maxlocalLen = configuration.globalEmailLocalPartLengthMax;
}
if (propertyName != null) {
if (configuration.emailLocalPartLengthMin.get(propertyName) != null) {
minlocalLen = configuration.emailLocalPartLengthMin.get(propertyName);
}
if (configuration.emailLocalPartLengthMax.get(propertyName) != null) {
maxlocalLen = configuration.emailLocalPartLengthMax.get(propertyName);
}
}
}
locals.add(generateRandomString(minlocalLen, maxlocalLen));
}
// The assumption is the length of email strings
// Can make it more configurable
return new JsonString(
locals.get(rnd.nextInt(locals.size()))
+ "@"
+ hosts.get(rnd.nextInt(hosts.size())));
}
}
|
package com.jaquadro.minecraft.storagedrawers.block.tile;
import com.jaquadro.minecraft.storagedrawers.StorageDrawers;
import com.jaquadro.minecraft.storagedrawers.api.storage.IDrawer;
import com.jaquadro.minecraft.storagedrawers.config.CompTierRegistry;
import com.jaquadro.minecraft.storagedrawers.config.ConfigManager;
import com.jaquadro.minecraft.storagedrawers.network.CountUpdateMessage;
import com.jaquadro.minecraft.storagedrawers.storage.*;
import com.jaquadro.minecraft.storagedrawers.storage.IStorageProvider;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.item.crafting.ShapedRecipes;
import net.minecraft.item.crafting.ShapelessRecipes;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.oredict.ShapedOreRecipe;
import net.minecraftforge.oredict.ShapelessOreRecipe;
import org.apache.logging.log4j.Level;
import java.util.ArrayList;
import java.util.List;
public class TileEntityDrawersComp extends TileEntityDrawers
{
private static InventoryLookup lookup1 = new InventoryLookup(1, 1);
private static InventoryLookup lookup2 = new InventoryLookup(2, 2);
private static InventoryLookup lookup3 = new InventoryLookup(3, 3);
private ICentralInventory centralInventory;
private int pooledCount;
private int lookupSizeResult;
private ItemStack[] protoStack;
private int[] convRate;
public TileEntityDrawersComp () {
super(3);
protoStack = new ItemStack[getDrawerCount()];
convRate = new int[getDrawerCount()];
}
protected ICentralInventory getCentralInventory () {
if (centralInventory == null)
centralInventory = new CompCentralInventory();
return centralInventory;
}
public int getStoredItemRemainder (int slot) {
int count = centralInventory.getStoredItemCount(slot);
if (slot > 0 && convRate[slot] > 0)
count -= centralInventory.getStoredItemCount(slot - 1) * (convRate[slot - 1] / convRate[slot]);
return count;
}
@Override
protected IDrawer createDrawer (int slot) {
return new CompDrawerData(getCentralInventory(), slot);
}
@Override
public boolean isDrawerEnabled (int slot) {
if (slot > 0 && convRate[slot] == 0)
return false;
return super.isDrawerEnabled(slot);
}
@Override
public int putItemsIntoSlot (int slot, ItemStack stack, int count) {
if (stack != null && convRate != null && convRate[0] == 0) {
populateSlots(stack);
int added = 0;
for (int i = 0; i < getDrawerCount(); i++) {
if (BaseDrawerData.areItemsEqual(protoStack[i], stack))
added = super.putItemsIntoSlot(i, stack, count);
}
for (int i = 0; i < getDrawerCount(); i++) {
IDrawer drawer = getDrawer(i);
if (drawer instanceof CompDrawerData)
((CompDrawerData) drawer).refresh();
}
}
return super.putItemsIntoSlot(slot, stack, count);
}
@Override
public void readFromNBT (NBTTagCompound tag) {
pooledCount = 0;
for (int i = 0; i < getDrawerCount(); i++) {
protoStack[i] = null;
convRate[i] = 0;
}
super.readFromNBT(tag);
try {
pooledCount = tag.getInteger("Count");
if (tag.hasKey("Conv0"))
convRate[0] = tag.getByte("Conv0");
if (tag.hasKey("Conv1"))
convRate[1] = tag.getByte("Conv1");
if (tag.hasKey("Conv2"))
convRate[2] = tag.getByte("Conv2");
}
catch (Throwable t) {
trapLoadFailure(t, tag);
}
}
@Override
public void writeToNBT (NBTTagCompound tag) {
super.writeToNBT(tag);
if (loadDidFail())
return;
tag.setInteger("Count", pooledCount);
if (convRate[0] > 0)
tag.setByte("Conv0", (byte)convRate[0]);
if (convRate[1] > 0)
tag.setByte("Conv1", (byte)convRate[1]);
if (convRate[2] > 0)
tag.setByte("Conv2", (byte)convRate[2]);
}
@Override
public void clientUpdateCount (int slot, int count) {
if (count != pooledCount) {
pooledCount = count;
getWorldObj().func_147479_m(xCoord, yCoord, zCoord); // markBlockForRenderUpdate
}
}
private void populateSlots (ItemStack stack) {
int index = 0;
ItemStack uTier1 = findHigherTier(stack);
if (uTier1 != null) {
int uCount1 = lookupSizeResult;
ItemStack uTier2 = findHigherTier(uTier1);
if (uTier2 != null)
populateSlot(index++, uTier2, lookupSizeResult * uCount1);
populateSlot(index++, uTier1, uCount1);
}
populateSlot(index++, stack, 1);
if (index == 3)
return;
ItemStack lTier1 = findLowerTier(stack);
if (lTier1 != null) {
populateSlot(index++, lTier1, 1);
for (int i = 0; i < index - 1; i++)
convRate[i] *= lookupSizeResult;
}
if (index == 3 || lTier1 == null)
return;
ItemStack lTier2 = findLowerTier(lTier1);
if (lTier2 != null) {
populateSlot(index++, lTier2, 1);
for (int i = 0; i < index - 1; i++)
convRate[i] *= lookupSizeResult;
}
}
private void populateSlot (int slot, ItemStack stack, int conversion) {
convRate[slot] = conversion;
protoStack[slot] = stack.copy();
//centralInventory.setStoredItem(slot, stack, 0);
//getDrawer(slot).setStoredItem(stack, 0);
}
private ItemStack findHigherTier (ItemStack stack) {
CompTierRegistry.Record record = StorageDrawers.compRegistry.findHigherTier(stack);
if (record != null) {
lookupSizeResult = record.convRate;
return record.upper;
}
CraftingManager cm = CraftingManager.getInstance();
setupLookup(lookup3, stack);
ItemStack match = cm.findMatchingRecipe(lookup3, worldObj);
if (match == null || match.getItem() == null) {
setupLookup(lookup2, stack);
match = cm.findMatchingRecipe(lookup2, worldObj);
}
if (match != null && match.getItem() != null) {
int size = lookupSizeResult;
setupLookup(lookup1, match);
ItemStack comp = cm.findMatchingRecipe(lookup1, worldObj);
if (!DrawerData.areItemsEqual(comp, stack) || comp.stackSize != size)
return null;
lookupSizeResult = size;
}
return match;
}
private ItemStack findLowerTier (ItemStack stack) {
CompTierRegistry.Record record = StorageDrawers.compRegistry.findLowerTier(stack);
if (record != null) {
lookupSizeResult = record.convRate;
return record.lower;
}
CraftingManager cm = CraftingManager.getInstance();
List recipeList = cm.getRecipeList();
for (int i = 0, n = recipeList.size(); i < n; i++) {
IRecipe recipe = (IRecipe) recipeList.get(i);
ItemStack match = null;
ItemStack output = recipe.getRecipeOutput();
if (!DrawerData.areItemsEqual(stack, output))
continue;
if (recipe instanceof ShapelessOreRecipe)
match = tryMatch(stack, ((ShapelessOreRecipe) recipe).getInput());
else if (recipe instanceof ShapelessRecipes)
match = tryMatch(stack, ((ShapelessRecipes) recipe).recipeItems);
else if (recipe instanceof ShapedOreRecipe)
match = tryMatch(stack, ((ShapedOreRecipe) recipe).getInput());
else if (recipe instanceof ShapedRecipes)
match = tryMatch(stack, ((ShapedRecipes) recipe).recipeItems);
if (match != null) {
setupLookup(lookup1, stack);
ItemStack comp = cm.findMatchingRecipe(lookup1, worldObj);
if (DrawerData.areItemsEqual(match, comp) && comp.stackSize == recipe.getRecipeSize()) {
lookupSizeResult = recipe.getRecipeSize();
return match;
}
}
}
return null;
}
private ItemStack tryMatch (ItemStack stack, List list) {
if (list.size() != 9 && list.size() != 4)
return null;
Object item = list.get(0);
if (item instanceof ItemStack) {
ItemStack item1 = (ItemStack)item;
for (int i = 1, n = list.size(); i < n; i++) {
Object item2 = list.get(i);
if (item2.getClass() != ItemStack.class)
return null;
if (!item1.isItemEqual((ItemStack)item2))
return null;
}
return item1;
}
else if (item instanceof ArrayList) {
for (int i = 1, n = list.size(); i < n; i++) {
if (item != list.get(i))
return null;
}
ArrayList itemList = (ArrayList)item;
if (itemList.size() > 0) {
Object item1 = itemList.get(0);
if (item1 instanceof ItemStack)
return (ItemStack)item1;
}
}
return null;
}
private ItemStack tryMatch (ItemStack stack, Object[] list) {
if (list.length != 9 && list.length != 4)
return null;
Object item = list[0];
if (item instanceof ItemStack) {
ItemStack item1 = (ItemStack)item;
for (int i = 1, n = list.length; i < n; i++) {
Object item2 = list[i];
if (item2 == null || item2.getClass() != ItemStack.class)
return null;
if (!item1.isItemEqual((ItemStack)item2))
return null;
}
return item1;
}
else if (item instanceof ArrayList) {
for (int i = 1, n = list.length; i < n; i++) {
if (item != list[i])
return null;
}
ArrayList itemList = (ArrayList)item;
if (itemList.size() > 0) {
Object item1 = itemList.get(0);
if (item1 instanceof ItemStack)
return (ItemStack)item1;
}
}
return null;
}
private void setupLookup (InventoryLookup inv, ItemStack stack) {
for (int i = 0, n = inv.getSizeInventory(); i < n; i++)
inv.setInventorySlotContents(i, stack);
lookupSizeResult = inv.getSizeInventory();
}
private class CompCentralInventory implements ICentralInventory
{
@Override
public ItemStack getStoredItemPrototype (int slot) {
return protoStack[slot];
}
@Override
public void setStoredItem (int slot, ItemStack itemPrototype, int amount) {
if (itemPrototype != null && convRate != null && convRate[0] == 0) {
populateSlots(itemPrototype);
for (int i = 0; i < getDrawerCount(); i++) {
if (BaseDrawerData.areItemsEqual(protoStack[i], itemPrototype))
pooledCount = (pooledCount % convRate[slot]) + convRate[slot] * amount;
}
for (int i = 0; i < getDrawerCount(); i++) {
if (i == slot)
continue;
IDrawer drawer = getDrawer(i);
if (drawer instanceof CompDrawerData)
((CompDrawerData) drawer).refresh();
}
if (worldObj != null && !worldObj.isRemote) {
//TileEntityDrawersComp.this.markDirty();
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
}
}
else if (itemPrototype == null) {
setStoredItemCount(slot, 0);
}
}
@Override
public int getStoredItemCount (int slot) {
if (convRate == null || convRate[slot] == 0)
return 0;
return pooledCount / convRate[slot];
}
@Override
public void setStoredItemCount (int slot, int amount) {
if (convRate == null || convRate[slot] == 0)
return;
int oldCount = pooledCount;
pooledCount = (pooledCount % convRate[slot]) + convRate[slot] * amount;
if (pooledCount != oldCount) {
if (pooledCount != 0)
markAmountDirty();
else {
clear();
if (worldObj != null && !worldObj.isRemote) {
//TileEntityDrawersComp.this.markDirty();
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
}
}
}
}
@Override
public int getMaxCapacity (int slot) {
if (protoStack[slot] == null || convRate == null || convRate[slot] == 0)
return 0;
return protoStack[slot].getItem().getItemStackLimit(protoStack[slot]) * getStackCapacity(slot);
}
@Override
public int getRemainingCapacity (int slot) {
return getMaxCapacity(slot) - getStoredItemCount(slot);
}
@Override
public int getStoredItemStackSize (int slot) {
if (protoStack[slot] == null || convRate == null || convRate[slot] == 0)
return 0;
return protoStack[slot].getItem().getItemStackLimit(protoStack[slot]);
}
private void clear () {
for (int i = 0; i < getDrawerCount(); i++) {
protoStack[i] = null;
convRate[i] = 0;
}
refresh();
TileEntityDrawersComp.this.markDirty();
}
public void refresh () {
for (int i = 0; i < getDrawerCount(); i++) {
IDrawer drawer = getDrawer(i);
if (drawer instanceof CompDrawerData)
((CompDrawerData) drawer).refresh();
}
}
private int getStackCapacity (int slot) {
if (convRate == null || convRate[slot] == 0)
return 0;
ConfigManager config = StorageDrawers.config;
int slotStacks = config.getStorageUpgradeMultiplier(getStorageLevel()) * TileEntityDrawersComp.this.getDrawerCapacity();
int stackLimit = convRate[0] * slotStacks;
return stackLimit / convRate[slot];
}
public void markAmountDirty () {
if (getWorldObj().isRemote)
return;
IMessage message = new CountUpdateMessage(xCoord, yCoord, zCoord, 0, pooledCount);
NetworkRegistry.TargetPoint targetPoint = new NetworkRegistry.TargetPoint(getWorldObj().provider.dimensionId, xCoord, yCoord, zCoord, 500);
StorageDrawers.network.sendToAllAround(message, targetPoint);
}
public void markDirty (int slot) {
if (getWorldObj().isRemote)
return;
getWorldObj().markBlockForUpdate(xCoord, yCoord, zCoord);
}
}
/*private class CompStorageProvider extends DefaultStorageProvider
{
public CompStorageProvider () {
super(TileEntityDrawersComp.this, TileEntityDrawersComp.this);
}
@Override
public boolean isCentrallyManaged () {
return true;
}
@Override
public int getSlotStackCapacity (int slot) {
if (convRate == null || convRate[slot] == 0)
return 0;
int stackLimit = convRate[0] * TileEntityDrawersComp.this.getDrawerCapacity();
return stackLimit / convRate[slot];
}
@Override
public int getSlotCount (int slot) {
if (convRate == null || convRate[slot] == 0)
return 0;
return pooledCount / convRate[slot];
}
@Override
public void setSlotCount (int slot, int amount) {
if (convRate == null || convRate[slot] == 0)
return;
pooledCount = (pooledCount % convRate[slot]) + convRate[slot] * amount;
}
}*/
private static class InventoryLookup extends InventoryCrafting
{
private ItemStack[] stackList;
public InventoryLookup (int width, int height) {
super(null, width, height);
stackList = new ItemStack[width * height];
}
@Override
public int getSizeInventory ()
{
return this.stackList.length;
}
@Override
public ItemStack getStackInSlot (int slot)
{
return slot >= this.getSizeInventory() ? null : this.stackList[slot];
}
@Override
public ItemStack getStackInSlotOnClosing (int slot) {
return null;
}
@Override
public ItemStack decrStackSize (int slot, int count) {
return null;
}
@Override
public void setInventorySlotContents (int slot, ItemStack stack) {
stackList[slot] = stack;
}
}
}
|
/*
* Cardinal-Components-API
* Copyright (C) 2019-2020 OnyxStudios
*
* 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 nerdhub.cardinal.components.mixins.common.chunk;
import nerdhub.cardinal.components.api.component.Component;
import nerdhub.cardinal.components.api.component.ComponentContainer;
import nerdhub.cardinal.components.api.component.ComponentProvider;
import nerdhub.cardinal.components.api.component.extension.CopyableComponent;
import nerdhub.cardinal.components.internal.ChunkAccessor;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.ProtoChunk;
import net.minecraft.world.chunk.WorldChunk;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(WorldChunk.class)
public abstract class MixinWorldChunk implements Chunk, ComponentProvider, ChunkAccessor {
@SuppressWarnings({"unchecked", "rawtypes"})
@Inject(method = "<init>(Lnet/minecraft/world/World;Lnet/minecraft/world/chunk/ProtoChunk;)V", at = @At("RETURN"))
private void copyFromProto(World world, ProtoChunk proto, CallbackInfo ci) {
ComponentContainer<CopyableComponent<?>> ourComponents = this.cardinal_getComponentContainer();
ComponentContainer<CopyableComponent<?>> theirComponents = ((ChunkAccessor)proto).cardinal_getComponentContainer();
theirComponents.forEach((type, component) -> {
Component other = ourComponents.get(type);
if (other != null) {
((CopyableComponent)other).copyFrom(component);
}
});
}
}
|
package com.ABC.bc.wallet.config;
/**
*
* <p> TODO</p>
* @author: shangxl
* @Date : 2018年3月7日 下午5:37:00
*/
public class Constant {
/**
* zcash币编码
*/
public static final String ZCASH = "zec";
/**
* tv编码
*/
public static final String TV = "tv";
/**
* usdt编码
*/
public static final String USDT = "USDT";
/**
* usdt的token Id
*/
public static final String PROPERTYID_USDT = "31";
/**
* 精度
*/
public static final String DECIMALS = "_DECIMALS";
/**
* neo
*/
public static final String NEO = "NEO";
/**
* bds
*/
public static final String BDS = "BDS";
/**
* bts
*/
public static final String BTS = "BTS";
/**
* gxs
*/
public static final String GXS = "GXS";
/**
* eth编码
*/
public static final String ETHER = "ETH";
/**
* etc编码
*/
public static final String ETC = "ETC";
/**
* etz编码
*/
public static final String ETZ = "ETZ";
}
|
/**
* Copyright Dingxuan. All Rights Reserved.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.bcia.julongchain.common.exception;
/**
* JulongChain异常父类
*
* @author zhouhui
* @date 2018/3/29
* @company Dingxuan
*/
public class JulongChainException extends Exception {
public JulongChainException() {
super();
}
public JulongChainException(String message) {
super(message);
}
public JulongChainException(String message, Throwable cause) {
super(message, cause);
}
public JulongChainException(Throwable cause) {
super(cause);
}
protected JulongChainException(String message, Throwable cause,
boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
|
/*
* Copyright 2013-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.comprehend.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Describes the level of confidence that Amazon Comprehend has in the accuracy of its detection of sentiments.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/comprehend-2017-11-27/SentimentScore" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class SentimentScore implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The level of confidence that Amazon Comprehend has in the accuracy of its detection of the <code>POSITIVE</code>
* sentiment.
* </p>
*/
private Float positive;
/**
* <p>
* The level of confidence that Amazon Comprehend has in the accuracy of its detection of the <code>NEGATIVE</code>
* sentiment.
* </p>
*/
private Float negative;
/**
* <p>
* The level of confidence that Amazon Comprehend has in the accuracy of its detection of the <code>NEUTRAL</code>
* sentiment.
* </p>
*/
private Float neutral;
/**
* <p>
* The level of confidence that Amazon Comprehend has in the accuracy of its detection of the <code>MIXED</code>
* sentiment.
* </p>
*/
private Float mixed;
/**
* <p>
* The level of confidence that Amazon Comprehend has in the accuracy of its detection of the <code>POSITIVE</code>
* sentiment.
* </p>
*
* @param positive
* The level of confidence that Amazon Comprehend has in the accuracy of its detection of the
* <code>POSITIVE</code> sentiment.
*/
public void setPositive(Float positive) {
this.positive = positive;
}
/**
* <p>
* The level of confidence that Amazon Comprehend has in the accuracy of its detection of the <code>POSITIVE</code>
* sentiment.
* </p>
*
* @return The level of confidence that Amazon Comprehend has in the accuracy of its detection of the
* <code>POSITIVE</code> sentiment.
*/
public Float getPositive() {
return this.positive;
}
/**
* <p>
* The level of confidence that Amazon Comprehend has in the accuracy of its detection of the <code>POSITIVE</code>
* sentiment.
* </p>
*
* @param positive
* The level of confidence that Amazon Comprehend has in the accuracy of its detection of the
* <code>POSITIVE</code> sentiment.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SentimentScore withPositive(Float positive) {
setPositive(positive);
return this;
}
/**
* <p>
* The level of confidence that Amazon Comprehend has in the accuracy of its detection of the <code>NEGATIVE</code>
* sentiment.
* </p>
*
* @param negative
* The level of confidence that Amazon Comprehend has in the accuracy of its detection of the
* <code>NEGATIVE</code> sentiment.
*/
public void setNegative(Float negative) {
this.negative = negative;
}
/**
* <p>
* The level of confidence that Amazon Comprehend has in the accuracy of its detection of the <code>NEGATIVE</code>
* sentiment.
* </p>
*
* @return The level of confidence that Amazon Comprehend has in the accuracy of its detection of the
* <code>NEGATIVE</code> sentiment.
*/
public Float getNegative() {
return this.negative;
}
/**
* <p>
* The level of confidence that Amazon Comprehend has in the accuracy of its detection of the <code>NEGATIVE</code>
* sentiment.
* </p>
*
* @param negative
* The level of confidence that Amazon Comprehend has in the accuracy of its detection of the
* <code>NEGATIVE</code> sentiment.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SentimentScore withNegative(Float negative) {
setNegative(negative);
return this;
}
/**
* <p>
* The level of confidence that Amazon Comprehend has in the accuracy of its detection of the <code>NEUTRAL</code>
* sentiment.
* </p>
*
* @param neutral
* The level of confidence that Amazon Comprehend has in the accuracy of its detection of the
* <code>NEUTRAL</code> sentiment.
*/
public void setNeutral(Float neutral) {
this.neutral = neutral;
}
/**
* <p>
* The level of confidence that Amazon Comprehend has in the accuracy of its detection of the <code>NEUTRAL</code>
* sentiment.
* </p>
*
* @return The level of confidence that Amazon Comprehend has in the accuracy of its detection of the
* <code>NEUTRAL</code> sentiment.
*/
public Float getNeutral() {
return this.neutral;
}
/**
* <p>
* The level of confidence that Amazon Comprehend has in the accuracy of its detection of the <code>NEUTRAL</code>
* sentiment.
* </p>
*
* @param neutral
* The level of confidence that Amazon Comprehend has in the accuracy of its detection of the
* <code>NEUTRAL</code> sentiment.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SentimentScore withNeutral(Float neutral) {
setNeutral(neutral);
return this;
}
/**
* <p>
* The level of confidence that Amazon Comprehend has in the accuracy of its detection of the <code>MIXED</code>
* sentiment.
* </p>
*
* @param mixed
* The level of confidence that Amazon Comprehend has in the accuracy of its detection of the
* <code>MIXED</code> sentiment.
*/
public void setMixed(Float mixed) {
this.mixed = mixed;
}
/**
* <p>
* The level of confidence that Amazon Comprehend has in the accuracy of its detection of the <code>MIXED</code>
* sentiment.
* </p>
*
* @return The level of confidence that Amazon Comprehend has in the accuracy of its detection of the
* <code>MIXED</code> sentiment.
*/
public Float getMixed() {
return this.mixed;
}
/**
* <p>
* The level of confidence that Amazon Comprehend has in the accuracy of its detection of the <code>MIXED</code>
* sentiment.
* </p>
*
* @param mixed
* The level of confidence that Amazon Comprehend has in the accuracy of its detection of the
* <code>MIXED</code> sentiment.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SentimentScore withMixed(Float mixed) {
setMixed(mixed);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getPositive() != null)
sb.append("Positive: ").append(getPositive()).append(",");
if (getNegative() != null)
sb.append("Negative: ").append(getNegative()).append(",");
if (getNeutral() != null)
sb.append("Neutral: ").append(getNeutral()).append(",");
if (getMixed() != null)
sb.append("Mixed: ").append(getMixed());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof SentimentScore == false)
return false;
SentimentScore other = (SentimentScore) obj;
if (other.getPositive() == null ^ this.getPositive() == null)
return false;
if (other.getPositive() != null && other.getPositive().equals(this.getPositive()) == false)
return false;
if (other.getNegative() == null ^ this.getNegative() == null)
return false;
if (other.getNegative() != null && other.getNegative().equals(this.getNegative()) == false)
return false;
if (other.getNeutral() == null ^ this.getNeutral() == null)
return false;
if (other.getNeutral() != null && other.getNeutral().equals(this.getNeutral()) == false)
return false;
if (other.getMixed() == null ^ this.getMixed() == null)
return false;
if (other.getMixed() != null && other.getMixed().equals(this.getMixed()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getPositive() == null) ? 0 : getPositive().hashCode());
hashCode = prime * hashCode + ((getNegative() == null) ? 0 : getNegative().hashCode());
hashCode = prime * hashCode + ((getNeutral() == null) ? 0 : getNeutral().hashCode());
hashCode = prime * hashCode + ((getMixed() == null) ? 0 : getMixed().hashCode());
return hashCode;
}
@Override
public SentimentScore clone() {
try {
return (SentimentScore) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.comprehend.model.transform.SentimentScoreMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
|
package com.tedu.webserver.core;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import com.tedu.webserver.http.HttpRequest;
import com.tedu.webserver.http.HttpResponse;
/*
* 线程任务类,用于处理某个客户端的请求并予以响应。
*/
public class ClientHandler implements Runnable {
private Socket socket;
public ClientHandler(Socket socket) {
this.socket = socket;
}
public void run() {
System.out.println("一个客户端连接了!!!");
try {
/*
* 处理客户端请求的流程:
* 第一步:解析请求
* 第二步:处理请求
* 第三步:给予响应
*/
HttpRequest request = new HttpRequest(socket); //(1)创建request对象,把socket传过来就可以了
HttpResponse response = new HttpResponse(socket);
String url = request.getUrl(); //(2)获取请求的路径
System.out.println("url:"+url);
File file = new File("webapps"+url);
if(file.exists()) {
System.out.println("找到该文件!!!");
response.setEntity(file); //将客户端请求的文件设置到response中
}else {
/* 响应404
* 1:设置响应的状态代码为404
* 2:设置错误页面
*/
response.setStatusCode(404); //第一步:设置响应的状态代码404.
File notFoundPage = new File("webapps/sys/404.html"); //第二步:设置错误页面
response.setEntity(notFoundPage);
}
response.flush(); //响应客户端
}catch(Exception e) {
}finally {
try { //与客户端断开连接
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|
/*
* $Id$
*/
/*
Copyright (c) 2000-2012 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
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
STANFORD UNIVERSITY 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.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.crawler;
import java.io.*;
import java.util.*;
import java.net.*;
import org.lockss.config.Configuration;
import org.lockss.daemon.*;
import org.lockss.config.*;
import org.lockss.plugin.*;
import org.lockss.protocol.*;
import org.lockss.state.*;
import org.lockss.util.*;
import org.lockss.util.urlconn.*;
import org.lockss.clockss.*;
import org.lockss.test.*;
import org.lockss.test.MockCrawler.MockCrawlerFacade;
import org.lockss.crawler.BaseCrawler.StorePermissionScheme;
/**
* This is the test class for org.lockss.crawler.BaseCrawler
*
* @author Thomas S. Robertson
* @version 0.0
*/
public class TestBaseCrawler extends LockssPermissionCheckerTestCase {
// private PermissionChecker checker;
private MockLockssDaemon theDaemon;
private CrawlManagerImpl crawlMgr;
private MockArchivalUnit mau = null;
private List startUrls = null;
// private Crawler crawler = null;
private TestableBaseCrawler crawler = null;
public static final String EMPTY_PAGE = "";
public static final String LINKLESS_PAGE = "Nothing here";
public static final String startUrl = "http://www.example.com/index.html";
private MockCrawlRule crawlRule;
private MockAuState aus = new MockAuState();
private MockLinkExtractor extractor = new MockLinkExtractor();
private static final String PARAM_RETRY_TIMES =
BaseCrawler.PARAM_DEFAULT_RETRY_COUNT;
private static final int DEFAULT_RETRY_TIMES =
BaseCrawler.DEFAULT_DEFAULT_RETRY_COUNT;
private MockCachedUrlSet cus;
private String permissionPage = "http://example.com/permission.html";
private String permissionPage2 = "http://example.com/permission2.html";
private MockCrawlerFacade mcf;
private MockNodeManager nodeMgr;
public static Class testedClasses[] = {
org.lockss.crawler.BaseCrawler.class
};
public void setUp() throws Exception {
super.setUp();
TimeBase.setSimulated(10);
theDaemon = getMockLockssDaemon();
crawlMgr = new NoPauseCrawlManagerImpl();
theDaemon.setCrawlManager(crawlMgr);
crawlMgr.initService(theDaemon);
theDaemon.getAlertManager();
mau = new MockArchivalUnit();
mau.setPlugin(new MockPlugin(theDaemon));
startUrls = ListUtil.list(startUrl);
cus = new MyMockCachedUrlSet(mau, null);
mau.setAuCachedUrlSet(cus);
crawlRule = new MockCrawlRule();
crawlRule.addUrlToCrawl(startUrl);
crawlRule.addUrlToCrawl(permissionPage);
mau.setStartUrls(startUrls);
mau.setPermissionUrls(ListUtil.list(permissionPage));
mau.setCrawlRule(crawlRule);
crawler = new TestableBaseCrawler(mau, aus);
mcf = new MockCrawler().new MockCrawlerFacade(mau);
List checkers = ListUtil.list(new MyMockPermissionChecker(true));
crawler.setDaemonPermissionCheckers(checkers);
mau.setLinkExtractor("text/html", extractor);
mau.addUrl(startUrl);
mau.addUrl(permissionPage);
Properties p = new Properties();
p.setProperty(BaseCrawler.PARAM_DEFAULT_RETRY_DELAY, "0");
ConfigurationUtil.setCurrentConfigFromProps(p);
}
public void testConstructorNullAu() {
try {
new TestableBaseCrawler(null, aus);
fail("Trying to create a BaseCrawler with a null au should throw");
} catch (IllegalArgumentException e) {
}
}
public void testConstructorNullAuState() {
try {
new TestableBaseCrawler(mau, null);
fail("Trying to create a BaseCrawler with a null aus should throw");
} catch (IllegalArgumentException e) {
}
}
public void testIsSupportedUrlProtocol() {
assertTrue(BaseCrawler.isSupportedUrlProtocol("http://www.example.com"));
assertTrue(BaseCrawler.isSupportedUrlProtocol("HTTP://www.example.com"));
assertFalse(BaseCrawler.isSupportedUrlProtocol("ftp://www.example.com"));
assertFalse(BaseCrawler.isSupportedUrlProtocol("gopher://www.example.com"));
assertTrue(BaseCrawler.isSupportedUrlProtocol("https://www.example.com"));
}
public void testIsIgnoredException() {
assertTrue(crawler.isIgnoredException(null));
assertTrue(crawler.isIgnoredException(new CacheSuccess()));
assertFalse(crawler.isIgnoredException(new CacheException.RetryableException()));
}
public void testGetAu() {
assertSame(mau, crawler.getAu());
}
public void testDoCrawlSignalsEndOfCrawl() {
TestableBaseCrawler crawler = new TestableBaseCrawler(mau, aus);
crawler.doCrawl();
MockCrawlStatus status = (MockCrawlStatus)crawler.getCrawlerStatus();
assertTrue(status.crawlEndSignaled());
}
public void testDoCrawlSignalsEndOfCrawlExceptionThrown() {
TestableBaseCrawler crawler = new TestableBaseCrawler(mau, aus);
crawler.setDoCrawlThrowException(new ExpectedRuntimeException("Blah"));
try {
crawler.doCrawl();
} catch (RuntimeException e) {
//don't do anything with it, since we're causing it to be thrown
}
MockCrawlStatus status = (MockCrawlStatus)crawler.getCrawlerStatus();
assertTrue(status.crawlEndSignaled());
}
void setupAuState() {
MockNodeManager nodeManager = new MockNodeManager();
getMockLockssDaemon().setNodeManager(nodeManager, mau);
nodeManager.setAuState(aus);
}
public void testWholeCrawlUpdatesLastCrawlTime() {
setupAuState();
long lastCrawlTime = aus.getLastCrawlTime();
TestableBaseCrawler crawler = new TestableBaseCrawler(mau, aus);
crawler.setWholeAu(true);
crawler.doCrawl();
assertNotEquals(lastCrawlTime, aus.getLastCrawlTime());
}
public void testPartialCrawlDoesntUpdateLastCrawlTime() {
setupAuState();
long lastCrawlTime = aus.getLastCrawlTime();
TestableBaseCrawler crawler = new TestableBaseCrawler(mau, aus);
crawler.setWholeAu(false);
crawler.doCrawl();
assertEquals(lastCrawlTime, aus.getLastCrawlTime());
}
public void testFailedCrawlDoesntUpdateLastCrawlTime() {
setupAuState();
long lastCrawlTime = aus.getLastCrawlTime();
TestableBaseCrawler crawler = new TestableBaseCrawler(mau, aus);
crawler.setWholeAu(true);
crawler.setResult(false);
crawler.doCrawl();
assertEquals(lastCrawlTime, aus.getLastCrawlTime());
}
public void testThrowingCrawlDoesntUpdateLastCrawlTime() {
setupAuState();
long lastCrawlTime = aus.getLastCrawlTime();
TestableBaseCrawler crawler = new TestableBaseCrawler(mau, aus);
crawler.setWholeAu(true);
crawler.setDoCrawlThrowException(new ExpectedRuntimeException("Blah"));
try {
crawler.doCrawl();
} catch (RuntimeException e) {
// expected
}
assertEquals(lastCrawlTime, aus.getLastCrawlTime());
}
public void testWholeCrawlUpdatesLastCrawlAttempt() {
setupAuState();
long lastCrawlAttempt = aus.getLastCrawlAttempt();
TestableBaseCrawler crawler = new TestableBaseCrawler(mau, aus);
crawler.setWholeAu(true);
crawler.doCrawl();
assertNotEquals(lastCrawlAttempt, aus.getLastCrawlAttempt());
}
public void testPartialCrawlDoesntUpdateLastCrawlAttempt() {
setupAuState();
long lastCrawlAttempt = aus.getLastCrawlAttempt();
TestableBaseCrawler crawler = new TestableBaseCrawler(mau, aus);
crawler.setWholeAu(false);
crawler.doCrawl();
assertEquals(lastCrawlAttempt, aus.getLastCrawlAttempt());
}
public void testFailedCrawlUpdatesLastCrawlAttempt() {
setupAuState();
long lastCrawlAttempt = aus.getLastCrawlAttempt();
TestableBaseCrawler crawler = new TestableBaseCrawler(mau, aus);
crawler.setWholeAu(true);
crawler.setResult(false);
crawler.doCrawl();
assertNotEquals(lastCrawlAttempt, aus.getLastCrawlAttempt());
}
public void testThrowingCrawlUpdatesLastCrawlAttempt() {
setupAuState();
long lastCrawlAttempt = aus.getLastCrawlAttempt();
TestableBaseCrawler crawler = new TestableBaseCrawler(mau, aus);
crawler.setWholeAu(true);
crawler.setDoCrawlThrowException(new ExpectedRuntimeException("Blah"));
try {
crawler.doCrawl();
} catch (RuntimeException e) {
// expected
}
assertNotEquals(lastCrawlAttempt, aus.getLastCrawlAttempt());
}
/**
* Subclasses rely on setWatchdog(wdog) assigning this value to the instance
* varable wdog, so we're testing it
*/
public void testSetWatchDog() {
LockssWatchdog wdog = new MockLockssWatchdog();
TestableBaseCrawler crawler = new TestableBaseCrawler(mau, aus);
crawler.setWatchdog(wdog);
assertSame(wdog, crawler.wdog);
}
public void testMakeUrlCacher() {
crawler.setCrawlConfig(ConfigManager.getCurrentConfig());
UrlCacher uc = crawler.makeUrlCacher(new UrlData(null, null, startUrl));
assertNotNull(uc);
MockUrlCacher muc = (MockUrlCacher)uc;
assertSame(crawler.getAu(), muc.getArchivalUnit());
}
public void testUrlCacherWatchDog() {
MockLockssWatchdog wdog = new MockLockssWatchdog();
TestableBaseCrawler crawler = new TestableBaseCrawler(mau, aus);
crawler.setWatchdog(wdog);
UrlCacher uc = crawler.makeUrlCacher(
new UrlData(new StringInputStream("hello"),
new CIProperties(), startUrl));
assertSame(wdog, uc.getWatchdog());
}
public void testUrlFetcherWatchDog() {
MockLockssWatchdog wdog = new MockLockssWatchdog();
TestableBaseCrawler crawler = new TestableBaseCrawler(mau, aus);
crawler.setWatchdog(wdog);
UrlFetcher uf = crawler.makeUrlFetcher(startUrl);
assertSame(wdog, uf.getWatchdog());
}
StorePermissionScheme getConfigPermissionScheme() {
Configuration config = ConfigManager.getCurrentConfig();
return (StorePermissionScheme)
config.getEnum(StorePermissionScheme.class,
BaseCrawler.PARAM_STORE_PERMISSION_SCHEME,
BaseCrawler.DEFAULT_STORE_PERMISSION_SCHEME);
}
public void testMakePermissionUrlFetcherLegacy() {
assertEquals(StorePermissionScheme.Legacy, getConfigPermissionScheme());
crawlMgr.newCrawlRateLimiter(mau);
crawler.setCrawlConfig(ConfigManager.getCurrentConfig());
UrlFetcher uf = crawler.makePermissionUrlFetcher(startUrl);
assertNotNull(uf);
assertFalse("UrlFetcher shouldn't be a ClockssUrlFetcher",
uf instanceof ClockssUrlFetcher);
MockUrlFetcher muf = (MockUrlFetcher)uf;
assertSame(crawler.getAu(), muf.getArchivalUnit());
assertNull(muf.getLocalAddress());
assertNotNull(muf.getCrawlRateLimiter());
assertEquals(UrlFetcher.REDIRECT_SCHEME_FOLLOW_ON_HOST,
muf.getRedirectScheme());
}
public void testMakeUrlFetcherCrawlFromAddr() {
ConfigurationUtil.addFromArgs(BaseCrawler.PARAM_CRAWL_FROM_ADDR,
"127.3.1.4");
crawler.setCrawlConfig(ConfigManager.getCurrentConfig());
UrlFetcher uf = crawler.makeUrlFetcher(startUrl);
assertNotNull(uf);
assertFalse("UrlFetcher shouldn't be a ClockssUrlFetcher",
uf instanceof ClockssUrlFetcher);
MockUrlFetcher muf = (MockUrlFetcher)uf;
assertSame(crawler.getAu(), muf.getArchivalUnit());
assertEquals("127.3.1.4", muf.getLocalAddress().getHostAddress());
}
public void testMakeUrlFetcherCrawlFromLocalAddr() {
ConfigurationUtil.addFromArgs(BaseCrawler.PARAM_CRAWL_FROM_LOCAL_ADDR,
"true",
IdentityManager.PARAM_LOCAL_IP,
"127.1.2.3");
crawler.setCrawlConfig(ConfigManager.getCurrentConfig());
UrlFetcher uf = crawler.makeUrlFetcher(startUrl);
assertNotNull(uf);
assertFalse("UrlFetcher shouldn't be a ClockssUrlFetcher",
uf instanceof ClockssUrlFetcher);
MockUrlFetcher muf = (MockUrlFetcher)uf;
assertEquals("127.1.2.3", muf.getLocalAddress().getHostAddress());
}
public void testMakeUrlFetcherCrawlFromAddrPrecedence() {
ConfigurationUtil.addFromArgs(BaseCrawler.PARAM_CRAWL_FROM_ADDR,
"127.3.1.4",
BaseCrawler.PARAM_CRAWL_FROM_LOCAL_ADDR,
"true",
IdentityManager.PARAM_LOCAL_IP,
"127.1.2.3");
crawler.setCrawlConfig(ConfigManager.getCurrentConfig());
UrlFetcher uf = crawler.makeUrlFetcher(startUrl);
assertNotNull(uf);
assertFalse("UrlFetcher shouldn't be a ClockssUrlFetcher",
uf instanceof ClockssUrlFetcher);
MockUrlFetcher muf = (MockUrlFetcher)uf;
assertNull(muf.getPreviousContentType());
assertEquals("127.3.1.4", muf.getLocalAddress().getHostAddress());
}
public void testMakeUrlFetcherClockss() {
ConfigurationUtil.setFromArgs(ConfigManager.PARAM_PLATFORM_PROJECT,
"clockss");
crawler.setCrawlConfig(ConfigManager.getCurrentConfig());
UrlFetcher uf = crawler.makeUrlFetcher(startUrl);
assertNotNull(uf);
assertTrue("UrlFetcher should be a ClockssUrlFetcher",
uf instanceof ClockssUrlFetcher);
}
public void testMakeUrlFetcherWithMimeType() {
crawler.previousContentType = "app/foo";
UrlFetcher uf = crawler.makeUrlFetcher(startUrl);
assertNotNull(uf);
assertFalse("UrlFetcher shouldn't be a ClockssUrlFetcher",
uf instanceof ClockssUrlFetcher);
MockUrlFetcher muf = (MockUrlFetcher)uf;
assertEquals("app/foo", muf.getPreviousContentType());
UrlFetcher uf2 = crawler.makeUrlFetcher(permissionPage);
assertEquals("app/foo", ((MockUrlFetcher)uf2).getPreviousContentType());
}
// public void testGetPermissionMap() throws MalformedURLException {
// Set cachedUrls = cus.getCachedUrls();
// assertSameElements(ListUtil.list(), cachedUrls);
//
// PermissionMap pMap = crawler.getPermissionMap();
// assertNotNull(pMap);
// assertEquals(PermissionRecord.PERMISSION_OK,
// pMap.getStatus("http://example.com/blah.html"));
//
// //verify that it fetched the permission page
// cachedUrls = cus.getCachedUrls();
// assertSameElements(ListUtil.list(permissionPage), cachedUrls);
// }
private boolean hasPermission(String page) throws IOException {
return MiscTestUtil.hasPermission(crawler.getDaemonPermissionCheckers(),
page, mcf);
}
public void testGetDaemonPermissionCheckers() throws IOException {
nodeMgr = new MockNodeManager();
nodeMgr.setAuState(aus);
theDaemon.setNodeManager(new MockNodeManager(), mau);
crawler.setDaemonPermissionCheckers(null);
assertTrue(hasPermission(LockssPermission.LOCKSS_PERMISSION_STRING));
assertFalse(hasPermission(ClockssPermission.CLOCKSS_PERMISSION_STRING));
ConfigurationUtil.setFromArgs(ConfigManager.PARAM_PLATFORM_PROJECT,
"clockss");
crawler.setDaemonPermissionCheckers(null);
assertFalse(hasPermission(LockssPermission.LOCKSS_PERMISSION_STRING));
assertTrue(hasPermission(ClockssPermission.CLOCKSS_PERMISSION_STRING));
ConfigurationUtil.setFromArgs(ConfigManager.PARAM_PLATFORM_PROJECT,
"lockss");
crawler.setDaemonPermissionCheckers(null);
assertTrue(hasPermission(LockssPermission.LOCKSS_PERMISSION_STRING));
assertFalse(hasPermission(ClockssPermission.CLOCKSS_PERMISSION_STRING));
}
public void testToString() {
assertTrue(crawler.toString().startsWith("[BaseCrawler:"));
}
public void testAbortedCrawlDoesntStart() {
String url1= "http://www.example.com/link1.html";
String url2= "http://www.example.com/link2.html";
String url3= "http://www.example.com/link3.html";
MockCachedUrlSet cus = (MockCachedUrlSet)mau.getAuCachedUrlSet();
extractor.addUrlsToReturn(url1, SetUtil.set(url1, url2, url3));
mau.addUrl(startUrl);
mau.addUrl(url1);
mau.addUrl(url2);
mau.addUrl(url3);
crawler.abortCrawl();
assertFalse(crawler.doCrawl());
assertEmpty(cus.getCachedUrls());
// assertFalse(crawler.doCrawl0Called());
}
public void testReturnsTrueWhenCrawlSuccessful() {
MockCachedUrlSet cus = (MockCachedUrlSet)mau.getAuCachedUrlSet();
String url1="http://www.example.com/blah.html";
mau.addUrl(startUrl, false, true);
extractor.addUrlsToReturn(startUrl, SetUtil.set(url1));
mau.addUrl(url1, false, true);
assertTrue(crawler.doCrawl());
}
// public void testReturnsFalseWhenFailingUnretryableExceptionThrown() {
// MockCachedUrlSet cus = (MockCachedUrlSet)mau.getAuCachedUrlSet();
// String url1="http://www.example.com/blah.html";
// mau.addUrl(startUrl, false, true);
// extractor.addUrlsToReturn(startUrl, SetUtil.set(url1));
// MyMockUnretryableCacheException exception =
// new MyMockUnretryableCacheException("Test exception");
// mau.addUrl(url1, exception, DEFAULT_RETRY_TIMES);
// crawlRule.addUrlToCrawl(url1);
// assertFalse(crawler.doCrawl());
// }
// public void testReturnsFalseWhenIOExceptionThrown() {
// MockCachedUrlSet cus = (MockCachedUrlSet)mau.getAuCachedUrlSet();
// String url1="http://www.example.com/blah.html";
// mau.addUrl(startUrl, false, true);
// extractor.addUrlsToReturn(startUrl, SetUtil.set(url1));
// mau.addUrl(url1, new IOException("Test exception"), DEFAULT_RETRY_TIMES);
// crawlRule.addUrlToCrawl(url1);
// assertFalse(crawler.doCrawl());
// }
// public void testReturnsTrueWhenNonFailingUnretryableExceptionThrown() {
// MockCachedUrlSet cus = (MockCachedUrlSet)mau.getAuCachedUrlSet();
// String url1="http://www.example.com/blah.html";
// mau.addUrl(startUrl, false, true);
// extractor.addUrlsToReturn(startUrl, SetUtil.set(url1));
// MyMockCacheException exception = new MyMockCacheException("Test exception");
// mau.addUrl(url1, exception, DEFAULT_RETRY_TIMES);
// crawlRule.addUrlToCrawl(url1);
// assertTrue(crawler.doCrawl());
// }
// public void testReturnsRetriesWhenRetryableExceptionThrown() {
// MockCachedUrlSet cus = (MockCachedUrlSet)mau.getAuCachedUrlSet();
// String url1="http://www.example.com/blah.html";
// mau.addUrl(startUrl, false, true);
// extractor.addUrlsToReturn(startUrl, SetUtil.set(url1));
// MyMockRetryableCacheException exception =
// new MyMockRetryableCacheException("Test exception");
// mau.addUrl(url1, exception, DEFAULT_RETRY_TIMES-1);
// crawlRule.addUrlToCrawl(url1);
// crawler.doCrawl();
// Set expected = SetUtil.set(startUrl, url1);
// assertEquals(expected, cus.getCachedUrls());
// }
// public void testReturnsDoesntRetryWhenUnretryableExceptionThrown() {
// MockCachedUrlSet cus = (MockCachedUrlSet)mau.getAuCachedUrlSet();
// String url1="http://www.example.com/blah.html";
// mau.addUrl(startUrl, false, true);
// extractor.addUrlsToReturn(startUrl, SetUtil.set(url1));
// MyMockUnretryableCacheException exception =
// new MyMockUnretryableCacheException("Test exception");
// mau.addUrl(url1, exception, DEFAULT_RETRY_TIMES-1);
// crawlRule.addUrlToCrawl(url1);
// crawler.doCrawl();
// Set expected = SetUtil.set(startUrl);
// assertEquals(expected, cus.getCachedUrls());
// }
// public void testRetryNumSetByParam() {
// int retryNum = DEFAULT_RETRY_TIMES + 3;
// assertTrue("Test is worthless unless retryNum is greater than "
// +"DEFAULT_RETRY_TIMES", retryNum > DEFAULT_RETRY_TIMES);
// Properties p = new Properties();
// p.setProperty(PARAM_RETRY_TIMES, String.valueOf(retryNum));
// p.setProperty(NewContentCrawler.PARAM_DEFAULT_RETRY_DELAY, "0");
// ConfigurationUtil.setCurrentConfigFromProps(p);
// MockCachedUrlSet cus = (MockCachedUrlSet)mau.getAuCachedUrlSet();
// String url1="http://www.example.com/blah.html";
// mau.addUrl(startUrl, false, true);
// extractor.addUrlsToReturn(startUrl, SetUtil.set(url1));
// mau.addUrl(url1,
// new MyMockRetryableCacheException("Test exception"),
// retryNum-1);
// crawlRule.addUrlToCrawl(url1);
// crawler.doCrawl();
// Set expected = SetUtil.set(startUrl, url1);
// assertEquals(expected, cus.getCachedUrls());
// }
// public void testCachesFailedFetches() {
// int retryNum = 3;
// Properties p = new Properties();
// p.setProperty(PARAM_RETRY_TIMES, String.valueOf(retryNum));
// p.setProperty(NewContentCrawler.PARAM_DEFAULT_RETRY_DELAY, "0");
// ConfigurationUtil.setCurrentConfigFromProps(p);
// MyMockCachedUrlSet cus = (MyMockCachedUrlSet)mau.getAuCachedUrlSet();
// String url1="http://www.example.com/blah.html";
// String url2="http://www.example.com/blah2.html";
// String url3="http://www.example.com/blah3.html";
// mau.addUrl(startUrl, false, true);
// extractor.addUrlsToReturn(startUrl, SetUtil.set(url1, url2, url3));
// mau.addUrl(url2,
// new CacheException.UnretryableException("Test exception"),
// retryNum);
// extractor.addUrlsToReturn(url2, SetUtil.set(url1));
// mau.addUrl(url3,
// new CacheException.RetryableException("Test exception"),
// retryNum);
// extractor.addUrlsToReturn(url3, SetUtil.set(url1));
// mau.addUrl(url1, new IOException("Test exception"), retryNum);
// crawlRule.addUrlToCrawl(url1);
// crawlRule.addUrlToCrawl(url2);
// crawlRule.addUrlToCrawl(url3);
// crawler.doCrawl();
// // IOException should not be retried
// assertEquals(1, cus.getNumCacheAttempts(url1));
// // UnretryableException should not be retried
// assertEquals(1, cus.getNumCacheAttempts(url2));
// // RetryableException should be retried
// assertEquals(retryNum, cus.getNumCacheAttempts(url3));
// }
// public void testReturnsTrueWhenNonFailingExceptionThrown() {
// MockCachedUrlSet cus = (MockCachedUrlSet)mau.getAuCachedUrlSet();
// String url1="http://www.example.com/blah.html";
// mau.addUrl(startUrl, false, true);
// extractor.addUrlsToReturn(startUrl, SetUtil.set(url1));
// mau.addUrl(url1, new FileNotFoundException("Test exception"), 0);
// crawlRule.addUrlToCrawl(url1);
// assertTrue(crawler.doCrawl());
// }
// public void testPluginThrowsRuntimeException() {
// MockCachedUrlSet cus = (MockCachedUrlSet)mau.getAuCachedUrlSet();
// String url1="http://www.example.com/blah.html";
// mau.addUrl(startUrl, false, true);
// extractor.addUrlsToReturn(startUrl, SetUtil.set(url1));
// mau.addUrl(url1, new ExpectedRuntimeException("Test exception"), 0);
// crawlRule.addUrlToCrawl(url1);
// assertFalse(crawler.doCrawl());
// }
public void testGetStatusCrawlNotStarted() {
CrawlerStatus crawlStatus = crawler.getCrawlerStatus();
assertEquals(-1, crawlStatus.getStartTime());
assertEquals(-1, crawlStatus.getEndTime());
assertEquals(0, crawlStatus.getNumFetched());
assertEquals(0, crawlStatus.getNumParsed());
}
public void testGetStatusCrawlDone() {
String url1 = "http://www.example.com/link1.html";
String url2 = "http://www.example.com/link2.html";
String url3 = "http://www.example.com/link3.html";
MockCachedUrlSet cus = (MockCachedUrlSet)mau.getAuCachedUrlSet();
mau.addUrl(startUrl);
extractor.addUrlsToReturn(startUrl, SetUtil.set(url1, url2, url3));
mau.addUrl(url1);
mau.addUrl(url2);
mau.addUrl(url3);
crawlRule.addUrlToCrawl(url1);
crawlRule.addUrlToCrawl(url2);
crawlRule.addUrlToCrawl(url3);
long expectedStart = TimeBase.nowMs();
crawler.doCrawl();
long expectedEnd = TimeBase.nowMs();
CrawlerStatus crawlStatus = crawler.getCrawlerStatus();
assertEquals(expectedStart, crawlStatus.getStartTime());
assertEquals(expectedEnd, crawlStatus.getEndTime());
// assertEquals(5, crawlStatus.getNumFetched());
// assertEquals(4, crawlStatus.getNumParsed());
}
// public void testGetStatusIncomplete() {
// //System.out.println("CrawlStatus is " + crawler.getStatus().getCrawlStatus());
// assertEquals(Crawler.STATUS_INCOMPLETE,
// crawler.getStatus().getCrawlStatus());
// }
// public void testGetStatusSuccessful() {
// MockCachedUrlSet cus = (MockCachedUrlSet)mau.getAuCachedUrlSet();
// mau.addUrl(startUrl);
// crawler.doCrawl();
// assertEquals(Crawler.STATUS_SUCCESSFUL,
// crawler.getStatus().getCrawlStatus());
// }
// public void testGetStatusError() {
// MockCachedUrlSet cus = (MockCachedUrlSet)mau.getAuCachedUrlSet();
// String url1="http://www.example.com/blah.html";
// mau.addUrl(startUrl, false, true);
// extractor.addUrlsToReturn(startUrl, SetUtil.set(url1));
// mau.addUrl(url1, new IOException("Test exception"), DEFAULT_RETRY_TIMES);
// crawlRule.addUrlToCrawl(url1);
// crawler.doCrawl();
// assertEquals(Crawler.STATUS_ERROR,
// crawler.getStatus().getCrawlStatus());
// }
// public void testCrawlWindow() {
// String url1 = "http://www.example.com/link1.html";
// String url2 = "http://www.example.com/link2.html";
// String url3 = "http://www.example.com/link3.html";
// CrawlSpec spec = new CrawlSpec(startUrl, crawlRule);
// spec.setCrawlWindow(new MockCrawlWindowThatCountsDown(3));
// mau.setCrawlSpec(spec);
// MockCachedUrlSet cus = (MockCachedUrlSet)mau.getAuCachedUrlSet();
// mau.addUrl(startUrl);
// extractor.addUrlsToReturn(startUrl, SetUtil.set(url1, url2, url3));
// mau.addUrl(url1);
// mau.addUrl(url2);
// mau.addUrl(url3);
// crawlRule.addUrlToCrawl(url1);
// crawlRule.addUrlToCrawl(url2);
// crawlRule.addUrlToCrawl(url3);
// crawler = new TestableBaseCrawler(mau, spec, aus);
// // crawler = new NewContentCrawler(mau, spec, new MockAuState());
// ((BaseCrawler)crawler).daemonPermissionCheckers = ListUtil.list(new MockPermissionChecker(true));
// mau.setLinkExtractor(extractor);
// crawler.doCrawl();
// // only gets 2 urls because start url is fetched twice (manifest & parse)
// Set expected = SetUtil.set(startUrl, url1);
// assertEquals(expected, cus.getCachedUrls());
// }
private class MockCrawlWindowThatCountsDown implements CrawlWindow {
int counter;
public MockCrawlWindowThatCountsDown(int counter) {
this.counter = counter;
}
public int getCurrentCount() {
return counter;
}
public boolean canCrawl() {
if (counter > 0) {
counter--;
return true;
}
return false;
}
public boolean canCrawl(Date serverDate) {
return canCrawl();
}
public boolean crawlIsPossible() {
return true;
}
}
private class MyMockPermissionChecker implements PermissionChecker {
boolean permission = false;
MyMockPermissionChecker(boolean permission) {
this.permission = permission;
}
/**
* checkPermission
*
* @param reader Reader
* @return boolean
*/
public boolean checkPermission(Crawler.CrawlerFacade crawlFacade,
Reader reader, String permissionUrl) {
return permission;
}
public void setPermission(boolean permission) {
this.permission = permission;
}
}
private class MyMockCacheException
extends CacheException {
public MyMockCacheException(String msg) {
super(msg);
}
public void setFailing() {
attributeBits.set(CacheException.ATTRIBUTE_FAIL);
}
}
private class MyMockRetryableCacheException
extends CacheException.RetryableException {
public MyMockRetryableCacheException(String msg) {
super(msg);
}
// public void setFailing() {
// attributeBits.set(CacheException.ATTRIBUTE_FAIL);
// }
}
private class MyMockUnretryableCacheException
extends CacheException.UnretryableException {
public MyMockUnretryableCacheException(String msg) {
super(msg);
}
// public void setFailing() {
// attributeBits.set(CacheException.ATTRIBUTE_FAIL);
// }
}
private class MyMockCachedUrlSet extends MockCachedUrlSet {
public MyMockCachedUrlSet(MockArchivalUnit owner, CachedUrlSetSpec spec) {
super(owner, spec);
}
protected MockUrlCacher makeMockUrlCacher(String url,
MockArchivalUnit parent) {
return new MockUrlCacherThatStepsTimebase(parent, new UrlData(null, null, url));
}
}
private class MockUrlCacherThatStepsTimebase extends MockUrlCacher {
public MockUrlCacherThatStepsTimebase(MockArchivalUnit au, UrlData ud) {
super(au, ud);
}
public void storeContent() throws IOException {
TimeBase.step();
super.storeContent();
}
}
private class TestableBaseCrawler extends BaseCrawler {
RuntimeException crawlExceptionToThrow = null;
boolean isWholeAU = false;
boolean result = true;
List<PermissionChecker> daemonPermissionCheckers;
protected TestableBaseCrawler(ArchivalUnit au, AuState aus) {
super(au, aus);
crawlStatus = new MockCrawlStatus();
setCrawlManager(TestBaseCrawler.this.crawlMgr);
}
public Crawler.Type getType() {
throw new UnsupportedOperationException("not implemented");
}
public String getTypeString() {
return "Testable";
}
public boolean isWholeAU() {
return isWholeAU;
}
void setWholeAu(boolean val) {
isWholeAU = val;
}
protected boolean doCrawl0() {
if (crawlExceptionToThrow != null) {
throw crawlExceptionToThrow;
}
return result;
}
public void setResult(boolean val) {
result = val;
}
List<PermissionChecker> getDaemonPermissionCheckers() {
if(daemonPermissionCheckers != null) {
return daemonPermissionCheckers;
}
return super.getDaemonPermissionCheckers();
}
public void setDaemonPermissionCheckers(List<PermissionChecker> pc) {
this.daemonPermissionCheckers = pc;
}
public void setDoCrawlThrowException(RuntimeException e) {
crawlExceptionToThrow = e;
}
}
public static void main(String[] argv) {
String[] testCaseList = {TestBaseCrawler.class.getName()};
junit.textui.TestRunner.main(testCaseList);
}
}
|
package org.galaxyproject.gxformat2.v19_09;
import org.galaxyproject.gxformat2.v19_09.utils.Savable;
/** Auto-generated interface for <I>https://w3id.org/cwl/cwl#OutputParameter</I><br> */
public interface OutputParameter extends Parameter, Savable {
/**
* Getter for property <I>https://w3id.org/cwl/salad#Documented/doc</I><br>
*
* <BLOCKQUOTE>
*
* A documentation string for this object, or an array of strings which should be concatenated. *
*
* </BLOCKQUOTE>
*/
Object getDoc();
}
|
/*******************************************************************************
* Copyright 2016 Intuit
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.intuit.wasabi.experimentobjects;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* A Class to hold a list of experiment labels for batch assignment
*/
public class ExperimentBatch {
@ApiModelProperty(required = true, value = "a list of experiment labels for batch assignment")
private Set<Experiment.Label> labels;
@ApiModelProperty(required = false, value = "a user profile for segmentation")
private Map<String, Object> profile;
@ApiModelProperty(required = false, value = "a user profile for personalization", hidden = true)
private Map<String, Object> personalizationParameters;
protected ExperimentBatch() {
super();
}
public static Builder newInstance() {
return new Builder();
}
public static Builder from(ExperimentBatch batch) {
return new Builder(batch);
}
public static class Builder {
private Builder() {
instance = new ExperimentBatch();
}
private Builder(ExperimentBatch other) {
this();
instance.labels = new HashSet<>(other.labels);
instance.profile = new HashMap<>(other.profile);
instance.personalizationParameters = new HashMap<>(other.personalizationParameters);
}
public ExperimentBatch build() {
ExperimentBatch result = instance;
instance = null;
return result;
}
public Builder withLabels(final Set<Experiment.Label> labels) {
instance.labels = labels;
return this;
}
public Builder withProfile(final Map<String, Object> profile) {
instance.profile = profile;
return this;
}
public Builder withPersonalizationParameters(final Map<String, Object> personalizationParameters) {
instance.personalizationParameters = personalizationParameters;
return this;
}
private ExperimentBatch instance;
}
public Set<Experiment.Label> getLabels() {
return labels;
}
public Map<String, Object> getProfile() {
return profile;
}
public Map<String, Object> getPersonalizationParameters() {
return personalizationParameters;
}
public void setProfile(Map<String, Object> profile) {
this.profile = profile;
}
public void setLabels(Set<Experiment.Label> labels) {
this.labels = labels;
}
@Override
public String toString() {
return "ExperimentBatch labels=" + labels
+ ", profile=" + profile
+ ", personalizationParameters=" + personalizationParameters;
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
@Override
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
}
|
package eu.daiad.scheduler.service.etl;
import eu.daiad.common.model.error.ApplicationException;
/**
* Provides methods for exporting data from HBASE and PostgreSQL
*/
public interface IDataExportService {
/**
* Exports data for a single user to a temporary file.
*
* @param query the query that selects the data to export.
* @return a unique token for downloading the exported file.
*
* @throws ApplicationException if the query execution or file creation fails.
*/
String export(UserDataExportQuery query) throws ApplicationException;
/**
* Exports data for a single utility to a file. Any exported data file is replaced.
*
* @param query the query that selects the data to export.
*
* @throws ApplicationException if the query execution or file creation fails.
*/
void export(UtilityDataExportQuery query) throws ApplicationException;
}
|
/*
* Copyright (C) 2012-2018 DuyHai DOAN
*
* 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 info.archinnov.achilles.internals.parser.context;
import java.util.List;
import java.util.Set;
import com.squareup.javapoet.TypeName;
public class FunctionsContext {
public final List<FunctionSignature> functionSignatures;
public final Set<TypeName> allUsedTypes;
public FunctionsContext(List<FunctionSignature> functionSignatures, Set<TypeName> allUsedTypes) {
this.functionSignatures = functionSignatures;
this.allUsedTypes = allUsedTypes;
}
}
|
package com.tencent.wxcloudrun.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tencent.wxcloudrun.config.ApiResponse;
import com.tencent.wxcloudrun.config.L;
import com.tencent.wxcloudrun.model.Order;
import com.tencent.wxcloudrun.model.Session;
import com.tencent.wxcloudrun.model.User;
import com.tencent.wxcloudrun.model.Warehouse;
import com.tencent.wxcloudrun.model.util.Cargo;
import com.tencent.wxcloudrun.model.util.OrderStatus;
import com.tencent.wxcloudrun.model.util.UserRole;
import com.tencent.wxcloudrun.service.OrderService;
import com.tencent.wxcloudrun.service.UserService;
import com.tencent.wxcloudrun.service.WarehouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
@RestController
@RequestMapping("/order")
public class OrderController {
final private OrderService orderService;
final private UserService userService;
final private WarehouseService warehouseService;
public OrderController(@Autowired OrderService orderService, @Autowired UserService userService, @Autowired WarehouseService warehouseService) {
this.orderService = orderService;
this.userService = userService;
this.warehouseService = warehouseService;
}
@GetMapping("/list")
public ApiResponse orderList(
@RequestParam(name = "session") String session,
@RequestParam(name = "creationDate", required = false) String creationDate,
@RequestParam(name = "targetDate", required = false) String targetDate,
@RequestParam(name = "status", required = false) int stat,
@RequestParam(name = "page", required = false, defaultValue = "0") int page,
@RequestParam(name = "pageSize", required = false, defaultValue = "20") int pageSize,
@RequestParam(name = "warehouseId", required = false) Integer warehouseId,
@RequestParam(name = "orderId", required = false) Integer orderId
) {
Optional<LocalDateTime> creationDatetime = Optional.empty();
if (!(creationDate == null || creationDate.length() == 0)) {
creationDatetime = Optional.of(LocalDateTime.parse(creationDate));
}
Optional<OrderStatus> status = Optional.empty();
if (stat != -1)
status = Optional.of(OrderStatus.from(stat));
Optional<Session> sop = userService.isUserLoggedIn(session);
if (!sop.isPresent()) {
return ApiResponse.error("请先登录");
}
Iterable<Order> orders = orderService.getListByParams(creationDatetime, status, sop.get().getUser(), PageRequest.of(page, pageSize));
List<JSONObject> ret = new ArrayList<>();
for (Order order :
orders) {
JSONObject object = new JSONObject();
object.put("id", order.getId());
object.put("senderName", order.getSenderName());
object.put("senderPhone", order.getSenderPhone());
object.put("warehouseId", order.getTargetWarehouse().getId());
JSONObject warehouse = new JSONObject();
warehouse.put("location", order.getTargetWarehouse().getLocation());
warehouse.put("name", order.getTargetWarehouse().getName());
warehouse.put("id", order.getTargetWarehouse().getId());
warehouse.put("description", order.getTargetWarehouse().getDescription());
object.put("warehouse", warehouse);
object.put("receiverId", order.getReceiverId());
object.put("creationDate", order.getCreationDate());
object.put("option", order.getOption());
object.put("targetTime", order.getTargetTime());
object.put("targetEndTime", order.getTargetTime().plusMinutes(order.getTargetWarehouse().getWorktimeConfig().getInterval()));
object.put("status", order.getStatus().value);
object.put("note", order.getNote());
ret.add(object);
}
return ApiResponse.ok(ret);
}
@GetMapping("/query")
public ApiResponse orderList(
@RequestParam(name = "session") String session,
@RequestParam(name = "creationDate", required = false) String creationDate,
@RequestParam(name = "targetDate", required = false) String targetDate,
@RequestParam(name = "receiverId", required = false) String receiverId,
@RequestParam(name = "status", required = false, defaultValue = "-1") int stat,
@RequestParam(name = "page", required = false, defaultValue = "0") int page,
@RequestParam(name = "pageSize", required = false, defaultValue = "20") int pageSize,
@RequestParam(name = "warehouseId", required = false, defaultValue = "-1") Integer warehouseId,
@RequestParam(name = "orderId", required = false, defaultValue = "-1") Integer orderId
) {
LocalDateTime timer = LocalDateTime.now();
Long interval = 0L;
LocalDateTime creationDatetime = null;
LocalDateTime targetDateTime = null;
if (!(creationDate == null || creationDate.length() == 0)) {
creationDatetime = LocalDateTime.parse(creationDate);
}
if (!(targetDate == null || targetDate.length() == 0)) {
targetDateTime = LocalDateTime.parse(targetDate);
}
Optional<Session> sop = userService.isUserLoggedIn(session);
if (!sop.isPresent()) {
return ApiResponse.error("请先登录");
}
interval = (LocalDateTime.now().toEpochSecond(ZoneOffset.UTC) - timer.toEpochSecond(ZoneOffset.UTC));
L.info("check took time:"+interval.toString());
User user = sop.get().getUser();
Page<Order> orders;
Integer whId = null;
Integer creatorId = null;
Integer oId = orderId <= 0 ? null : orderId;
switch (user.getRole()) {
case user:
case driver:
whId = warehouseId <= 0 ? null : warehouseId;
creatorId = user.getId();
break;
case warehouse_manager:
case warehouse_worker:
whId = user.getWarehouse().getId();
break;
case platform_manager:
whId = warehouseId <= 0 ? null : warehouseId;
break;
}
interval = (LocalDateTime.now().toEpochSecond(ZoneOffset.UTC) - timer.toEpochSecond(ZoneOffset.UTC));
L.info("prep took time:"+interval.toString());
orders = orderService.queryOrders(
whId,
receiverId,
oId,
creatorId,
stat < 0 ? null : stat,
targetDateTime,
creationDatetime,
PageRequest.of(page, pageSize)
);
interval = (LocalDateTime.now().toEpochSecond(ZoneOffset.UTC) - timer.toEpochSecond(ZoneOffset.UTC));
L.info("query took time:"+interval.toString());
List<JSONObject> ret = new ArrayList<>();
for (Order order :
orders) {
JSONObject object = new JSONObject();
object.put("id", order.getId());
object.put("senderName", order.getSenderName());
object.put("senderPhone", order.getSenderPhone());
object.put("warehouseId", order.getTargetWarehouse().getId());
JSONObject warehouse = new JSONObject();
warehouse.put("location", order.getTargetWarehouse().getLocation());
warehouse.put("name", order.getTargetWarehouse().getName());
warehouse.put("id", order.getTargetWarehouse().getId());
warehouse.put("description", order.getTargetWarehouse().getDescription());
object.put("warehouse", warehouse);
object.put("receiverId", order.getReceiverId());
object.put("creationDate", order.getCreationDate());
object.put("option", order.getOption());
object.put("targetTime", order.getTargetTime());
object.put("targetEndTime", order.getTargetTime().plusMinutes(order.getTargetWarehouse().getWorktimeConfig().getInterval()));
object.put("status", order.getStatus().value);
object.put("note", order.getNote());
ret.add(object);
}
interval = (LocalDateTime.now().toEpochSecond(ZoneOffset.UTC) - timer.toEpochSecond(ZoneOffset.UTC));
L.info("total took time:"+interval.toString());
return ApiResponse.ok(ret).paged(pageSize,page,orders.getTotalPages());
}
@GetMapping("/detail")
public ApiResponse detailOrder(@RequestParam(name = "session") String session, @RequestParam(name = "id") Integer id) {
Optional<Session> s = userService.isUserLoggedIn(session);
if (!s.isPresent()) {
return ApiResponse.error("请先登录");
}
Optional<Order> ord = orderService.getById(id);
if (!ord.isPresent()) {
return ApiResponse.error("订单不存在");
}
Order order = ord.get();
JSONObject object = new JSONObject();
object.put("id", order.getId());
object.put("senderName", order.getSenderName());
object.put("senderPhone", order.getSenderPhone());
object.put("warehouseId", order.getTargetWarehouse().getId());
JSONObject warehouse = new JSONObject();
warehouse.put("location", order.getTargetWarehouse().getLocation());
warehouse.put("name", order.getTargetWarehouse().getName());
warehouse.put("id", order.getTargetWarehouse().getId());
warehouse.put("description", order.getTargetWarehouse().getDescription());
object.put("warehouse", warehouse);
List<JSONObject> cgs = new ArrayList<>();
for (Cargo cargo: order.getCargos()) {
cgs.add(cargo.toJSON());
}
object.put("cargos", cgs);
object.put("receiverId", order.getReceiverId());
object.put("creationDate", order.getCreationDate());
object.put("option", order.getOption());
object.put("canEdit", canEdit(s.get(), order));
object.put("targetTime", order.getTargetTime());
object.put("targetEndTime", order.getTargetTime().plusMinutes(order.getTargetWarehouse().getWorktimeConfig().getInterval()));
object.put("status", order.getStatus().value);
object.put("note", order.getNote());
return ApiResponse.ok(object);
}
boolean canEdit(Session s, Order order) {
return (
(order.getCreator().getWxUnionId().equals(s.getUser().getWxUnionId())
&& order.getStatus() == OrderStatus.created)
|
((s.getUser().getRole() == UserRole.warehouse_manager || s.getUser().getRole() == UserRole.warehouse_worker)
&& order.getTargetWarehouse().getId() == s.getUser().getWarehouse().getId())
| s.getUser().getRole() == UserRole.platform_manager);
}
@PostMapping("/create")
public ApiResponse createOrder(@RequestParam(name = "session") String session, @RequestBody JSONObject body) {
Optional<Session> s = userService.isUserLoggedIn(session);
if (!s.isPresent()) {
return ApiResponse.error("请先登录");
}
User creator = s.get().getUser();
// if(creator.getRole() != UserRole.driver || creator.getRole() != UserRole.user){
// return ApiResponse.error("登录用户身份错误!");
// }
Order order = new Order();
order.setCreator(creator); // 1
order.setCreationDate(LocalDateTime.now());
return setOrderData(body, order, creator);
}
@PostMapping("/edit")
public ApiResponse editOrder(@RequestParam(name = "session") String session, @RequestBody JSONObject body) {
Optional<Session> sop = userService.isUserLoggedIn(session);
if (!sop.isPresent()) {
return ApiResponse.error("请先登录");
}
Optional<Order> ord = orderService.getById(body.getIntValue("id"));
if (!ord.isPresent()) {
return ApiResponse.error("订单不存在");
}
Order order = ord.get();
order.setLastModifiedDate(LocalDateTime.now());
// Optional<Warehouse> wh = warehouseService.findById(body.getIntValue("id"));
switch (sop.get().getUser().getRole()) {
case user:
case driver:
if (sop.get().getUser().getId() != order.getCreator().getId())
return ApiResponse.error("没有权限:不是您创建的订单");
if (order.getStatus() != OrderStatus.created) {
return ApiResponse.error("没有权限,管理员已锁定订单");
}
break;
case warehouse_manager:
case warehouse_worker:
if (sop.get().getUser().getWarehouse().getId() != order.getTargetWarehouse().getId()) {
return ApiResponse.error("没有权限:不是您仓库的订单");
}
case platform_manager:
break;
default:
return ApiResponse.error("没有权限!");
}
return setOrderData(body, order, sop.get().getUser());
}
private ApiResponse setOrderData(@RequestBody JSONObject body, Order order, User user) {
order.setSenderName(body.getString("senderName")); // 2
order.setSenderPhone(body.getString("senderPhone")); // 3
order.setReceiverId(body.getString("receiverId")); // 4
List<JSONObject> rawList = body.getJSONArray("cargos").toJavaList(JSONObject.class);
L.info(body.getJSONArray("cargos").toString());
List<Cargo> list = new ArrayList<Cargo>();
for (JSONObject jsonObject : rawList) {
list.add(Cargo.objectify(jsonObject.toString()));
}
order.setCargos(list); // 5
Optional<Warehouse> target = warehouseService.getById(body.getIntValue("warehouseId"));
if (!target.isPresent()) {
return ApiResponse.error("仓库不存在");
}
order.setTargetWarehouse(target.get()); // 6
order.setNote(body.getString("note"));
int newOption = (body.getIntValue("option")); // 7
if (newOption == 0) {
if (order.getId() == 0 || order.getOption() == 1) {
order.setOption(newOption);
order.setTargetTime(warehouseService.pickTimeFor(order));
}
} else {
order.setOption(newOption);
order.setTargetTime(LocalDateTime.parse(body.getString("targetTime").replace(" ", "T")));
}
if (order.getId() == 0) {
order.setStatus(OrderStatus.created);
} else if (user.getRole().value > 2) {
order.setStatus(OrderStatus.locked);
}
order = orderService.saveOrder(order);
if(order.getStatus() == OrderStatus.created){
userService.sendCreationMessage(order);
}
if(order.getStatus() == OrderStatus.locked){
userService.sendStatusChange(order);
}
JSONObject ret = new JSONObject();
ret.put("orderId", order.getId());
return ApiResponse.ok(ret);
}
@PostMapping("/status/edit")
public ApiResponse switchStatus(@RequestParam(name = "session") String session, @RequestBody JSONObject body) {
Optional<Session> sop = userService.isUserLoggedIn(session);
if (!sop.isPresent()) {
return ApiResponse.error("请先登录");
}
Optional<Order> ord = orderService.getById(body.getIntValue("orderId"));
if (!ord.isPresent()) {
return ApiResponse.error("订单不存在");
}
OrderStatus newStatus = OrderStatus.from(body.getIntValue("newStatus"));
Order order = ord.get();
User user = sop.get().getUser();
switch (user.getRole()) {
case user:
case driver:
if (order.getStatus() != OrderStatus.created && newStatus != OrderStatus.canceled) {
return ApiResponse.error("没有权限进行操作!");
}
break;
case warehouse_manager:
case warehouse_worker:
if (order.getTargetWarehouse().getId() != user.getWarehouse().getId()) {
return ApiResponse.error("没有权限,不是您仓库的订单");
}
break;
case platform_manager:
break;
default:
return ApiResponse.error("没有权限");
}
order.setStatus(newStatus);
if(newStatus == OrderStatus.delivered){
order.setArrivalTime(LocalDateTime.now());
}
order = orderService.saveOrder(order);
if(newStatus == OrderStatus.delivered){
userService.sendArrival(order);
}
return ApiResponse.ok();
}
}
|
/*
* 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.nifi.processors.grpc;
import org.apache.nifi.reporting.InitializationException;
import org.apache.nifi.ssl.SSLContextService;
import org.apache.nifi.ssl.StandardSSLContextService;
import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.Assert;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.grpc.stub.StreamObserver;
import io.netty.handler.ssl.ClientAuth;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
public class TestInvokeGRPC {
// ids placed on flowfiles and used to dictate response codes in the DummyFlowFileService below
private static final long ERROR = 500;
private static final long SUCCESS = 501;
private static final long RETRY = 502;
@Test
public void testSuccess() throws Exception {
final TestGRPCServer<DummyFlowFileService> server = new TestGRPCServer<>(DummyFlowFileService.class);
try {
final int port = TestGRPCServer.randomPort();
server.start(port);
final TestRunner runner = TestRunners.newTestRunner(InvokeGRPC.class);
runner.setProperty(InvokeGRPC.PROP_SERVICE_HOST, TestGRPCServer.HOST);
runner.setProperty(InvokeGRPC.PROP_SERVICE_PORT, String.valueOf(port));
final MockFlowFile mockFlowFile = new MockFlowFile(SUCCESS);
runner.enqueue(mockFlowFile);
runner.run();
runner.assertTransferCount(InvokeGRPC.REL_RESPONSE, 1);
runner.assertTransferCount(InvokeGRPC.REL_SUCCESS_REQ, 1);
runner.assertTransferCount(InvokeGRPC.REL_RETRY, 0);
runner.assertTransferCount(InvokeGRPC.REL_NO_RETRY, 0);
runner.assertTransferCount(InvokeGRPC.REL_FAILURE, 0);
final List<MockFlowFile> responseFiles = runner.getFlowFilesForRelationship(InvokeGRPC.REL_RESPONSE);
assertThat(responseFiles.size(), equalTo(1));
final MockFlowFile response = responseFiles.get(0);
response.assertAttributeEquals(InvokeGRPC.RESPONSE_CODE, String.valueOf(FlowFileReply.ResponseCode.SUCCESS));
response.assertAttributeEquals(InvokeGRPC.RESPONSE_BODY, "success");
response.assertAttributeEquals(InvokeGRPC.SERVICE_HOST, TestGRPCServer.HOST);
response.assertAttributeEquals(InvokeGRPC.SERVICE_PORT, String.valueOf(port));
final List<MockFlowFile> successFiles = runner.getFlowFilesForRelationship(InvokeGRPC.REL_SUCCESS_REQ);
assertThat(successFiles.size(), equalTo(1));
final MockFlowFile successFile = successFiles.get(0);
successFile.assertAttributeEquals(InvokeGRPC.RESPONSE_CODE, String.valueOf(FlowFileReply.ResponseCode.SUCCESS));
successFile.assertAttributeEquals(InvokeGRPC.RESPONSE_BODY, "success");
successFile.assertAttributeEquals(InvokeGRPC.SERVICE_HOST, TestGRPCServer.HOST);
successFile.assertAttributeEquals(InvokeGRPC.SERVICE_PORT, String.valueOf(port));
} finally {
server.stop();
}
}
@Test
public void testSuccessWithFlowFileContent() throws Exception {
final TestGRPCServer<DummyFlowFileService> server = new TestGRPCServer<>(DummyFlowFileService.class);
try {
final int port = TestGRPCServer.randomPort();
server.start(port);
final TestRunner runner = TestRunners.newTestRunner(InvokeGRPC.class);
runner.setProperty(InvokeGRPC.PROP_SERVICE_HOST, TestGRPCServer.HOST);
runner.setProperty(InvokeGRPC.PROP_SERVICE_PORT, String.valueOf(port));
runner.enqueue("content");
runner.run();
runner.assertTransferCount(InvokeGRPC.REL_RESPONSE, 1);
runner.assertTransferCount(InvokeGRPC.REL_SUCCESS_REQ, 1);
runner.assertTransferCount(InvokeGRPC.REL_RETRY, 0);
runner.assertTransferCount(InvokeGRPC.REL_NO_RETRY, 0);
runner.assertTransferCount(InvokeGRPC.REL_FAILURE, 0);
final List<MockFlowFile> responseFiles = runner.getFlowFilesForRelationship(InvokeGRPC.REL_RESPONSE);
assertThat(responseFiles.size(), equalTo(1));
final MockFlowFile response = responseFiles.get(0);
response.assertAttributeEquals(InvokeGRPC.RESPONSE_CODE, String.valueOf(FlowFileReply.ResponseCode.SUCCESS));
response.assertAttributeEquals(InvokeGRPC.RESPONSE_BODY, "content");
response.assertAttributeEquals(InvokeGRPC.SERVICE_HOST, TestGRPCServer.HOST);
response.assertAttributeEquals(InvokeGRPC.SERVICE_PORT, String.valueOf(port));
final List<MockFlowFile> successFiles = runner.getFlowFilesForRelationship(InvokeGRPC.REL_SUCCESS_REQ);
assertThat(successFiles.size(), equalTo(1));
final MockFlowFile successFile = successFiles.get(0);
successFile.assertAttributeEquals(InvokeGRPC.RESPONSE_CODE, String.valueOf(FlowFileReply.ResponseCode.SUCCESS));
successFile.assertAttributeEquals(InvokeGRPC.RESPONSE_BODY, "content");
successFile.assertAttributeEquals(InvokeGRPC.SERVICE_HOST, TestGRPCServer.HOST);
successFile.assertAttributeEquals(InvokeGRPC.SERVICE_PORT, String.valueOf(port));
} finally {
server.stop();
}
}
@Test
public void testSuccessAlwaysOutputResponse() throws Exception {
final TestGRPCServer<DummyFlowFileService> server = new TestGRPCServer<>(DummyFlowFileService.class);
try {
final int port = TestGRPCServer.randomPort();
server.start(port);
final TestRunner runner = TestRunners.newTestRunner(InvokeGRPC.class);
runner.setProperty(InvokeGRPC.PROP_SERVICE_HOST, TestGRPCServer.HOST);
runner.setProperty(InvokeGRPC.PROP_SERVICE_PORT, String.valueOf(port));
runner.setProperty(InvokeGRPC.PROP_OUTPUT_RESPONSE_REGARDLESS, "true");
final MockFlowFile mockFlowFile = new MockFlowFile(SUCCESS);
runner.enqueue(mockFlowFile);
runner.run();
runner.assertTransferCount(InvokeGRPC.REL_RESPONSE, 1);
runner.assertTransferCount(InvokeGRPC.REL_SUCCESS_REQ, 1);
runner.assertTransferCount(InvokeGRPC.REL_RETRY, 0);
runner.assertTransferCount(InvokeGRPC.REL_NO_RETRY, 0);
runner.assertTransferCount(InvokeGRPC.REL_FAILURE, 0);
final List<MockFlowFile> responseFiles = runner.getFlowFilesForRelationship(InvokeGRPC.REL_RESPONSE);
assertThat(responseFiles.size(), equalTo(1));
final MockFlowFile response = responseFiles.get(0);
response.assertAttributeEquals(InvokeGRPC.RESPONSE_CODE, String.valueOf(FlowFileReply.ResponseCode.SUCCESS));
response.assertAttributeEquals(InvokeGRPC.RESPONSE_BODY, "success");
response.assertAttributeEquals(InvokeGRPC.SERVICE_HOST, TestGRPCServer.HOST);
response.assertAttributeEquals(InvokeGRPC.SERVICE_PORT, String.valueOf(port));
final List<MockFlowFile> successFiles = runner.getFlowFilesForRelationship(InvokeGRPC.REL_SUCCESS_REQ);
assertThat(successFiles.size(), equalTo(1));
final MockFlowFile successFile = successFiles.get(0);
successFile.assertAttributeEquals(InvokeGRPC.RESPONSE_CODE, String.valueOf(FlowFileReply.ResponseCode.SUCCESS));
successFile.assertAttributeEquals(InvokeGRPC.RESPONSE_BODY, "success");
successFile.assertAttributeEquals(InvokeGRPC.SERVICE_HOST, TestGRPCServer.HOST);
successFile.assertAttributeEquals(InvokeGRPC.SERVICE_PORT, String.valueOf(port));
} finally {
server.stop();
}
}
@Test
public void testExceedMaxMessageSize() throws Exception {
final TestGRPCServer<DummyFlowFileService> server = new TestGRPCServer<>(DummyFlowFileService.class);
try {
final int port = TestGRPCServer.randomPort();
server.start(port);
final TestRunner runner = TestRunners.newTestRunner(InvokeGRPC.class);
runner.setProperty(InvokeGRPC.PROP_SERVICE_HOST, TestGRPCServer.HOST);
runner.setProperty(InvokeGRPC.PROP_SERVICE_PORT, String.valueOf(port));
// set max message size to 1B to force error
runner.setProperty(InvokeGRPC.PROP_MAX_MESSAGE_SIZE, "1B");
final MockFlowFile mockFlowFile = new MockFlowFile(SUCCESS);
runner.enqueue(mockFlowFile);
runner.run();
runner.assertTransferCount(InvokeGRPC.REL_RESPONSE, 0);
runner.assertTransferCount(InvokeGRPC.REL_SUCCESS_REQ, 0);
runner.assertTransferCount(InvokeGRPC.REL_RETRY, 0);
runner.assertTransferCount(InvokeGRPC.REL_NO_RETRY, 0);
runner.assertTransferCount(InvokeGRPC.REL_FAILURE, 1);
final List<MockFlowFile> responseFiles = runner.getFlowFilesForRelationship(InvokeGRPC.REL_FAILURE);
assertThat(responseFiles.size(), equalTo(1));
final MockFlowFile response = responseFiles.get(0);
response.assertAttributeEquals(InvokeGRPC.SERVICE_HOST, TestGRPCServer.HOST);
response.assertAttributeEquals(InvokeGRPC.SERVICE_PORT, String.valueOf(port));
// an exception should be thrown indicating that the max message size was exceeded.
response.assertAttributeEquals(InvokeGRPC.EXCEPTION_CLASS, "io.grpc.StatusRuntimeException");
} finally {
server.stop();
}
}
@Test
public void testRetry() throws Exception {
final TestGRPCServer<DummyFlowFileService> server = new TestGRPCServer<>(DummyFlowFileService.class);
try {
final int port = TestGRPCServer.randomPort();
server.start(port);
final TestRunner runner = TestRunners.newTestRunner(InvokeGRPC.class);
runner.setProperty(InvokeGRPC.PROP_SERVICE_HOST, TestGRPCServer.HOST);
runner.setProperty(InvokeGRPC.PROP_SERVICE_PORT, String.valueOf(port));
final MockFlowFile mockFlowFile = new MockFlowFile(RETRY);
runner.enqueue(mockFlowFile);
runner.run();
runner.assertTransferCount(InvokeGRPC.REL_RESPONSE, 0);
runner.assertTransferCount(InvokeGRPC.REL_SUCCESS_REQ, 0);
runner.assertTransferCount(InvokeGRPC.REL_RETRY, 1);
runner.assertTransferCount(InvokeGRPC.REL_NO_RETRY, 0);
runner.assertTransferCount(InvokeGRPC.REL_FAILURE, 0);
runner.assertPenalizeCount(1);
final List<MockFlowFile> responseFiles = runner.getFlowFilesForRelationship(InvokeGRPC.REL_RETRY);
assertThat(responseFiles.size(), equalTo(1));
final MockFlowFile response = responseFiles.get(0);
response.assertAttributeEquals(InvokeGRPC.RESPONSE_CODE, String.valueOf(FlowFileReply.ResponseCode.RETRY));
response.assertAttributeEquals(InvokeGRPC.RESPONSE_BODY, "retry");
response.assertAttributeEquals(InvokeGRPC.SERVICE_HOST, TestGRPCServer.HOST);
response.assertAttributeEquals(InvokeGRPC.SERVICE_PORT, String.valueOf(port));
} finally {
server.stop();
}
}
@Test
public void testRetryAlwaysOutputResponse() throws Exception {
final TestGRPCServer<DummyFlowFileService> server = new TestGRPCServer<>(DummyFlowFileService.class);
try {
final int port = TestGRPCServer.randomPort();
server.start(port);
final TestRunner runner = TestRunners.newTestRunner(InvokeGRPC.class);
runner.setProperty(InvokeGRPC.PROP_SERVICE_HOST, TestGRPCServer.HOST);
runner.setProperty(InvokeGRPC.PROP_SERVICE_PORT, String.valueOf(port));
runner.setProperty(InvokeGRPC.PROP_OUTPUT_RESPONSE_REGARDLESS, "true");
final MockFlowFile mockFlowFile = new MockFlowFile(RETRY);
runner.enqueue(mockFlowFile);
runner.run();
runner.assertTransferCount(InvokeGRPC.REL_RESPONSE, 1);
runner.assertTransferCount(InvokeGRPC.REL_SUCCESS_REQ, 0);
runner.assertTransferCount(InvokeGRPC.REL_RETRY, 1);
runner.assertTransferCount(InvokeGRPC.REL_NO_RETRY, 0);
runner.assertTransferCount(InvokeGRPC.REL_FAILURE, 0);
runner.assertPenalizeCount(1);
final List<MockFlowFile> retryFiles = runner.getFlowFilesForRelationship(InvokeGRPC.REL_RETRY);
assertThat(retryFiles.size(), equalTo(1));
final MockFlowFile retry = retryFiles.get(0);
retry.assertAttributeEquals(InvokeGRPC.RESPONSE_CODE, String.valueOf(FlowFileReply.ResponseCode.RETRY));
retry.assertAttributeEquals(InvokeGRPC.RESPONSE_BODY, "retry");
retry.assertAttributeEquals(InvokeGRPC.SERVICE_HOST, TestGRPCServer.HOST);
retry.assertAttributeEquals(InvokeGRPC.SERVICE_PORT, String.valueOf(port));
final List<MockFlowFile> responseFiles = runner.getFlowFilesForRelationship(InvokeGRPC.REL_RESPONSE);
assertThat(responseFiles.size(), equalTo(1));
final MockFlowFile response = responseFiles.get(0);
response.assertAttributeEquals(InvokeGRPC.RESPONSE_CODE, String.valueOf(FlowFileReply.ResponseCode.RETRY));
response.assertAttributeEquals(InvokeGRPC.RESPONSE_BODY, "retry");
response.assertAttributeEquals(InvokeGRPC.SERVICE_HOST, TestGRPCServer.HOST);
response.assertAttributeEquals(InvokeGRPC.SERVICE_PORT, String.valueOf(port));
} finally {
server.stop();
}
}
@Test
public void testNoRetryOnError() throws Exception {
final TestGRPCServer<DummyFlowFileService> server = new TestGRPCServer<>(DummyFlowFileService.class);
try {
final int port = TestGRPCServer.randomPort();
server.start(port);
final TestRunner runner = TestRunners.newTestRunner(InvokeGRPC.class);
runner.setProperty(InvokeGRPC.PROP_SERVICE_HOST, TestGRPCServer.HOST);
runner.setProperty(InvokeGRPC.PROP_SERVICE_PORT, String.valueOf(port));
final MockFlowFile mockFlowFile = new MockFlowFile(ERROR);
runner.enqueue(mockFlowFile);
runner.run();
runner.assertTransferCount(InvokeGRPC.REL_RESPONSE, 0);
runner.assertTransferCount(InvokeGRPC.REL_SUCCESS_REQ, 0);
runner.assertTransferCount(InvokeGRPC.REL_RETRY, 0);
runner.assertTransferCount(InvokeGRPC.REL_NO_RETRY, 1);
runner.assertTransferCount(InvokeGRPC.REL_FAILURE, 0);
final List<MockFlowFile> responseFiles = runner.getFlowFilesForRelationship(InvokeGRPC.REL_NO_RETRY);
assertThat(responseFiles.size(), equalTo(1));
final MockFlowFile response = responseFiles.get(0);
response.assertAttributeEquals(InvokeGRPC.RESPONSE_CODE, String.valueOf(FlowFileReply.ResponseCode.ERROR));
response.assertAttributeEquals(InvokeGRPC.RESPONSE_BODY, "error");
response.assertAttributeEquals(InvokeGRPC.SERVICE_HOST, TestGRPCServer.HOST);
response.assertAttributeEquals(InvokeGRPC.SERVICE_PORT, String.valueOf(port));
} finally {
server.stop();
}
}
@Test
public void testNoRetryOnErrorAlwaysOutputResponseAndPenalize() throws Exception {
final TestGRPCServer<DummyFlowFileService> server = new TestGRPCServer<>(DummyFlowFileService.class);
try {
final int port = TestGRPCServer.randomPort();
server.start(port);
final TestRunner runner = TestRunners.newTestRunner(InvokeGRPC.class);
runner.setProperty(InvokeGRPC.PROP_SERVICE_HOST, TestGRPCServer.HOST);
runner.setProperty(InvokeGRPC.PROP_SERVICE_PORT, String.valueOf(port));
runner.setProperty(InvokeGRPC.PROP_OUTPUT_RESPONSE_REGARDLESS, "true");
runner.setProperty(InvokeGRPC.PROP_PENALIZE_NO_RETRY, "true");
final MockFlowFile mockFlowFile = new MockFlowFile(ERROR);
runner.enqueue(mockFlowFile);
runner.run();
runner.assertTransferCount(InvokeGRPC.REL_RESPONSE, 1);
runner.assertTransferCount(InvokeGRPC.REL_SUCCESS_REQ, 0);
runner.assertTransferCount(InvokeGRPC.REL_RETRY, 0);
runner.assertTransferCount(InvokeGRPC.REL_NO_RETRY, 1);
runner.assertTransferCount(InvokeGRPC.REL_FAILURE, 0);
runner.assertPenalizeCount(1);
final List<MockFlowFile> noRetryFiles = runner.getFlowFilesForRelationship(InvokeGRPC.REL_NO_RETRY);
assertThat(noRetryFiles.size(), equalTo(1));
final MockFlowFile noRetry = noRetryFiles.get(0);
noRetry.assertAttributeEquals(InvokeGRPC.RESPONSE_CODE, String.valueOf(FlowFileReply.ResponseCode.ERROR));
noRetry.assertAttributeEquals(InvokeGRPC.RESPONSE_BODY, "error");
noRetry.assertAttributeEquals(InvokeGRPC.SERVICE_HOST, TestGRPCServer.HOST);
noRetry.assertAttributeEquals(InvokeGRPC.SERVICE_PORT, String.valueOf(port));
final List<MockFlowFile> responseFiles = runner.getFlowFilesForRelationship(InvokeGRPC.REL_RESPONSE);
assertThat(responseFiles.size(), equalTo(1));
final MockFlowFile response = responseFiles.get(0);
response.assertAttributeEquals(InvokeGRPC.RESPONSE_CODE, String.valueOf(FlowFileReply.ResponseCode.ERROR));
response.assertAttributeEquals(InvokeGRPC.RESPONSE_BODY, "error");
response.assertAttributeEquals(InvokeGRPC.SERVICE_HOST, TestGRPCServer.HOST);
response.assertAttributeEquals(InvokeGRPC.SERVICE_PORT, String.valueOf(port));
} finally {
server.stop();
}
}
@Test
public void testNoInput() throws Exception {
final TestGRPCServer<DummyFlowFileService> server = new TestGRPCServer<>(DummyFlowFileService.class);
try {
final int port = TestGRPCServer.randomPort();
server.start(port);
final TestRunner runner = TestRunners.newTestRunner(InvokeGRPC.class);
runner.setProperty(InvokeGRPC.PROP_SERVICE_HOST, TestGRPCServer.HOST);
runner.setProperty(InvokeGRPC.PROP_SERVICE_PORT, String.valueOf(port));
runner.run();
runner.assertTransferCount(InvokeGRPC.REL_RESPONSE, 0);
runner.assertTransferCount(InvokeGRPC.REL_SUCCESS_REQ, 0);
runner.assertTransferCount(InvokeGRPC.REL_RETRY, 0);
runner.assertTransferCount(InvokeGRPC.REL_NO_RETRY, 0);
runner.assertTransferCount(InvokeGRPC.REL_FAILURE, 0);
runner.assertPenalizeCount(0);
} finally {
server.stop();
}
}
@Test
public void testServerConnectionFail() throws Exception {
final int port = TestGRPCServer.randomPort();
// should be no gRPC server running @ that port, so processor will fail
final TestRunner runner = TestRunners.newTestRunner(InvokeGRPC.class);
runner.setProperty(InvokeGRPC.PROP_SERVICE_HOST, TestGRPCServer.HOST);
runner.setProperty(InvokeGRPC.PROP_SERVICE_PORT, Integer.toString(port));
final MockFlowFile mockFlowFile = new MockFlowFile(SUCCESS);
runner.enqueue(mockFlowFile);
runner.run();
runner.assertTransferCount(InvokeGRPC.REL_RESPONSE, 0);
runner.assertTransferCount(InvokeGRPC.REL_SUCCESS_REQ, 0);
runner.assertTransferCount(InvokeGRPC.REL_RETRY, 0);
runner.assertTransferCount(InvokeGRPC.REL_NO_RETRY, 0);
runner.assertTransferCount(InvokeGRPC.REL_FAILURE, 1);
final List<MockFlowFile> responseFiles = runner.getFlowFilesForRelationship(InvokeGRPC.REL_FAILURE);
assertThat(responseFiles.size(), equalTo(1));
final MockFlowFile response = responseFiles.get(0);
response.assertAttributeEquals(InvokeGRPC.SERVICE_HOST, TestGRPCServer.HOST);
response.assertAttributeEquals(InvokeGRPC.SERVICE_PORT, Integer.toString(port));
response.assertAttributeEquals(InvokeGRPC.EXCEPTION_CLASS, "io.grpc.StatusRuntimeException");
}
@Test
public void testSecureTwoWaySsl() throws Exception {
final Map<String, String> sslProperties = getKeystoreProperties();
sslProperties.putAll(getTruststoreProperties());
final TestGRPCServer<DummyFlowFileService> server = new TestGRPCServer<>(DummyFlowFileService.class, sslProperties);
try {
final int port = TestGRPCServer.randomPort();
final TestRunner runner = TestRunners.newTestRunner(InvokeGRPC.class);
runner.setProperty(InvokeGRPC.PROP_SERVICE_HOST, TestGRPCServer.HOST);
runner.setProperty(InvokeGRPC.PROP_SERVICE_PORT, String.valueOf(port));
runner.setProperty(InvokeGRPC.PROP_USE_SECURE, "true");
useSSLContextService(runner, sslProperties);
server.start(port);
final MockFlowFile mockFlowFile = new MockFlowFile(SUCCESS);
runner.enqueue(mockFlowFile);
runner.run();
runner.assertTransferCount(InvokeGRPC.REL_RESPONSE, 1);
runner.assertTransferCount(InvokeGRPC.REL_SUCCESS_REQ, 1);
runner.assertTransferCount(InvokeGRPC.REL_RETRY, 0);
runner.assertTransferCount(InvokeGRPC.REL_NO_RETRY, 0);
runner.assertTransferCount(InvokeGRPC.REL_FAILURE, 0);
final List<MockFlowFile> responseFiles = runner.getFlowFilesForRelationship(InvokeGRPC.REL_RESPONSE);
assertThat(responseFiles.size(), equalTo(1));
final MockFlowFile response = responseFiles.get(0);
response.assertAttributeEquals(InvokeGRPC.RESPONSE_CODE, String.valueOf(FlowFileReply.ResponseCode.SUCCESS));
response.assertAttributeEquals(InvokeGRPC.RESPONSE_BODY, "success");
response.assertAttributeEquals(InvokeGRPC.SERVICE_HOST, TestGRPCServer.HOST);
response.assertAttributeEquals(InvokeGRPC.SERVICE_PORT, String.valueOf(port));
final List<MockFlowFile> successFiles = runner.getFlowFilesForRelationship(InvokeGRPC.REL_SUCCESS_REQ);
assertThat(successFiles.size(), equalTo(1));
final MockFlowFile successFile = successFiles.get(0);
successFile.assertAttributeEquals(InvokeGRPC.RESPONSE_CODE, String.valueOf(FlowFileReply.ResponseCode.SUCCESS));
successFile.assertAttributeEquals(InvokeGRPC.RESPONSE_BODY, "success");
successFile.assertAttributeEquals(InvokeGRPC.SERVICE_HOST, TestGRPCServer.HOST);
successFile.assertAttributeEquals(InvokeGRPC.SERVICE_PORT, String.valueOf(port));
} finally {
server.stop();
}
}
@Test
public void testSecureOneWaySsl() throws Exception {
final Map<String, String> sslProperties = getKeystoreProperties();
sslProperties.put(TestGRPCServer.NEED_CLIENT_AUTH, ClientAuth.NONE.name());
final TestGRPCServer<DummyFlowFileService> server = new TestGRPCServer<>(DummyFlowFileService.class, sslProperties);
try {
final int port = TestGRPCServer.randomPort();
final TestRunner runner = TestRunners.newTestRunner(InvokeGRPC.class);
runner.setProperty(InvokeGRPC.PROP_SERVICE_HOST, TestGRPCServer.HOST);
runner.setProperty(InvokeGRPC.PROP_SERVICE_PORT, String.valueOf(port));
runner.setProperty(InvokeGRPC.PROP_USE_SECURE, "true");
useSSLContextService(runner, getTruststoreProperties());
server.start(port);
final MockFlowFile mockFlowFile = new MockFlowFile(SUCCESS);
runner.enqueue(mockFlowFile);
runner.run();
runner.assertTransferCount(InvokeGRPC.REL_RESPONSE, 1);
runner.assertTransferCount(InvokeGRPC.REL_SUCCESS_REQ, 1);
runner.assertTransferCount(InvokeGRPC.REL_RETRY, 0);
runner.assertTransferCount(InvokeGRPC.REL_NO_RETRY, 0);
runner.assertTransferCount(InvokeGRPC.REL_FAILURE, 0);
final List<MockFlowFile> responseFiles = runner.getFlowFilesForRelationship(InvokeGRPC.REL_RESPONSE);
assertThat(responseFiles.size(), equalTo(1));
final MockFlowFile response = responseFiles.get(0);
response.assertAttributeEquals(InvokeGRPC.RESPONSE_CODE, String.valueOf(FlowFileReply.ResponseCode.SUCCESS));
response.assertAttributeEquals(InvokeGRPC.RESPONSE_BODY, "success");
response.assertAttributeEquals(InvokeGRPC.SERVICE_HOST, TestGRPCServer.HOST);
response.assertAttributeEquals(InvokeGRPC.SERVICE_PORT, String.valueOf(port));
final List<MockFlowFile> successFiles = runner.getFlowFilesForRelationship(InvokeGRPC.REL_SUCCESS_REQ);
assertThat(successFiles.size(), equalTo(1));
final MockFlowFile successFile = successFiles.get(0);
successFile.assertAttributeEquals(InvokeGRPC.RESPONSE_CODE, String.valueOf(FlowFileReply.ResponseCode.SUCCESS));
successFile.assertAttributeEquals(InvokeGRPC.RESPONSE_BODY, "success");
successFile.assertAttributeEquals(InvokeGRPC.SERVICE_HOST, TestGRPCServer.HOST);
successFile.assertAttributeEquals(InvokeGRPC.SERVICE_PORT, String.valueOf(port));
} finally {
server.stop();
}
}
private static Map<String, String> getTruststoreProperties() {
final Map<String, String> props = new HashMap<>();
props.put(StandardSSLContextService.TRUSTSTORE.getName(), "src/test/resources/localhost-ts.jks");
props.put(StandardSSLContextService.TRUSTSTORE_PASSWORD.getName(), "localtest");
props.put(StandardSSLContextService.TRUSTSTORE_TYPE.getName(), "JKS");
return props;
}
private static Map<String, String> getKeystoreProperties() {
final Map<String, String> properties = new HashMap<>();
properties.put(StandardSSLContextService.KEYSTORE.getName(), "src/test/resources/localhost-ks.jks");
properties.put(StandardSSLContextService.KEYSTORE_PASSWORD.getName(), "localtest");
properties.put(StandardSSLContextService.KEYSTORE_TYPE.getName(), "JKS");
return properties;
}
private void useSSLContextService(final TestRunner controller, final Map<String, String> sslProperties) {
final SSLContextService service = new StandardSSLContextService();
try {
controller.addControllerService("ssl-service", service, sslProperties);
controller.enableControllerService(service);
} catch (InitializationException ex) {
ex.printStackTrace();
Assert.fail("Could not create SSL Context Service");
}
controller.setProperty(InvokeGRPC.PROP_SSL_CONTEXT_SERVICE, "ssl-service");
}
/**
* Dummy gRPC service whose responses are dictated by the IDs on the messages it receives
*/
private static class DummyFlowFileService extends FlowFileServiceGrpc.FlowFileServiceImplBase {
public DummyFlowFileService() {
}
@Override
public void send(FlowFileRequest request, StreamObserver<FlowFileReply> responseObserver) {
final FlowFileReply.Builder replyBuilder = FlowFileReply.newBuilder();
// use the id to dictate response codes
final long id = request.getId();
if (id == ERROR) {
replyBuilder.setResponseCode(FlowFileReply.ResponseCode.ERROR)
.setBody("error");
} else if (id == SUCCESS) {
replyBuilder.setResponseCode(FlowFileReply.ResponseCode.SUCCESS)
.setBody("success");
} else if (id == RETRY) {
replyBuilder.setResponseCode(FlowFileReply.ResponseCode.RETRY)
.setBody("retry");
// else, assume the request is to include the flowfile content in the response
} else {
replyBuilder.setResponseCode(FlowFileReply.ResponseCode.SUCCESS)
.setBody(request.getContent().toStringUtf8());
}
responseObserver.onNext(replyBuilder.build());
responseObserver.onCompleted();
}
}
}
|
package org.some.thing.rx.loader.data;
import lombok.Builder;
import lombok.Data;
@Builder
@Data
public class Event {
private String min;
private String max;
private String avg;
private String stdev;
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pulsar.proxy.stats;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.servlet.ServletContext;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.POST;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;
import org.apache.pulsar.proxy.server.ProxyService;
import io.netty.channel.Channel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
@Path("/")
@Api(value = "/proxy-stats", description = "Stats for proxy", tags = "proxy-stats", hidden = true)
@Produces(MediaType.APPLICATION_JSON)
public class ProxyStats {
public static final String ATTRIBUTE_PULSAR_PROXY_NAME = "pulsar-proxy";
private ProxyService service;
@Context
protected ServletContext servletContext;
@GET
@Path("/connections")
@ApiOperation(value = "Proxy stats api to get info for live connections", response = List.class, responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 503, message = "Proxy service is not initialized") })
public List<ConnectionStats> metrics() {
List<ConnectionStats> stats = new ArrayList<>();
proxyService().getClientCnxs().forEach(cnx -> {
if (cnx.getDirectProxyHandler() == null) {
return;
}
double requestRate = cnx.getDirectProxyHandler().getInboundChannelRequestsRate().getRate();
double byteRate = cnx.getDirectProxyHandler().getInboundChannelRequestsRate().getValueRate();
Channel inboundChannel = cnx.getDirectProxyHandler().getInboundChannel();
Channel outboundChannel = cnx.getDirectProxyHandler().getOutboundChannel();
stats.add(new ConnectionStats(requestRate, byteRate, inboundChannel, outboundChannel));
});
return stats;
}
@GET
@Path("/topics")
@ApiOperation(value = "Proxy topic stats api", response = Map.class, responseContainer = "Map")
@ApiResponses(value = { @ApiResponse(code = 412, message = "Proxy logging should be > 2 to capture topic stats"),
@ApiResponse(code = 503, message = "Proxy service is not initialized") })
public Map<String, TopicStats> topics() {
Optional<Integer> logLevel = proxyService().getConfiguration().getProxyLogLevel();
if (!logLevel.isPresent() || logLevel.get() < 2) {
throw new RestException(Status.PRECONDITION_FAILED, "Proxy doesn't have logging level 2");
}
return proxyService().getTopicStats();
}
@POST
@Path("/logging/{logLevel}")
@ApiOperation(hidden = true, value = "Change proxy logging level dynamically", notes = "It only changes log-level in memory, change it config file to persist the change")
@ApiResponses(value = { @ApiResponse(code = 412, message = "Proxy log level can be [0-2]"), })
public void updateProxyLogLevel(@PathParam("logLevel") int logLevel) {
if (logLevel < 0 || logLevel > 2) {
throw new RestException(Status.PRECONDITION_FAILED, "Proxy log level can be only [0-2]");
}
proxyService().setProxyLogLevel(logLevel);
}
@GET
@Path("/logging")
@ApiOperation(hidden = true, value = "Get proxy logging")
public int getProxyLogLevel(@PathParam("logLevel") int logLevel) {
return proxyService().getProxyLogLevel();
}
protected ProxyService proxyService() {
if (service == null) {
service = (ProxyService) servletContext.getAttribute(ATTRIBUTE_PULSAR_PROXY_NAME);
if (service == null) {
throw new RestException(Status.SERVICE_UNAVAILABLE, "Proxy service is not initialized");
}
}
return service;
}
}
|
package com.taobao.arthas.core.command.logger;
import java.security.CodeSource;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Appender;
import org.apache.log4j.AsyncAppender;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
/**
*
* @author hengyunabc 2019-09-06
*
*/
public class Log4jHelper {
private static boolean Log4j = false;
static {
try {
Class<?> loggerClass = Log4jHelper.class.getClassLoader().loadClass("org.apache.log4j.Logger");
// 这里可能会加载到其它上游ClassLoader的log4j,因此需要判断是否当前classloader
if (loggerClass.getClassLoader().equals(Log4jHelper.class.getClassLoader())) {
Log4j = true;
}
} catch (Throwable t) {
}
}
public static Boolean updateLevel(String name, String level) {
if (Log4j) {
Level l = Level.toLevel(level, Level.ERROR);
Logger logger = LogManager.getLoggerRepository().exists(name);
if (logger != null) {
logger.setLevel(l);
return true;
} else {
Logger root = LogManager.getLoggerRepository().getRootLogger();
if (root.getName().equals(name)) {
root.setLevel(l);
return true;
}
}
return false;
}
return null;
}
public static Map<String, Map<String, Object>> getLoggers(String name, boolean includeNoAppender) {
Map<String, Map<String, Object>> loggerInfoMap = new HashMap<String, Map<String, Object>>();
if (!Log4j) {
return loggerInfoMap;
}
if (name != null && !name.trim().isEmpty()) {
Logger logger = LogManager.getLoggerRepository().exists(name);
if (logger != null) {
loggerInfoMap.put(name, doGetLoggerInfo(logger));
}
} else {
// 获取所有logger时,如果没有appender则忽略
@SuppressWarnings("unchecked")
Enumeration<Logger> loggers = LogManager.getLoggerRepository().getCurrentLoggers();
if (loggers != null) {
while (loggers.hasMoreElements()) {
Logger logger = loggers.nextElement();
Map<String, Object> info = doGetLoggerInfo(logger);
if (!includeNoAppender) {
List<?> appenders = (List<?>) info.get(LoggerHelper.appenders);
if (appenders != null && !appenders.isEmpty()) {
loggerInfoMap.put(logger.getName(), info);
}
} else {
loggerInfoMap.put(logger.getName(), info);
}
}
}
Logger root = LogManager.getLoggerRepository().getRootLogger();
if (root != null) {
Map<String, Object> info = doGetLoggerInfo(root);
if (!includeNoAppender) {
List<?> appenders = (List<?>) info.get(LoggerHelper.appenders);
if (appenders != null && !appenders.isEmpty()) {
loggerInfoMap.put(root.getName(), info);
}
} else {
loggerInfoMap.put(root.getName(), info);
}
}
}
return loggerInfoMap;
}
private static Map<String, Object> doGetLoggerInfo(Logger logger) {
Map<String, Object> info = new HashMap<String, Object>();
info.put(LoggerHelper.name, logger.getName());
info.put(LoggerHelper.clazz, logger.getClass());
CodeSource codeSource = logger.getClass().getProtectionDomain().getCodeSource();
if (codeSource != null) {
info.put(LoggerHelper.codeSource, codeSource.getLocation());
}
info.put(LoggerHelper.additivity, logger.getAdditivity());
Level level = logger.getLevel(), effectiveLevel = logger.getEffectiveLevel();
if (level != null) {
info.put(LoggerHelper.level, level.toString());
}
if (effectiveLevel != null) {
info.put(LoggerHelper.effectiveLevel, effectiveLevel.toString());
}
@SuppressWarnings("unchecked")
List<Map<String, Object>> result = doGetLoggerAppenders(logger.getAllAppenders());
info.put(LoggerHelper.appenders, result);
return info;
}
private static List<Map<String, Object>> doGetLoggerAppenders(Enumeration<Appender> appenders) {
List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
if (appenders == null) {
return result;
}
while (appenders.hasMoreElements()) {
Map<String, Object> info = new HashMap<String, Object>();
Appender appender = appenders.nextElement();
info.put(LoggerHelper.name, appender.getName());
info.put(LoggerHelper.clazz, appender.getClass());
result.add(info);
if (appender instanceof FileAppender) {
info.put(LoggerHelper.file, ((FileAppender) appender).getFile());
} else if (appender instanceof ConsoleAppender) {
info.put(LoggerHelper.target, ((ConsoleAppender) appender).getTarget());
} else if (appender instanceof AsyncAppender) {
@SuppressWarnings("unchecked")
Enumeration<Appender> appendersOfAsync = ((AsyncAppender) appender).getAllAppenders();
if (appendersOfAsync != null) {
List<Map<String, Object>> asyncs = doGetLoggerAppenders(appendersOfAsync);
// 标明异步appender
List<String> appenderRef = new ArrayList<String>();
for (Map<String, Object> a : asyncs) {
appenderRef.add((String) a.get(LoggerHelper.name));
result.add(a);
}
info.put(LoggerHelper.blocking, ((AsyncAppender) appender).getBlocking());
info.put(LoggerHelper.appenderRef, appenderRef);
}
}
}
return result;
}
}
|
package fi.vincit.multiusertest.rule.expectation.call;
import fi.vincit.multiusertest.exception.CallFailedError;
import fi.vincit.multiusertest.rule.expectation.AssertionCall;
import fi.vincit.multiusertest.rule.expectation.ConsumerProducerSet;
import fi.vincit.multiusertest.rule.expectation.TestExpectation;
public class FunctionCallExceptionExpectation<T extends Throwable> implements TestExpectation {
private final Class<? extends Throwable> defaultExpectedException;
private final AssertionCall<T> assertion;
public FunctionCallExceptionExpectation(Class<T> defaultExpectedException) {
this(defaultExpectedException, null);
}
public FunctionCallExceptionExpectation(Class<T> exception, AssertionCall<T> assertion) {
this.defaultExpectedException = exception;
this.assertion = assertion;
}
public void handleExceptionNotThrown(ConsumerProducerSet consumerProducerSet) {
throw CallFailedError.expectedCallToFail(consumerProducerSet, defaultExpectedException);
}
public void handleThrownException(ConsumerProducerSet consumerProducerSet, Throwable thrownException) throws Throwable {
if (!defaultExpectedException.isInstance(thrownException)) {
throw CallFailedError.unexpectedException(consumerProducerSet, defaultExpectedException, thrownException);
}
if (assertion != null) {
assertion.call((T) thrownException);
}
}
@Override
public String toString() {
return "Expect exception: " + defaultExpectedException.getSimpleName();
}
}
|
/*
* 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.jmeter.config;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.io.IOException;
import java.util.ResourceBundle;
import org.apache.commons.lang3.StringUtils;
import org.apache.jmeter.engine.event.LoopIterationEvent;
import org.apache.jmeter.engine.event.LoopIterationListener;
import org.apache.jmeter.engine.util.NoConfigMerge;
import org.apache.jmeter.gui.GUIMenuSortOrder;
import org.apache.jmeter.save.CSVSaveService;
import org.apache.jmeter.services.FileServer;
import org.apache.jmeter.testbeans.TestBean;
import org.apache.jmeter.testbeans.gui.GenericTestBeanCustomizer;
import org.apache.jmeter.testelement.property.JMeterProperty;
import org.apache.jmeter.testelement.property.StringProperty;
import org.apache.jmeter.threads.JMeterContext;
import org.apache.jmeter.threads.JMeterVariables;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.util.JMeterStopThreadException;
import org.apache.jorphan.util.JOrphanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Read lines from a file and split int variables.
*
* The iterationStart() method is used to set up each set of values.
*
* By default, the same file is shared between all threads
* (and other thread groups, if they use the same file name).
*
* The shareMode can be set to:
* <ul>
* <li>All threads - default, as described above</li>
* <li>Current thread group</li>
* <li>Current thread</li>
* <li>Identifier - all threads sharing the same identifier</li>
* </ul>
*
* The class uses the FileServer alias mechanism to provide the different share modes.
* For all threads, the file alias is set to the file name.
* Otherwise, a suffix is appended to the filename to make it unique within the required context.
* For current thread group, the thread group identityHashcode is used;
* for individual threads, the thread hashcode is used as the suffix.
* Or the user can provide their own suffix, in which case the file is shared between all
* threads with the same suffix.
*
*/
@GUIMenuSortOrder(1)
public class CSVDataSet extends ConfigTestElement
implements TestBean, LoopIterationListener, NoConfigMerge {
private static final Logger log = LoggerFactory.getLogger(CSVDataSet.class);
private static final long serialVersionUID = 233L;
private static final String EOFVALUE = // value to return at EOF
JMeterUtils.getPropDefault("csvdataset.eofstring", "<EOF>"); //$NON-NLS-1$ //$NON-NLS-2$
private transient String filename;
private transient String fileEncoding;
private transient String variableNames;
private transient String delimiter;
private transient boolean quoted;
private transient boolean recycle = true;
private transient boolean stopThread;
private transient String[] vars;
private transient String alias;
private transient String shareMode;
private boolean firstLineIsNames = false;
private boolean ignoreFirstLine = false;
private Object readResolve(){
recycle = true;
return this;
}
/**
* Override the setProperty method in order to convert
* the original String shareMode property.
* This used the locale-dependent display value, so caused
* problems when the language was changed.
* If the "shareMode" value matches a resource value then it is converted
* into the resource key.
* To reduce the need to look up resources, we only attempt to
* convert values with spaces in them, as these are almost certainly
* not variables (and they are definitely not resource keys).
*/
@Override
public void setProperty(JMeterProperty property) {
if (property instanceof StringProperty) {
final String propName = property.getName();
if ("shareMode".equals(propName)) { // The original name of the property
final String propValue = property.getStringValue();
if (propValue.contains(" ")){ // variables are unlikely to contain spaces, so most likely a translation
try {
final BeanInfo beanInfo = Introspector.getBeanInfo(this.getClass());
final ResourceBundle rb = (ResourceBundle) beanInfo.getBeanDescriptor().getValue(GenericTestBeanCustomizer.RESOURCE_BUNDLE);
for(String resKey : CSVDataSetBeanInfo.getShareTags()) {
if (propValue.equals(rb.getString(resKey))) {
if (log.isDebugEnabled()) {
log.debug("Converted {}={} to {} using Locale: {}", propName, propValue, resKey, rb.getLocale());
}
((StringProperty) property).setValue(resKey); // reset the value
super.setProperty(property);
return;
}
}
// This could perhaps be a variable name
log.warn("Could not translate {}={} using Locale: {}", propName, propValue, rb.getLocale());
} catch (IntrospectionException e) {
log.error("Could not find BeanInfo; cannot translate shareMode entries", e);
}
}
}
}
super.setProperty(property);
}
@Override
public void iterationStart(LoopIterationEvent iterEvent) {
FileServer server = FileServer.getFileServer();
final JMeterContext context = getThreadContext();
String delim = getDelimiter();
if ("\\t".equals(delim)) { // $NON-NLS-1$
delim = "\t";// Make it easier to enter a Tab // $NON-NLS-1$
} else if (delim.isEmpty()){
log.debug("Empty delimiter, will use ','");
delim=",";
}
if (vars == null) {
String fileName = getFilename().trim();
String mode = getShareMode();
int modeInt = CSVDataSetBeanInfo.getShareModeAsInt(mode);
switch(modeInt){
case CSVDataSetBeanInfo.SHARE_ALL:
alias = fileName;
break;
case CSVDataSetBeanInfo.SHARE_GROUP:
alias = fileName+"@"+System.identityHashCode(context.getThreadGroup());
break;
case CSVDataSetBeanInfo.SHARE_THREAD:
alias = fileName+"@"+System.identityHashCode(context.getThread());
break;
default:
alias = fileName+"@"+mode; // user-specified key
break;
}
final String names = getVariableNames();
if (StringUtils.isEmpty(names)) {
String header = server.reserveFile(fileName, getFileEncoding(), alias, true);
try {
vars = CSVSaveService.csvSplitString(header, delim.charAt(0));
firstLineIsNames = true;
} catch (IOException e) {
throw new IllegalArgumentException("Could not split CSV header line from file:" + fileName,e);
}
} else {
server.reserveFile(fileName, getFileEncoding(), alias, ignoreFirstLine);
vars = JOrphanUtils.split(names, ","); // $NON-NLS-1$
}
trimVarNames(vars);
}
// TODO: fetch this once as per vars above?
JMeterVariables threadVars = context.getVariables();
String[] lineValues = {};
try {
if (getQuotedData()) {
lineValues = server.getParsedLine(alias, recycle,
firstLineIsNames || ignoreFirstLine, delim.charAt(0));
} else {
String line = server.readLine(alias, recycle,
firstLineIsNames || ignoreFirstLine);
lineValues = JOrphanUtils.split(line, delim, false);
}
for (int a = 0; a < vars.length && a < lineValues.length; a++) {
threadVars.put(vars[a], lineValues[a]);
}
} catch (IOException e) { // treat the same as EOF
log.error(e.toString());
}
if (lineValues.length == 0) {// i.e. EOF
if (getStopThread()) {
throw new JMeterStopThreadException("End of file:"+ getFilename()+" detected for CSV DataSet:"
+getName()+" configured with stopThread:"+ getStopThread()+", recycle:" + getRecycle());
}
for (String var :vars) {
threadVars.put(var, EOFVALUE);
}
}
}
/**
* trim content of array varNames
* @param varsNames
*/
private void trimVarNames(String[] varsNames) {
for (int i = 0; i < varsNames.length; i++) {
varsNames[i] = varsNames[i].trim();
}
}
/**
* @return Returns the filename.
*/
public String getFilename() {
return filename;
}
/**
* @param filename
* The filename to set.
*/
public void setFilename(String filename) {
this.filename = filename;
}
/**
* @return Returns the file encoding.
*/
public String getFileEncoding() {
return fileEncoding;
}
/**
* @param fileEncoding
* The fileEncoding to set.
*/
public void setFileEncoding(String fileEncoding) {
this.fileEncoding = fileEncoding;
}
/**
* @return Returns the variableNames.
*/
public String getVariableNames() {
return variableNames;
}
/**
* @param variableNames
* The variableNames to set.
*/
public void setVariableNames(String variableNames) {
this.variableNames = variableNames;
}
public String getDelimiter() {
return delimiter;
}
public void setDelimiter(String delimiter) {
this.delimiter = delimiter;
}
public boolean getQuotedData() {
return quoted;
}
public void setQuotedData(boolean quoted) {
this.quoted = quoted;
}
public boolean getRecycle() {
return recycle;
}
public void setRecycle(boolean recycle) {
this.recycle = recycle;
}
public boolean getStopThread() {
return stopThread;
}
public void setStopThread(boolean value) {
this.stopThread = value;
}
public String getShareMode() {
return shareMode;
}
public void setShareMode(String value) {
this.shareMode = value;
}
/**
* @return the ignoreFirstLine
*/
public boolean isIgnoreFirstLine() {
return ignoreFirstLine;
}
/**
* @param ignoreFirstLine the ignoreFirstLine to set
*/
public void setIgnoreFirstLine(boolean ignoreFirstLine) {
this.ignoreFirstLine = ignoreFirstLine;
}
}
|
/*
* Copyright (c) Numerical Method Inc.
* http://www.numericalmethod.com/
*
* THIS SOFTWARE IS LICENSED, NOT SOLD.
*
* YOU MAY USE THIS SOFTWARE ONLY AS DESCRIBED IN THE LICENSE.
* IF YOU ARE NOT AWARE OF AND/OR DO NOT AGREE TO THE TERMS OF THE LICENSE,
* DO NOT USE THIS SOFTWARE.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITH NO WARRANTY WHATSOEVER,
* EITHER EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION,
* ANY WARRANTIES OF ACCURACY, ACCESSIBILITY, COMPLETENESS,
* FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, NON-INFRINGEMENT,
* TITLE AND USEFULNESS.
*
* IN NO EVENT AND UNDER NO LEGAL THEORY,
* WHETHER IN ACTION, CONTRACT, NEGLIGENCE, TORT, OR OTHERWISE,
* SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
* ANY CLAIMS, DAMAGES OR OTHER LIABILITIES,
* ARISING AS A RESULT OF USING OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.numericalmethod.suanshu.stats.dlm.multivariate;
import com.numericalmethod.suanshu.analysis.function.matrix.R1toConstantMatrix;
import com.numericalmethod.suanshu.analysis.function.matrix.R1toMatrix;
import com.numericalmethod.suanshu.matrix.doubles.ImmutableMatrix;
import com.numericalmethod.suanshu.matrix.doubles.Matrix;
import com.numericalmethod.suanshu.matrix.doubles.matrixtype.dense.DenseMatrix;
import com.numericalmethod.suanshu.matrix.doubles.operation.MatrixUtils;
import com.numericalmethod.suanshu.matrix.doubles.operation.SimilarMatrix;
import com.numericalmethod.suanshu.matrix.doubles.operation.positivedefinite.CholeskyWang2006;
import com.numericalmethod.suanshu.misc.SuanShuUtils;
import static com.numericalmethod.suanshu.misc.SuanShuUtils.assertArgument;
import com.numericalmethod.suanshu.stats.random.multivariate.NormalRvg;
import com.numericalmethod.suanshu.vector.doubles.ImmutableVector;
import com.numericalmethod.suanshu.vector.doubles.Vector;
import com.numericalmethod.suanshu.vector.doubles.dense.DenseVector;
import java.io.Serializable;
/**
* This is the observation equation in a controlled dynamic linear model.
* <blockquote><i>
* y<sub>t</sub> = F<sub>t</sub> * x<sub>t</sub> + v<sub>t</sub>
* </i></blockquote>
*
* @author Haksun Li
*/
public class ObservationEquation implements Serializable{
private static final long serialVersionUID = -2306654433597856064L;
/**
* For a time-invariant DLM (or time-invariant controlled DLM),
* this represents a (d * p) constant coefficient matrix of x_t in the observation equation.
* <p/>
* For a time varying DLM (or time varying controlled DLM),
* this outputs a time dependent (d * p) coefficient matrix of x_t in the observation equation.
*/
private final R1toMatrix F;
/**
* For a time-invariant DLM (or time-invariant controlled DLM),
* this represents a (d * d) constant covariance matrix of v_t in the observation equation.
* <p/>
* For a time varying DLM (or time varying controlled DLM),
* this outputs a time dependent (d * d) covariance matrix of v_t in the observation equation.
*/
private final R1toMatrix V;
/**
* the dimension of each observation y_t
*/
private final int d;
private final NormalRvg rmvnorm;
/**
* Construct an observation equation.
*
* @param F the coefficient matrix function of <i>x<sub>t</sub></i>, a function of time
* @param V the covariance matrix function of <i>v<sub>t</sub></i>, a function of time
* @param rmvnorm a <i>d</i>-dimensional standard multivariate Gaussian random vector generator (for seeding); <i>d</i> = the dimension of <i>V</i> or <i>y<sub>t</sub></i>
*/
public ObservationEquation(R1toMatrix F, R1toMatrix V, NormalRvg rmvnorm) {
this.d = F.evaluate(1).nRows();
assertArgument((V.evaluate(1).nRows() == d) && (V.evaluate(1).nCols() == d),
"the dimension of V is the same as the dimension of observation y_t");
this.F = F;
this.V = V;
this.rmvnorm = rmvnorm == null ? new NormalRvg(d) : rmvnorm;
}
/**
* Construct an observation equation.
*
* @param F the coefficient matrix function of <i>x<sub>t</sub></i>, a function of time
* @param V the covariance matrix function of <i>v<sub>t</sub></i>, a function of time
*/
public ObservationEquation(R1toMatrix F, R1toMatrix V) {
this(F, V, null);
}
/**
* Construct a time-invariant an observation equation.
*
* @param F the coefficient matrix of <i>x<sub>t</sub></i>
* @param V the covariance matrix of <i>v<sub>t</sub></i>
* @param rmvnorm a <i>d</i>-dimensional standard multivariate Gaussian random vector generator (for seeding); <i>d</i> = the dimension of <i>V</i> or <i>y<sub>t</sub></i>
*/
public ObservationEquation(Matrix F, Matrix V, NormalRvg rmvnorm) {
this(new R1toConstantMatrix(F), new R1toConstantMatrix(V), rmvnorm);
}
/**
* Construct a time-invariant an observation equation.
*
* @param F the coefficient matrix of <i>x<sub>t</sub></i>
* @param V the covariance matrix of <i>v<sub>t</sub></i>
*/
public ObservationEquation(Matrix F, Matrix V) {
this(new R1toConstantMatrix(F), new R1toConstantMatrix(V), null);
}
/**
* Construct a multivariate observation equation from a univariate observation equation.
*
* @param obs a univariate observation equation
*/
public ObservationEquation(final com.numericalmethod.suanshu.stats.dlm.univariate.ObservationEquation obs) {
this(
new R1toMatrix() {
private static final long serialVersionUID = -2758919671798674061L;
@Override
public Matrix evaluate(double t) {
return new DenseMatrix(new double[][]{{obs.F((int) t)}});
}
},
new R1toMatrix() {
private static final long serialVersionUID = 580198781265615049L;
@Override
public Matrix evaluate(double t) {
return new DenseMatrix(new double[][]{{obs.V((int) t)}});
}
});
}
/**
* Copy constructor.
*
* @param that a {@code ObservationEquation}
*/
public ObservationEquation(ObservationEquation that) {
this(that.F, that.V);
}
/**
* Get the dimension of observation <i>y<sub>t</sub></i>.
*
* @return the dimension of observations
*/
public int dimension() {
return d;
}
/**
* Get <i>F(t)</i>, the coefficient matrix of <i>x<sub>t</sub></i>.
*
* @param t time
* @return <i>F(t)</i>
*/
public ImmutableMatrix F(int t) {
return new ImmutableMatrix(F.evaluate(t));
}
/**
* Get <i>V(t)</i>, the covariance matrix of <i>v<sub>t</sub></i>.
*
* @param t time
* @return <i>V(t)</i>
*/
public ImmutableMatrix V(int t) {
return new ImmutableMatrix(V.evaluate(t));
}
/**
* Predict the next observation.
* <blockquote><i>
* E(y_t) = F_t * x_t
* </i></blockquote>
*
* @param t time
* @param xt state <i>x<sub>t</sub></i>
* @return the mean observation
*/
public ImmutableVector yt_mean(int t, Vector xt) {
Vector yt = F.evaluate(t).multiply(xt);
return new ImmutableVector(yt);
}
/**
* Get the covariance of the apriori prediction for the next observation.
* <blockquote><i>
* Var(y_{t | t - 1}) = F_t * Var(x_{t | t - 1}) * F_t' + V_t
* </i></blockquote>
*
* @param t time
* @param var_t_tlag <i>Var(y_{t | t - 1})</i>, the variance of the apriori prediction
* @return <i>Var(y_{t | t - 1})</i>
*/
public ImmutableMatrix yt_var(int t, Matrix var_t_tlag) {
Matrix F = F(t);
Matrix V = V(t);
Matrix var = new SimilarMatrix(F.t(), var_t_tlag).add(V);
return new ImmutableMatrix(var);
}
/**
* Evaluate the observation equation.
* <blockquote><i>
* y_t = F_t * x_t + v_t
* </i></blockquote>
*
* @param t time
* @param xt state <i>x<sub>t</sub></i>
* @return the mean observation
*/
public ImmutableVector yt(int t, Vector xt) {
Vector yt = yt_mean(t, xt);
Matrix Vt = V.evaluate(t);
Matrix A = new CholeskyWang2006(Vt, SuanShuUtils.autoEpsilon(MatrixUtils.to1DArray(Vt)));
Vector vt = A.multiply(new DenseVector(rmvnorm.nextVector()));
yt = yt.add(vt);
return new ImmutableVector(yt);
}
}
|
package us.ihmc.robotics.math.trajectories;
import us.ihmc.euclid.referenceFrame.FrameQuaternion;
import us.ihmc.euclid.referenceFrame.FrameVector3D;
import us.ihmc.euclid.referenceFrame.ReferenceFrame;
import us.ihmc.euclid.referenceFrame.interfaces.FrameQuaternionReadOnly;
import us.ihmc.commons.MathTools;
import us.ihmc.yoVariables.registry.YoVariableRegistry;
import us.ihmc.yoVariables.variable.YoDouble;
import us.ihmc.yoVariables.variable.YoFrameQuaternion;
import us.ihmc.yoVariables.variable.YoFrameVector3D;
import us.ihmc.robotics.math.frames.YoFrameQuaternionInMultipleFrames;
import us.ihmc.robotics.math.frames.YoFrameVectorInMultipleFrames;
import us.ihmc.robotics.math.interpolators.OrientationInterpolationCalculator;
public class SimpleOrientationTrajectoryGenerator extends OrientationTrajectoryGeneratorInMultipleFrames
{
private final YoVariableRegistry registry;
private final YoDouble currentTime;
private final YoDouble trajectoryTime;
private final YoPolynomial parameterPolynomial;
private final YoFrameQuaternion initialOrientation;
private final YoFrameQuaternion finalOrientation;
private final YoFrameQuaternion currentOrientation;
private final YoFrameVector3D currentAngularVelocity;
private final YoFrameVector3D currentAngularAcceleration;
private final OrientationInterpolationCalculator orientationInterpolationCalculator = new OrientationInterpolationCalculator();
public SimpleOrientationTrajectoryGenerator(String namePrefix, ReferenceFrame referenceFrame, YoVariableRegistry parentRegistry)
{
this(namePrefix, false, referenceFrame, parentRegistry);
}
public SimpleOrientationTrajectoryGenerator(String namePrefix, boolean allowMultipleFrames, ReferenceFrame referenceFrame, YoVariableRegistry parentRegistry)
{
super(allowMultipleFrames, referenceFrame);
registry = new YoVariableRegistry(namePrefix + getClass().getSimpleName());
trajectoryTime = new YoDouble(namePrefix + "TrajectoryTime", registry);
currentTime = new YoDouble(namePrefix + "Time", registry);
parameterPolynomial = new YoPolynomial(namePrefix + "ParameterPolynomial", 6, registry);
String initialOrientationName = namePrefix + "InitialOrientation";
String finalOrientationName = namePrefix + "FinalOrientation";
String currentOrientationName = namePrefix + "CurrentOrientation";
String currentAngularVelocityName = namePrefix + "CurrentAngularVelocity";
String currentAngularAccelerationName = namePrefix + "CurrentAngularAcceleration";
if (allowMultipleFrames)
{
YoFrameQuaternionInMultipleFrames initialOrientation = new YoFrameQuaternionInMultipleFrames(initialOrientationName, registry, referenceFrame);
YoFrameQuaternionInMultipleFrames finalOrientation = new YoFrameQuaternionInMultipleFrames(finalOrientationName, registry, referenceFrame);
YoFrameQuaternionInMultipleFrames currentOrientation = new YoFrameQuaternionInMultipleFrames(currentOrientationName, registry, referenceFrame);
YoFrameVectorInMultipleFrames currentAngularVelocity = new YoFrameVectorInMultipleFrames(currentAngularVelocityName, registry, referenceFrame);
YoFrameVectorInMultipleFrames currentAngularAcceleration = new YoFrameVectorInMultipleFrames(currentAngularAccelerationName, registry, referenceFrame);
registerMultipleFramesHolders(initialOrientation, finalOrientation, currentOrientation, currentAngularVelocity, currentAngularAcceleration);
this.initialOrientation = initialOrientation;
this.finalOrientation = finalOrientation;
this.currentOrientation = currentOrientation;
this.currentAngularVelocity = currentAngularVelocity;
this.currentAngularAcceleration = currentAngularAcceleration;
}
else
{
initialOrientation = new YoFrameQuaternion(initialOrientationName, referenceFrame, registry);
finalOrientation = new YoFrameQuaternion(finalOrientationName, referenceFrame, registry);
currentOrientation = new YoFrameQuaternion(currentOrientationName, referenceFrame, registry);
currentAngularVelocity = new YoFrameVector3D(currentAngularVelocityName, referenceFrame, registry);
currentAngularAcceleration = new YoFrameVector3D(currentAngularAccelerationName, referenceFrame, registry);
}
parentRegistry.addChild(registry);
}
public void setInitialOrientation(FrameQuaternionReadOnly initialOrientation)
{
this.initialOrientation.setMatchingFrame(initialOrientation);
}
public void setFinalOrientation(FrameQuaternionReadOnly finalOrientation)
{
this.finalOrientation.setMatchingFrame(finalOrientation);
}
public void setTrajectoryTime(double newTrajectoryTime)
{
trajectoryTime.set(newTrajectoryTime);
}
@Override
public void initialize()
{
currentTime.set(0.0);
MathTools.checkIntervalContains(trajectoryTime.getDoubleValue(), 0.0, Double.POSITIVE_INFINITY);
parameterPolynomial.setQuintic(0.0, trajectoryTime.getDoubleValue(), 0.0, 0.0, 0.0, 1.0, 0.0, 0.0);
currentOrientation.set(initialOrientation);
currentAngularVelocity.setToZero();
currentAngularAcceleration.setToZero();
}
@Override
public void compute(double time)
{
currentTime.set(time);
time = MathTools.clamp(time, 0.0, trajectoryTime.getDoubleValue());
parameterPolynomial.compute(time);
boolean shouldBeZero = isDone() || currentTime.getDoubleValue() < 0.0;
double alphaDot = shouldBeZero ? 0.0 : parameterPolynomial.getVelocity();
double alphaDDot = shouldBeZero ? 0.0 : parameterPolynomial.getAcceleration();
if (!isDone())
{
currentOrientation.interpolate(initialOrientation, finalOrientation, parameterPolynomial.getPosition());
orientationInterpolationCalculator.computeAngularVelocity(currentAngularVelocity, initialOrientation, finalOrientation, alphaDot);
orientationInterpolationCalculator.computeAngularAcceleration(currentAngularAcceleration, initialOrientation, finalOrientation, alphaDDot);
}
else
{
currentOrientation.set(finalOrientation);
currentAngularVelocity.setToZero();
currentAngularAcceleration.setToZero();
}
}
@Override
public boolean isDone()
{
return currentTime.getDoubleValue() >= trajectoryTime.getDoubleValue();
}
@Override
public void getOrientation(FrameQuaternion orientationToPack)
{
orientationToPack.setIncludingFrame(currentOrientation);
}
@Override
public void getAngularVelocity(FrameVector3D velocityToPack)
{
velocityToPack.setIncludingFrame(currentAngularVelocity);
}
@Override
public void getAngularAcceleration(FrameVector3D accelerationToPack)
{
accelerationToPack.setIncludingFrame(currentAngularAcceleration);
}
@Override
public void getAngularData(FrameQuaternion orientationToPack, FrameVector3D angularVelocityToPack, FrameVector3D angularAccelerationToPack)
{
getOrientation(orientationToPack);
getAngularVelocity(angularVelocityToPack);
getAngularAcceleration(angularAccelerationToPack);
}
@Override
public String toString()
{
String ret = "";
ret += "Current time: " + currentTime.getDoubleValue() + ", trajectory time: " + trajectoryTime.getDoubleValue();
ret += "\nCurrent orientation: " + currentOrientation.toString();
ret += "\nCurrent angular velocity: " + currentAngularVelocity.toString();
ret += "\nCurrent angular acceleration: " + currentAngularAcceleration.toString();
return ret;
}
}
|
package org.ovirt.engine.core.bll.storage.disk.image;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.ovirt.engine.core.common.businessentities.StorageDomain;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSStatus;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VMStatus;
import org.ovirt.engine.core.common.businessentities.storage.DiskImage;
import org.ovirt.engine.core.common.businessentities.storage.StorageType;
import org.ovirt.engine.core.common.businessentities.storage.VolumeFormat;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.Version;
import org.ovirt.engine.core.dao.StorageDomainDao;
import org.ovirt.engine.core.dao.VdsDao;
import org.ovirt.engine.core.dao.VmDao;
import org.ovirt.engine.core.utils.MockConfigDescriptor;
import org.ovirt.engine.core.utils.MockedConfig;
/** A test case for {@link ImagesHandler} */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
public class ImagesHandlerTest {
@Mock
private StorageDomainDao storageDomainDaoMock;
@Mock
private VmDao vmDao;
@Mock
private VdsDao vdsDao;
@InjectMocks
private ImagesHandler imagesHandler = new ImagesHandler();
/** The prefix to use for all tests */
private static final String prefix = "PREFIX";
/** The disks to use for testing */
private DiskImage disk1;
private DiskImage disk2;
private DiskImage disk3;
public static Stream<MockConfigDescriptor<?>> mockConfiguration() {
return Stream.of(
MockConfigDescriptor.of(ConfigValues.PropagateDiskErrors, false)
);
}
@BeforeEach
public void setUp() {
disk1 = new DiskImage();
disk2 = new DiskImage();
disk3 = new DiskImage();
}
@Test
public void testGetSuggestedDiskAliasNullDisk() {
assertEquals(prefix + ImagesHandler.DISK + ImagesHandler.DefaultDriveName,
ImagesHandler.getSuggestedDiskAlias(null, prefix, 1),
"null disk does not give the default name");
}
@Test
public void testGetSuggestedDiskAliasNullAliasDisk() {
disk1.setDiskAlias(null);
assertEquals(prefix + ImagesHandler.DISK + ImagesHandler.DefaultDriveName,
ImagesHandler.getSuggestedDiskAlias(disk1, prefix, 1),
"disk with null alias does not give the default name");
}
@Test
public void testGetSuggestedDiskAliasNotNullAliasDisk() {
disk1.setDiskAlias("someAlias");
assertEquals(disk1.getDiskAlias(), ImagesHandler.getSuggestedDiskAlias(disk1, prefix, 1),
"a new alias was generated instead of returning the pre-defined one");
}
@Test
public void testGetDiskAliasWithDefaultNullAlias() {
assertEquals(ImagesHandler.getDiskAliasWithDefault(disk1, "default"), "default");
}
@Test
public void testGetDiskAliasWithDefaultNotNullAlias() {
disk1.setDiskAlias("alias");
assertEquals("alias", ImagesHandler.getDiskAliasWithDefault(disk1, "default"));
}
@Test
public void testGetAllStorageIdsForImageIds() {
Guid sdIdShared = Guid.newGuid();
Guid sdId1 = Guid.newGuid();
Guid sdId2 = Guid.newGuid();
disk1.setStorageIds(new ArrayList<>(Arrays.asList(sdId1, sdIdShared)));
disk2.setStorageIds(new ArrayList<>(Arrays.asList(sdId2, sdIdShared)));
Set<Guid> result = ImagesHandler.getAllStorageIdsForImageIds(Arrays.asList(disk1, disk2));
assertEquals(3, result.size(), "Wrong number of Guids returned");
assertTrue(result.containsAll(Arrays.asList(sdId1, sdId2, sdIdShared)), "Wrong Guids returned");
}
@Test
public void testImagesSubtract() {
disk1.setId(Guid.newGuid());
disk2.setId(Guid.newGuid());
disk3.setId(Guid.newGuid());
List<DiskImage> list1 = new ArrayList<>(Arrays.asList(disk1, disk2, disk3));
List<DiskImage> list2 = new ArrayList<>(Arrays.asList(disk2, disk3));
List<DiskImage> intersection = ImagesHandler.imagesSubtract(list1, list2);
assertEquals(1, intersection.size(), "Intersection should contain only one disk");
assertTrue(intersection.contains(disk1), "Intersection should contains disk1");
}
@Test
public void testImagesIntersection() {
disk1.setId(Guid.newGuid());
disk2.setId(Guid.newGuid());
disk3.setId(Guid.newGuid());
List<DiskImage> list1 = new ArrayList<>(Arrays.asList(disk1, disk2));
List<DiskImage> list2 = new ArrayList<>(Arrays.asList(disk1, disk3));
List<DiskImage> intersection = ImagesHandler.imagesIntersection(list1, list2);
assertTrue(intersection.size() == 1 && intersection.contains(disk1), "Intersection should contain only disk1");
}
@Test
public void testDetermineTotalImageInitialSizeFromNfsToCow() {
DiskImage disk = new DiskImage();
disk.setSize(5000);
disk.setActualSizeInBytes(0);
Guid srcDomainGuid = Guid.newGuid();
StorageDomain srcDomain = new StorageDomain();
srcDomain.setId(srcDomainGuid);
srcDomain.setStorageType(StorageType.NFS);
when(storageDomainDaoMock.get(srcDomainGuid)).thenReturn(srcDomain);
Guid dstDomainGuid = Guid.newGuid();
StorageDomain destDomain = new StorageDomain();
destDomain.setId(dstDomainGuid);
destDomain.setStorageType(StorageType.ISCSI);
when(storageDomainDaoMock.get(dstDomainGuid)).thenReturn(destDomain);
assertEquals(Long.valueOf(0L),
imagesHandler.determineTotalImageInitialSize(disk, VolumeFormat.COW, srcDomainGuid, dstDomainGuid),
"Total Initial Size should be 0");
}
@Test
@MockedConfig("mockConfiguration")
public void testAggregateDiskImagesSnapshots() {
disk1.setId(Guid.newGuid());
disk1.setActive(true);
disk1.setStorageIds(new ArrayList<>());
disk2.setId(disk1.getId());
disk2.setActive(false);
disk3.setId(disk1.getId());
disk3.setActive(false);
DiskImage diskWithoutSnapshots = new DiskImage();
diskWithoutSnapshots.setId(Guid.newGuid());
diskWithoutSnapshots.setActive(true);
diskWithoutSnapshots.setStorageIds(new ArrayList<>());
List<DiskImage> result =
new ArrayList<>(imagesHandler.aggregateDiskImagesSnapshots(Arrays.asList(
disk1,
disk2,
disk3,
diskWithoutSnapshots)));
DiskImage resultDisk =
result.stream().filter(diskImage -> diskImage.getId() == disk1.getId()).findFirst().orElse(null);
assertNotNull(resultDisk, "resultDisk should hold a reference to DiskImage object");
assertEquals(2, result.size(), "wrong number of disks returned");
assertEquals(3, resultDisk.getSnapshots().size(), "wrong number of snapshots for disk1");
}
@Test
public void testAggregateDiskImagesSnapshotsWithEmptyList() {
Collection<DiskImage> result = imagesHandler.aggregateDiskImagesSnapshots(Collections.emptyList());
assertTrue(result.isEmpty(), "should return an empty list");
}
@Test
public void testGetHostForExecutionRunningVM() {
Guid storagePoolID = Guid.newGuid();
Guid imageGroupID = Guid.newGuid();
VDS vds1 = new VDS();
vds1.setId(Guid.newGuid());
vds1.setClusterCompatibilityVersion(Version.v4_4);
vds1.setStatus(VDSStatus.Up);
VM runningVM = new VM();
runningVM.setRunOnVds(vds1.getId());
runningVM.setStatus(VMStatus.Up);
disk1.setId(imageGroupID);
disk1.setActive(true);
Map<Boolean, List<VM>> pluggedVMs = new HashMap<>();
pluggedVMs.put(Boolean.TRUE, List.of(runningVM));
when(vmDao.getForDisk(imageGroupID, true)).thenReturn(pluggedVMs);
when(vdsDao.get(vds1.getId())).thenReturn(vds1);
assertEquals(imagesHandler.getHostForMeasurement(storagePoolID, imageGroupID), vds1.getId());
}
}
|
package com.codepath.apps.mysimpletweets;
import android.content.Context;
import android.util.Log;
import com.codepath.oauth.OAuthBaseClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.scribe.builder.api.Api;
import org.scribe.builder.api.TwitterApi;
/*
*
* This is the object responsible for communicating with a REST API.
* Specify the constants below to change the API being communicated with.
* See a full list of supported API classes:
* https://github.com/fernandezpablo85/scribe-java/tree/master/src/main/java/org/scribe/builder/api
* Key and Secret are provided by the developer site for the given API i.e dev.twitter.com
* Add methods for each relevant endpoint in the API.
*
* NOTE: You may want to rename this object based on the service i.e TwitterClient or FlickrClient
*
*/
public class TwitterClient extends OAuthBaseClient {
public static final Class<? extends Api> REST_API_CLASS = TwitterApi.class;
public static final String REST_URL = "https://api.twitter.com/1.1";
public static final String REST_CONSUMER_KEY = "5rNbRoSJRonvEpjBOPDrzd9fx";
public static final String REST_CONSUMER_SECRET = "oC04V0QY80mUg2tBWDyLkNvd7iXzFFphxGySKc6QWbIKu1R5o6";
public static final String REST_CALLBACK_URL = "x-oauthflow-twitter://cpsimpletweets"; // Change this (here and in manifest)
public TwitterClient(Context context) {
super(context, REST_API_CLASS, REST_URL, REST_CONSUMER_KEY, REST_CONSUMER_SECRET, REST_CALLBACK_URL);
}
private void getHomeTimeline(long lastTweetId, AsyncHttpResponseHandler handler ){
String apiUrl = getApiUrl("statuses/home_timeline.json");
// specify params
RequestParams params = new RequestParams();
params.put("count", 25); // grab 25 tweets
params.put("since_id", lastTweetId); // oldest id of tweet to grab
//execute request
getClient().get(apiUrl, params, handler);
}
public void getInitialHomeTimeline(AsyncHttpResponseHandler handler){
getHomeTimeline(1, handler);
}
public void getLatestTweetsSince( long lastTweetId, AsyncHttpResponseHandler handler){
getHomeTimeline(lastTweetId, handler);
}
public void getTweetsAfterMyTweet(long myTweetId, AsyncHttpResponseHandler handler){
String apiUrl = getApiUrl("statuses/home_timeline.json");
// specify params
RequestParams params = new RequestParams();
params.put("count", 25); // grab 25 tweets
params.put("max_id", myTweetId); // oldest id of tweet to grab
//execute request
getClient().get(apiUrl, params, handler);
}
// get user info about self
public void getCurrentUser(AsyncHttpResponseHandler handler){
Log.d("ERROR", "get current user...?");
String apiUrl = getApiUrl("account/verify_credentials.json");
getClient().get(apiUrl, null, handler);
}
public void postTweet(String body, AsyncHttpResponseHandler handler) {
String apiUrl = getApiUrl("statuses/update.json");
RequestParams params = new RequestParams();
params.put("status", body);
getClient().post(apiUrl, params, handler);
}
}
|
package com.rajven.todo.converter;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import io.r2dbc.spi.Clob;
import org.springframework.core.convert.converter.Converter;
import reactor.core.publisher.Flux;
/**
* Workaround for H2 having issues converting between Clob and String
*/
public class ClobConverter implements Converter<Clob, String> {
public String convert(Clob source) {
List<CharSequence> charSequence = null;
try {
charSequence = ((Flux<CharSequence>) source.stream()).collectList().toFuture().get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
return Objects.isNull(charSequence)
? ""
: String.join("", charSequence);
}
}
|
package org.hl7.fhir.tools.publisher;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.hl7.fhir.definitions.validation.ValueSetValidator;
import org.hl7.fhir.instance.formats.FormatUtilities;
import org.hl7.fhir.instance.model.ContactPoint.ContactPointSystem;
import org.hl7.fhir.instance.model.DateTimeType;
import org.hl7.fhir.instance.model.Enumerations.ConformanceResourceStatus;
import org.hl7.fhir.instance.model.Factory;
import org.hl7.fhir.instance.model.Narrative;
import org.hl7.fhir.instance.model.Narrative.NarrativeStatus;
import org.hl7.fhir.instance.model.ValueSet;
import org.hl7.fhir.instance.model.ValueSet.ConceptDefinitionComponent;
import org.hl7.fhir.instance.model.ValueSet.ConceptDefinitionDesignationComponent;
import org.hl7.fhir.instance.model.ValueSet.ConceptReferenceComponent;
import org.hl7.fhir.instance.model.ValueSet.ConceptSetComponent;
import org.hl7.fhir.instance.model.ValueSet.ValueSetCodeSystemComponent;
import org.hl7.fhir.instance.terminologies.ValueSetUtilities;
import org.hl7.fhir.instance.utils.ToolingExtensions;
import org.hl7.fhir.instance.validation.ValidationMessage;
import org.hl7.fhir.tools.publisher.ValueSetImporterV2.TableRegistration;
import org.hl7.fhir.utilities.CSFile;
import org.hl7.fhir.utilities.CSFileInputStream;
import org.hl7.fhir.utilities.IniFile;
import org.hl7.fhir.utilities.TextFile;
import org.hl7.fhir.utilities.Utilities;
import org.hl7.fhir.utilities.xhtml.XhtmlNode;
import org.hl7.fhir.utilities.xhtml.XhtmlParser;
import org.hl7.fhir.utilities.xml.XMLUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class ValueSetImporterV2 {
private static final String HTTP_separator = "/";
private static final String MAX_VER = "2.8.2";
public class TableRegistration {
private List<String> versionPoints = new ArrayList<String>();
}
private class OIDEntry {
private String id;
private String name;
private String oid;
private String code;
private String ver;
public OIDEntry(String id, String name, String oid, String code, String ver) {
super();
this.id = id;
this.name = name;
this.oid = oid;
this.code = code;
this.ver = ver;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getOid() {
return oid;
}
public String getCode() {
return code;
}
}
private List<ValidationMessage> errors;
private PageProcessor page;
private List<ValueSet> valuesets = new ArrayList<ValueSet>();
private Map<String, OIDEntry> oids = new HashMap<String, OIDEntry>();
private Map<String, Set<String>> vsImports = new HashMap<String, Set<String>>();
private Map<String, TableRegistration> tables = new HashMap<String, TableRegistration>();
private String date;
private IniFile ini;
public ValueSetImporterV2(PageProcessor page, List<ValidationMessage> errors) {
super();
this.page = page;
this.errors = errors;
ini = new IniFile(Utilities.path(page.getFolders().srcDir, "v2", "v2.ini"));
}
public void execute() throws Exception {
loadOIds();
executeMaster();
// now, load additional language sources
date = ini.getStringProperty("v2", "date");
int count = ini.getIntegerProperty("v2", "langcount");
for (int i = 1; i <= count; i++) {
loadLanguagePack(ini.getStringProperty("v2", "lang"+Integer.toString(i)));
}
for (ValueSet vs : valuesets)
updateNarrative(vs);
}
private void loadOIds() throws IOException {
oids.clear();
valuesets.clear();
tables.clear();
FileInputStream fis = new FileInputStream(Utilities.path(page.getFolders().srcDir, "v2", "v2oids.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line = br.readLine()) != null) {
if (!line.startsWith("//")) {
String[] cells = line.split("\\t");
String id = Utilities.padLeft(cells[0], '0', 4) + (cells.length == 5 ? "-"+cells[4] : "");
oids.put(id, new OIDEntry(cells[0], cells[1], cells[2], cells[3], cells.length > 4 ? cells[4] : null));
if (cells.length > 4) {
if (!tables.containsKey(Utilities.padLeft(cells[0], '0', 4))) {
TableRegistration tr = new TableRegistration();
tables.put(Utilities.padLeft(cells[0], '0', 4), tr);
}
tables.get(Utilities.padLeft(cells[0], '0', 4)).versionPoints.add(cells[4]);
} else
tables.put(id, new TableRegistration());
}
}
br.close();
for (String n : ini.getPropertyNames("valuesets")) {
String v = ini.getStringProperty("valuesets", n);
Set<String> cslist = new HashSet<String>();
for (String p : v.split("\\;")) {
if (p.length() == 4)
cslist.add("http://hl7.org/fhir/v2/"+p);
else
cslist.add(p);
}
vsImports.put(n, cslist);
}
}
private void updateNarrative(ValueSet vs) {
XhtmlNode table = vs.getText().getDiv().getElement("table");
List<String> langs = new ArrayList<String>();
for (ConceptDefinitionComponent c : vs.getCodeSystem().getConcept()) {
for (ConceptDefinitionDesignationComponent d : c.getDesignation()) {
if (d.hasLanguage() && !d.hasUse()) {
if (!langs.contains(d.getLanguage()))
langs.add(d.getLanguage());
}
}
}
Collections.sort(langs);
XhtmlNode tr = table.getChildNodes().get(0);
int i = 2;
for (String s : langs) {
tr.addTag(i, "td").addTag("b").addText(page.getTranslations().getLangDesc(s));
i++;
}
int r = 1;
for (ConceptDefinitionComponent c : vs.getCodeSystem().getConcept()) {
tr = table.getChildNodes().get(r);
i = 2;
for (String s : langs) {
tr.addTag(i, "td").addText(getLang(c, s));
i++;
}
r++;
}
}
private String getLang(ConceptDefinitionComponent c, String s) {
for (ConceptDefinitionDesignationComponent d : c.getDesignation()) {
if (d.hasLanguage() && !d.hasUse()) {
if (d.getLanguage().equals(s))
return d.getValue();
}
}
return "";
}
private void loadLanguagePack(String source) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new CSFileInputStream(new CSFile(page.getFolders().srcDir + "v2" + File.separator + source)));
Map<String, Element> tblindex = new HashMap<String, Element>();
// index the table list
Element e = XMLUtil.getFirstChild(doc.getDocumentElement());
while (e != null) {
String id = Utilities.padLeft(e.getAttribute("id"), '0', 4);
tblindex.put(id, e);
e = XMLUtil.getNextSibling(e);
}
for (ValueSet vs : valuesets) {
String id = vs.getId().substring(3);
if (id.contains("-")) {
// version specific
} else {
processV2Table(vs, tblindex.get(id));
}
}
}
private void processV2Table(ValueSet vs, Element element) {
if (element != null) {
for (ConceptDefinitionComponent c : vs.getCodeSystem().getConcept()) {
processV2Code(c, element);
}
}
for (Element e : getLangList(element)) {
if (!ToolingExtensions.hasLanguageTranslation(vs.getNameElement(), e.getAttribute("lang")))
ToolingExtensions.addLanguageTranslation(vs.getNameElement(), e.getAttribute("lang"), e.getAttribute("value"));
}
}
private void processV2Code(ConceptDefinitionComponent c, Element element) {
Element ver = XMLUtil.getLastChild(element);
while (ver != null) {
Element code = getChildForCode(ver, c.getCode());
for (Element e : getLangList(code)) {
if (!hasLangDesc(c, e.getAttribute("lang")))
addLangDesc(c, e.getAttribute("lang"), e.getAttribute("value"));
}
ver = XMLUtil.getPrevSibling(ver);
}
}
private boolean hasLangDesc(ConceptDefinitionComponent c, String lang) {
for (ConceptDefinitionDesignationComponent cd : c.getDesignation()) {
if (cd.getLanguage().equals(lang))
return true;
}
return false;
}
private void addLangDesc(ConceptDefinitionComponent c, String lang, String value) {
c.addDesignation().setLanguage(lang).setValue(value);
}
private List<Element> getLangList(Element node) {
List<Element> results = new ArrayList<Element>();
if (node != null) {
Element e = XMLUtil.getFirstChild(node);
while (e != null) {
if (e.getNodeName().equals("desc") && e.hasAttribute("lang"))
results.add(e);
e = XMLUtil.getNextSibling(e);
}
}
return results;
}
private Element getChildForCode(Element node, String code) {
Element e = XMLUtil.getFirstChild(node);
while (e != null) {
if (e.getNodeName().equals("item") && e.getAttribute("code").equals(code))
return e;
e = XMLUtil.getNextSibling(e);
}
return null;
}
public void executeMaster() throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
page.setV2src(builder.parse(new CSFileInputStream(new CSFile(page.getFolders().srcDir + "v2" + File.separator + "source.xml"))));
Element e = XMLUtil.getFirstChild(page.getV2src().getDocumentElement());
while (e != null) {
String id = Utilities.padLeft(e.getAttribute("id"), '0', 4);
if (tables.containsKey(id)) {
if (tables.get(id).versionPoints.isEmpty()) {
ValueSet vs = buildV2CodeSystem(id, e);
valuesets.add(vs);
vs.setId("v2-"+FormatUtilities.makeId(id));
vs.setUserData("path", "v2" + HTTP_separator + id + HTTP_separator + "index.html");
page.getDefinitions().getValuesets().put(vs.getUrl(), vs);
page.getDefinitions().getCodeSystems().put(vs.getCodeSystem().getSystem(), vs);
page.getValueSets().put(vs.getUrl(), vs);
page.getCodeSystems().put(vs.getCodeSystem().getSystem().toString(), vs);
} else { // versioned
TableRegistration tbl = tables.get(id);
for (int i = 0; i < tbl.versionPoints.size(); i++) {
String ver = tbl.versionPoints.get(i);
String nver = i < tbl.versionPoints.size() - 1 ? tbl.versionPoints.get(i+1) : null;
ValueSet vs = buildV2CodeSystemVersioned(id, ver, nver, e);
valuesets.add(vs);
vs.setId("v2-"+FormatUtilities.makeId(ver)+"-"+id);
vs.setUserData("path", "v2" + HTTP_separator + id + HTTP_separator + ver + HTTP_separator + "index.html");
page.getDefinitions().getValuesets().put(vs.getUrl(), vs);
page.getDefinitions().getCodeSystems().put(vs.getCodeSystem().getSystem(), vs);
page.getValueSets().put(vs.getUrl(), vs);
page.getCodeSystems().put(vs.getCodeSystem().getSystem().toString(), vs);
}
}
}
e = XMLUtil.getNextSibling(e);
}
// now, value sets
e = XMLUtil.getFirstChild(page.getV2src().getDocumentElement());
while (e != null) {
String id = Utilities.padLeft(e.getAttribute("id"), '0', 4);
if (vsImports.containsKey(id)) {
ValueSet vs = buildV2ValueSet(id, e);
valuesets.add(vs);
vs.setId("v2-"+FormatUtilities.makeId(id));
vs.setUserData("path", "v2" + HTTP_separator + id + HTTP_separator + "index.html");
page.getDefinitions().getValuesets().put(vs.getUrl(), vs);
page.getValueSets().put(vs.getUrl(), vs);
}
e = XMLUtil.getNextSibling(e);
}
}
private ValueSet buildV2ValueSet(String id, Element e) throws Exception {
ValueSet vs = new ValueSet();
ValueSetUtilities.makeShareable(vs);
vs.setId("v2-"+FormatUtilities.makeId(id));
vs.setUserData("filename", Utilities.path("v2", id, "index.html"));
vs.setUrl("http://hl7.org/fhir/ValueSet/" + vs.getId());
vs.setName("v2 table " + id);
vs.setPublisher("HL7, Inc");
vs.setVersion(MAX_VER);
vs.addContact().getTelecom().add(Factory.newContactPoint(ContactPointSystem.OTHER, "http://hl7.org"));
vs.setStatus(ConformanceResourceStatus.ACTIVE);
vs.setExperimental(true);
vs.setDateElement(new DateTimeType(date));
StringBuilder s = new StringBuilder();
Set<String> sources = vsImports.get(id);
String desc = "";
// we use the latest description of the table
Element c = XMLUtil.getFirstChild(e);
Map<String, String> codes = new HashMap<String, String>();
Map<String, String> comments = new HashMap<String, String>();
while (c != null) {
String ver = c.getAttribute("version");
if (!ver.contains(" ")) {
desc = c.getAttribute("desc");
vs.setDescription("FHIR Value set/code system definition for HL7 v2 table " + id + " ( " + desc + ")");
vs.setName("v2 " + desc);
Element g = XMLUtil.getFirstChild(c);
while (g != null) {
codes.put(g.getAttribute("code"), g.getAttribute("desc"));
if (!Utilities.noString(g.getAttribute("comments")))
comments.put(g.getAttribute("code"), g.getAttribute("comments"));
g = XMLUtil.getNextSibling(g);
}
}
c = XMLUtil.getNextSibling(c);
}
s.append("<p>").append(Utilities.escapeXml(desc)).append("</p>\r\n");
s.append("<table class=\"grid\">");
s.append("<tr><td><b>Code</b></td><td><b>System</b></td><td><b>Description</b></td><td><b>Comment</b></td><td><b>Version</b></td></tr>");
List<String> cs = new ArrayList<String>();
cs.addAll(codes.keySet());
Collections.sort(cs);
for (String cd : cs) {
String min = null;
String max = null;
c = XMLUtil.getFirstChild(e);
while (c != null) {
String ver = c.getAttribute("version");
if (!ver.contains(" ")) {
Element g = XMLUtil.getFirstChild(c);
while (g != null) {
if (cd.equals(g.getAttribute("code"))) {
if (min == null)
min = ver;
max = ver;
}
g = XMLUtil.getNextSibling(g);
}
}
c = XMLUtil.getNextSibling(c);
}
String ver = "added v" + min + (MAX_VER.equals(max) ? "" : ", removed after v" + max);
ConceptSetComponent cset = checkAddCSReference(vs, sources, cd);
if (cset == null) {
String translate = ini.getStringProperty("translate", id+"/"+cd);
if (!Utilities.noString(translate)) {
if (!vs.hasCodeSystem())
vs.getCodeSystem().setCaseSensitive(false).setSystem("http://hl7.org/fhir/v2/" + id);
vs.getCodeSystem().addConcept().setCode(cd).setDisplay(codes.get(cd)).setDefinition("This code is an error - it actually refers to "+translate);
cset = checkAddCSReference(vs, sources, translate);
ConceptReferenceComponent concept = cset.addConcept().setCode(translate).setDisplay(codes.get(cd)+". Wrongly included with a wrong code '"+cd+"'");
String comment = "";
if (comments.containsKey(cd)) {
comment = comments.get(cd);
ToolingExtensions.addComment(concept, comment);
}
String nm = Utilities.nmtokenize(cd);
s.append("<tr><td>" + Utilities.escapeXml(cd) + "<a name=\"" + Utilities.escapeXml(nm) + "\"> </a></td><td>"+cset.getSystem()+"::<b>"+translate+"</b></td><td>" + Utilities.escapeXml(codes.get(cd))
+ "</td><td>Wrongly Included as "+cd+". " + Utilities.escapeXml(comment) + "</td><td>" + ver + "</td></tr>");
} else if (!ini.getBooleanProperty("ignore", id+"/"+cd))
throw new Exception("No Match for "+cd+" in "+sources.toString());
} else {
ConceptReferenceComponent concept = cset.addConcept();
concept.setCode(cd);
concept.setDisplay(codes.get(cd)); // we deem the v2 description to
String comment = "";
if (comments.containsKey(cd)) {
comment = comments.get(cd);
ToolingExtensions.addComment(concept, comment);
}
// be display name, not
// definition. Open for
// consideration
String nm = Utilities.nmtokenize(cd);
s.append("<tr><td>" + Utilities.escapeXml(cd) + "<a name=\"" + Utilities.escapeXml(nm) + "\"> </a></td><td>"+cset.getSystem()+"</td><td>" + Utilities.escapeXml(codes.get(cd))
+ "</td><td>" + Utilities.escapeXml(comment) + "</td><td>" + ver + "</td></tr>");
}
}
s.append("</table>\r\n");
vs.setText(new Narrative());
vs.getText().setStatus(NarrativeStatus.ADDITIONAL); // because we add
// v2 versioning
// information
vs.getText().setDiv(new XhtmlParser().parse("<div>" + s.toString() + "</div>", "div").getElement("div"));
page.getVsValidator().validate(errors, "v2 table "+id, vs, false, true);
return vs;
}
private ConceptSetComponent checkAddCSReference(ValueSet vs, Set<String> sources, String cd) throws Exception {
ConceptSetComponent cset = null;
for (String system : sources) {
ValueSet vsc = page.getCodeSystems().get(system);
if (vsc == null)
throw new Exception("Unable to resolve code system "+system);
if (definesCode(vsc.getCodeSystem().getConcept(), cd)) {
if (cset != null)
throw new Exception("Multiple possible matches for "+cd+" in "+sources.toString());
for (ConceptSetComponent cc : vs.getCompose().getInclude()) {
if (cc.getSystem().equals(system))
cset = cc;
}
if (cset == null)
cset = vs.getCompose().addInclude().setSystem(system);
}
}
return cset;
}
private boolean definesCode(List<ConceptDefinitionComponent> list, String cd) {
for (ConceptDefinitionComponent c : list) {
if (cd.equals(c.getCode()))
return true;
if (definesCode(c.getConcept(), cd))
return true;
}
return false;
}
private ValueSet buildV2CodeSystem(String id, Element e) throws Exception {
ValueSet vs = new ValueSet();
ValueSetUtilities.makeShareable(vs);
vs.setId("v2-"+FormatUtilities.makeId(id));
vs.setUserData("filename", Utilities.path("v2", id, "index.html"));
vs.setUrl("http://hl7.org/fhir/ValueSet/" + vs.getId());
vs.setName("v2 table " + id);
vs.setPublisher("HL7, Inc");
vs.setVersion(MAX_VER);
vs.addContact().getTelecom().add(Factory.newContactPoint(ContactPointSystem.OTHER, "http://hl7.org"));
vs.setStatus(ConformanceResourceStatus.ACTIVE);
vs.setExperimental(true);
vs.setDateElement(new DateTimeType(date));
ValueSetCodeSystemComponent def = new ValueSet.ValueSetCodeSystemComponent();
vs.setCodeSystem(def);
OIDEntry oe = oids.get(id);
if (oe != null)
ToolingExtensions.setOID(def, "urn:oid:"+oe.getOid());
def.setCaseSensitive(false);
def.setSystem("http://hl7.org/fhir/v2/" + id);
StringBuilder s = new StringBuilder();
String desc = "";
// we use the latest description of the table
Element c = XMLUtil.getFirstChild(e);
Map<String, String> codes = new HashMap<String, String>();
Map<String, String> comments = new HashMap<String, String>();
while (c != null) {
String ver = c.getAttribute("version");
if (!ver.contains(" ")) {
desc = c.getAttribute("desc");
vs.setDescription("FHIR Value set/code system definition for HL7 v2 table " + id + " ( " + desc + ")");
vs.setName("v2 " + desc);
Element g = XMLUtil.getFirstChild(c);
while (g != null) {
codes.put(g.getAttribute("code"), g.getAttribute("desc"));
if (!Utilities.noString(g.getAttribute("comments")))
comments.put(g.getAttribute("code"), g.getAttribute("comments"));
g = XMLUtil.getNextSibling(g);
}
}
c = XMLUtil.getNextSibling(c);
}
s.append("<p>").append(Utilities.escapeXml(desc)).append("</p>\r\n");
s.append("<table class=\"grid\">");
s.append("<tr><td><b>Code</b></td><td><b>Description</b></td><td><b>Comment</b></td><td><b>Version</b></td></tr>");
List<String> cs = new ArrayList<String>();
cs.addAll(codes.keySet());
Collections.sort(cs);
for (String cd : cs) {
String min = null;
String max = null;
c = XMLUtil.getFirstChild(e);
while (c != null) {
String ver = c.getAttribute("version");
if (!ver.contains(" ")) {
Element g = XMLUtil.getFirstChild(c);
while (g != null) {
if (cd.equals(g.getAttribute("code"))) {
if (min == null)
min = ver;
max = ver;
}
g = XMLUtil.getNextSibling(g);
}
}
c = XMLUtil.getNextSibling(c);
}
String ver = ("2.1".equals(min) ? "from v2.1" : "added v" + min) + (MAX_VER.equals(max) ? "" : ", removed after v" + max);
ConceptDefinitionComponent concept = new ValueSet.ConceptDefinitionComponent();
concept.setCode(cd);
concept.setDisplay(codes.get(cd)); // we deem the v2 description to
String comment = "";
if (comments.containsKey(cd)) {
comment = comments.get(cd);
ToolingExtensions.addComment(concept, comment);
}
// be display name, not
// definition. Open for
// consideration
if (!(MAX_VER.equals(max)) || comment.equalsIgnoreCase("deprecated"))
ToolingExtensions.markDeprecated(concept);
if (ToolingExtensions.hasDeprecated(concept) && Utilities.noString(comment))
comment = "deprecated";
def.getConcept().add(concept);
String nm = Utilities.nmtokenize(cd);
s.append("<tr><td>" + Utilities.escapeXml(cd) + "<a name=\"" + Utilities.escapeXml(nm) + "\"> </a></td><td>" + Utilities.escapeXml(codes.get(cd))
+ "</td><td>" + Utilities.escapeXml(comment) + "</td><td>" + ver + "</td></tr>");
}
s.append("</table>\r\n");
vs.setText(new Narrative());
vs.getText().setStatus(NarrativeStatus.ADDITIONAL); // because we add
// v2 versioning
// information
vs.getText().setDiv(new XhtmlParser().parse("<div>" + s.toString() + "</div>", "div").getElement("div"));
page.getVsValidator().validate(errors, "v2 table "+id, vs, false, true);
return vs;
}
private ValueSet buildV2CodeSystemVersioned(String id, String version, String endVersion, Element e) throws Exception {
StringBuilder s = new StringBuilder();
ValueSet vs = new ValueSet();
ValueSetUtilities.makeShareable(vs);
vs.setId("v2-"+FormatUtilities.makeId(version)+"-"+id);
vs.setUserData("filename", Utilities.path("v2", id, version, "index.html"));
vs.setUrl("http://hl7.org/fhir/ValueSet/"+vs.getId());
vs.setName("v2 table " + id + ", Version " + version);
vs.setPublisher("HL7, Inc");
vs.addContact().getTelecom().add(Factory.newContactPoint(ContactPointSystem.OTHER, "http://hl7.org"));
vs.setStatus(ConformanceResourceStatus.ACTIVE);
vs.setExperimental(false);
vs.setVersion(id);
vs.setDateElement(new DateTimeType(date));
ValueSetCodeSystemComponent def = new ValueSet.ValueSetCodeSystemComponent();
OIDEntry oe = oids.get(id+"-"+version);
if (oe != null)
ToolingExtensions.setOID(def, "urn:oid:"+oe.getOid());
vs.setCodeSystem(def);
def.setCaseSensitive(true);
def.setSystem("http://hl7.org/fhir/v2/" + id + "/" + version);
String desc = "";
String minlim = null;
String maxlim = null;
// we use the latest description of the table
Element c = XMLUtil.getFirstChild(e);
Map<String, String> codes = new HashMap<String, String>();
Map<String, String> comments = new HashMap<String, String>();
boolean started = false;
while (c != null) {
String ver = c.getAttribute("version");
if (!ver.contains(" ")) {
if ((!started && ver.equals(version)) || (started && !ver.equals(endVersion))) {
started = true;
if (minlim == null)
minlim = ver;
maxlim = ver;
desc = c.getAttribute("desc");
vs.setDescription("FHIR Value set/code system definition for HL7 v2 table " + id + " ver " + ver + " ( " + desc + ")");
Element g = XMLUtil.getFirstChild(c);
while (g != null) {
codes.put(g.getAttribute("code"), g.getAttribute("desc"));
if (!Utilities.noString(g.getAttribute("comments")))
comments.put(g.getAttribute("code"), g.getAttribute("comments"));
g = XMLUtil.getNextSibling(g);
}
} else if (started)
started = false;
}
c = XMLUtil.getNextSibling(c);
}
s.append("<p>").append(Utilities.escapeXml(desc)).append("</p>\r\n");
s.append("<table class=\"grid\">");
s.append("<tr><td><b>Code</b></td><td><b>Description</b></td><td><b>Version</b></td></tr>");
List<String> cs = new ArrayList<String>();
cs.addAll(codes.keySet());
Collections.sort(cs);
started = false;
for (String cd : cs) {
String min = null;
String max = null;
c = XMLUtil.getFirstChild(e);
started = false;
while (c != null) {
String ver = c.getAttribute("version");
if (!ver.contains(" ")) {
if ((!started && ver.equals(version)) || (started && !ver.equals(endVersion))) {
started = true;
Element g = XMLUtil.getFirstChild(c);
while (g != null) {
if (cd.equals(g.getAttribute("code"))) {
if (min == null)
min = ver;
max = ver;
}
g = XMLUtil.getNextSibling(g);
}
} else if (started)
started = false;
}
c = XMLUtil.getNextSibling(c);
}
String ver = (minlim.equals(min) ? "from v" + minlim : "added v" + min) + (maxlim.equals(max) ? "" : ", removed after v" + max);
ConceptDefinitionComponent concept = new ValueSet.ConceptDefinitionComponent();
concept.setCode(cd);
concept.setDisplay(codes.get(cd)); // we deem the v2 description to
if (comments.containsKey(cd))
ToolingExtensions.addComment(concept, comments.get(cd));
// be display name, not
// definition. Open for
// consideration
def.getConcept().add(concept);
s.append("<tr><td>" + Utilities.escapeXml(cd) + "<a name=\"" + Utilities.escapeXml(Utilities.nmtokenize(cd)) + "\"> </a></td><td>"
+ Utilities.escapeXml(codes.get(cd)) + "</td><td>" + ver + "</td></tr>");
}
s.append("</table>\r\n");
vs.setText(new Narrative());
vs.getText().setStatus(NarrativeStatus.ADDITIONAL); // because we add
// v2 versioning
// information
vs.getText().setDiv(new XhtmlParser().parse("<div>" + s.toString() + "</div>", "div").getElement("div"));
page.getVsValidator().validate(errors, "v2 table "+id, vs, false, true);
return vs;
}
public String getIndex(Document v2src) throws IOException {
loadOIds();
StringBuilder s = new StringBuilder();
s.append("<table class=\"grid\">\r\n");
s.append(" <tr><td><b>URI</b></td><td><b>ID</b></td><td><b>Comments</b></td></tr>\r\n");
Element e = XMLUtil.getFirstChild(v2src.getDocumentElement());
while (e != null) {
String id = Utilities.padLeft(e.getAttribute("id"), '0', 4);
if (tables.containsKey(id) || vsImports.containsKey(id)) {
String name = "";
// we use the latest description of the table
Element c = XMLUtil.getFirstChild(e);
while (c != null) {
name = c.getAttribute("desc");
c = XMLUtil.getNextSibling(c);
}
if (tables.containsKey(id) && !tables.get(id).versionPoints.isEmpty()) {
s.append(" <tr><td>http://hl7.org/fhir/v2/").append(id).append("</td><td>").append(name).append("</td><td>").append("Version Dependent. Use one of:<ul>");
for (String v : tables.get(id).versionPoints)
s.append(" <li><a href=\"v2/").append(id).append("/").append(v).append("/index.html\">").append(v).append("+</a></li>");
s.append("</ul></td></tr>\r\n");
} else
s.append(" <tr><td><a href=\"v2/").append(id).append("/index.html\">http://hl7.org/fhir/v2/").append(id).append("</a></td><td>").append(name).append("</td><td></td></tr>\r\n");
}
e = XMLUtil.getNextSibling(e);
}
s.append("</table>\r\n");
return s.toString();
}
public void produce(SectionNumberer sects) throws Exception {
loadOIds();
Element e = XMLUtil.getFirstChild(page.getV2src().getDocumentElement());
while (e != null) {
String id = Utilities.padLeft(e.getAttribute("id"), '0', 4);
String iid = id;
while (iid.startsWith("0"))
iid = iid.substring(1);
if (tables.containsKey(id)) {
if (tables.get(id).versionPoints.isEmpty()) {
Utilities.createDirectory(page.getFolders().dstDir + "v2" + File.separator + id);
Utilities.clearDirectory(page.getFolders().dstDir + "v2" + File.separator + id);
String src = TextFile.fileToString(page.getFolders().srcDir + "v2" + File.separator + "template-tbl.html");
ValueSet vs = page.getValueSets().get("http://hl7.org/fhir/ValueSet/v2-"+id);
String sf = page.processPageIncludes(id + ".html", src, "v2Vocab", null, "v2" + File.separator + id + File.separator + "index.html", vs, null, "V2 Table", null);
sf = sects.addSectionNumbers("v2" + File.separator + id + File.separator + "index.html", "template-v2", sf, iid, 2, null, null);
TextFile.stringToFile(sf, page.getFolders().dstDir + "v2" + File.separator + id + File.separator + "index.html");
page.getEpub().registerExternal("v2" + File.separator + id + File.separator + "index.html");
} else {
Utilities.createDirectory(page.getFolders().dstDir + "v2" + File.separator + id);
Utilities.clearDirectory(page.getFolders().dstDir + "v2" + File.separator + id);
int i = 0;
for (String ver : tables.get(id).versionPoints) {
if (!Utilities.noString(ver)) {
i++;
Utilities.createDirectory(page.getFolders().dstDir + "v2" + File.separator + id + File.separator + ver);
Utilities.clearDirectory(page.getFolders().dstDir + "v2" + File.separator + id + File.separator + ver);
String src = TextFile.fileToString(page.getFolders().srcDir + "v2" + File.separator + "template-tbl-ver.html");
ValueSet vs = page.getValueSets().get("http://hl7.org/fhir/ValueSet/v2-"+FormatUtilities.makeId(ver)+"-"+id);
String sf = page.processPageIncludes(id + "|" + ver + ".html", src, "v2Vocab", null, "v2" + File.separator + id + File.separator + ver + File.separator + "index.html", vs, null, "V2 Table", null);
sf = sects.addSectionNumbers("v2" + File.separator + id + "/" + ver + File.separator + "index.html", "template-v2", sf, iid + "." + Integer.toString(i), 3, null, null);
TextFile.stringToFile(sf, page.getFolders().dstDir + "v2" + File.separator + id + File.separator + ver + File.separator + "index.html");
page.getEpub().registerExternal("v2" + File.separator + id + File.separator + ver + File.separator + "index.html");
}
}
}
} else if (vsImports.containsKey(id)) {
Utilities.createDirectory(page.getFolders().dstDir + "v2" + File.separator + id);
Utilities.clearDirectory(page.getFolders().dstDir + "v2" + File.separator + id);
String src = TextFile.fileToString(page.getFolders().srcDir + "v2" + File.separator + "template-tbl.html");
ValueSet vs = page.getValueSets().get("http://hl7.org/fhir/ValueSet/v2-"+id);
String sf = page.processPageIncludes(id + ".html", src, "v2Vocab", null, "v2" + File.separator + id + File.separator + "index.html", vs, null, "V2 Table", null);
sf = sects.addSectionNumbers("v2" + File.separator + id + File.separator + "index.html", "template-v2", sf, iid, 2, null, null);
TextFile.stringToFile(sf, page.getFolders().dstDir + "v2" + File.separator + id + File.separator + "index.html");
page.getEpub().registerExternal("v2" + File.separator + id + File.separator + "index.html");
}
e = XMLUtil.getNextSibling(e);
}
}
}
|
/*
* 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.spark.network.shuffle;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import com.google.common.collect.Maps;
import io.netty.buffer.Unpooled;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.mockito.AdditionalMatchers.*;
import static org.mockito.Mockito.*;
import org.apache.spark.network.buffer.ManagedBuffer;
import org.apache.spark.network.buffer.NettyManagedBuffer;
import org.apache.spark.network.buffer.NioManagedBuffer;
import org.apache.spark.network.client.RpcResponseCallback;
import org.apache.spark.network.client.TransportClient;
import org.apache.spark.network.shuffle.protocol.BlockTransferMessage;
import org.apache.spark.network.shuffle.protocol.PushBlockStream;
public class OneForOneBlockPusherSuite {
@Test
public void testPushOne() {
LinkedHashMap<String, ManagedBuffer> blocks = Maps.newLinkedHashMap();
blocks.put("shufflePush_0_0_0", new NioManagedBuffer(ByteBuffer.wrap(new byte[1])));
String[] blockIds = blocks.keySet().toArray(new String[blocks.size()]);
BlockPushingListener listener = pushBlocks(
blocks,
blockIds,
Arrays.asList(new PushBlockStream("app-id", 0, 0, 0, 0, 0)));
verify(listener).onBlockPushSuccess(eq("shufflePush_0_0_0"), any());
}
@Test
public void testPushThree() {
LinkedHashMap<String, ManagedBuffer> blocks = Maps.newLinkedHashMap();
blocks.put("shufflePush_0_0_0", new NioManagedBuffer(ByteBuffer.wrap(new byte[12])));
blocks.put("shufflePush_0_1_0", new NioManagedBuffer(ByteBuffer.wrap(new byte[23])));
blocks.put("shufflePush_0_2_0", new NettyManagedBuffer(Unpooled.wrappedBuffer(new byte[23])));
String[] blockIds = blocks.keySet().toArray(new String[blocks.size()]);
BlockPushingListener listener = pushBlocks(
blocks,
blockIds,
Arrays.asList(new PushBlockStream("app-id",0, 0, 0, 0, 0),
new PushBlockStream("app-id", 0, 0, 1, 0, 1),
new PushBlockStream("app-id", 0, 0, 2, 0, 2)));
verify(listener, times(1)).onBlockPushSuccess(eq("shufflePush_0_0_0"), any());
verify(listener, times(1)).onBlockPushSuccess(eq("shufflePush_0_1_0"), any());
verify(listener, times(1)).onBlockPushSuccess(eq("shufflePush_0_2_0"), any());
}
@Test
public void testServerFailures() {
LinkedHashMap<String, ManagedBuffer> blocks = Maps.newLinkedHashMap();
blocks.put("shufflePush_0_0_0", new NioManagedBuffer(ByteBuffer.wrap(new byte[12])));
blocks.put("shufflePush_0_1_0", new NioManagedBuffer(ByteBuffer.wrap(new byte[0])));
blocks.put("shufflePush_0_2_0", new NioManagedBuffer(ByteBuffer.wrap(new byte[0])));
String[] blockIds = blocks.keySet().toArray(new String[blocks.size()]);
BlockPushingListener listener = pushBlocks(
blocks,
blockIds,
Arrays.asList(new PushBlockStream("app-id", 0, 0, 0, 0, 0),
new PushBlockStream("app-id", 0, 0, 1, 0, 1),
new PushBlockStream("app-id", 0, 0, 2, 0, 2)));
verify(listener, times(1)).onBlockPushSuccess(eq("shufflePush_0_0_0"), any());
verify(listener, times(1)).onBlockPushFailure(eq("shufflePush_0_1_0"), any());
verify(listener, times(1)).onBlockPushFailure(eq("shufflePush_0_2_0"), any());
}
@Test
public void testHandlingRetriableFailures() {
LinkedHashMap<String, ManagedBuffer> blocks = Maps.newLinkedHashMap();
blocks.put("shufflePush_0_0_0", new NioManagedBuffer(ByteBuffer.wrap(new byte[12])));
blocks.put("shufflePush_0_1_0", null);
blocks.put("shufflePush_0_2_0", new NioManagedBuffer(ByteBuffer.wrap(new byte[0])));
String[] blockIds = blocks.keySet().toArray(new String[blocks.size()]);
BlockPushingListener listener = pushBlocks(
blocks,
blockIds,
Arrays.asList(new PushBlockStream("app-id", 0, 0, 0, 0, 0),
new PushBlockStream("app-id", 0, 0, 1, 0, 1),
new PushBlockStream("app-id", 0, 0, 2, 0, 2)));
verify(listener, times(1)).onBlockPushSuccess(eq("shufflePush_0_0_0"), any());
verify(listener, times(0)).onBlockPushSuccess(not(eq("shufflePush_0_0_0")), any());
verify(listener, times(0)).onBlockPushFailure(eq("shufflePush_0_0_0"), any());
verify(listener, times(1)).onBlockPushFailure(eq("shufflePush_0_1_0"), any());
verify(listener, times(2)).onBlockPushFailure(eq("shufflePush_0_2_0"), any());
}
/**
* Begins a push on the given set of blocks by mocking the response from server side.
* If a block is an empty byte, a server side retriable exception will be thrown.
* If a block is null, a non-retriable exception will be thrown.
*/
private static BlockPushingListener pushBlocks(
LinkedHashMap<String, ManagedBuffer> blocks,
String[] blockIds,
Iterable<BlockTransferMessage> expectMessages) {
TransportClient client = mock(TransportClient.class);
BlockPushingListener listener = mock(BlockPushingListener.class);
OneForOneBlockPusher pusher =
new OneForOneBlockPusher(client, "app-id", 0, blockIds, listener, blocks);
Iterator<Map.Entry<String, ManagedBuffer>> blockIterator = blocks.entrySet().iterator();
Iterator<BlockTransferMessage> msgIterator = expectMessages.iterator();
doAnswer(invocation -> {
ByteBuffer header = ((ManagedBuffer) invocation.getArguments()[0]).nioByteBuffer();
BlockTransferMessage message = BlockTransferMessage.Decoder.fromByteBuffer(header);
RpcResponseCallback callback = (RpcResponseCallback) invocation.getArguments()[2];
Map.Entry<String, ManagedBuffer> entry = blockIterator.next();
ManagedBuffer block = entry.getValue();
if (block != null && block.nioByteBuffer().capacity() > 0) {
callback.onSuccess(header);
} else if (block != null) {
callback.onFailure(new RuntimeException("Failed " + entry.getKey()
+ ErrorHandler.BlockPushErrorHandler.BLOCK_APPEND_COLLISION_DETECTED_MSG_PREFIX));
} else {
callback.onFailure(new RuntimeException("Quick fail " + entry.getKey()
+ ErrorHandler.BlockPushErrorHandler.TOO_LATE_MESSAGE_SUFFIX));
}
assertEquals(msgIterator.next(), message);
return null;
}).when(client).uploadStream(any(ManagedBuffer.class), any(), any(RpcResponseCallback.class));
pusher.start();
return listener;
}
}
|
package com.alishangtian.nettyexample.objectecho;
import com.alibaba.fastjson.JSON;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Handles both client-side and server-side handler depending on which constructor was called.
*/
public class ObjectEchoServerHandler extends ChannelInboundHandlerAdapter {
private static Logger logger = LoggerFactory.getLogger(ObjectEchoClientHandler.class);
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
logger.info("msg from client,address:{},msg:{}", ctx.channel().remoteAddress(), JSON.toJSONString(msg));
ctx.write(new Message("pong"));
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
|
package com.bumptech.glide.util;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketTimeoutException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class ExceptionCatchingInputStreamTest {
private InputStream wrapped;
private ExceptionCatchingInputStream is;
@Before
public void setUp() throws Exception {
wrapped = mock(InputStream.class);
is = new ExceptionCatchingInputStream();
is.setInputStream(wrapped);
}
@After
public void tearDown() {
ExceptionCatchingInputStream.clearQueue();
}
@Test
public void testReturnsWrappedAvailable() throws IOException {
when(wrapped.available()).thenReturn(25);
assertEquals(25, is.available());
}
@Test
public void testCallsCloseOnWrapped() throws IOException {
is.close();
verify(wrapped).close();
}
@Test
public void testCallsMarkOnWrapped() {
int toMark = 50;
is.mark(toMark);
verify(wrapped).mark(eq(toMark));
}
@Test
public void testReturnsWrappedMarkSupported() {
when(wrapped.markSupported()).thenReturn(true);
assertTrue(is.markSupported());
}
@Test
public void testCallsReadByteArrayOnWrapped() throws IOException {
byte[] buffer = new byte[100];
when(wrapped.read(eq(buffer))).thenReturn(buffer.length);
assertEquals(buffer.length, is.read(buffer));
}
@Test
public void testCallsReadArrayWithOffsetAndCountOnWrapped() throws IOException {
int offset = 5;
int count = 100;
byte[] buffer = new byte[105];
when(wrapped.read(eq(buffer), eq(offset), eq(count))).thenReturn(count);
assertEquals(count, is.read(buffer, offset, count));
}
@Test
public void testCallsReadOnWrapped() throws IOException {
when(wrapped.read()).thenReturn(1);
assertEquals(1, is.read());
}
@Test
public void testCallsResetOnWrapped() throws IOException {
is.reset();
verify(wrapped).reset();
}
@Test
public void testCallsSkipOnWrapped() throws IOException {
long toSkip = 67;
long expected = 55;
when(wrapped.skip(eq(toSkip))).thenReturn(expected);
assertEquals(expected, is.skip(toSkip));
}
@Test
public void testCatchesExceptionOnRead() throws IOException {
IOException expected = new SocketTimeoutException();
when(wrapped.read()).thenThrow(expected);
int read = is.read();
assertEquals(-1, read);
assertEquals(expected, is.getException());
}
@Test
public void testCatchesExceptionOnReadBuffer() throws IOException {
IOException exception = new SocketTimeoutException();
when(wrapped.read(any(byte[].class))).thenThrow(exception);
int read = is.read(new byte[0]);
assertEquals(-1, read);
assertEquals(exception, is.getException());
}
@Test
public void testCatchesExceptionOnReadBufferWithOffsetAndCount() throws IOException {
IOException exception = new SocketTimeoutException();
when(wrapped.read(any(byte[].class), anyInt(), anyInt())).thenThrow(exception);
int read = is.read(new byte[0], 10, 100);
assertEquals(-1, read);
assertEquals(exception, is.getException());
}
@Test
public void testCatchesExceptionOnSkip() throws IOException {
IOException exception = new SocketTimeoutException();
when(wrapped.skip(anyLong())).thenThrow(exception);
long skipped = is.skip(100);
assertEquals(0, skipped);
assertEquals(exception, is.getException());
}
@Test
public void testExceptionIsNotSetInitially() {
assertNull(is.getException());
}
@SuppressWarnings("ResultOfMethodCallIgnored")
@Test
public void testResetsExceptionToNullOnRelease() throws IOException {
IOException exception = new SocketTimeoutException();
when(wrapped.read()).thenThrow(exception);
is.read();
is.release();
assertNull(is.getException());
}
@Test
public void testCanReleaseAnObtainFromPool() {
is.release();
InputStream fromPool = ExceptionCatchingInputStream.obtain(wrapped);
assertEquals(is, fromPool);
}
@Test
public void testCanObtainNewStreamFromPool() throws IOException {
InputStream fromPool = ExceptionCatchingInputStream.obtain(wrapped);
when(wrapped.read()).thenReturn(1);
int read = fromPool.read();
assertEquals(1, read);
}
}
|
package org.joder.stock.core.service.process;
import org.joder.stock.core.StockStrategy;
/**
* @author Joder 2020/8/15 15:48
*/
public abstract class AbstractBackTestProcess implements BackTestProcess {
protected StockStrategy getStrategy(String code) {
return StockStrategy.parseStrategy(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 com.globo.globonetwork.cloudstack.api.loadbalancer;
import com.cloud.event.EventTypes;
import com.cloud.exception.NetworkRuleConflictException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.IpAddress;
import com.cloud.network.Network;
import com.cloud.network.addr.PublicIp;
import com.cloud.network.rules.HealthCheckPolicy;
import com.cloud.network.rules.StickinessPolicy;
import com.cloud.utils.StringUtils;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.exception.UserCloudRuntimeException;
import com.globo.globonetwork.cloudstack.manager.GloboNetworkService;
import com.globo.globonetwork.cloudstack.manager.HealthCheckHelper;
import com.globo.globonetwork.cloudstack.resource.GloboNetworkResource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.inject.Inject;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiCommandJobType;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.BaseAsyncCmd;
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.command.user.loadbalancer.CreateLBHealthCheckPolicyCmd;
import org.apache.cloudstack.api.command.user.loadbalancer.CreateLBStickinessPolicyCmd;
import org.apache.cloudstack.api.command.user.loadbalancer.CreateLoadBalancerRuleCmd;
import org.apache.cloudstack.api.response.LoadBalancerResponse;
import org.apache.cloudstack.api.response.ProjectResponse;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.globoconfig.GloboResourceConfiguration;
import org.apache.cloudstack.globoconfig.GloboResourceConfigurationVO;
import org.apache.cloudstack.globoconfig.GloboResourceType;
import org.apache.log4j.Logger;
@APICommand(name = "createGloboLoadBalancer", description = "Creates a globo load balancer", responseObject = LoadBalancerResponse.class,
requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
public class CreateGloboLoadBalancerCmd extends CreateLoadBalancerRuleCmd /*implements LoadBalancer */{
public static final Logger s_logger = Logger.getLogger(CreateGloboLoadBalancerCmd.class.getName());
private static final String s_name = "creategloboloadbalancerresponse";
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
/////////////////////////////////////////////////////
@Inject
private GloboNetworkService globoNetworkSvc;
@Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.UUID, entityType = ProjectResponse.class, description = "Project the IP address will be associated with")
private Long projectId;
@Parameter(name = "lbenvironmentid", type = CommandType.LONG, description = "Globo Network LB Environment Id", required = true)
private Long globoNetworkLBEnvironmentId;
@Parameter(name = "healthcheckrequest", type = CommandType.STRING, required = false, description = "HTTP Request Path (ex: /healthcheck.html)")
private String healthcheckRequest;
@Parameter(name = "stickinessmethodname", type = CommandType.STRING,
description = "name of the LB Stickiness policy method.")
private String stickinessMethodName;
private static final String DEFAULT_ERROR_MESSAGE = "Error trying to create load balancer, please contact your system administrator.";
@Inject
GloboNetworkService _globoNetworkService;
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
private boolean ipCreated = false;
private CreateLBHealthCheckPolicyCmd healthCmd;
private CreateLBStickinessPolicyCmd stickinessCmd;
private Long ipAddressId = null;
@Override
public String getCommandName() {
return s_name;
}
@Override
public void create() throws CloudRuntimeException{
validation();
CallContext current = CallContext.current();
final String name = getName();
try {
PublicIp ip = globoNetworkSvc.acquireLbIp(getNetworkId(), getProjectId(), getGloboNetworkLBEnvironmentId());
IpAddress ipAddress = _networkService.associateIPToNetwork(ip.getId(), getNetworkId());
ipAddressId = ipAddress.getId();
ipCreated = true;
setPublicIpId(ip.getId());
setSourceIpAddressId(ipAddress.getId());
s_logger.debug("[load_balancer " + name + "] portable ip created with id " + ip.getId() + ", ipaddress " + ipAddress.getId());
super.create();
} catch (UserCloudRuntimeException e) {
throw e;
} catch (Exception e) {
s_logger.error("[load_balancer " + name + "] error creating load balancer ", e);
handleErrorAfterIpCreated(name, ipCreated, ipAddressId);
String msg = DEFAULT_ERROR_MESSAGE;
if ( current != null) {
msg += " Context: " + current.getNdcContext() + ". Error: " + e.getLocalizedMessage();
}
throw new CloudRuntimeException(msg, e);
}
}
@Override
public void execute() throws ResourceAllocationException, ResourceUnavailableException {
final String name = getName();
try {
s_logger.debug("[load_balancer " + name + "] processing execute createGloboLoadBalance");
super.execute();
createHealthcheck();
createStickiness();
loadGloboResourceConfig();
} catch (Exception e) {
s_logger.warn("[load_balancer " + name + "] removing loadbalancer after error", e);
_lbService.deleteLoadBalancerRule(getEntityId(), false);
handleErrorAfterIpCreated(name, ipCreated, ipAddressId);
throw e;
}
}
private void validation() {
HealthCheckHelper healthcheck = HealthCheckHelper.build(getName(), getHealthCheckType(), healthcheckRequest, getExpectedHealthCheck());
if ( HealthCheckHelper.HealthCheckType.isLayer7(healthcheck.getHealthCheckType())
&& healthcheck.getHealthCheck().isEmpty()) {
throw new CloudRuntimeException("Health check validation: when health check type is HTTP/HTTPS, health check request can not be empty. type: " + healthcheck.getHealthCheckType() + ", request: " + healthcheck.getHealthCheck());
}
if (stickinessMethodName != null && !stickinessMethodName.isEmpty())
GloboNetworkResource.PersistenceMethod.validateValue(stickinessMethodName);
}
protected void createStickiness() throws ResourceUnavailableException {
final String name = getName();
if (!isToCreateStickiness()) {
s_logger.debug("[load_balancer " + name + "] it is not necessary to create stickiness. stickinessmethodname: " + stickinessMethodName);
return;
}
try {
s_logger.debug("[load_balancer " + name + "] creating stickiness policy ");
stickinessCmd = new CreateLBStickinessPolicyCmd();
stickinessCmd.setStickinessMethodName(stickinessMethodName);
stickinessCmd.setLbStickinessPolicyName(stickinessMethodName);
stickinessCmd.setLbRuleId(getEntityId());
StickinessPolicy result = _lbService.createLBStickinessPolicy(stickinessCmd);
stickinessCmd.setEntityId(result.getId());
stickinessCmd.setEntityUuid(result.getUuid());
boolean success = _lbService.applyLBStickinessPolicy(stickinessCmd); // with error it already rollback the stickiness
if (!success) {
throw new CloudRuntimeException(DEFAULT_ERROR_MESSAGE);
}
} catch (NetworkRuleConflictException e) {
throw new CloudRuntimeException(DEFAULT_ERROR_MESSAGE, e);
}
}
protected void createHealthcheck() {
final String name = getName();
if (!isToCreateHealthcheck()) {
s_logger.debug("[load_balancer " + name + "] it is not necessary to create healthcheck. healthcheckRequest: " + healthcheckRequest);
return;
}
s_logger.debug("[load_balancer " + name + "] creating healthcheck ");
healthCmd = new CreateLBHealthCheckPolicyCmd();
healthCmd.setFullUrlParams(new HashMap<String, String>());
healthCmd.setPingPath(healthcheckRequest);
healthCmd.setLbRuleId(this.getEntityId());
HealthCheckPolicy healthcheck = _lbService.createLBHealthCheckPolicy(healthCmd);
healthCmd.setEntityId(healthcheck.getId());
healthCmd.setEntityUuid(healthcheck.getUuid());
s_logger.debug("[load_balancer " + name + "] apply healthcheck: " + healthcheck.getUuid());
try {
_lbService.applyLBHealthCheckPolicy(healthCmd); // with error it already rollback the healthcheck
} catch (ResourceUnavailableException e) {
throw new CloudRuntimeException(DEFAULT_ERROR_MESSAGE, e);
}
}
private void loadGloboResourceConfig() {
LoadBalancerResponse lbResponse = (LoadBalancerResponse)getResponseObject();
List<GloboResourceConfigurationVO> globoResourceConfigs = _globoNetworkService.getGloboResourceConfigs(this.getEntityUuid(), GloboResourceType.LOAD_BALANCER);
List<LoadBalancerResponse.GloboResourceConfigurationResponse> configs = new ArrayList<LoadBalancerResponse.GloboResourceConfigurationResponse>();
for (GloboResourceConfiguration config : globoResourceConfigs) {
LoadBalancerResponse.GloboResourceConfigurationResponse conf = new LoadBalancerResponse.GloboResourceConfigurationResponse();
conf.setConfigurationKey(config.getKey().name());
conf.setConfigurationValue(config.getValue());
configs.add(conf);
}
lbResponse.setGloboResourceConfigs(configs);
}
@Override
public long getEntityOwnerId() {
return getAccountId();
}
@Override
public String getEventType() {
return EventTypes.EVENT_LOAD_BALANCER_CREATE;
}
@Override
public String getEventDescription() {
return "creating load balancer: " + getName() + " account: " + getAccountName();
}
@Override
public ApiCommandJobType getInstanceType() {
return ApiCommandJobType.FirewallRule;
}
@Override
public String getSyncObjType() {
return BaseAsyncCmd.networkSyncObject;
}
@Override
public Long getSyncObjId() {
return getNetworkId();
}
public Long getProjectId() {
return projectId;
}
public void setProjectId(Long projectId) {
this.projectId = projectId;
}
public Long getGloboNetworkLBEnvironmentId() {
return globoNetworkLBEnvironmentId;
}
public void setGloboNetworkLBEnvironmentId(Long globoNetworkLBEnvironmentId) {
this.globoNetworkLBEnvironmentId = globoNetworkLBEnvironmentId;
}
public long getAccountId() {
long networkId = getNetworkId();
Network network = _networkService.getNetwork(networkId);
return network.getAccountId();
}
private void handleErrorAfterIpCreated(String lbName, boolean ipCreated, Long ipAddressId) {
if (ipCreated) {
boolean result = globoNetworkSvc.disassociateIpAddrFromGloboNetwork(ipAddressId);
if (result) {
s_logger.warn("[load_balancer " + lbName + "] error after try to disassociateIp " + ipAddressId);
}
}
}
public boolean isToCreateStickiness() {
return stickinessMethodName != null && !stickinessMethodName.isEmpty();
}
public boolean isToCreateHealthcheck() {
return healthcheckRequest != null && !healthcheckRequest.isEmpty();
}
public void setPingPath(String pingPath) {
this.healthcheckRequest = pingPath;
}
public void setStickinessMethodName(String stickinessMethodName) {
this.stickinessMethodName = stickinessMethodName;
}
public String getStickinessMethodName() {
return stickinessMethodName;
}
@Override
public String getHealthCheckType() {
try {
HealthCheckHelper.HealthCheckType.valueOf(healthCheckType);
}catch (IllegalArgumentException e) {
throw new UserCloudRuntimeException("Health check type \'"+ healthCheckType + "\' not allow, possible values: " + StringUtils.join(", ", HealthCheckHelper.HealthCheckType.values()) + ".");
}
return healthCheckType;
}
}
|
/**
* Copyright (C) 2012 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.dashboard.ui.config.components.panelInstance;
import javax.enterprise.context.SessionScoped;
import org.jboss.dashboard.ui.UIServices;
import org.jboss.dashboard.workspace.PanelInstance;
import org.jboss.dashboard.workspace.WorkspaceImpl;
import org.jboss.dashboard.workspace.WorkspacesManager;
import org.jboss.dashboard.workspace.PanelInstance;
import org.jboss.dashboard.workspace.PanelProviderParameter;
import org.jboss.dashboard.workspace.WorkspaceImpl;
import org.jboss.dashboard.workspace.WorkspacesManager;
@SessionScoped
public class PanelInstanceSpecificPropertiesHandler extends PanelInstancePropertiesHandler {
public WorkspacesManager getWorkspacesManager() {
return UIServices.lookup().getWorkspacesManager();
}
public PanelProviderParameter[] getPanelProviderParameters(PanelInstance instance) {
return instance.getCustomParameters();
}
public void savePanelInstanceProperties(PanelInstance instance) throws Exception {
instance.saveCustomProperties();
}
public PanelInstance getPanelInstance() throws Exception {
return ((WorkspaceImpl) getWorkspacesManager().getWorkspace(getWorkspaceId())).getPanelInstance(getPanelInstanceId());
}
public PanelInstance getPanelInstance(String workspaceId, Long panelId) throws Exception {
return ((WorkspaceImpl) getWorkspacesManager().getWorkspace(workspaceId)).getPanelInstance(panelId);
}
}
|
/*
* Copyright 2020 The Federal Authorities of the Swiss Confederation
*
* 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 ch.admin.localsigner.listener;
import java.io.File;
import org.apache.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import ch.admin.localsigner.gui.profile.PropertiesGUI;
/**
* This listener is called when the user clicks the 'choose' button to find the
* background image for the signature.
* @author boris
* @author $Author$
* @version $Revision$
*/
public class ChooseImageListener implements Listener {
private static final Logger LOGGER = Logger.getLogger(ChooseImageListener.class);
private final PropertiesGUI propertiesGui;
private final Shell shell;
/**
* Constructor
* @param propertiesGui
* properties GUI
* @param shell
* Parent shell
*/
public ChooseImageListener(final PropertiesGUI propertiesGui,
final Shell shell) {
this.propertiesGui = propertiesGui;
this.shell = shell;
}
/**
* Handle listener event.
* @param event
*/
@Override
public void handleEvent(final Event event) {
LOGGER.debug("choose image listener");
// open a dialog for pdf file loading
final FileDialog dialog = new FileDialog(this.shell, SWT.OPEN);
dialog.setFilterNames(new String[] { "JPEG" });
dialog.setFilterExtensions(new String[] { "*.jpg" });
dialog.open();
// if the user did not select a file just return
if (dialog.getFileName().equals("")) {
return;
}
final String path = dialog.getFilterPath() + File.separator
+ dialog.getFileName();
// store into gui
propertiesGui.setBackgroundImage(path);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.