text
stringlengths 7
1.01M
|
|---|
/**
* generated by Xtext 2.12.0
*/
package markHammil.mm.myDsl.tests;
import junit.textui.TestRunner;
import markHammil.mm.myDsl.MyDslFactory;
import markHammil.mm.myDsl.ScratchExpression;
/**
* <!-- begin-user-doc -->
* A test case for the model object '<em><b>Scratch Expression</b></em>'.
* <!-- end-user-doc -->
* @generated
*/
public class ScratchExpressionTest extends EmphasisExpressionTest {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static void main(String[] args) {
TestRunner.run(ScratchExpressionTest.class);
}
/**
* Constructs a new Scratch Expression test case with the given name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ScratchExpressionTest(String name) {
super(name);
}
/**
* Returns the fixture for this Scratch Expression test case.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected ScratchExpression getFixture() {
return (ScratchExpression)fixture;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see junit.framework.TestCase#setUp()
* @generated
*/
@Override
protected void setUp() throws Exception {
setFixture(MyDslFactory.eINSTANCE.createScratchExpression());
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see junit.framework.TestCase#tearDown()
* @generated
*/
@Override
protected void tearDown() throws Exception {
setFixture(null);
}
} //ScratchExpressionTest
|
package VerificatorInterpritator.Tokens;
import java.util.ArrayList;
import java.util.List;
public class Function {
private String name;
private SimpleType argument;
private List<SimpleType> result = new ArrayList<>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public SimpleType getArgument() {
return argument;
}
public void setArgument(SimpleType argument) {
this.argument = argument;
}
public List<SimpleType> getResult() {
return result;
}
public void setResult(List<SimpleType> result) {
this.result = result;
}
public String toString() {
final String[] ans = {""};
ans[0] = "<" + name + " " + argument.toString() + "> == ";
result.stream().forEach(simpleType -> ans[0] = ans[0] + " " + simpleType.toString());
return ans[0];
}
}
|
package com.t2tierp.folhapagamento.java;
import com.t2tierp.cadastros.java.ColaboradorVO;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.openswing.swing.message.receive.java.ValueObjectImpl;
/**
* <p>Title: T2Ti ERP
* <p>Description: VO relacionado a tabela [FOLHA_RESCISAO]
*
* <p>The MIT License
*
* <p>Copyright: Copyright (C) 2010 T2Ti.COM
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* The author may be contacted at:
* t2ti.com@gmail.com</p>
*
* @author Claudio de Barros (t2ti.com@gmail.com)
* @version 1.0
*/
@Entity
@Table(name = "FOLHA_RESCISAO")
public class FolhaRescisaoVO extends ValueObjectImpl implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "ID")
private Integer id;
@Temporal(TemporalType.DATE)
@Column(name = "DATA_DEMISSAO")
private Date dataDemissao;
@Temporal(TemporalType.DATE)
@Column(name = "DATA_PAGAMENTO")
private Date dataPagamento;
@Column(name = "MOTIVO")
private String motivo;
@Temporal(TemporalType.DATE)
@Column(name = "DATA_AVISO_PREVIO")
private Date dataAvisoPrevio;
@Column(name = "DIAS_AVISO_PREVIO")
private Integer diasAvisoPrevio;
@Column(name = "COMPROVOU_NOVO_EMPREGO")
private String comprovouNovoEmprego;
@Column(name = "DISPENSOU_EMPREGADO")
private String dispensouEmpregado;
@Column(name = "PENSAO_ALIMENTICIA")
private BigDecimal pensaoAlimenticia;
@Column(name = "PENSAO_ALIMENTICIA_FGTS")
private BigDecimal pensaoAlimenticiaFgts;
@Column(name = "FGTS_VALOR_RESCISAO")
private BigDecimal fgtsValorRescisao;
@Column(name = "FGTS_SALDO_BANCO")
private BigDecimal fgtsSaldoBanco;
@Column(name = "FGTS_COMPLEMENTO_SALDO")
private BigDecimal fgtsComplementoSaldo;
@Column(name = "FGTS_CODIGO_AFASTAMENTO")
private String fgtsCodigoAfastamento;
@Column(name = "FGTS_CODIGO_SAQUE")
private String fgtsCodigoSaque;
@JoinColumn(name = "ID_COLABORADOR", referencedColumnName = "ID")
@ManyToOne(optional = false)
private ColaboradorVO colaborador;
public FolhaRescisaoVO() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Date getDataDemissao() {
return dataDemissao;
}
public void setDataDemissao(Date dataDemissao) {
this.dataDemissao = dataDemissao;
}
public Date getDataPagamento() {
return dataPagamento;
}
public void setDataPagamento(Date dataPagamento) {
this.dataPagamento = dataPagamento;
}
public String getMotivo() {
return motivo;
}
public void setMotivo(String motivo) {
this.motivo = motivo;
}
public Date getDataAvisoPrevio() {
return dataAvisoPrevio;
}
public void setDataAvisoPrevio(Date dataAvisoPrevio) {
this.dataAvisoPrevio = dataAvisoPrevio;
}
public Integer getDiasAvisoPrevio() {
return diasAvisoPrevio;
}
public void setDiasAvisoPrevio(Integer diasAvisoPrevio) {
this.diasAvisoPrevio = diasAvisoPrevio;
}
public String getComprovouNovoEmprego() {
return comprovouNovoEmprego;
}
public void setComprovouNovoEmprego(String comprovouNovoEmprego) {
this.comprovouNovoEmprego = comprovouNovoEmprego;
}
public String getDispensouEmpregado() {
return dispensouEmpregado;
}
public void setDispensouEmpregado(String dispensouEmpregado) {
this.dispensouEmpregado = dispensouEmpregado;
}
public BigDecimal getPensaoAlimenticia() {
return pensaoAlimenticia;
}
public void setPensaoAlimenticia(BigDecimal pensaoAlimenticia) {
this.pensaoAlimenticia = pensaoAlimenticia;
}
public BigDecimal getPensaoAlimenticiaFgts() {
return pensaoAlimenticiaFgts;
}
public void setPensaoAlimenticiaFgts(BigDecimal pensaoAlimenticiaFgts) {
this.pensaoAlimenticiaFgts = pensaoAlimenticiaFgts;
}
public BigDecimal getFgtsValorRescisao() {
return fgtsValorRescisao;
}
public void setFgtsValorRescisao(BigDecimal fgtsValorRescisao) {
this.fgtsValorRescisao = fgtsValorRescisao;
}
public BigDecimal getFgtsSaldoBanco() {
return fgtsSaldoBanco;
}
public void setFgtsSaldoBanco(BigDecimal fgtsSaldoBanco) {
this.fgtsSaldoBanco = fgtsSaldoBanco;
}
public BigDecimal getFgtsComplementoSaldo() {
return fgtsComplementoSaldo;
}
public void setFgtsComplementoSaldo(BigDecimal fgtsComplementoSaldo) {
this.fgtsComplementoSaldo = fgtsComplementoSaldo;
}
public String getFgtsCodigoAfastamento() {
return fgtsCodigoAfastamento;
}
public void setFgtsCodigoAfastamento(String fgtsCodigoAfastamento) {
this.fgtsCodigoAfastamento = fgtsCodigoAfastamento;
}
public String getFgtsCodigoSaque() {
return fgtsCodigoSaque;
}
public void setFgtsCodigoSaque(String fgtsCodigoSaque) {
this.fgtsCodigoSaque = fgtsCodigoSaque;
}
public ColaboradorVO getColaborador() {
return colaborador;
}
public void setColaborador(ColaboradorVO colaborador) {
this.colaborador = colaborador;
}
}
|
package ly.com.project.sample0503;
import android.opengl.GLES20;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import ly.com.base.utils.Constant;
import ly.com.base.utils.MatrixState;
import ly.com.base.utils.ShaderUtil;
/**
* @author:ly on 2019-11-23 21:05
* @mail:liuyan@zhimei.ai
*/
public class Cube {
int mProgram;//自定义渲染管线着色器程序id
int muMVPMatrixHandle;//总变换矩阵引用
int maPositionHandle; //顶点位置属性引用
int maColorHandle; //顶点颜色属性引用
String mVertexShader;//顶点着色器代码脚本
String mFragmentShader;//片元着色器代码脚本
FloatBuffer mVertexBuffer;//顶点坐标数据缓冲
FloatBuffer mColorBuffer;//顶点着色数据缓冲
int vCount=0;
public Cube(Project0503SurfaceView mv)
{
//初始化顶点坐标与着色数据
initVertexData();
//初始化shader
initShader(mv);
}
//初始化顶点坐标与着色数据的方法
public void initVertexData()
{
//顶点坐标数据的初始化================begin============================
vCount=12*6;
float vertices[]=new float[]
{
//前面
0,0, Constant.UNIT_SIZE,
Constant.UNIT_SIZE,Constant.UNIT_SIZE,Constant.UNIT_SIZE,
-Constant.UNIT_SIZE,Constant.UNIT_SIZE,Constant.UNIT_SIZE,
0,0,Constant.UNIT_SIZE,
-Constant.UNIT_SIZE,Constant.UNIT_SIZE,Constant.UNIT_SIZE,
-Constant.UNIT_SIZE,-Constant.UNIT_SIZE,Constant.UNIT_SIZE,
0,0,Constant.UNIT_SIZE,
-Constant.UNIT_SIZE,-Constant.UNIT_SIZE,Constant.UNIT_SIZE,
Constant.UNIT_SIZE,-Constant.UNIT_SIZE,Constant.UNIT_SIZE,
0,0,Constant.UNIT_SIZE,
Constant.UNIT_SIZE,-Constant.UNIT_SIZE,Constant.UNIT_SIZE,
Constant.UNIT_SIZE,Constant.UNIT_SIZE,Constant.UNIT_SIZE,
//后面
0,0,-Constant.UNIT_SIZE,
Constant.UNIT_SIZE,Constant.UNIT_SIZE,-Constant.UNIT_SIZE,
Constant.UNIT_SIZE,-Constant.UNIT_SIZE,-Constant.UNIT_SIZE,
0,0,-Constant.UNIT_SIZE,
Constant.UNIT_SIZE,-Constant.UNIT_SIZE,-Constant.UNIT_SIZE,
-Constant.UNIT_SIZE,-Constant.UNIT_SIZE,-Constant.UNIT_SIZE,
0,0,-Constant.UNIT_SIZE,
-Constant.UNIT_SIZE,-Constant.UNIT_SIZE,-Constant.UNIT_SIZE,
-Constant.UNIT_SIZE,Constant.UNIT_SIZE,-Constant.UNIT_SIZE,
0,0,-Constant.UNIT_SIZE,
-Constant.UNIT_SIZE,Constant.UNIT_SIZE,-Constant.UNIT_SIZE,
Constant.UNIT_SIZE,Constant.UNIT_SIZE,-Constant.UNIT_SIZE,
//左面
-Constant.UNIT_SIZE,0,0,
-Constant.UNIT_SIZE,Constant.UNIT_SIZE,Constant.UNIT_SIZE,
-Constant.UNIT_SIZE,Constant.UNIT_SIZE,-Constant.UNIT_SIZE,
-Constant.UNIT_SIZE,0,0,
-Constant.UNIT_SIZE,Constant.UNIT_SIZE,-Constant.UNIT_SIZE,
-Constant.UNIT_SIZE,-Constant.UNIT_SIZE,-Constant.UNIT_SIZE,
-Constant.UNIT_SIZE,0,0,
-Constant.UNIT_SIZE,-Constant.UNIT_SIZE,-Constant.UNIT_SIZE,
-Constant.UNIT_SIZE,-Constant.UNIT_SIZE,Constant.UNIT_SIZE,
-Constant.UNIT_SIZE,0,0,
-Constant.UNIT_SIZE,-Constant.UNIT_SIZE,Constant.UNIT_SIZE,
-Constant.UNIT_SIZE,Constant.UNIT_SIZE,Constant.UNIT_SIZE,
//右面
Constant.UNIT_SIZE,0,0,
Constant.UNIT_SIZE,Constant.UNIT_SIZE,Constant.UNIT_SIZE,
Constant.UNIT_SIZE,-Constant.UNIT_SIZE,Constant.UNIT_SIZE,
Constant.UNIT_SIZE,0,0,
Constant.UNIT_SIZE,-Constant.UNIT_SIZE,Constant.UNIT_SIZE,
Constant.UNIT_SIZE,-Constant.UNIT_SIZE,-Constant.UNIT_SIZE,
Constant.UNIT_SIZE,0,0,
Constant.UNIT_SIZE,-Constant.UNIT_SIZE,-Constant.UNIT_SIZE,
Constant.UNIT_SIZE,Constant.UNIT_SIZE,-Constant.UNIT_SIZE,
Constant.UNIT_SIZE,0,0,
Constant.UNIT_SIZE,Constant.UNIT_SIZE,-Constant.UNIT_SIZE,
Constant.UNIT_SIZE,Constant.UNIT_SIZE,Constant.UNIT_SIZE,
//上面
0,Constant.UNIT_SIZE,0,
Constant.UNIT_SIZE,Constant.UNIT_SIZE,Constant.UNIT_SIZE,
Constant.UNIT_SIZE,Constant.UNIT_SIZE,-Constant.UNIT_SIZE,
0,Constant.UNIT_SIZE,0,
Constant.UNIT_SIZE,Constant.UNIT_SIZE,-Constant.UNIT_SIZE,
-Constant.UNIT_SIZE,Constant.UNIT_SIZE,-Constant.UNIT_SIZE,
0,Constant.UNIT_SIZE,0,
-Constant.UNIT_SIZE,Constant.UNIT_SIZE,-Constant.UNIT_SIZE,
-Constant.UNIT_SIZE,Constant.UNIT_SIZE,Constant.UNIT_SIZE,
0,Constant.UNIT_SIZE,0,
-Constant.UNIT_SIZE,Constant.UNIT_SIZE,Constant.UNIT_SIZE,
Constant.UNIT_SIZE,Constant.UNIT_SIZE,Constant.UNIT_SIZE,
//下面
0,-Constant.UNIT_SIZE,0,
Constant.UNIT_SIZE,-Constant.UNIT_SIZE,Constant.UNIT_SIZE,
-Constant.UNIT_SIZE,-Constant.UNIT_SIZE,Constant.UNIT_SIZE,
0,-Constant.UNIT_SIZE,0,
-Constant.UNIT_SIZE,-Constant.UNIT_SIZE,Constant.UNIT_SIZE,
-Constant.UNIT_SIZE,-Constant.UNIT_SIZE,-Constant.UNIT_SIZE,
0,-Constant.UNIT_SIZE,0,
-Constant.UNIT_SIZE,-Constant.UNIT_SIZE,-Constant.UNIT_SIZE,
Constant.UNIT_SIZE,-Constant.UNIT_SIZE,-Constant.UNIT_SIZE,
0,-Constant.UNIT_SIZE,0,
Constant.UNIT_SIZE,-Constant.UNIT_SIZE,-Constant.UNIT_SIZE,
Constant.UNIT_SIZE,-Constant.UNIT_SIZE,Constant.UNIT_SIZE,
};
//创建顶点坐标数据缓冲
//vertices.length*4是因为一个整数四个字节
ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length*4);
vbb.order(ByteOrder.nativeOrder());//设置字节顺序
mVertexBuffer = vbb.asFloatBuffer();//转换为Float型缓冲
mVertexBuffer.put(vertices);//向缓冲区中放入顶点坐标数据
mVertexBuffer.position(0);//设置缓冲区起始位置
//特别提示:由于不同平台字节顺序不同数据单元不是字节的一定要经过ByteBuffer
//转换,关键是要通过ByteOrder设置nativeOrder(),否则有可能会出问题
//顶点坐标数据的初始化================end============================
//顶点颜色值数组,每个顶点4个色彩值RGBA
float colors[]=new float[]{
//前面
1,1,1,0,//中间为白色
1,0,0,0,
1,0,0,0,
1,1,1,0,//中间为白色
1,0,0,0,
1,0,0,0,
1,1,1,0,//中间为白色
1,0,0,0,
1,0,0,0,
1,1,1,0,//中间为白色
1,0,0,0,
1,0,0,0,
//后面
1,1,1,0,//中间为白色
0,0,1,0,
0,0,1,0,
1,1,1,0,//中间为白色
0,0,1,0,
0,0,1,0,
1,1,1,0,//中间为白色
0,0,1,0,
0,0,1,0,
1,1,1,0,//中间为白色
0,0,1,0,
0,0,1,0,
//左面
1,1,1,0,//中间为白色
1,0,1,0,
1,0,1,0,
1,1,1,0,//中间为白色
1,0,1,0,
1,0,1,0,
1,1,1,0,//中间为白色
1,0,1,0,
1,0,1,0,
1,1,1,0,//中间为白色
1,0,1,0,
1,0,1,0,
//右面
1,1,1,0,//中间为白色
1,1,0,0,
1,1,0,0,
1,1,1,0,//中间为白色
1,1,0,0,
1,1,0,0,
1,1,1,0,//中间为白色
1,1,0,0,
1,1,0,0,
1,1,1,0,//中间为白色
1,1,0,0,
1,1,0,0,
//上面
1,1,1,0,//中间为白色
0,1,0,0,
0,1,0,0,
1,1,1,0,//中间为白色
0,1,0,0,
0,1,0,0,
1,1,1,0,//中间为白色
0,1,0,0,
0,1,0,0,
1,1,1,0,//中间为白色
0,1,0,0,
0,1,0,0,
//下面
1,1,1,0,//中间为白色
0,1,1,0,
0,1,1,0,
1,1,1,0,//中间为白色
0,1,1,0,
0,1,1,0,
1,1,1,0,//中间为白色
0,1,1,0,
0,1,1,0,
1,1,1,0,//中间为白色
0,1,1,0,
0,1,1,0,
};
//创建顶点着色数据缓冲
ByteBuffer cbb = ByteBuffer.allocateDirect(colors.length*4);
cbb.order(ByteOrder.nativeOrder());//设置字节顺序
mColorBuffer = cbb.asFloatBuffer();//转换为Float型缓冲
mColorBuffer.put(colors);//向缓冲区中放入顶点着色数据
mColorBuffer.position(0);//设置缓冲区起始位置
//特别提示:由于不同平台字节顺序不同数据单元不是字节的一定要经过ByteBuffer
//转换,关键是要通过ByteOrder设置nativeOrder(),否则有可能会出问题
//顶点着色数据的初始化================end============================
}
//初始化shader
public void initShader(Project0503SurfaceView mv)
{
// 加载顶点着色器的脚本内容
mVertexShader = ShaderUtil.loadFromAssetsFile("project_sample_5_3/vertex.glsl",
mv.getResources());
// 加载片元着色器的脚本内容
mFragmentShader = ShaderUtil.loadFromAssetsFile("project_sample_5_3/frag.glsl",
mv.getResources());
//基于顶点着色器与片元着色器创建程序
mProgram = ShaderUtil.createProgram(mVertexShader, mFragmentShader);
//获取程序中顶点位置属性引用id
maPositionHandle = GLES20.glGetAttribLocation(mProgram, "aPosition");
//获取程序中顶点颜色属性引用id
maColorHandle= GLES20.glGetAttribLocation(mProgram, "aColor");
//获取程序中总变换矩阵引用id
muMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
}
public void drawSelf()
{
//制定使用某套shader程序
GLES20.glUseProgram(mProgram);
//将最终变换矩阵传入shader程序
GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, MatrixState.getFinalMatrix(), 0);
//为画笔指定顶点位置数据
GLES20.glVertexAttribPointer
(
maPositionHandle,
3,
GLES20.GL_FLOAT,
false,
3*4,
mVertexBuffer
);
//为画笔指定顶点着色数据
GLES20.glVertexAttribPointer
(
maColorHandle,
4,
GLES20.GL_FLOAT,
false,
4*4,
mColorBuffer
);
//允许顶点位置数据数组
GLES20.glEnableVertexAttribArray(maPositionHandle);
GLES20.glEnableVertexAttribArray(maColorHandle);
//绘制立方体
GLES20.glDrawArrays(GLES20.GL_TRIANGLES,0, vCount);
}
}
|
/*-
* #%L
* anchor-feature
* %%
* Copyright (C) 2010 - 2020 Owen Feehan, ETH Zurich, University of Zurich, Hoffmann-La Roche
* %%
* 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.
* #L%
*/
/**
* Classes to cache feature-results or parts of feature-results that occur repeatedly among features
* or across calculations of the same feature.
*/
package org.anchoranalysis.feature.calculate.cache;
|
package org.innovateuk.ifs.user.transactional;
import org.innovateuk.ifs.commons.service.ServiceResult;
import org.innovateuk.ifs.user.domain.RoleProfileStatus;
import org.innovateuk.ifs.user.domain.User;
import org.innovateuk.ifs.user.mapper.RoleProfileStatusMapper;
import org.innovateuk.ifs.user.mapper.UserMapper;
import org.innovateuk.ifs.user.repository.RoleProfileStatusRepository;
import org.innovateuk.ifs.user.repository.UserRepository;
import org.innovateuk.ifs.user.resource.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
import static java.util.stream.Collectors.toList;
import static org.innovateuk.ifs.commons.error.CommonErrors.notFoundError;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess;
import static org.innovateuk.ifs.util.EntityLookupCallbacks.find;
@Service
public class RoleProfileStatusServiceImpl implements RoleProfileStatusService {
@Autowired
private RoleProfileStatusRepository roleProfileStatusRepository;
@Autowired
private RoleProfileStatusMapper roleProfileStatusMapper;
@Autowired
private UserRepository userRepository;
@Autowired
private UserMapper userMapper;
@Override
@Transactional
public ServiceResult<Void> updateUserStatus(long userId, RoleProfileStatusResource roleProfileStatusResource) {
return getUser(userId).andOnSuccessReturnVoid(user -> updateRoleProfileStatus(user, roleProfileStatusResource));
}
@Override
public ServiceResult<List<RoleProfileStatusResource>> findByUserId(long userId) {
return find(roleProfileStatusRepository.findByUserId(userId), notFoundError(RoleProfileStatus.class, userId))
.andOnSuccessReturn(rp -> rp.stream()
.map(roleProfileStatusMapper::mapToResource)
.collect(toList()));
}
@Override
public ServiceResult<RoleProfileStatusResource> findByUserIdAndProfileRole(long userId, ProfileRole profileRole) {
return find(roleProfileStatusRepository.findByUserIdAndProfileRole(userId, profileRole), notFoundError(RoleProfileStatus.class, userId))
.andOnSuccessReturn(roleProfileStatusMapper::mapToResource);
}
@Override
@Transactional
public ServiceResult<UserPageResource> findByRoleProfile(RoleProfileState state, ProfileRole profileRole, String filter, Pageable pageable) {
return userPageResource(
roleProfileStatusRepository.findByRoleProfileStateAndProfileRoleAndUserEmailContainingAndUserStatus(state, profileRole, filter, UserStatus.ACTIVE, pageable)
.map(RoleProfileStatus::getUser)
);
}
private ServiceResult<UserPageResource> userPageResource(Page<User> pagedResult) {
return serviceSuccess(new UserPageResource(
pagedResult.getTotalElements(),
pagedResult.getTotalPages(),
pagedResult.getContent().stream().map(userMapper::mapToResource).collect(toList()),
pagedResult.getNumber(),
pagedResult.getSize())
);
}
private void updateRoleProfileStatus(User user, RoleProfileStatusResource roleProfileStatusResource) {
findOrCreateRoleProfileStatus(user, roleProfileStatusResource).andOnSuccessReturnVoid(roleProfileStatus -> {
roleProfileStatus.setRoleProfileState(roleProfileStatusResource.getRoleProfileState());
roleProfileStatus.setDescription(roleProfileStatusResource.getDescription());
roleProfileStatusRepository.save(roleProfileStatus);
});
}
private ServiceResult<RoleProfileStatus> findOrCreateRoleProfileStatus(User user, RoleProfileStatusResource roleProfileStatusResource) {
Optional<RoleProfileStatus> roleProfileStatus =
roleProfileStatusRepository.findByUserIdAndProfileRole(roleProfileStatusResource.getUserId(), roleProfileStatusResource.getProfileRole());
if (roleProfileStatus.isPresent()) {
return serviceSuccess(roleProfileStatus.get());
}
return serviceSuccess(new RoleProfileStatus(user, roleProfileStatusResource.getProfileRole()));
}
private ServiceResult<User> getUser(long id) {
return find(userRepository.findById(id), notFoundError(User.class, id));
}
}
|
package com.jx.intelligent.http.dao;
import android.content.Context;
import android.support.annotation.NonNull;
import com.jx.intelligent.constant.Constant;
import com.jx.intelligent.http.callback.HttpResponseCallback;
import com.jx.intelligent.util.HTTPSUtils;
import com.jx.intelligent.util.LogUtil;
import com.jx.intelligent.util.NetConfig;
import com.jx.intelligent.util.StringUtil;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
public abstract class OkHttpDao<RESPONSE> extends HttpDao<RESPONSE> {
/**
* okHttp客户端
*/
private static OkHttpClient httpClient;
/**
* 当前正在执行的请求
*/
private Call call;
/**
* 保存正在执行的请求
*/
private List<Call> requests = new ArrayList<>();
/**
* 用于处理JSON参数
*/
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
/**
* 用于处理文件表单上传参数
*/
public static final MediaType FORM = MediaType.parse("image/jpg");
/**
* 用于处理String参数,只有键没有值的单个String参数
*/
public static final MediaType STRING = MediaType.parse("text/x-markdown; charset=utf-8");
public static final void getInstance(Context context, InputStream inputStream) {
// httpClient = HttpClient.getInstance(); //没有https验证的
httpClient = HTTPSUtils.getInstance(context, inputStream).getClient(); //有https验证的
}
/**
* 单例模式获取HTTP客户端
*/
private static class HttpClient {
private static OkHttpClient instance;
/**
* 获取OkHttpClient实例
*
* @return OkHttpClient实例对象
*/
public static OkHttpClient getInstance() {
if (instance == null) {
synchronized (HttpClient.class) {
if (instance == null) {
OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
instance = builder.build();
}
}
}
return instance;
}
}
/**
* 设置HttpResponseCallback相关参数
*
* @param responseEntityClass
* @param httpResponseCallback
*/
private void setHttpResponseCallback(Class<RESPONSE> responseEntityClass, @NonNull HttpResponseCallback<RESPONSE> httpResponseCallback) {
if (responseEntityClass != null) {
httpResponseCallback.setResponseEntityClass(responseEntityClass);
}
}
@Override
public RESPONSE sendSyncRequest(@NonNull HttpMethod httpMethod, @NonNull String url) {
return null;
}
@Override
public RESPONSE sendSyncRequest(@NonNull HttpMethod httpMethod, @NonNull String url, @NonNull Map<String, Object> params) {
return null;
}
@Override
public RESPONSE sendSyncRequest(@NonNull HttpMethod httpMethod, @NonNull String url, @NonNull String params) {
return null;
}
@Override
public void sendAsyncRequest(@NonNull HttpMethod httpMethod, @NonNull String url, @NonNull HttpResponseCallback<RESPONSE> httpResponseCallback) {
if (!checkCurrentNetwork(url, httpResponseCallback))
return;
setHttpResponseCallback(null, httpResponseCallback);
// 判断HTTP请求方法
switch (httpMethod) {
case GET:
Request.Builder builder = new Request.Builder();
builder = setRequestHeader(builder); //设置请求头,没有则不设置
final Request request_get = builder.url(url).get().build();
call = httpClient.newCall(request_get);
addRequest(call);
call.enqueue(httpResponseCallback);
break;
case POST:
// 提交post表单请求
final RequestBody formBody = new FormBody.Builder().build();
Request.Builder postBuilder = new Request.Builder();
postBuilder = setRequestHeader(postBuilder);
final Request request_post = postBuilder.url(url).post(formBody).build();
call = httpClient.newCall(request_post);
addRequest(call);
call.enqueue(httpResponseCallback);
break;
}
}
/**
* 上传表单文件
*
* @param url 统一资源定位符
* @param param 请求参数json字符串
* @param value 请求参数值文件
* @param responseEntityClass
* @param httpResponseCallback HTTP响应回调
*/
@Override
public void sendAsyncRequest(@NonNull String url, @NonNull String param, @NonNull File value, @NonNull Class<RESPONSE> responseEntityClass, @NonNull HttpResponseCallback<RESPONSE> httpResponseCallback) {
if (!checkCurrentNetwork(url, httpResponseCallback))
return;
setHttpResponseCallback(responseEntityClass, httpResponseCallback);
// 提交post表单请求
MultipartBody.Builder partBuilder = new MultipartBody.Builder();
partBuilder.addFormDataPart("formParam", param);
partBuilder.addFormDataPart("formFile", value.getName(), RequestBody.create(FORM, value));
final RequestBody formBody = partBuilder.build();
Request.Builder postBuilder = new Request.Builder();
postBuilder = setRequestHeader(postBuilder);//添加请求头
final Request request_post = postBuilder.url(url).post(formBody).build();
call = httpClient.newCall(request_post);
addRequest(call);
call.enqueue(httpResponseCallback);
}
/**无参*/
@Override
public void sendAsyncRequest(@NonNull HttpMethod httpMethod, @NonNull String url, @NonNull Class<RESPONSE> responseEntityClass, @NonNull HttpResponseCallback<RESPONSE> httpResponseCallback) {
if (!checkCurrentNetwork(url, httpResponseCallback))
return;
setHttpResponseCallback(responseEntityClass, httpResponseCallback);
// 判断HTTP请求方法
switch (httpMethod) {
case GET:
Request.Builder builder = new Request.Builder();
builder = setRequestHeader(builder); //设置请求头,没有则不设置
final Request request_get = builder.url(url).get().build();
call = httpClient.newCall(request_get);
addRequest(call);
call.enqueue(httpResponseCallback);
break;
case POST:
// 提交post表单请求
final RequestBody formBody = new FormBody.Builder().build();
Request.Builder postBuilder = new Request.Builder();
postBuilder = setRequestHeader(postBuilder);
final Request request_post = postBuilder.url(url).post(formBody).build();
call = httpClient.newCall(request_post);
addRequest(call);
call.enqueue(httpResponseCallback);
break;
}
}
/**
* 请求参数为键值对
*/
@Override
public void sendAsyncRequest(@NonNull HttpMethod httpMethod, @NonNull String url, @NonNull Map<String, Object> params, @NonNull Class<RESPONSE> responseEntityClass, @NonNull HttpResponseCallback<RESPONSE> httpResponseCallback) {
if (!checkCurrentNetwork(url, httpResponseCallback))
return;
setHttpResponseCallback(responseEntityClass, httpResponseCallback);
// 判断HTTP请求方法
switch (httpMethod) {
case GET:
final Request request_get = new Request.Builder().url(buildGetUrl(url, params)).build();
call = httpClient.newCall(request_get);
addRequest(call);
call.enqueue(httpResponseCallback);
break;
case POST:
final FormBody.Builder formBodyBuilder = new FormBody.Builder();
for (Map.Entry<String, Object> entry : params.entrySet()) {
formBodyBuilder.add(entry.getKey(), entry.getValue().toString());
}
// 提交post表单请求
final RequestBody formBody = formBodyBuilder.build();
Request.Builder postBuilder = new Request.Builder();
postBuilder = setRequestHeader(postBuilder);
final Request request_post = postBuilder.url(url).post(formBody).build();
call = httpClient.newCall(request_post);
addRequest(call);
call.enqueue(httpResponseCallback);
break;
}
}
/**
* @param url 统一资源定位符
* @param json 请求参数为json字符串
* @param responseEntityClass HTTP响应数据解析对应的实体类的class字节码
* @param httpResponseCallback HTTP响应回调
*/
@Override
public void sendAsyncRequest(@NonNull String url, @NonNull String json, @NonNull Class<RESPONSE> responseEntityClass, @NonNull HttpResponseCallback<RESPONSE> httpResponseCallback) {
LogUtil.e("请求参数:"+json);
if (!checkCurrentNetwork(url, httpResponseCallback))
return;
setHttpResponseCallback(responseEntityClass, httpResponseCallback);
RequestBody body = RequestBody.create(JSON, StringUtil.encrypt(json));
Request.Builder postBuilder = new Request.Builder();
postBuilder = setRequestHeader(postBuilder);
Request request_post = postBuilder.url(url).post(body).build();
call = httpClient.newCall(request_post);
addRequest(call);
call.enqueue(httpResponseCallback);
}
@Override
public void sendAsyncRequestString(@NonNull String url, @NonNull String params, @NonNull Class<RESPONSE> responseEntityClass, @NonNull HttpResponseCallback<RESPONSE> httpResponseCallback){
LogUtil.e("请求参数:"+params);
if (!checkCurrentNetwork(url, httpResponseCallback))
return;
setHttpResponseCallback(responseEntityClass, httpResponseCallback);
RequestBody requestBody = RequestBody.create(STRING, params);
Request request_post = new Request.Builder().url(url).post(requestBody).build();
call = httpClient.newCall(request_post);
addRequest(call);
call.enqueue(httpResponseCallback);
}
/**
* 设置网络请求的请求头
*
* @param builder
* @return
*/
protected abstract Request.Builder setRequestHeader(Request.Builder builder);
/**
* 针对get请求,通过url和参数构建带参数的url
*
* @param url 最基本的url
* @param params 请求的参数
* @return 添加了参数的url
*/
private String buildGetUrl(String url, Map<String, Object> params) {
return url + buildParams(params);
}
/**
* 构建GET请求参数
*
* @param params 请求参数Map键值对
* @return 拼接的GET请求参数
*/
private String buildParams(@NonNull Map<String, Object> params) {
final StringBuilder sb = new StringBuilder("?");
if (params != null && !params.isEmpty()) {
for (String key : params.keySet()) {
sb.append(key).append("=").append(params.get(key)).append("&");
}
}
return sb.deleteCharAt(sb.length() - 1).toString();
}
@Override
public void cancelRequests() {
for (Call call : requests) {
if (!call.isCanceled())
call.cancel();
}
requests.clear();
requests = null;
}
@Override
public void cancelRequest() {
if (!call.isCanceled())
call.cancel();
call = null;
}
@Override
public void cancelRequest(@NonNull String tag) {
}
private void addRequest(@NonNull Call call) {
if (call != null && !requests.contains(call)) {
requests.add(call);
}
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.cache.consistency;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.cache.CacheEntry;
import org.apache.ignite.internal.util.typedef.G;
import org.junit.Test;
/**
*
*/
public abstract class AbstractFullSetReadRepairTest extends AbstractReadRepairTest {
/**
*
*/
protected static final Consumer<ReadRepairData> GET_CHECK_AND_FIX = (data) -> {
IgniteCache<Integer, Integer> cache = data.cache;
Set<Integer> keys = data.data.keySet();
boolean raw = data.raw;
boolean async = data.async;
assert keys.size() == 1;
for (Map.Entry<Integer, InconsistentMapping> entry : data.data.entrySet()) { // Once.
Integer key = entry.getKey();
Integer latest = entry.getValue().latest;
Integer res =
raw ?
async ?
cache.withReadRepair().getEntryAsync(key).get().getValue() :
cache.withReadRepair().getEntry(key).getValue() :
async ?
cache.withReadRepair().getAsync(key).get() :
cache.withReadRepair().get(key);
assertEquals(latest, res);
}
};
/**
*
*/
protected static final Consumer<ReadRepairData> GETALL_CHECK_AND_FIX = (data) -> {
IgniteCache<Integer, Integer> cache = data.cache;
Set<Integer> keys = data.data.keySet();
boolean raw = data.raw;
boolean async = data.async;
assert !keys.isEmpty();
if (raw) {
Collection<CacheEntry<Integer, Integer>> res =
async ?
cache.withReadRepair().getEntriesAsync(keys).get() :
cache.withReadRepair().getEntries(keys);
for (CacheEntry<Integer, Integer> entry : res)
assertEquals(data.data.get(entry.getKey()).latest, entry.getValue());
}
else {
Map<Integer, Integer> res =
async ?
cache.withReadRepair().getAllAsync(keys).get() :
cache.withReadRepair().getAll(keys);
for (Map.Entry<Integer, Integer> entry : res.entrySet())
assertEquals(data.data.get(entry.getKey()).latest, entry.getValue());
}
};
/**
*
*/
protected static final Consumer<ReadRepairData> GET_NULL = (data) -> {
IgniteCache<Integer, Integer> cache = data.cache;
Set<Integer> keys = data.data.keySet();
boolean raw = data.raw;
boolean async = data.async;
assert keys.size() == 1;
for (Integer key : data.data.keySet()) { // Once.
Integer missed = key * -1; // Negative to gain null.
Object res =
raw ?
async ?
cache.withReadRepair().getEntryAsync(missed).get() :
cache.withReadRepair().getEntry(missed) :
async ?
cache.withReadRepair().getAsync(missed).get() :
cache.withReadRepair().get(missed);
assertEquals(null, res);
}
};
/**
*
*/
protected static final Consumer<ReadRepairData> CONTAINS_CHECK_AND_FIX = (data) -> {
IgniteCache<Integer, Integer> cache = data.cache;
Set<Integer> keys = data.data.keySet();
boolean async = data.async;
assert keys.size() == 1;
for (Integer key : data.data.keySet()) { // Once.
boolean res = async ?
cache.withReadRepair().containsKeyAsync(key).get() :
cache.withReadRepair().containsKey(key);
assertEquals(true, res);
}
};
/**
*
*/
protected static final Consumer<ReadRepairData> CONTAINS_ALL_CHECK_AND_FIX = (data) -> {
IgniteCache<Integer, Integer> cache = data.cache;
Set<Integer> keys = data.data.keySet();
boolean async = data.async;
boolean res = async ?
cache.withReadRepair().containsKeysAsync(keys).get() :
cache.withReadRepair().containsKeys(keys);
assertEquals(true, res);
};
/**
*
*/
protected static final Consumer<ReadRepairData> CHECK_FIXED = (data) -> {
IgniteCache<Integer, Integer> cache = data.cache;
boolean raw = data.raw;
for (Map.Entry<Integer, InconsistentMapping> entry : data.data.entrySet()) {
Integer key = entry.getKey();
Integer latest = entry.getValue().latest;
Integer res = raw ?
cache.getEntry(key).getValue() :
cache.get(key);
assertEquals(latest, res);
}
};
/**
* @param data Data.
*/
protected void check(ReadRepairData data, boolean checkEvtRecorded, boolean checkFixed) {
if (checkEvtRecorded)
checkEvent(data, checkFixed);
else
checkEventMissed();
if (checkFixed)
CHECK_FIXED.accept(data);
}
/**
*
*/
@Test
public void test() throws Exception {
for (Ignite node : G.allGrids()) {
testGetVariations(node);
testGetNull(node);
testContainsVariations(node);
}
}
/**
*
*/
private void testGetVariations(Ignite initiator) throws Exception {
testGet(initiator, 1, false); // just get
testGet(initiator, 1, true); // 1 (all keys available at primary)
testGet(initiator, 2, true); // less than backups
testGet(initiator, 3, true); // equals to backups
testGet(initiator, 4, true); // equals to backups + primary
testGet(initiator, 10, true); // more than backups
}
/**
*
*/
private void testContainsVariations(Ignite initiator) throws Exception {
testContains(initiator, 1, false); // just contains
testContains(initiator, 1, true); // 1 (all keys available at primary)
testContains(initiator, 2, true); // less than backups
testContains(initiator, 3, true); // equals to backups
testContains(initiator, 4, true); // equals to backups + primary
testContains(initiator, 10, true); // more than backups
}
/**
*
*/
protected abstract void testGet(Ignite initiator, Integer cnt, boolean all) throws Exception;
/**
*
*/
protected abstract void testGetNull(Ignite initiator) throws Exception;
/**
*
*/
protected abstract void testContains(Ignite initiator, Integer cnt, boolean all) throws Exception;
}
|
/*
* ========================================================================
*
* 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.manning.junitbook.ch09.ant;
import static org.junit.Assert.fail;
import com.manning.junitbook.ch03.mastering.DefaultController;
import com.manning.junitbook.ch03.mastering.Request;
import com.manning.junitbook.ch03.mastering.RequestHandler;
import com.manning.junitbook.ch03.mastering.Response;
import org.junit.Before;
import org.junit.Test;
/**
* A test-case for the DefaultController8.
*
* @version $Id$
*/
public class TestDefaultController8
{
private DefaultController controller;
private Request request;
private RequestHandler handler;
@Before
public void setUp()
throws Exception
{
controller = new DefaultController();
request = new TestRequest();
handler = new TestHandler();
controller.addHandler( request, handler );
}
private class TestRequest
implements Request
{
private static final String DEFAULT_NAME = "Test";
private String name;
public TestRequest( String name )
{
this.name = name;
}
public TestRequest()
{
this( DEFAULT_NAME );
}
public String getName()
{
return this.name;
}
}
private class TestHandler
implements RequestHandler
{
public Response process(Request request )
throws Exception
{
return new TestResponse();
}
}
private class TestResponse
implements Response
{
// empty
}
@Test()
// @Test( expected = RuntimeException.class )
public void testGetHandlerNotDefined()
{
TestRequest request = new TestRequest( "testNotDefined" );
controller.getHandler( request );
fail( "An exception should be raised if the requested " + "handler has not been registered" );
}
@Test( expected = RuntimeException.class )
public void testAddRequestDuplicateName()
{
TestRequest request = new TestRequest();
TestHandler handler = new TestHandler();
controller.addHandler( request, handler );
fail( "An exception should be raised if the default " + "TestRequest has already been registered" );
}
}
|
package org.cloudfoundry.credhub.endToEnd.v2.permissions;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.cloudfoundry.credhub.PermissionOperation;
import org.cloudfoundry.credhub.helpers.JsonTestHelper;
import org.cloudfoundry.credhub.views.PermissionsV2View;
import static org.cloudfoundry.credhub.AuthConstants.ALL_PERMISSIONS_TOKEN;
import static org.cloudfoundry.credhub.AuthConstants.USER_A_ACTOR_ID;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
final class PermissionsV2EndToEndTestHelper {
private PermissionsV2EndToEndTestHelper() {
super();
}
static UUID setPermissions(final MockMvc mockMvc, final String credentialName, final PermissionOperation operation) throws Exception {
final MockHttpServletRequestBuilder addPermissionRequest = post("/api/v2/permissions")
.header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN)
.accept(APPLICATION_JSON)
.contentType(APPLICATION_JSON)
.content("{"
+ " \"actor\": \"" + USER_A_ACTOR_ID + "\",\n"
+ " \"path\": \"" + credentialName + "\",\n"
+ " \"operations\": [\"" + operation.getOperation() + "\"]\n"
+ "}");
final String content = mockMvc.perform(addPermissionRequest).andExpect(status().isCreated()).andReturn().getResponse().getContentAsString();
final PermissionsV2View returnValue = JsonTestHelper.deserialize(content, PermissionsV2View.class);
assertThat(returnValue.getActor(), equalTo(USER_A_ACTOR_ID));
assertThat(returnValue.getPath(), equalTo(credentialName));
assertThat(returnValue.getOperations(), equalTo(Collections.singletonList(operation)));
assertThat(returnValue.getUuid(), notNullValue());
return returnValue.getUuid();
}
static ResultActions setPassword(
final MockMvc mockMvc, final String credentialName, final String passwordValue, final String token) throws Exception {
final Map<String, String> passwordRequestBody = new HashMap<>();
passwordRequestBody.put("name", credentialName);
passwordRequestBody.put("type", "password");
passwordRequestBody.put("value", passwordValue);
final String content = JsonTestHelper.serializeToString(passwordRequestBody);
final MockHttpServletRequestBuilder put = put("/api/v1/data")
.header("Authorization", "Bearer " + token)
.accept(APPLICATION_JSON)
.contentType(APPLICATION_JSON)
.content(content);
return mockMvc.perform(put);
}
}
|
package music.util;
import jakarta.servlet.http.Cookie;
public class CookieUtil {
public static String getCookieValue(Cookie[] cookies, String cookieName) {
String cookieValue = "";
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookieName.equals(cookie.getName())) {
cookieValue = cookie.getValue();
}
}
}
return cookieValue;
}
}
|
package com.ceiba.envio.puerto.repositorio;
import com.ceiba.envio.modelo.entidad.Envio;
public interface RepositorioEnvio {
/**
* Permite crear un envio
* @param envio
* @return el id generado
*/
Long crear(Envio envio);
/**
* Permite actualizar un envio
* @param envio
*/
void actualizar(Envio envio);
/**
* Permite eliminar un envio
* @param id
*/
void eliminar(Long id);
}
|
package org.sw.alarm;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.view.Window;
import android.view.WindowManager;
import trikita.anvil.RenderableView;
import trikita.jedux.Action;
import org.sw.Actions;
import org.sw.App;
import org.sw.estimote.BeaconID;
import org.sw.estimote.BeaconAlarmManager;
import org.sw.ui.ActiveAlarmLayout;
import org.sw.ui.Theme;
public class AlarmActivity extends Activity {
private PowerManager.WakeLock mWakeLock;
private BeaconAlarmManager beaconAlarmManager;
@Override
protected void onCreate(Bundle b) {
super.onCreate(b);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK |
PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "AlarmActivity");
mWakeLock.acquire();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
// fill status bar with a theme dark color on post-Lollipop devices
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(Theme.get(App.getState().settings().theme()).primaryDarkColor);
}
setContentView(new RenderableView(this) {
public void view() {
ActiveAlarmLayout.view();
}
});
BluetoothUtils.setBluetooth(true);
startBeaconAlarmManager();
}
private void startBeaconAlarmManager() {
beaconAlarmManager = new BeaconAlarmManager(this);
beaconAlarmManager.addBeacon(new BeaconID("B9407F30-F5F8-466E-AFF9-25556B57FE6D", 55175, 50165));
beaconAlarmManager.startMonitoring();
}
@Override
protected void onDestroy() {
super.onDestroy();
mWakeLock.release();
}
public void stopAlarm() {
beaconAlarmManager.stopMonitoring();
App.dispatch(new Action<>(Actions.Alarm.DISMISS));
Intent i = new Intent(this, TemperatureActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_TASK_ON_HOME);
startActivity(i);
finish();
}
}
|
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.ethereum.eth.manager.task;
import org.hyperledger.besu.ethereum.eth.manager.EthContext;
import org.hyperledger.besu.ethereum.eth.manager.EthPeers;
import org.hyperledger.besu.plugin.services.MetricsSystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Waits for some number of peers to connect. */
public class WaitForPeersTask extends AbstractEthTask<Void> {
private static final Logger LOG = LoggerFactory.getLogger(WaitForPeersTask.class);
private final int targetPeerCount;
private final EthContext ethContext;
private volatile Long peerListenerId;
private WaitForPeersTask(
final EthContext ethContext, final int targetPeerCount, final MetricsSystem metricsSystem) {
super(metricsSystem);
this.targetPeerCount = targetPeerCount;
this.ethContext = ethContext;
}
public static WaitForPeersTask create(
final EthContext ethContext, final int targetPeerCount, final MetricsSystem metricsSystem) {
return new WaitForPeersTask(ethContext, targetPeerCount, metricsSystem);
}
@Override
protected void executeTask() {
final EthPeers ethPeers = ethContext.getEthPeers();
if (ethPeers.peerCount() >= targetPeerCount) {
// We already hit our target
result.complete(null);
return;
}
LOG.info(
"Waiting for {} peers to connect. {} peers currently connected.",
targetPeerCount,
ethPeers.peerCount());
// Listen for peer connections and complete task when we hit our target
peerListenerId =
ethPeers.subscribeConnect(
(peer) -> {
final int peerCount = ethPeers.peerCount();
if (peerCount >= targetPeerCount) {
LOG.info("Finished waiting for {} peers to connect.", targetPeerCount);
// We hit our target
result.complete(null);
} else {
LOG.info("Waiting for {} peers to connect.", targetPeerCount - peerCount);
}
});
}
@Override
protected void cleanup() {
super.cleanup();
final Long listenerId = peerListenerId;
if (listenerId != null) {
ethContext.getEthPeers().unsubscribeConnect(peerListenerId);
}
}
}
|
package resonant.api;
/** Add this to a container class if using WatchedSlot to trigger the container on slot change */
public interface ISlotWatcher
{
/** Will trigger if the watched slot has changed */
public void slotContentsChanged(int slot);
}
|
/*******************************************************************************
* Copyright (c) 2000, 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.core.util;
/**
* This interface is intended to be implemented to disassemble
* IClassFileReader onto a String using the proper line separator.
*
* @since 2.0
* @deprecated Use {@link ClassFileBytesDisassembler} instead
*/
public interface IClassFileDisassembler {
/**
* The mode is the detailed mode to disassemble IClassFileReader. It returns the magic
* numbers, the version numbers and field and method descriptors.
*/
int DETAILED = 1;
/**
* The mode is the default mode to disassemble IClassFileReader.
*/
int DEFAULT = 2;
/**
* Answers back the disassembled string of the IClassFileReader using the default
* mode.
* This is an output quite similar to the javap tool, using DEFAULT mode.
*
* @param classFileReader The classFileReader to be disassembled
* @param lineSeparator the line separator to use.
*
* @return the disassembled string of the IClassFileReader using the default mode.
*/
String disassemble(IClassFileReader classFileReader, String lineSeparator);
/**
* Answers back the disassembled string of the IClassFileReader according to the
* mode.
* This is an output quite similar to the javap tool.
*
* @param classFileReader The classFileReader to be disassembled
* @param lineSeparator the line separator to use.
* @param mode the mode used to disassemble the IClassFileReader
*
* @return the disassembled string of the IClassFileReader according to the mode
*/
String disassemble(IClassFileReader classFileReader, String lineSeparator, int mode);
}
|
/*
* 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
*
* 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.springframework.scheduling.config;
import org.w3c.dom.Element;
import org.springframework.aop.config.AopNamespaceUtils;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.parsing.BeanComponentDefinition;
import org.springframework.beans.factory.parsing.CompositeComponentDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.util.StringUtils;
/**
* Parser for the 'annotation-driven' element of the 'task' namespace.
*
* @author Mark Fisher
* @author Juergen Hoeller
* @author Ramnivas Laddad
* @author Chris Beams
* @author Stephane Nicoll
* @since 3.0
*/
public class AnnotationDrivenBeanDefinitionParser implements BeanDefinitionParser {
private static final String ASYNC_EXECUTION_ASPECT_CLASS_NAME =
"org.springframework.scheduling.aspectj.AnnotationAsyncExecutionAspect";
@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
Object source = parserContext.extractSource(element);
// Register component for the surrounding <task:annotation-driven> element.
CompositeComponentDefinition compDefinition = new CompositeComponentDefinition(element.getTagName(), source);
parserContext.pushContainingComponent(compDefinition);
// Nest the concrete post-processor bean in the surrounding component.
BeanDefinitionRegistry registry = parserContext.getRegistry();
String mode = element.getAttribute("mode");
if ("aspectj".equals(mode)) {
// mode="aspectj"
registerAsyncExecutionAspect(element, parserContext);
}
else {
// mode="proxy"
if (registry.containsBeanDefinition(TaskManagementConfigUtils.ASYNC_ANNOTATION_PROCESSOR_BEAN_NAME)) {
parserContext.getReaderContext().error(
"Only one AsyncAnnotationBeanPostProcessor may exist within the context.", source);
}
else {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(
"org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor");
builder.getRawBeanDefinition().setSource(source);
String executor = element.getAttribute("executor");
if (StringUtils.hasText(executor)) {
builder.addPropertyReference("executor", executor);
}
String exceptionHandler = element.getAttribute("exception-handler");
if (StringUtils.hasText(exceptionHandler)) {
builder.addPropertyReference("exceptionHandler", exceptionHandler);
}
if (Boolean.valueOf(element.getAttribute(AopNamespaceUtils.PROXY_TARGET_CLASS_ATTRIBUTE))) {
builder.addPropertyValue("proxyTargetClass", true);
}
registerPostProcessor(parserContext, builder, TaskManagementConfigUtils.ASYNC_ANNOTATION_PROCESSOR_BEAN_NAME);
}
}
if (registry.containsBeanDefinition(TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
parserContext.getReaderContext().error(
"Only one ScheduledAnnotationBeanPostProcessor may exist within the context.", source);
}
else {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(
"org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor");
builder.getRawBeanDefinition().setSource(source);
String scheduler = element.getAttribute("scheduler");
if (StringUtils.hasText(scheduler)) {
builder.addPropertyReference("scheduler", scheduler);
}
registerPostProcessor(parserContext, builder, TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME);
}
// Finally register the composite component.
parserContext.popAndRegisterContainingComponent();
return null;
}
private void registerAsyncExecutionAspect(Element element, ParserContext parserContext) {
if (!parserContext.getRegistry().containsBeanDefinition(TaskManagementConfigUtils.ASYNC_EXECUTION_ASPECT_BEAN_NAME)) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(ASYNC_EXECUTION_ASPECT_CLASS_NAME);
builder.setFactoryMethod("aspectOf");
String executor = element.getAttribute("executor");
if (StringUtils.hasText(executor)) {
builder.addPropertyReference("executor", executor);
}
String exceptionHandler = element.getAttribute("exception-handler");
if (StringUtils.hasText(exceptionHandler)) {
builder.addPropertyReference("exceptionHandler", exceptionHandler);
}
parserContext.registerBeanComponent(new BeanComponentDefinition(builder.getBeanDefinition(),
TaskManagementConfigUtils.ASYNC_EXECUTION_ASPECT_BEAN_NAME));
}
}
private static void registerPostProcessor(
ParserContext parserContext, BeanDefinitionBuilder builder, String beanName) {
builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
parserContext.getRegistry().registerBeanDefinition(beanName, builder.getBeanDefinition());
BeanDefinitionHolder holder = new BeanDefinitionHolder(builder.getBeanDefinition(), beanName);
parserContext.registerComponent(new BeanComponentDefinition(holder));
}
}
|
package io.reactivex.observers;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.internal.disposables.DisposableHelper;
import io.reactivex.internal.util.EndConsumerHelper;
public abstract class DefaultObserver<T> implements Observer<T> {
private Disposable f2654s;
public final void onSubscribe(@NonNull Disposable s) {
if (EndConsumerHelper.validate(this.f2654s, s, getClass())) {
this.f2654s = s;
onStart();
}
}
protected final void cancel() {
Disposable s = this.f2654s;
this.f2654s = DisposableHelper.DISPOSED;
s.dispose();
}
protected void onStart() {
}
}
|
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.component.salesforce.api.dto
package|package
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|component
operator|.
name|salesforce
operator|.
name|api
operator|.
name|dto
package|;
end_package
begin_class
DECL|class|ActionOverride
specifier|public
class|class
name|ActionOverride
extends|extends
name|AbstractDTOBase
block|{
DECL|field|name
specifier|private
name|String
name|name
decl_stmt|;
DECL|field|pageId
specifier|private
name|String
name|pageId
decl_stmt|;
DECL|field|url
specifier|private
name|String
name|url
decl_stmt|;
DECL|field|isAvailableInTouch
specifier|private
name|Boolean
name|isAvailableInTouch
decl_stmt|;
DECL|method|getName ()
specifier|public
name|String
name|getName
parameter_list|()
block|{
return|return
name|name
return|;
block|}
DECL|method|setName (String name)
specifier|public
name|void
name|setName
parameter_list|(
name|String
name|name
parameter_list|)
block|{
name|this
operator|.
name|name
operator|=
name|name
expr_stmt|;
block|}
DECL|method|getPageId ()
specifier|public
name|String
name|getPageId
parameter_list|()
block|{
return|return
name|pageId
return|;
block|}
DECL|method|setPageId (String pageId)
specifier|public
name|void
name|setPageId
parameter_list|(
name|String
name|pageId
parameter_list|)
block|{
name|this
operator|.
name|pageId
operator|=
name|pageId
expr_stmt|;
block|}
DECL|method|getUrl ()
specifier|public
name|String
name|getUrl
parameter_list|()
block|{
return|return
name|url
return|;
block|}
DECL|method|setUrl (String url)
specifier|public
name|void
name|setUrl
parameter_list|(
name|String
name|url
parameter_list|)
block|{
name|this
operator|.
name|url
operator|=
name|url
expr_stmt|;
block|}
DECL|method|getIsAvailableInTouch ()
specifier|public
name|Boolean
name|getIsAvailableInTouch
parameter_list|()
block|{
return|return
name|isAvailableInTouch
return|;
block|}
DECL|method|setIsAvailableInTouch (Boolean isAvailableInTouch)
specifier|public
name|void
name|setIsAvailableInTouch
parameter_list|(
name|Boolean
name|isAvailableInTouch
parameter_list|)
block|{
name|this
operator|.
name|isAvailableInTouch
operator|=
name|isAvailableInTouch
expr_stmt|;
block|}
block|}
end_class
end_unit
|
package com.example.brom.activitiesapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
public static String EXTRA_MESSAGE = " ";
private String[] mountainNames = {"Matterhorn","Mont Blanc","Denali"};
private String[] mountainLocations = {"Alps","Alps","Alaska"};
private int[] mountainHeights ={4478,4808,6190};
// Create ArrayLists from the raw data above and use these lists when populating your ListView.
private ArrayList<String> listData=new ArrayList<>(Arrays.asList(mountainNames));
private ArrayList<mountain> mountainArrayList=new ArrayList<>(); //här
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.startaActivity);
b.setText("TestKnapp!(Gör inget)");
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,R.layout.my_item,R.id.my_item,listData);//Här
ListView my_listview=(ListView) findViewById(R.id.my_item);//här
my_listview.setAdapter(adapter);//här
mountainArrayList.add(new mountain("Matterhorn","Alps",4478)); //här
mountainArrayList.add(new mountain("Mont Blanc","Alps",4808)); //här
mountainArrayList.add(new mountain("Denali","Alaska",6190)); //här
ArrayAdapter<mountain> adapter2=new ArrayAdapter<mountain>(this,R.layout.my_item,R.id.my_item,mountainArrayList); //här
my_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { //Min Toast
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, MountainDetailsActivity.class);
String mountaininfo = mountainArrayList.get(position).info();
intent.putExtra(EXTRA_MESSAGE, mountaininfo);
startActivity(intent);
}
});
// 1. Create a ListView as in previous assignment
// 2. Create a new activity named "MountainDetailsActivity
// 3. Create a new Layout file for the MountainDetailsActivity called
// "activity_mountaindetails". MountainDetailsActivity must have MainActivity as its
// ´parent activity.
// 4. The layout file created in step 3 must have a LinearLayout
// 5. The layout file created in step 3 must be able to display
// * Mountain Name
// * Mountain Location
// * Mountain Height
// 6. When tapping on a list item: create an Intent that includes
// * Mountain Name
// * Mountain Location
// * Mountain Height
// 7. Display the MountainDetailsActivity with the data from the Intent created in step
// 6
// 8. From the MountainDetailsActivity you should have an option to "go back" using an
// left arro button. This is done by letting the MainActivity be the parent activity to
// MountainDetailsActivity.
}
@Override
protected void onStop() {
super.onStop();
}
}
|
package com.skullmangames.darksouls.common.block;
import java.util.HashMap;
import java.util.Map;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Mirror;
import net.minecraft.world.level.block.Rotation;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.BlockStateProperties;
import net.minecraft.world.level.block.state.properties.DirectionProperty;
import net.minecraft.world.phys.shapes.VoxelShape;
public class BaseHorizontalBlock extends Block
{
public static final DirectionProperty HORIZONTAL_FACING = BlockStateProperties.HORIZONTAL_FACING;
protected static final Map<Direction, VoxelShape> SHAPES = new HashMap<Direction, VoxelShape>();
public BaseHorizontalBlock(Properties properties)
{
super(properties);
}
@SuppressWarnings("deprecation")
@Override
public BlockState mirror(BlockState p_185471_1_, Mirror p_185471_2_)
{
return p_185471_1_.rotate(p_185471_2_.getRotation(p_185471_1_.getValue(HORIZONTAL_FACING)));
}
@Override
public BlockState rotate(BlockState state, LevelAccessor level, BlockPos vertex, Rotation direction)
{
return state.setValue(HORIZONTAL_FACING, direction.rotate(state.getValue(HORIZONTAL_FACING)));
}
@Override
public BlockState getStateForPlacement(BlockPlaceContext context)
{
return this.defaultBlockState().setValue(HORIZONTAL_FACING, context.getHorizontalDirection().getOpposite());
}
protected void runCalculation(VoxelShape shape)
{
for (Direction direction : Direction.values())
{
if (direction != Direction.UP && direction != Direction.DOWN) SHAPES.put(direction, shape.getFaceShape(direction));
}
}
}
|
package com.awgp.org.service.registry;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
import org.springframework.context.annotation.Bean;
import brave.sampler.Sampler;
@SpringBootApplication
@EnableEurekaServer
public class ServiceRegistryApplication {
@Bean
public Sampler defaultSampler() {
return Sampler.ALWAYS_SAMPLE;
}
public static void main(String[] args) {
SpringApplication.run(ServiceRegistryApplication.class, args);
}
}
|
package org.zhenchao.chain.main;
import org.zhenchao.chain.hetero.AbstractMethodResultHandler;
import org.zhenchao.chain.hetero.ValueAHandler;
import org.zhenchao.chain.hetero.ValueBHandler;
import org.zhenchao.chain.hetero.ValueCHandler;
import org.zhenchao.chain.model.Result;
import org.zhenchao.chain.pure.AssetsHandler;
import org.zhenchao.chain.pure.DepartmentManagerHandler;
import org.zhenchao.chain.pure.GeneralManagerHandler;
import org.zhenchao.chain.pure.ProjectManagerHandler;
/**
* 驱动类
*
* @author zhenchao.wang 2016-09-11 17:01
* @version 1.0.0
*/
public class Main {
public static void main(String[] args) {
AssetsHandler assetsHandler = new ProjectManagerHandler(new DepartmentManagerHandler(new GeneralManagerHandler()));
assetsHandler.handle(123456L, 500);
assetsHandler.handle(123456L, 1000);
assetsHandler.handle(123456L, 1500);
AbstractMethodResultHandler resultHandler = new ValueAHandler(new ValueBHandler(new ValueCHandler()));
Result result = new Result();
resultHandler.handle(result);
System.out.println(result);
}
}
|
//
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.xml;
import java.io.Closeable;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Map;
import java.util.Stack;
import org.eclipse.jetty.util.StringUtil;
public class XmlAppendable
{
private final String SPACES=" ";
private final Appendable _out;
private final int _indent;
private final Stack<String> _tags = new Stack<>();
private String _space="";
public XmlAppendable(OutputStream out,String encoding) throws IOException
{
this(new OutputStreamWriter(out,encoding),encoding);
}
public XmlAppendable(Appendable out) throws IOException
{
this(out,2);
}
public XmlAppendable(Appendable out,String encoding) throws IOException
{
this(out,2,encoding);
}
public XmlAppendable(Appendable out, int indent) throws IOException
{
this(out,indent,"utf-8");
}
public XmlAppendable(Appendable out, int indent, String encoding) throws IOException
{
_out=out;
_indent=indent;
_out.append("<?xml version=\"1.0\" encoding=\""+encoding+"\"?>\n");
}
public XmlAppendable openTag(String tag, Map<String,String> attributes) throws IOException
{
_out.append(_space).append('<').append(tag);
attributes(attributes);
_out.append(">\n");
_space=_space+SPACES.substring(0,_indent);
_tags.push(tag);
return this;
}
public XmlAppendable openTag(String tag) throws IOException
{
_out.append(_space).append('<').append(tag).append(">\n");
_space=_space+SPACES.substring(0,_indent);
_tags.push(tag);
return this;
}
public XmlAppendable content(String s) throws IOException
{
if (s!=null)
_out.append(StringUtil.sanitizeXmlString(s));
return this;
}
public XmlAppendable cdata(String s) throws IOException
{
_out.append("<![CDATA[").append(s).append("]]>");
return this;
}
public XmlAppendable tag(String tag) throws IOException
{
_out.append(_space).append('<').append(tag).append("/>\n");
return this;
}
public XmlAppendable tag(String tag, Map<String,String> attributes) throws IOException
{
_out.append(_space).append('<').append(tag);
attributes(attributes);
_out.append("/>\n");
return this;
}
public XmlAppendable tag(String tag,String content) throws IOException
{
_out.append(_space).append('<').append(tag).append('>');
content(content);
_out.append("</").append(tag).append(">\n");
return this;
}
public XmlAppendable tagCDATA(String tag,String data) throws IOException
{
_out.append(_space).append('<').append(tag).append('>');
cdata(data);
_out.append("</").append(tag).append(">\n");
return this;
}
public XmlAppendable tag(String tag, Map<String,String> attributes,String content) throws IOException
{
_out.append(_space).append('<').append(tag);
attributes(attributes);
_out.append('>');
content(content);
_out.append("</").append(tag).append(">\n");
return this;
}
public XmlAppendable closeTag() throws IOException
{
if (_tags.isEmpty())
throw new IllegalStateException("Tags closed");
String tag=_tags.pop();
_space=_space.substring(0,_space.length()-_indent);
_out.append(_space).append("</").append(tag).append(">\n");
if (_tags.isEmpty() && _out instanceof Closeable)
((Closeable)_out).close();
return this;
}
private void attributes(Map<String,String> attributes) throws IOException
{
for (String k:attributes.keySet())
{
String v = attributes.get(k);
_out.append(' ').append(k).append("=\"");
content(v);
_out.append('"');
}
}
public void literal(String xml) throws IOException
{
_out.append(xml);
}
}
|
package com.bootsrc.nio.selector;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
public class Client1 {
public static void main(String[] args) throws IOException {
try {
SocketChannel socketChannel = SocketChannel.open();
socketChannel.connect(new InetSocketAddress("127.0.0.1", 8000));
ByteBuffer writeBuffer = ByteBuffer.allocate(128);
ByteBuffer readBuffer = ByteBuffer.allocate(128);
writeBuffer.put("client1:hello".getBytes());
writeBuffer.flip();
while (true) {
writeBuffer.rewind();
socketChannel.write(writeBuffer);
readBuffer.clear();
socketChannel.read(readBuffer);
readBuffer.flip();
int rem = readBuffer.remaining();
byte[] arr = new byte[rem];
readBuffer.get(arr);
System.out.println("receivedContent=" + new String(arr));
String.valueOf(arr);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
}
}
}
|
package org.infinispan.statetransfer;
import org.infinispan.Cache;
import org.infinispan.persistence.spi.CacheLoader;
import org.infinispan.test.TestingUtil;
/**
* StateTransferTestingUtil.
*
* @author Galder Zamarreño
* @since 4.0
*/
public class StateTransferTestingUtil {
public static final String A_B_NAME = "a_b_name";
public static final String A_C_NAME = "a_c_name";
public static final String A_D_NAME = "a_d_age";
public static final String A_B_AGE = "a_b_age";
public static final String A_C_AGE = "a_c_age";
public static final String A_D_AGE = "a_d_age";
public static final String JOE = "JOE";
public static final String BOB = "BOB";
public static final String JANE = "JANE";
public static final Integer TWENTY = 20;
public static final Integer FORTY = 40;
public static void verifyNoDataOnLoader(Cache<Object, Object> c) throws Exception {
CacheLoader l = TestingUtil.getFirstLoader(c);
assert !l.contains(A_B_AGE);
assert !l.contains(A_B_NAME);
assert !l.contains(A_C_AGE);
assert !l.contains(A_C_NAME);
assert !l.contains(A_D_AGE);
assert !l.contains(A_D_NAME);
}
public static void verifyNoData(Cache<Object, Object> c) {
assert c.isEmpty() : "Cache should be empty!";
}
public static void writeInitialData(final Cache<Object, Object> c) {
c.put(A_B_NAME, JOE);
c.put(A_B_AGE, TWENTY);
c.put(A_C_NAME, BOB);
c.put(A_C_AGE, FORTY);
c.evict(A_B_NAME);
c.evict(A_B_AGE);
c.evict(A_C_NAME);
c.evict(A_C_AGE);
c.evict(A_D_NAME);
c.evict(A_D_AGE);
}
public static void verifyInitialDataOnLoader(Cache<Object, Object> c) throws Exception {
CacheLoader l = TestingUtil.getFirstLoader(c);
assert l.contains(A_B_AGE);
assert l.contains(A_B_NAME);
assert l.contains(A_C_AGE);
assert l.contains(A_C_NAME);
assert l.loadEntry(A_B_AGE).getValue().equals(TWENTY);
assert l.loadEntry(A_B_NAME).getValue().equals(JOE);
assert l.loadEntry(A_C_AGE).getValue().equals(FORTY);
assert l.loadEntry(A_C_NAME).getValue().equals(BOB);
}
public static void verifyInitialData(Cache<Object, Object> c) {
assert JOE.equals(c.get(A_B_NAME)) : "Incorrect value for key " + A_B_NAME;
assert TWENTY.equals(c.get(A_B_AGE)) : "Incorrect value for key " + A_B_AGE;
assert BOB.equals(c.get(A_C_NAME)) : "Incorrect value for key " + A_C_NAME;
assert FORTY.equals(c.get(A_C_AGE)) : "Incorrect value for key " + A_C_AGE;
}
}
|
/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.base;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.Iterator;
import java.util.Set;
import javax.annotation.Nullable;
/**
* An immutable object that may contain a non-null reference to another object. Each instance of
* this type either contains a non-null reference, or contains nothing (in which case we say that
* the reference is "absent"); it is never said to "contain {@code
* null}".
*
* <p>A non-null {@code Optional<T>} reference can be used as a replacement for a nullable {@code T}
* reference. It allows you to represent "a {@code T} that must be present" and a
* "a {@code T} that might be absent" as two distinct types in your program, which can aid clarity.
*
* <p>Some uses of this class include
*
* <ul>
* <li>As a method return type, as an alternative to returning {@code null} to indicate that no
* value was available
* <li>To distinguish between "unknown" (for example, not present in a map) and "known to have no
* value" (present in the map, with value {@code Optional.absent()})
* <li>To wrap nullable references for storage in a collection that does not support {@code null}
* (though there are
* <a href="https://github.com/google/guava/wiki/LivingWithNullHostileCollections">several other
* approaches to this</a> that should be considered first)
* </ul>
*
* <p>A common alternative to using this class is to find or create a suitable
* <a href="http://en.wikipedia.org/wiki/Null_Object_pattern">null object</a> for the type in
* question.
*
* <p>This class is not intended as a direct analogue of any existing "option" or "maybe" construct
* from other programming environments, though it may bear some similarities.
*
* <p><b>Comparison to {@code java.util.Optional} (JDK 8 and higher):</b> A new {@code Optional}
* class was added for Java 8. The two classes are extremely similar, but incompatible (they cannot
* share a common supertype). <i>All</i> known differences are listed either here or with the
* relevant methods below.
*
* <ul>
* <li>This class is serializable; {@code java.util.Optional} is not.
* <li>{@code java.util.Optional} has the additional methods {@code ifPresent}, {@code filter},
* {@code flatMap}, and {@code orElseThrow}.
* <li>{@code java.util} offers the primitive-specialized versions {@code OptionalInt}, {@code
* OptionalLong} and {@code OptionalDouble}, the use of which is recommended; Guava does not
* have these.
* </ul>
*
* <p><b>There are no plans to deprecate this class in the foreseeable future.</b> However, we do
* gently recommend that you prefer the new, standard Java class whenever possible.
*
* <p>See the Guava User Guide article on
* <a href="https://github.com/google/guava/wiki/UsingAndAvoidingNullExplained#optional">using
* {@code Optional}</a>.
*
* @param <T> the type of instance that can be contained. {@code Optional} is naturally covariant on
* this type, so it is safe to cast an {@code Optional<T>} to {@code
* Optional<S>} for any supertype {@code S} of {@code T}.
* @author Kurt Alfred Kluever
* @author Kevin Bourrillion
* @since 10.0
*/
@GwtCompatible(serializable = true)
public abstract class Optional<T> implements Serializable {
/**
* Returns an {@code Optional} instance with no contained reference.
*
* <p><b>Comparison to {@code java.util.Optional}:</b> this method is equivalent to Java 8's
* {@code Optional.empty}.
*/
public static <T> Optional<T> absent() {
return Absent.withType();
}
/**
* Returns an {@code Optional} instance containing the given non-null reference. To have {@code
* null} treated as {@link #absent}, use {@link #fromNullable} instead.
*
* <p><b>Comparison to {@code java.util.Optional}:</b> no differences.
*
* @throws NullPointerException if {@code reference} is null
*/
public static <T> Optional<T> of(T reference) {
return new Present<T>(checkNotNull(reference));
}
/**
* If {@code nullableReference} is non-null, returns an {@code Optional} instance containing that
* reference; otherwise returns {@link Optional#absent}.
*
* <p><b>Comparison to {@code java.util.Optional}:</b> this method is equivalent to Java 8's
* {@code Optional.ofNullable}.
*/
public static <T> Optional<T> fromNullable(@Nullable T nullableReference) {
return (nullableReference == null)
? Optional.<T>absent()
: new Present<T>(nullableReference);
}
Optional() {}
/**
* Returns {@code true} if this holder contains a (non-null) instance.
*
* <p><b>Comparison to {@code java.util.Optional}:</b> no differences.
*/
public abstract boolean isPresent();
/**
* Returns the contained instance, which must be present. If the instance might be absent, use
* {@link #or(Object)} or {@link #orNull} instead.
*
* <p><b>Comparison to {@code java.util.Optional}:</b> when the value is absent, this method
* throws {@link IllegalStateException}, whereas the Java 8 counterpart throws
* {@link NoSuchElementException}.
*
* @throws IllegalStateException if the instance is absent ({@link #isPresent} returns
* {@code false}); depending on this <i>specific</i> exception type (over the more general
* {@link RuntimeException}) is discouraged
*/
public abstract T get();
/**
* Returns the contained instance if it is present; {@code defaultValue} otherwise. If no default
* value should be required because the instance is known to be present, use {@link #get()}
* instead. For a default value of {@code null}, use {@link #orNull}.
*
* <p>Note about generics: The signature {@code public T or(T defaultValue)} is overly
* restrictive. However, the ideal signature, {@code public <S super T> S or(S)}, is not legal
* Java. As a result, some sensible operations involving subtypes are compile errors:
* <pre> {@code
*
* Optional<Integer> optionalInt = getSomeOptionalInt();
* Number value = optionalInt.or(0.5); // error
*
* FluentIterable<? extends Number> numbers = getSomeNumbers();
* Optional<? extends Number> first = numbers.first();
* Number value = first.or(0.5); // error}</pre>
*
* <p>As a workaround, it is always safe to cast an {@code Optional<? extends T>} to {@code
* Optional<T>}. Casting either of the above example {@code Optional} instances to {@code
* Optional<Number>} (where {@code Number} is the desired output type) solves the problem:
* <pre> {@code
*
* Optional<Number> optionalInt = (Optional) getSomeOptionalInt();
* Number value = optionalInt.or(0.5); // fine
*
* FluentIterable<? extends Number> numbers = getSomeNumbers();
* Optional<Number> first = (Optional) numbers.first();
* Number value = first.or(0.5); // fine}</pre>
*
* <p><b>Comparison to {@code java.util.Optional}:</b> this method is similar to Java 8's
* {@code Optional.orElse}, but will not accept {@code null} as a {@code defaultValue}
* ({@link #orNull} must be used instead). As a result, the value returned by this method is
* guaranteed non-null, which is not the case for the {@code java.util} equivalent.
*/
public abstract T or(T defaultValue);
/**
* Returns this {@code Optional} if it has a value present; {@code secondChoice} otherwise.
*
* <p><b>Comparison to {@code java.util.Optional}:</b> this method has no equivalent in Java 8's
* {@code Optional} class; write {@code thisOptional.isPresent() ? thisOptional : secondChoice}
* instead.
*/
public abstract Optional<T> or(Optional<? extends T> secondChoice);
/**
* Returns the contained instance if it is present; {@code supplier.get()} otherwise.
*
* <p><b>Comparison to {@code java.util.Optional}:</b> this method is similar to Java 8's
* {@code Optional.orElseGet}, except when {@code supplier} returns {@code null}. In this case
* this method throws an exception, whereas the Java 8 method returns the {@code null} to the
* caller.
*
* @throws NullPointerException if this optional's value is absent and the supplier returns
* {@code null}
*/
@Beta
public abstract T or(Supplier<? extends T> supplier);
/**
* Returns the contained instance if it is present; {@code null} otherwise. If the instance is
* known to be present, use {@link #get()} instead.
*
* <p><b>Comparison to {@code java.util.Optional}:</b> this method is equivalent to Java 8's
* {@code Optional.orElse(null)}.
*/
@Nullable
public abstract T orNull();
/**
* Returns an immutable singleton {@link Set} whose only element is the contained instance if it
* is present; an empty immutable {@link Set} otherwise.
*
* <p><b>Comparison to {@code java.util.Optional}:</b> this method has no equivalent in Java 8's
* {@code Optional} class. However, this common usage: <pre> {@code
*
* for (Foo foo : possibleFoo.asSet()) {
* doSomethingWith(foo);
* }}</pre>
*
* ... can be replaced with: <pre> {@code
*
* possibleFoo.ifPresent(foo -> doSomethingWith(foo));}</pre>
*
* @since 11.0
*/
public abstract Set<T> asSet();
/**
* If the instance is present, it is transformed with the given {@link Function}; otherwise,
* {@link Optional#absent} is returned.
*
* <p><b>Comparison to {@code java.util.Optional}:</b> this method is similar to Java 8's
* {@code Optional.map}, except when {@code function} returns {@code null}. In this case this
* method throws an exception, whereas the Java 8 method returns {@code Optional.absent()}.
*
* @throws NullPointerException if the function returns {@code null}
* @since 12.0
*/
public abstract <V> Optional<V> transform(Function<? super T, V> function);
/**
* Returns {@code true} if {@code object} is an {@code Optional} instance, and either the
* contained references are {@linkplain Object#equals equal} to each other or both are absent.
* Note that {@code Optional} instances of differing parameterized types can be equal.
*
* <p><b>Comparison to {@code java.util.Optional}:</b> no differences.
*/
@Override
public abstract boolean equals(@Nullable Object object);
/**
* Returns a hash code for this instance.
*
* <p><b>Comparison to {@code java.util.Optional}:</b> this class leaves the specific choice of
* hash code unspecified, unlike the Java 8 equivalent.
*/
@Override
public abstract int hashCode();
/**
* Returns a string representation for this instance.
*
* <p><b>Comparison to {@code java.util.Optional}:</b> this class leaves the specific string
* representation unspecified, unlike the Java 8 equivalent.
*/
@Override
public abstract String toString();
/**
* Returns the value of each present instance from the supplied {@code optionals}, in order,
* skipping over occurrences of {@link Optional#absent}. Iterators are unmodifiable and are
* evaluated lazily.
*
* <p><b>Comparison to {@code java.util.Optional}:</b> this method has no equivalent in Java 8's
* {@code Optional} class; use
* {@code optionals.stream().filter(Optional::isPresent).map(Optional::get)} instead.
*
* @since 11.0 (generics widened in 13.0)
*/
@Beta
public static <T> Iterable<T> presentInstances(final Iterable<? extends Optional<? extends T>> optionals) {
checkNotNull(optionals);
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new AbstractIterator<T>() {
private final Iterator<? extends Optional<? extends T>> iterator = checkNotNull(optionals.iterator());
@Override
protected T computeNext() {
while (iterator.hasNext()) {
Optional<? extends T> optional = iterator.next();
if (optional.isPresent()) {
return optional.get();
}
}
return endOfData();
}
};
}
};
}
private static final long serialVersionUID = 0;
}
|
/**
* Copyright (C) 2015 Valkyrie RCP
*
* 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.valkyriercp.rules.closure.support;
/**
* Simple implementation of AbstractClosure: makes it easy to just execute a
* block of code without any additional parameters.
*/
public abstract class NoArgBlock extends AbstractClosure {
/**
* {@inheritDoc}
*
* @return allways <code>null</code>, only code is executed.
*/
public final Object call(Object argument) {
handle();
return null;
}
/**
* Block of code to be executed. Implement this.
*/
protected void handle() {
throw new UnsupportedOperationException("You must override call() for a noArg block that returns a value, or "
+ "override handle() for a noArg block that returns no value");
}
}
|
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.workbench.common.stunner.bpmn.client.forms.fields.variablesEditor;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.regexp.shared.RegExp;
import com.google.gwtmockito.GwtMock;
import com.google.gwtmockito.GwtMockito;
import elemental2.dom.HTMLInputElement;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.TextBox;
import org.gwtbootstrap3.client.ui.ValueListBox;
import org.gwtbootstrap3.client.ui.constants.IconType;
import org.jboss.errai.databinding.client.api.DataBinder;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.stunner.bpmn.client.forms.fields.model.Variable;
import org.kie.workbench.common.stunner.bpmn.client.forms.fields.model.VariableRow;
import org.kie.workbench.common.stunner.bpmn.client.forms.util.ListBoxValues;
import org.kie.workbench.common.stunner.bpmn.client.forms.widgets.ComboBox;
import org.kie.workbench.common.stunner.bpmn.client.forms.widgets.CustomDataTypeTextBox;
import org.kie.workbench.common.stunner.bpmn.client.forms.widgets.VariableNameTextBox;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Tests the data get/set methods of VariableListItemWidget
*/
@RunWith(MockitoJUnitRunner.class)
public class VariableListItemWidgetTest {
ValueListBox<String> dataType;
CustomDataTypeTextBox customDataType;
ComboBox dataTypeComboBox;
HTMLInputElement kpi;
@GwtMock
VariableNameTextBox name;
@GwtMock
Button deleteButton;
@GwtMock
DataBinder<VariableRow> variable;
//@Spy // - cannot make Spy because of GWT error
//@InjectMocks // - cannot InjectMocks because of GWT error
private VariableListItemWidgetViewImpl widget;
@Before
public void initTestCase() {
GwtMockito.initMocks(this);
dataType = mock(ValueListBox.class);
customDataType = mock(CustomDataTypeTextBox.class);
dataTypeComboBox = mock(ComboBox.class);
kpi = mock(HTMLInputElement.class);
widget = GWT.create(VariableListItemWidgetViewImpl.class);
VariableRow variableRow = new VariableRow();
widget.dataType = dataType;
widget.customDataType = customDataType;
widget.dataTypeComboBox = dataTypeComboBox;
widget.name = name;
widget.deleteButton = deleteButton;
widget.variableRow = variable;
widget.kpi = kpi;
Mockito.doCallRealMethod().when(widget).setTextBoxModelValue(any(TextBox.class),
anyString());
Mockito.doCallRealMethod().when(widget).setListBoxModelValue(any(ValueListBox.class),
anyString());
Mockito.doCallRealMethod().when(widget).getModelValue(any(ValueListBox.class));
Mockito.doCallRealMethod().when(widget).setDataTypeDisplayName(anyString());
Mockito.doCallRealMethod().when(widget).getDataTypeDisplayName();
Mockito.doCallRealMethod().when(widget).setCustomDataType(anyString());
Mockito.doCallRealMethod().when(widget).getCustomDataType();
Mockito.doCallRealMethod().when(widget).setDataTypes(any(ListBoxValues.class));
Mockito.doCallRealMethod().when(widget).init();
Mockito.doCallRealMethod().when(widget).setModel(any(VariableRow.class));
when(widget.getModel()).thenReturn(variableRow);
}
@Test
public void testInitWidget() {
widget.init();
verify(widget,
times(1)).init();
verify(dataTypeComboBox,
times(1)).init(widget,
true,
dataType,
customDataType,
false,
true,
VariableListItemWidgetView.CUSTOM_PROMPT,
VariableListItemWidgetView.ENTER_TYPE_PROMPT);
ArgumentCaptor<String> nameRegExpCaptor = ArgumentCaptor.forClass(String.class);
verify(name,
times(1)).setRegExp(nameRegExpCaptor.capture(),
anyString(),
anyString());
RegExp nameRegExp = RegExp.compile(nameRegExpCaptor.getValue());
assertEquals(false, nameRegExp.test("a 1"));
assertEquals(false, nameRegExp.test("a@1"));
assertEquals(true, nameRegExp.test("a1"));
verify(name, times(1)).addChangeHandler(any(ChangeHandler.class));
ArgumentCaptor<String> customValueRegExpCaptor = ArgumentCaptor.forClass(String.class);
verify(customDataType,
times(1)).setRegExp(customValueRegExpCaptor.capture(),
anyString(),
anyString());
RegExp customValueRegExp = RegExp.compile(customValueRegExpCaptor.getValue());
assertEquals(false, customValueRegExp.test("a 1"));
assertEquals(false, customValueRegExp.test("<a1"));
assertEquals(false, customValueRegExp.test("a1>"));
assertEquals(false, customValueRegExp.test("<a1>"));
assertEquals(false, customValueRegExp.test("<a1/>"));
assertEquals(false, customValueRegExp.test("<a1\\>"));
assertEquals(false, customValueRegExp.test("a@1"));
assertEquals(true, customValueRegExp.test("a1"));
assertEquals(true, customValueRegExp.test("org.kie.Object"));
verify(customDataType, times(1)).addKeyDownHandler(any(KeyDownHandler.class));
}
@Test
public void testSetTextBoxModelValue() {
widget.setTextBoxModelValue(customDataType,
"com.test.Pencil");
verify(widget,
times(1)).setCustomDataType("com.test.Pencil");
}
@Test
public void testSetListBoxModelValue() {
widget.setListBoxModelValue(dataType,
"Paper [org.stationery");
verify(widget,
times(1)).setDataTypeDisplayName("Paper [org.stationery");
}
@Test
public void testSetModel() {
when(widget.getVariableType()).thenReturn(Variable.VariableType.PROCESS);
widget.setModel(new VariableRow());
verify(deleteButton).setIcon(IconType.TRASH);
verify(widget).getCustomDataType();
verify(widget).getDataTypeDisplayName();
}
@Test
public void testSetGetCustomDataType() {
String customDataType = "com.test.MyType";
widget.setTextBoxModelValue(widget.customDataType,
customDataType);
String returnedCustomDataType1 = widget.getCustomDataType();
assertEquals(customDataType,
returnedCustomDataType1);
String returnedCustomDataType2 = widget.getModelValue(widget.dataType);
assertEquals(customDataType,
returnedCustomDataType2);
}
@Test
public void testSetGetDataType() {
String sDataType = "Boolean";
widget.setListBoxModelValue(widget.dataType,
sDataType);
String returnedDataType1 = widget.getDataTypeDisplayName();
assertEquals(sDataType,
returnedDataType1);
String returnedDataType2 = widget.getModelValue(widget.dataType);
assertEquals(sDataType,
returnedDataType2);
}
@Test
public void testSetDataTypes() {
ListBoxValues dataTypeListBoxValues = new ListBoxValues(null,
null,
null);
String sCustomType = "com.test.CustomType";
widget.setCustomDataType(sCustomType);
widget.setDataTypes(dataTypeListBoxValues);
verify(dataTypeComboBox).setListBoxValues(dataTypeListBoxValues);
verify(dataTypeComboBox).addCustomValueToListBoxValues(sCustomType,
"");
}
@Test
public void testSetKPI() {
String sDataType = "Boolean";
widget.setListBoxModelValue(widget.dataType,
sDataType);
kpi.checked = true;
String returnedDataType1 = widget.getDataTypeDisplayName();
assertEquals(sDataType,
returnedDataType1);
String returnedDataType2 = widget.getModelValue(widget.dataType);
assertEquals(sDataType,
returnedDataType2);
boolean returnedDataType3 = widget.kpi.checked;
assertEquals(true,
returnedDataType3);
}
}
|
/* Copyright (c) 2019 AT&T Intellectual Property. #
# #
# 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.oran.otf.common.model.local;
import org.oran.otf.common.utility.gson.Convert;
import java.io.Serializable;
public class PfloNode implements Serializable {
private static final long serialVersionUID = 1L;
private String bpmnPlfoTaskId;
private String label;
public PfloNode() {
}
public PfloNode(String bpmnPlfoTaskId, String label) {
this.bpmnPlfoTaskId = bpmnPlfoTaskId;
this.label = label;
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
public String getBpmnPlfoTaskId() {
return bpmnPlfoTaskId;
}
public void setBpmnPlfoTaskId(String bpmnPlfoTaskId) {
this.bpmnPlfoTaskId = bpmnPlfoTaskId;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
@Override
public String toString() {
return Convert.objectToJson(this);
}
}
|
package com.codermy.myspringsecurityplus.car.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
@Configuration
public class UploadConfig {
@Bean(name="multipartResolver")
public MultipartResolver multipartResolver(){
return new CommonsMultipartResolver();
}
}
|
package edu.mum.cs.ds.atm.model;
public class Request {
private String actionType; //withdraw, check balance,
private String machineId;
private String cardNo;
private String branchCode;
private double amount;
private String status;
private String message;
private String accountId;
private int pin = 0;
public void setAmount(double amount) {
this.amount = amount;
}
private String billId;
public Request(String actionType, String machineId, String cardNo,
String branchCode, String accountId) {
super();
this.actionType = actionType;
this.machineId = machineId;
this.cardNo = cardNo;
this.branchCode = branchCode;
this.accountId = accountId;
}
public Request(String actionType, String machineId, String cardNo,
String branchCode, double amount, String accountId) {
super();
this.actionType = actionType;
this.machineId = machineId;
this.cardNo = cardNo;
this.branchCode = branchCode;
this.amount = amount;
this.accountId=accountId;
System.out.println("----- "+actionType+" request is created -------");
}
public Request(String actionType, String machineId, String cardNo,
String branchCode, double amount, String accountId, int pin) {
super();
this.actionType = actionType;
this.machineId = machineId;
this.cardNo = cardNo;
this.branchCode = branchCode;
this.amount = amount;
this.accountId=accountId;
this.pin=pin;
System.out.println("----- "+actionType+" request is created -------");
}
public Request(String actionType, String machineId, String cardNo,
String branchCode, double amount, String accountId, int pin, String billId) {
super();
this.actionType = actionType;
this.machineId = machineId;
this.cardNo = cardNo;
this.branchCode = branchCode;
this.amount = amount;
this.accountId=accountId;
this.pin=pin;
this.billId=billId;
System.out.println("----- "+actionType+" request is created -------");
}
public String getActionType() {
return actionType;
}
public String getMachineId() {
return machineId;
}
public String getCardNo() {
return cardNo;
}
public String getBranchCode() {
return branchCode;
}
public double getAmount() {
return amount;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getAccountId() {
return accountId;
}
public int getPin() {
return pin;
}
public void setPin(int pin) {
this.pin = pin;
}
public String getBillId() {
return billId;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((accountId == null) ? 0 : accountId.hashCode());
result = prime * result + ((actionType == null) ? 0 : actionType.hashCode());
long temp;
temp = Double.doubleToLongBits(amount);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + ((branchCode == null) ? 0 : branchCode.hashCode());
result = prime * result + ((cardNo == null) ? 0 : cardNo.hashCode());
result = prime * result + ((machineId == null) ? 0 : machineId.hashCode());
result = prime * result + ((message == null) ? 0 : message.hashCode());
result = prime * result + ((status == null) ? 0 : status.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Request other = (Request) obj;
if (accountId == null) {
if (other.accountId != null)
return false;
} else if (!accountId.equals(other.accountId))
return false;
if (actionType == null) {
if (other.actionType != null)
return false;
} else if (!actionType.equals(other.actionType))
return false;
if (Double.doubleToLongBits(amount) != Double.doubleToLongBits(other.amount))
return false;
if (branchCode == null) {
if (other.branchCode != null)
return false;
} else if (!branchCode.equals(other.branchCode))
return false;
if (cardNo == null) {
if (other.cardNo != null)
return false;
} else if (!cardNo.equals(other.cardNo))
return false;
if (machineId == null) {
if (other.machineId != null)
return false;
} else if (!machineId.equals(other.machineId))
return false;
if (message == null) {
if (other.message != null)
return false;
} else if (!message.equals(other.message))
return false;
if (status == null) {
if (other.status != null)
return false;
} else if (!status.equals(other.status))
return false;
return true;
}
@Override
public String toString() {
return "Request [actionType=" + actionType + ", machineId=" + machineId + ", cardNo=" + cardNo + ", branchCode="
+ branchCode + ", amount=" + amount + ", status=" + status + ", message=" + message + ", accountId="
+ accountId + "]";
}
}
|
package antlr;
/* ANTLR Translator Generator
* Project led by Terence Parr at http://www.jGuru.com
* Software rights: http://www.antlr.org/RIGHTS.html
*
* $Id: //depot/code/org.antlr/release/antlr-2.7.2/antlr/Tool.java#1 $
*/
import java.io.*;
import antlr.collections.impl.BitSet;
import antlr.collections.impl.Vector;
import antlr.PreservingFileWriter;
import antlr.Version;
public class Tool {
public static String version = "";
/** Object that handles analysis errors */
ToolErrorHandler errorHandler;
/** Was there an error during parsing or analysis? */
protected boolean hasError = false;
/** Generate diagnostics? (vs code) */
boolean genDiagnostics = false;
/** Generate DocBook vs code? */
boolean genDocBook = false;
/** Generate HTML vs code? */
boolean genHTML = false;
/** Current output directory for generated files */
protected static String outputDir = ".";
// Grammar input
protected String grammarFile;
transient Reader f = new InputStreamReader(System.in);
// SAS: changed for proper text io
// transient DataInputStream in = null;
protected static String literalsPrefix = "LITERAL_";
protected static boolean upperCaseMangledLiterals = false;
/** C++ file level options */
protected NameSpace nameSpace = null;
protected String namespaceAntlr = null;
protected String namespaceStd = null;
protected boolean genHashLines = true;
protected boolean noConstructors = false;
private BitSet cmdLineArgValid = new BitSet();
/** Construct a new Tool. */
public Tool() {
errorHandler = new DefaultToolErrorHandler(this);
}
public String getGrammarFile() {
return grammarFile;
}
public boolean hasError() {
return hasError;
}
public NameSpace getNameSpace() {
return nameSpace;
}
public String getNamespaceStd() {
return namespaceStd;
}
public String getNamespaceAntlr() {
return namespaceAntlr;
}
public boolean getGenHashLines() {
return genHashLines;
}
public String getLiteralsPrefix() {
return literalsPrefix;
}
public boolean getUpperCaseMangledLiterals() {
return upperCaseMangledLiterals;
}
public void setFileLineFormatter(FileLineFormatter formatter) {
FileLineFormatter.setFormatter(formatter);
}
protected void checkForInvalidArguments(String[] args, BitSet cmdLineArgValid) {
// check for invalid command line args
for (int a = 0; a < args.length; a++) {
if (!cmdLineArgValid.member(a)) {
warning("invalid command-line argument: " + args[a] + "; ignored");
}
}
}
/** This example is from the book _Java in a Nutshell_ by David
* Flanagan. Written by David Flanagan. Copyright (c) 1996
* O'Reilly & Associates. You may study, use, modify, and
* distribute this example for any purpose. This example is
* provided WITHOUT WARRANTY either expressed or implied. */
public void copyFile(String source_name, String dest_name)
throws IOException {
File source_file = new File(source_name);
File destination_file = new File(dest_name);
Reader source = null;
Writer destination = null;
char[] buffer;
int bytes_read;
try {
// First make sure the specified source file
// exists, is a file, and is readable.
if (!source_file.exists() || !source_file.isFile())
throw new FileCopyException("FileCopy: no such source file: " +
source_name);
if (!source_file.canRead())
throw new FileCopyException("FileCopy: source file " +
"is unreadable: " + source_name);
// If the destination exists, make sure it is a writeable file
// and ask before overwriting it. If the destination doesn't
// exist, make sure the directory exists and is writeable.
if (destination_file.exists()) {
if (destination_file.isFile()) {
DataInputStream in = new DataInputStream(System.in);
String response;
if (!destination_file.canWrite())
throw new FileCopyException("FileCopy: destination " +
"file is unwriteable: " + dest_name);
/*
System.out.print("File " + dest_name +
" already exists. Overwrite? (Y/N): ");
System.out.flush();
response = in.readLine();
if (!response.equals("Y") && !response.equals("y"))
throw new FileCopyException("FileCopy: copy cancelled.");
*/
}
else {
throw new FileCopyException("FileCopy: destination "
+ "is not a file: " + dest_name);
}
}
else {
File parentdir = parent(destination_file);
if (!parentdir.exists())
throw new FileCopyException("FileCopy: destination "
+ "directory doesn't exist: " + dest_name);
if (!parentdir.canWrite())
throw new FileCopyException("FileCopy: destination "
+ "directory is unwriteable: " + dest_name);
}
// If we've gotten this far, then everything is okay; we can
// copy the file.
source = new BufferedReader(new FileReader(source_file));
destination = new BufferedWriter(new FileWriter(destination_file));
buffer = new char[1024];
while (true) {
bytes_read = source.read(buffer, 0, 1024);
if (bytes_read == -1) break;
destination.write(buffer, 0, bytes_read);
}
}
// No matter what happens, always close any streams we've opened.
finally {
if (source != null) {
try {
source.close();
}
catch (IOException e) {
;
}
}
if (destination != null) {
try {
destination.close();
}
catch (IOException e) {
;
}
}
}
}
/** Perform processing on the grammar file. Can only be called
* from main() @param args The command-line arguments passed to
* main(). This wrapper does the System.exit for use with command-line.
*/
public void doEverythingWrapper(String[] args) {
int exitCode = doEverything(args);
System.exit(exitCode);
}
/** Process args and have ANTLR do it's stuff without calling System.exit.
* Just return the result code. Makes it easy for ANT build tool.
*/
public int doEverything(String[] args) {
// run the preprocessor to handle inheritance first.
// Start preprocessor. This strips generates an argument list
// without -glib options (inside preTool)
antlr.preprocessor.Tool preTool = new antlr.preprocessor.Tool(this, args);
boolean preprocess_ok = preTool.preprocess();
String[] modifiedArgs = preTool.preprocessedArgList();
// process arguments for the Tool
processArguments(modifiedArgs);
if (!preprocess_ok) {
return 1;
}
f = getGrammarReader();
ANTLRLexer lexer = new ANTLRLexer(f);
TokenBuffer tokenBuf = new TokenBuffer(lexer);
LLkAnalyzer analyzer = new LLkAnalyzer(this);
MakeGrammar behavior = new MakeGrammar(this, args, analyzer);
try {
ANTLRParser p = new ANTLRParser(tokenBuf, behavior, this);
p.setFilename(grammarFile);
p.grammar();
if (hasError()) {
fatalError("Exiting due to errors.");
}
checkForInvalidArguments(modifiedArgs, cmdLineArgValid);
// Create the right code generator according to the "language" option
CodeGenerator codeGen;
// SAS: created getLanguage() method so subclass can override
// (necessary for VAJ interface)
String codeGenClassName = "antlr." + getLanguage(behavior) + "CodeGenerator";
try {
Class codeGenClass = Class.forName(codeGenClassName);
codeGen = (CodeGenerator)codeGenClass.newInstance();
codeGen.setBehavior(behavior);
codeGen.setAnalyzer(analyzer);
codeGen.setTool(this);
codeGen.gen();
}
catch (ClassNotFoundException cnfe) {
panic("Cannot instantiate code-generator: " + codeGenClassName);
}
catch (InstantiationException ie) {
panic("Cannot instantiate code-generator: " + codeGenClassName);
}
catch (IllegalArgumentException ie) {
panic("Cannot instantiate code-generator: " + codeGenClassName);
}
catch (IllegalAccessException iae) {
panic("code-generator class '" + codeGenClassName + "' is not accessible");
}
}
catch (RecognitionException pe) {
fatalError("Unhandled parser error: " + pe.getMessage());
}
catch (TokenStreamException io) {
fatalError("TokenStreamException: " + io.getMessage());
}
return 0;
}
/** Issue an error
* @param s The message
*/
public void error(String s) {
hasError = true;
System.err.println("error: " + s);
}
/** Issue an error with line number information
* @param s The message
* @param file The file that has the error (or null)
* @param line The grammar file line number on which the error occured (or -1)
* @param column The grammar file column number on which the error occured (or -1)
*/
public void error(String s, String file, int line, int column) {
hasError = true;
System.err.println(FileLineFormatter.getFormatter().
getFormatString(file, line, column) + s);
}
/** When we are 1.1 compatible...
public static Object factory2 (String p, Object[] initargs) {
Class c;
Object o = null;
try {
int argslen = initargs.length;
Class cl[] = new Class[argslen];
for (int i=0;i<argslen;i++) {
cl[i] = Class.forName(initargs[i].getClass().getName());
}
c = Class.forName (p);
Constructor con = c.getConstructor (cl);
o = con.newInstance (initargs);
} catch (Exception e) {
System.err.println ("Can't make a " + p);
}
return o;
}
*/
public Object factory(String p) {
Class c;
Object o = null;
try {
c = Class.forName(p);// get class def
o = c.newInstance(); // make a new one
}
catch (Exception e) {
// either class not found,
// class is interface/abstract, or
// class or initializer is not accessible.
warning("Can't create an object of type " + p);
return null;
}
return o;
}
public String fileMinusPath(String f) {
String separator = System.getProperty("file.separator");
int endOfPath = f.lastIndexOf(separator);
if (endOfPath == -1) {
return f; // no path found
}
return f.substring(endOfPath + 1);
}
/** Determine the language used for this run of ANTLR
* This was made a method so the subclass can override it
*/
public String getLanguage(MakeGrammar behavior) {
if (genDiagnostics) {
return "Diagnostic";
}
if (genHTML) {
return "HTML";
}
if (genDocBook) {
return "DocBook";
}
return behavior.language;
}
public String getOutputDirectory() {
return outputDir;
}
private static void help() {
System.err.println("usage: java antlr.Tool [args] file.g");
System.err.println(" -o outputDir specify output directory where all output generated.");
System.err.println(" -glib superGrammar specify location of supergrammar file.");
System.err.println(" -debug launch the ParseView debugger upon parser invocation.");
System.err.println(" -html generate a html file from your grammar.");
System.err.println(" -docbook generate a docbook sgml file from your grammar.");
System.err.println(" -diagnostic generate a textfile with diagnostics.");
System.err.println(" -trace have all rules call traceIn/traceOut.");
System.err.println(" -traceLexer have lexer rules call traceIn/traceOut.");
System.err.println(" -traceParser have parser rules call traceIn/traceOut.");
System.err.println(" -traceTreeParser have tree parser rules call traceIn/traceOut.");
System.err.println(" -h|-help|--help this message");
}
public static void main(String[] args) {
System.err.println("ANTLR Parser Generator Version " +
Version.project_version + " 1989-2003 jGuru.com");
version = Version.project_version;
try {
if (args.length == 0) {
help();
System.exit(1);
}
for (int i = 0; i < args.length; ++i) {
if (args[i].equals("-h")
|| args[i].equals("-help")
|| args[i].equals("--help")
) {
help();
System.exit(1);
}
}
Tool theTool = new Tool();
theTool.doEverything(args);
theTool = null;
}
catch (Exception e) {
System.err.println(System.getProperty("line.separator") +
System.getProperty("line.separator"));
System.err.println("#$%%*&@# internal error: " + e.toString());
System.err.println("[complain to nearest government official");
System.err.println(" or send hate-mail to parrt@jguru.com;");
System.err.println(" please send stack trace with report.]" +
System.getProperty("line.separator"));
e.printStackTrace();
}
System.exit(0);
}
/** This method is used by all code generators to create new output
* files.
*/
public PrintWriter openOutputFile(String f) throws IOException {
return new PrintWriter(new PreservingFileWriter(outputDir + System.getProperty("file.separator") + f));
}
public Reader getGrammarReader() {
Reader f = null;
try {
if (grammarFile != null) {
f = new BufferedReader(new FileReader(grammarFile));
}
}
catch (IOException e) {
fatalError("cannot open grammar file " + grammarFile);
}
return f;
}
/** @since 2.7.2
*/
public void reportException(Exception e, String message) {
System.err.println(message == null ? e.getMessage()
: message + ": " + e.getMessage());
}
/** @since 2.7.2
*/
public void reportProgress(String message) {
System.out.println(message);
}
/** An error occured that should stop the Tool from doing any work.
* The default implementation currently exits (via
* {@link java.lang.System.exit(int)} after printing an error message to
* <var>stderr</var>. However, the tools should expect that a subclass
* will override this to throw an unchecked exception such as
* {@link java.lang.IllegalStateException} or another subclass of
* {@link java.lang.RuntimeException}. <em>If this method is overriden,
* <strong>it must never return normally</strong>; i.e. it must always
* throw an exception or call System.exit</em>.
* @since 2.7.2
* @param s The message
*/
public void fatalError(String message) {
System.err.println(message);
System.exit(1);
}
/** Issue an unknown fatal error. <em>If this method is overriden,
* <strong>it must never return normally</strong>; i.e. it must always
* throw an exception or call System.exit</em>.
* @deprecated as of 2.7.2 use {@link #fatalError(String)}. By default
* this method executes <code>fatalError("panic");</code>.
*/
public void panic() {
fatalError("panic");
}
/** Issue a fatal error message. <em>If this method is overriden,
* <strong>it must never return normally</strong>; i.e. it must always
* throw an exception or call System.exit</em>.
* @deprecated as of 2.7.2 use {@link #fatalError(String)}. By defaykt
* this method executes <code>fatalError("panic: " + s);</code>.
* @param s The message
*/
public void panic(String s) {
fatalError("panic: " + s);
}
// File.getParent() can return null when the file is specified without
// a directory or is in the root directory.
// This method handles those cases.
public File parent(File f) {
String dirname = f.getParent();
if (dirname == null) {
if (f.isAbsolute())
return new File(File.separator);
else
return new File(System.getProperty("user.dir"));
}
return new File(dirname);
}
/** Parse a list such as "f1.g;f2.g;..." and return a Vector
* of the elements.
*/
public static Vector parseSeparatedList(String list, char separator) {
Vector v = new Vector(10);
StringBuffer buf = new StringBuffer(100);
int i = 0;
while (i < list.length()) {
while (i < list.length() && list.charAt(i) != separator) {
buf.append(list.charAt(i));
i++;
}
// add element to vector
v.appendElement(buf.toString());
buf.setLength(0);
// must be a separator or finished.
if (i < list.length()) {
// not done?
i++; // skip separator
}
}
if (v.size() == 0) return null;
return v;
}
/** given a filename, strip off the directory prefix (if any)
* and return it. Return "./" if f has no dir prefix.
*/
public String pathToFile(String f) {
String separator = System.getProperty("file.separator");
int endOfPath = f.lastIndexOf(separator);
if (endOfPath == -1) {
// no path, use current directory
return "." + System.getProperty("file.separator");
}
return f.substring(0, endOfPath + 1);
}
/** <p>Process the command-line arguments. Can only be called by Tool.
* A bitset is collected of all correct arguments via setArgOk.</p>
* @param args The command-line arguments passed to main()
*
*/
protected void processArguments(String[] args) {
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-diagnostic")) {
genDiagnostics = true;
genHTML = false;
setArgOK(i);
}
else if (args[i].equals("-o")) {
setArgOK(i);
if (i + 1 >= args.length) {
error("missing output directory with -o option; ignoring");
}
else {
i++;
setOutputDirectory(args[i]);
setArgOK(i);
}
}
else if (args[i].equals("-html")) {
genHTML = true;
genDiagnostics = false;
setArgOK(i);
}
else if (args[i].equals("-docbook")) {
genDocBook = true;
genDiagnostics = false;
setArgOK(i);
}
else {
if (args[i].charAt(0) != '-') {
// Must be the grammar file
grammarFile = args[i];
setArgOK(i);
}
}
}
}
public void setArgOK(int i) {
cmdLineArgValid.add(i);
}
public void setOutputDirectory(String o) {
outputDir = o;
}
/** Issue an error; used for general tool errors not for grammar stuff
* @param s The message
*/
public void toolError(String s) {
System.err.println("error: " + s);
}
/** Issue a warning
* @param s the message
*/
public void warning(String s) {
System.err.println("warning: " + s);
}
/** Issue a warning with line number information
* @param s The message
* @param file The file that has the warning (or null)
* @param line The grammar file line number on which the warning occured (or -1)
* @param column The grammar file line number on which the warning occured (or -1)
*/
public void warning(String s, String file, int line, int column) {
System.err.println(FileLineFormatter.getFormatter().
getFormatString(file, line, column) + "warning:" + s);
}
/** Issue a warning with line number information
* @param s The lines of the message
* @param file The file that has the warning
* @param line The grammar file line number on which the warning occured
*/
public void warning(String[] s, String file, int line, int column) {
if (s == null || s.length == 0) {
panic("bad multi-line message to Tool.warning");
}
System.err.println(FileLineFormatter.getFormatter().
getFormatString(file, line, column) + "warning:" + s[0]);
for (int i = 1; i < s.length; i++) {
System.err.println(FileLineFormatter.getFormatter().
getFormatString(file, line, column) + " " + s[i]);
}
}
/**
* Support C++ & C# namespaces (for now).
* C++: Add a nested namespace name to the current namespace.
* C# : Specify an enclosing namespace for the generated code.
* DAW: David Wagner -- C# support by kunle odutola
*/
public void setNameSpace(String name) {
if (null == nameSpace)
nameSpace = new NameSpace(StringUtils.stripFrontBack(name, "\"", "\""));
}
}
|
package blt.moneys.beta.procedures;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.Entity;
public class QuickestFixEffectEffectStartedappliedProcedure {
public static void execute(Entity entity) {
if (entity == null)
return;
if (entity instanceof LivingEntity _entity)
_entity.setHealth((float) ((entity instanceof LivingEntity _livEnt ? _livEnt.getHealth() : -1) + 2));
}
}
|
/*
* Copyright 2018-2020 Radicalbit S.r.l.
*
* 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.apache.lucene.facet.range;
import org.apache.lucene.facet.FacetResult;
import org.apache.lucene.facet.Facets;
import org.apache.lucene.facet.FacetsCollector;
import org.apache.lucene.facet.FacetsCollector.MatchingDocs;
import org.apache.lucene.facet.LabelAndValue;
import org.apache.lucene.index.IndexReaderContext;
import org.apache.lucene.index.ReaderUtil;
import org.apache.lucene.search.*;
import java.io.IOException;
import java.util.List;
/** {@link Facets} implementation that computes sum for
* dynamic long ranges from a provided {@link LongValuesSource}. Use
* this for dimensions that change in real-time (e.g. a
* relative time based dimension like "Past day", "Past 2
* days", etc.) or that change for each request (e.g.
* distance from the user's location, "< 1 km", "< 2 km",
* etc.).
*/
public class LongRangeFacetLongSum extends RangeFacetCounts {
private final long[] summations;
/** Create {@code LongRangeFacetCounts}, using {@link
* LongValuesSource} from the specified rangeField. */
public LongRangeFacetLongSum(String rangeField, String valueField, FacetsCollector hits, LongRange... ranges) throws IOException {
super(rangeField, ranges, null);
summations = new long[ranges.length];
sum(LongValuesSource.fromLongField(rangeField), LongValuesSource.fromLongField(valueField), hits.getMatchingDocs());
}
private void sum(LongValuesSource rangeSource, LongValuesSource valueSource, List<MatchingDocs> matchingDocs) throws IOException {
LongRange[] ranges = (LongRange[]) this.ranges;
LongRangeLongSummation counter = new LongRangeLongSummation(ranges);
int missingCount = 0;
for (MatchingDocs hits : matchingDocs) {
LongValues fv = rangeSource.getValues(hits.context, null);
LongValues values = valueSource.getValues(hits.context, null);
totCount += hits.totalHits;
final DocIdSetIterator fastMatchDocs;
if (fastMatchQuery != null) {
final IndexReaderContext topLevelContext = ReaderUtil.getTopLevelContext(hits.context);
final IndexSearcher searcher = new IndexSearcher(topLevelContext);
searcher.setQueryCache(null);
final Weight fastMatchWeight = searcher.createWeight(searcher.rewrite(fastMatchQuery), ScoreMode.COMPLETE_NO_SCORES, 1);
Scorer s = fastMatchWeight.scorer(hits.context);
if (s == null) {
continue;
}
fastMatchDocs = s.iterator();
} else {
fastMatchDocs = null;
}
DocIdSetIterator docs = hits.bits.iterator();
for (int doc = docs.nextDoc(); doc != DocIdSetIterator.NO_MORE_DOCS; ) {
if (fastMatchDocs != null) {
int fastMatchDoc = fastMatchDocs.docID();
if (fastMatchDoc < doc) {
fastMatchDoc = fastMatchDocs.advance(doc);
}
if (doc != fastMatchDoc) {
doc = docs.advance(fastMatchDoc);
continue;
}
}
// Skip missing docs:
if (fv.advanceExact(doc) && values.advanceExact(doc)) {
counter.add(fv.longValue(),values.longValue());
} else {
missingCount++;
}
doc = docs.nextDoc();
}
}
int x = counter.fillCounts(summations);
missingCount += x;
totCount -= missingCount;
}
@Override
public FacetResult getTopChildren(int topN, String dim, String... path) {
if (!dim.equals(field)) {
throw new IllegalArgumentException("invalid dim \"" + dim + "\"; should be \"" + field + "\"");
}
if (path.length != 0) {
throw new IllegalArgumentException("path.length should be 0");
}
LabelAndValue[] labelValues = new LabelAndValue[counts.length];
for(int i=0;i<counts.length;i++) {
labelValues[i] = new LabelAndValue(ranges[i].label, summations[i]);
}
return new FacetResult(dim, path, totCount, labelValues, labelValues.length);
}
}
|
/***************************************************************************
* Copyright 2021 Kieker Project (http://kieker-monitoring.net)
*
* 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 kieker.monitoring.core.configuration;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Enumeration;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import kieker.common.configuration.Configuration;
/**
* A ConfigurationFactory for kieker.monitoring.
*
* @author Andre van Hoorn, Jan Waller
*
* @since 1.3
*/
public final class ConfigurationFactory {
private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurationFactory.class);
/**
* Private constructor to avoid instantiation.
*/
private ConfigurationFactory() {}
// factory methods
/**
* Creates the configuration for the singleton controller instance. Note that the {@link Properties} returned by
* this method are not a singleton instance, i.e., each call returns an equal but not same set of
* {@link Properties}.
*
* @return the configuration for the singleton controller
*/
public static Configuration createSingletonConfiguration() {
LOGGER.debug("Searching for JVM argument '{}' ...", ConfigurationConstants.CUSTOM_PROPERTIES_LOCATION_JVM);
final Configuration defaultConfiguration = ConfigurationFactory.defaultConfiguration();
// ignore default default-name and set to KIEKER-SINGLETON
defaultConfiguration.setProperty(ConfigurationConstants.CONTROLLER_NAME, "KIEKER-SINGLETON");
// Searching for configuration file location passed to JVM
String configurationFile = System.getProperty(ConfigurationConstants.CUSTOM_PROPERTIES_LOCATION_JVM);
final Configuration loadConfiguration;
if (configurationFile != null) {
LOGGER.info("Loading configuration from JVM-specified location: '{}'", configurationFile);
loadConfiguration = ConfigurationFactory.loadConfigurationFromFile(configurationFile, defaultConfiguration);
} else {
// No JVM property; Trying to find configuration file in classpath
configurationFile = ConfigurationConstants.CUSTOM_PROPERTIES_LOCATION_CLASSPATH;
LOGGER.info("Loading properties from properties file in classpath: '{}'", configurationFile);
loadConfiguration = ConfigurationFactory.loadConfigurationFromResource(configurationFile,
defaultConfiguration);
}
// 1.JVM-params -> 2.properties file -> 3.default properties file
return ConfigurationFactory.getSystemPropertiesStartingWith(ConfigurationConstants.PREFIX, loadConfiguration);
}
/**
* Returns an empty properties map with a fallback on the default configuration.
*
* @return default configuration
*/
public static Configuration createDefaultConfiguration() {
return new Configuration(ConfigurationFactory.defaultConfiguration());
}
/**
* Creates a new configuration based on the given properties file with fallback on the default values. If the file
* does not exists, a warning is logged and an empty configuration with fallback on the default configuration is
* returned.
*
* @param configurationFile
* The file which contains the configuration.
*
* @return The created Configuration
*/
public static Configuration createConfigurationFromFile(final String configurationFile) {
return ConfigurationFactory.loadConfigurationFromFile(configurationFile,
ConfigurationFactory.defaultConfiguration());
}
/**
* Returns a properties map with the default configuration.
*
* @return The created Configuration
*/
private static Configuration defaultConfiguration() {
return ConfigurationFactory.loadConfigurationFromResource(ConfigurationConstants.DEFAULT_PROPERTIES_LOCATION_CLASSPATH, null);
}
/**
* Returns the properties loaded from file propertiesFn with fallback on the default values. If the file does not
* exists, a warning is logged and an empty configuration with fallback on the default configuration is returned.
*
* @param filename
* The file which contains the properties.
* @param defaultValues
* The configuration containing the default values.
*
* @return The created Configuration
*/
private static Configuration loadConfigurationFromFile(final String filename,
final Configuration defaultValues) {
final Configuration properties = new Configuration(defaultValues);
InputStream is = null; // NOPMD (null)
try {
try {
is = Files.newInputStream(Paths.get(filename), StandardOpenOption.READ);
} catch (final FileNotFoundException ex) {
// if not found as absolute path try within the classpath
final URL resourceUrl = ConfigurationFactory.loadKiekerPropertiesFile(filename);
if (resourceUrl == null) {
LOGGER.warn("File '{}' not found", filename);
return new Configuration(defaultValues);
}
is = resourceUrl.openStream();
}
properties.load(is);
return properties;
} catch (final IOException ex) {
LOGGER.error("Error reading file '{}'", filename, ex);
} finally {
if (is != null) {
try {
is.close();
} catch (final IOException ex) {
LOGGER.warn("Failed to close FileInputStream", ex);
}
}
}
return new Configuration(defaultValues);
}
/**
* Returns the properties loaded from the resource name with fallback on the default values. If the file does not
* exists, a warning is logged and an empty configuration with fallback on the default configuration is returned.
*
* @param propertiesFn
* The resource name which contains the properties.
* @param defaultValues
* The configuration containing the default values.
*
* @return The created Configuration
*/
private static Configuration loadConfigurationFromResource(final String propertiesFn,
final Configuration defaultValues) {
final URL resourceUrl = ConfigurationFactory.loadKiekerPropertiesFile(propertiesFn);
if (resourceUrl == null) {
LOGGER.warn("File '{}' not found in classpath", propertiesFn);
} else {
try (final InputStream is = resourceUrl.openStream()) {
final Configuration properties = new Configuration(defaultValues);
properties.load(is);
return properties;
} catch (final IOException ex) {
LOGGER.error("Error reading file '{}'", propertiesFn, ex);
}
}
return new Configuration(defaultValues);
}
/**
* @param propertiesFileName
* the relative file name within the class path
* @return A {@link java.net.URL} object or null if no resource with this name is found
*/
private static URL loadKiekerPropertiesFile(final String propertiesFileName) {
String resourceName = propertiesFileName;
if (!resourceName.startsWith("/")) {
// Class.getResource(..) requires a "/" at the beginning to load non-class resources
resourceName = "/" + resourceName;
}
return ConfigurationFactory.class.getResource(resourceName);
}
/**
* Returns the system properties starting with the given prefix.
*
* @param prefix
* The prefix to search for.
* @param defaultValues
* The configuration containing the default values.
*
* @return The created Configuration
*/
private static Configuration getSystemPropertiesStartingWith(final String prefix,
final Configuration defaultValues) {
final Configuration configuration = new Configuration(defaultValues);
final Properties properties = System.getProperties();
final Enumeration<?> keys = properties.propertyNames();
while (keys.hasMoreElements()) {
final String property = (String) keys.nextElement();
if (property.startsWith(prefix)) {
configuration.setProperty(property, properties.getProperty(property));
}
}
return configuration;
}
}
|
package umm3601.ride;
import com.mongodb.MongoException;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.bson.Document;
import org.bson.types.ObjectId;
import java.util.Iterator;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Sorts.*;
import org.bson.conversions.Bson;
public class RideController {
private final MongoCollection<Document> rideCollection;
public RideController(MongoDatabase database) {
rideCollection = database.getCollection("Rides");
}
String getRide(String id) {
FindIterable<Document> jsonRides = rideCollection.find(eq("_id", new ObjectId(id)));
Iterator<Document> iterator = jsonRides.iterator();
if (iterator.hasNext()) {
Document ride = iterator.next();
return ride.toJson();
} else {
// We didn't find the desired ride
return null;
}
}
// Method for appending the filterDoc in getRides for strings
private Document appendFilterDocString(Map<String, String[]> appendParams, String targetString, Document appendDoc){
String targetContent = (appendParams.get(targetString)[0]);
Document contentRegQuery = new Document();
contentRegQuery.append("$regex", targetContent);
contentRegQuery.append("$options", "i");
appendDoc = appendDoc.append(targetString, contentRegQuery);
return appendDoc;
}
// Method for appending the filterDoc in getRides for booleans
private Document appendFilterDocBoolean(Map<String, String[]> appendParams, String appendBoolean, Document appendDoc){
String targetContent = (appendParams.get(appendBoolean)[0]);
System.err.println("This is the targetContent " + targetContent);
Boolean targetBoolean = Boolean.parseBoolean(targetContent);
System.err.println("This is the targetBoolean " + targetBoolean);
Document contentRegQuery = new Document();
contentRegQuery.append("$regex", targetContent);
contentRegQuery.append("$options", "i");
appendDoc = appendDoc.append(appendBoolean, contentRegQuery);
return appendDoc;
}
//Method for getting Rides from the database
String getRides(Map<String, String[]> queryParams){
Document filterDoc = new Document();
System.err.println("I got to ride Controller");
if (queryParams.containsKey("destination")) {
String key = "destination";
filterDoc = appendFilterDocString(queryParams, key, filterDoc);
}
System.err.println("I got past destination");
if (queryParams.containsKey("origin")) {
String key = "origin";
filterDoc = appendFilterDocString(queryParams, key, filterDoc);
}
System.err.println("I got past origin");
if (queryParams.containsKey("departureDate")) {
String targetContent = queryParams.get("departureDate")[0];
System.err.println("this is the targetContent before parse is " + targetContent);
String targetContent2 = parseDateController(targetContent);
System.err.println("this is the targetContent after parsing " + targetContent2);
Document contentRegQuery = new Document();
contentRegQuery.append("$regex", targetContent);
contentRegQuery.append("$options", "i");
System.err.println("this is the content reg " + contentRegQuery);
filterDoc = filterDoc.append("departureDate", contentRegQuery);
System.err.println("this is the filter Doc in date " + contentRegQuery);
}
System.err.println("I got past departureDate");
if (queryParams.containsKey("departureTime")) {
String key = "departureTime";
filterDoc = appendFilterDocString(queryParams, key, filterDoc);
}
System.err.println("I got past departureTime");
if (queryParams.containsKey("driving")) {
String key = "driving";
filterDoc = appendFilterDocString(queryParams, key, filterDoc);
}
System.err.println("I got past driving");
if (queryParams.containsKey("roundTrip")) {
String key = "roundTrip";
filterDoc = appendFilterDocBoolean(queryParams, key, filterDoc);
}
System.err.println("I got past roundTrip");
if (queryParams.containsKey("noSmoking")) {
String key = "noSmoking";
filterDoc = appendFilterDocBoolean(queryParams, key, filterDoc);
}
System.err.println("I got past noSmoking");
if (queryParams.containsKey("Eco")) {
String key = "Eco";
filterDoc = appendFilterDocBoolean(queryParams, key, filterDoc);
}
System.err.println("I got past Eco");
if (queryParams.containsKey("petFriendly")) {
String key = "petFriendly";
filterDoc = appendFilterDocBoolean(queryParams, key, filterDoc);
}
System.err.println("I got past petFriendly");
FindIterable<Document> matchingRides = rideCollection.find(filterDoc);
return serializeIterable(matchingRides);
}
private String serializeIterable(Iterable<Document> documents) {
return StreamSupport.stream(documents.spliterator(), false)
.map(Document::toJson)
.collect(Collectors.joining(", ", "[", "]"));
}
String addNewRide(String driver, String destination, String origin, Boolean roundTrip, Boolean driving, String departureDate,
String departureTime, String notes, String sortDateTime, Boolean noSmoking, Boolean Eco, Boolean petFriendly, int seatsAvailable) {
Document newRide = new Document();
newRide.append("driver", driver);
newRide.append("destination", destination);
newRide.append("origin", origin);
newRide.append("roundTrip", roundTrip);
newRide.append("driving", driving);
newRide.append("departureDate", departureDate);
newRide.append("departureTime", departureTime);
newRide.append("notes", notes);
newRide.append("sortDateTime",sortDateTime);
newRide.append("noSmoking", noSmoking);
newRide.append("Eco", Eco);
newRide.append("petFriendly", petFriendly);
newRide.append("seatsAvailable", seatsAvailable);
System.out.println(seatsAvailable);
try {
rideCollection.insertOne(newRide);
ObjectId _id = newRide.getObjectId("_id");
System.err.println("Successfully added new ride [_id=" + _id + ", driver=" + driver + ", destination=" + destination + ", origin=" + origin + ", roundTrip=" + roundTrip + ", driving="
+ driving + " departureDate=" + departureDate + " departureTime=" + departureTime + " notes=" + notes +
" sortDateTime=" + sortDateTime + " noSmoking=" + noSmoking + " Eco=" + Eco + "petFriendly=" + petFriendly + "seatsAvailable" + seatsAvailable +']');
return _id.toHexString();
} catch (MongoException me) {
me.printStackTrace();
return null;
}
}
Boolean deleteRide(String id){
ObjectId objId = new ObjectId(id);
try{
DeleteResult out = rideCollection.deleteOne(new Document("_id", objId));
//Returns true if at least 1 document was deleted
return out.getDeletedCount() != 0;
}
catch(MongoException e){
e.printStackTrace();
return false;
}
}
Boolean updateRide(String id, String driver, String destination, String origin, Boolean roundTrip, Boolean driving,
String departureDate, String departureTime, String notes, String sortDateTime, Boolean noSmoking, Boolean Eco, Boolean petFriendly, Number seatsAvailable){
ObjectId objId = new ObjectId(id);
Document filter = new Document("_id", objId);
Document updateFields = new Document();
updateFields.append("driver", driver);
updateFields.append("destination", destination);
updateFields.append("origin", origin);
updateFields.append("driving", driving);
updateFields.append("roundTrip", roundTrip);
updateFields.append("departureDate", departureDate);
updateFields.append("departureTime", departureTime);
updateFields.append("notes", notes);
updateFields.append("sortDateTime", sortDateTime);
updateFields.append("noSmoking" , noSmoking);
updateFields.append("Eco" , Eco);
updateFields.append("petFriendly" , petFriendly);
updateFields.append("seatsAvailable", seatsAvailable);
Document updateDoc = new Document("$set", updateFields);
try{
UpdateResult out = rideCollection.updateOne(filter, updateDoc);
//returns false if no documents were modified, true otherwise
return out.getModifiedCount() != 0;
}catch(MongoException e){
e.printStackTrace();
return false;
}
}
//Helper Functions
private String parseDateController(String rawDate) {
if (rawDate != null) {
System.err.println("This is the raw date " + rawDate);
String departureMonth = rawDate.split(" ", 5)[1];
System.err.println("This is the month " + departureMonth);
String departureDay = rawDate.split(" ", 5)[2];
System.err.println("This is the date " + departureDay);
String departureYear = rawDate.split(" ", 5)[3];
System.err.println("This is the year " + departureYear);
if(departureMonth.equals("Jan")){
departureMonth = "01";
}
if(departureMonth.equals("Feb")){
departureMonth = "02";
}
if(departureMonth.equals("Mar")){
departureMonth = "03";
}
if(departureMonth.equals("Apr")){
departureMonth = "04";
}
if(departureMonth.equals("May")){
departureMonth = "05";
}
if(departureMonth.equals("Jun")){
departureMonth = "06";
}
if(departureMonth.equals("Jul")){
departureMonth = "07";
}
if(departureMonth.equals("Aug")){
departureMonth = "08";
}
if(departureMonth.equals("Sep")){
departureMonth = "09";
}
if(departureMonth.equals("Oct")){
departureMonth = "10";
}
if(departureMonth.equals("Nov")){
departureMonth = "11";
}
if(departureMonth.equals("Dec")){
departureMonth = "12";
}
if(Integer.parseInt(departureDay)<10){
departureDay = "0" + departureDay;
}
return departureMonth + "-" + departureDay + "-" + departureYear;
} else {
return "";
}
}
}
|
package com.fengwenyi.about_me.index.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author Erwin Feng
* @since 2020/5/21
*/
@Controller
@RequestMapping
public class IndexController {
@RequestMapping("/")
public String index() {
return "index";
}
}
|
package com.example.sipanji.ui.gallery;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.example.sipanji.R;
public class GalleryFragment extends Fragment {
private GalleryViewModel galleryViewModel;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
galleryViewModel =
ViewModelProviders.of(this).get(GalleryViewModel.class);
View root = inflater.inflate(R.layout.fragment_gallery, container, false);
final TextView textView = root.findViewById(R.id.text_gallery);
galleryViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
@Override
public void onChanged(@Nullable String s) {
textView.setText(s);
}
});
return root;
}
}
|
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hbase
operator|.
name|quotas
package|;
end_package
begin_import
import|import static
name|org
operator|.
name|junit
operator|.
name|Assert
operator|.
name|assertEquals
import|;
end_import
begin_import
import|import static
name|org
operator|.
name|junit
operator|.
name|Assert
operator|.
name|assertFalse
import|;
end_import
begin_import
import|import static
name|org
operator|.
name|junit
operator|.
name|Assert
operator|.
name|assertNotNull
import|;
end_import
begin_import
import|import static
name|org
operator|.
name|junit
operator|.
name|Assert
operator|.
name|assertTrue
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Map
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Map
operator|.
name|Entry
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|concurrent
operator|.
name|atomic
operator|.
name|AtomicLong
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|concurrent
operator|.
name|atomic
operator|.
name|AtomicReference
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|conf
operator|.
name|Configuration
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hbase
operator|.
name|HBaseClassTestRule
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hbase
operator|.
name|HBaseTestingUtility
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hbase
operator|.
name|TableName
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hbase
operator|.
name|Waiter
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hbase
operator|.
name|Waiter
operator|.
name|Predicate
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hbase
operator|.
name|client
operator|.
name|Connection
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hbase
operator|.
name|client
operator|.
name|RegionInfo
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hbase
operator|.
name|client
operator|.
name|RetriesExhaustedWithDetailsException
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hbase
operator|.
name|master
operator|.
name|HMaster
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hbase
operator|.
name|quotas
operator|.
name|SpaceQuotaSnapshot
operator|.
name|SpaceQuotaStatus
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hbase
operator|.
name|quotas
operator|.
name|policies
operator|.
name|MissingSnapshotViolationPolicyEnforcement
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hbase
operator|.
name|regionserver
operator|.
name|HRegionServer
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hbase
operator|.
name|testclassification
operator|.
name|MediumTests
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|AfterClass
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Before
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|BeforeClass
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|ClassRule
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Rule
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Test
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|experimental
operator|.
name|categories
operator|.
name|Category
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|rules
operator|.
name|TestName
import|;
end_import
begin_import
import|import
name|org
operator|.
name|slf4j
operator|.
name|Logger
import|;
end_import
begin_import
import|import
name|org
operator|.
name|slf4j
operator|.
name|LoggerFactory
import|;
end_import
begin_comment
comment|/** * Test class for the quota status RPCs in the master and regionserver. */
end_comment
begin_class
annotation|@
name|Category
argument_list|(
block|{
name|MediumTests
operator|.
name|class
block|}
argument_list|)
specifier|public
class|class
name|TestQuotaStatusRPCs
block|{
annotation|@
name|ClassRule
specifier|public
specifier|static
specifier|final
name|HBaseClassTestRule
name|CLASS_RULE
init|=
name|HBaseClassTestRule
operator|.
name|forClass
argument_list|(
name|TestQuotaStatusRPCs
operator|.
name|class
argument_list|)
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|Logger
name|LOG
init|=
name|LoggerFactory
operator|.
name|getLogger
argument_list|(
name|TestQuotaStatusRPCs
operator|.
name|class
argument_list|)
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|HBaseTestingUtility
name|TEST_UTIL
init|=
operator|new
name|HBaseTestingUtility
argument_list|()
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|AtomicLong
name|COUNTER
init|=
operator|new
name|AtomicLong
argument_list|(
literal|0
argument_list|)
decl_stmt|;
annotation|@
name|Rule
specifier|public
name|TestName
name|testName
init|=
operator|new
name|TestName
argument_list|()
decl_stmt|;
specifier|private
name|SpaceQuotaHelperForTests
name|helper
decl_stmt|;
annotation|@
name|BeforeClass
specifier|public
specifier|static
name|void
name|setUp
parameter_list|()
throws|throws
name|Exception
block|{
name|Configuration
name|conf
init|=
name|TEST_UTIL
operator|.
name|getConfiguration
argument_list|()
decl_stmt|;
comment|// Increase the frequency of some of the chores for responsiveness of the test
name|SpaceQuotaHelperForTests
operator|.
name|updateConfigForQuotas
argument_list|(
name|conf
argument_list|)
expr_stmt|;
name|TEST_UTIL
operator|.
name|startMiniCluster
argument_list|(
literal|1
argument_list|)
expr_stmt|;
block|}
annotation|@
name|AfterClass
specifier|public
specifier|static
name|void
name|tearDown
parameter_list|()
throws|throws
name|Exception
block|{
name|TEST_UTIL
operator|.
name|shutdownMiniCluster
argument_list|()
expr_stmt|;
block|}
annotation|@
name|Before
specifier|public
name|void
name|setupForTest
parameter_list|()
throws|throws
name|Exception
block|{
name|helper
operator|=
operator|new
name|SpaceQuotaHelperForTests
argument_list|(
name|TEST_UTIL
argument_list|,
name|testName
argument_list|,
name|COUNTER
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testRegionSizesFromMaster
parameter_list|()
throws|throws
name|Exception
block|{
specifier|final
name|long
name|tableSize
init|=
literal|1024L
operator|*
literal|10L
decl_stmt|;
comment|// 10KB
specifier|final
name|int
name|numRegions
init|=
literal|10
decl_stmt|;
specifier|final
name|TableName
name|tn
init|=
name|helper
operator|.
name|createTableWithRegions
argument_list|(
name|numRegions
argument_list|)
decl_stmt|;
comment|// Will write at least `tableSize` data
name|helper
operator|.
name|writeData
argument_list|(
name|tn
argument_list|,
name|tableSize
argument_list|)
expr_stmt|;
specifier|final
name|HMaster
name|master
init|=
name|TEST_UTIL
operator|.
name|getMiniHBaseCluster
argument_list|()
operator|.
name|getMaster
argument_list|()
decl_stmt|;
specifier|final
name|MasterQuotaManager
name|quotaManager
init|=
name|master
operator|.
name|getMasterQuotaManager
argument_list|()
decl_stmt|;
comment|// Make sure the master has all of the reports
name|Waiter
operator|.
name|waitFor
argument_list|(
name|TEST_UTIL
operator|.
name|getConfiguration
argument_list|()
argument_list|,
literal|30
operator|*
literal|1000
argument_list|,
operator|new
name|Predicate
argument_list|<
name|Exception
argument_list|>
argument_list|()
block|{
annotation|@
name|Override
specifier|public
name|boolean
name|evaluate
parameter_list|()
throws|throws
name|Exception
block|{
name|Map
argument_list|<
name|RegionInfo
argument_list|,
name|Long
argument_list|>
name|regionSizes
init|=
name|quotaManager
operator|.
name|snapshotRegionSizes
argument_list|()
decl_stmt|;
name|LOG
operator|.
name|trace
argument_list|(
literal|"Region sizes="
operator|+
name|regionSizes
argument_list|)
expr_stmt|;
return|return
name|numRegions
operator|==
name|countRegionsForTable
argument_list|(
name|tn
argument_list|,
name|regionSizes
argument_list|)
operator|&&
name|tableSize
operator|<=
name|getTableSize
argument_list|(
name|tn
argument_list|,
name|regionSizes
argument_list|)
return|;
block|}
block|}
argument_list|)
expr_stmt|;
name|Map
argument_list|<
name|TableName
argument_list|,
name|Long
argument_list|>
name|sizes
init|=
name|TEST_UTIL
operator|.
name|getAdmin
argument_list|()
operator|.
name|getSpaceQuotaTableSizes
argument_list|()
decl_stmt|;
name|Long
name|size
init|=
name|sizes
operator|.
name|get
argument_list|(
name|tn
argument_list|)
decl_stmt|;
name|assertNotNull
argument_list|(
literal|"No reported size for "
operator|+
name|tn
argument_list|,
name|size
argument_list|)
expr_stmt|;
name|assertTrue
argument_list|(
literal|"Reported table size was "
operator|+
name|size
argument_list|,
name|size
operator|.
name|longValue
argument_list|()
operator|>=
name|tableSize
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testQuotaSnapshotsFromRS
parameter_list|()
throws|throws
name|Exception
block|{
specifier|final
name|long
name|sizeLimit
init|=
literal|1024L
operator|*
literal|1024L
decl_stmt|;
comment|// 1MB
specifier|final
name|long
name|tableSize
init|=
literal|1024L
operator|*
literal|10L
decl_stmt|;
comment|// 10KB
specifier|final
name|int
name|numRegions
init|=
literal|10
decl_stmt|;
specifier|final
name|TableName
name|tn
init|=
name|helper
operator|.
name|createTableWithRegions
argument_list|(
name|numRegions
argument_list|)
decl_stmt|;
comment|// Define the quota
name|QuotaSettings
name|settings
init|=
name|QuotaSettingsFactory
operator|.
name|limitTableSpace
argument_list|(
name|tn
argument_list|,
name|sizeLimit
argument_list|,
name|SpaceViolationPolicy
operator|.
name|NO_INSERTS
argument_list|)
decl_stmt|;
name|TEST_UTIL
operator|.
name|getAdmin
argument_list|()
operator|.
name|setQuota
argument_list|(
name|settings
argument_list|)
expr_stmt|;
comment|// Write at least `tableSize` data
name|helper
operator|.
name|writeData
argument_list|(
name|tn
argument_list|,
name|tableSize
argument_list|)
expr_stmt|;
specifier|final
name|HRegionServer
name|rs
init|=
name|TEST_UTIL
operator|.
name|getMiniHBaseCluster
argument_list|()
operator|.
name|getRegionServer
argument_list|(
literal|0
argument_list|)
decl_stmt|;
specifier|final
name|RegionServerSpaceQuotaManager
name|manager
init|=
name|rs
operator|.
name|getRegionServerSpaceQuotaManager
argument_list|()
decl_stmt|;
name|Waiter
operator|.
name|waitFor
argument_list|(
name|TEST_UTIL
operator|.
name|getConfiguration
argument_list|()
argument_list|,
literal|30
operator|*
literal|1000
argument_list|,
operator|new
name|Predicate
argument_list|<
name|Exception
argument_list|>
argument_list|()
block|{
annotation|@
name|Override
specifier|public
name|boolean
name|evaluate
parameter_list|()
throws|throws
name|Exception
block|{
name|SpaceQuotaSnapshot
name|snapshot
init|=
name|manager
operator|.
name|copyQuotaSnapshots
argument_list|()
operator|.
name|get
argument_list|(
name|tn
argument_list|)
decl_stmt|;
if|if
condition|(
name|snapshot
operator|==
literal|null
condition|)
block|{
return|return
literal|false
return|;
block|}
return|return
name|snapshot
operator|.
name|getUsage
argument_list|()
operator|>=
name|tableSize
return|;
block|}
block|}
argument_list|)
expr_stmt|;
annotation|@
name|SuppressWarnings
argument_list|(
literal|"unchecked"
argument_list|)
name|Map
argument_list|<
name|TableName
argument_list|,
name|SpaceQuotaSnapshot
argument_list|>
name|snapshots
init|=
operator|(
name|Map
argument_list|<
name|TableName
argument_list|,
name|SpaceQuotaSnapshot
argument_list|>
operator|)
name|TEST_UTIL
operator|.
name|getAdmin
argument_list|()
operator|.
name|getRegionServerSpaceQuotaSnapshots
argument_list|(
name|rs
operator|.
name|getServerName
argument_list|()
argument_list|)
decl_stmt|;
name|SpaceQuotaSnapshot
name|snapshot
init|=
name|snapshots
operator|.
name|get
argument_list|(
name|tn
argument_list|)
decl_stmt|;
name|assertNotNull
argument_list|(
literal|"Did not find snapshot for "
operator|+
name|tn
argument_list|,
name|snapshot
argument_list|)
expr_stmt|;
name|assertTrue
argument_list|(
literal|"Observed table usage was "
operator|+
name|snapshot
operator|.
name|getUsage
argument_list|()
argument_list|,
name|snapshot
operator|.
name|getUsage
argument_list|()
operator|>=
name|tableSize
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
name|sizeLimit
argument_list|,
name|snapshot
operator|.
name|getLimit
argument_list|()
argument_list|)
expr_stmt|;
name|SpaceQuotaStatus
name|pbStatus
init|=
name|snapshot
operator|.
name|getQuotaStatus
argument_list|()
decl_stmt|;
name|assertFalse
argument_list|(
name|pbStatus
operator|.
name|isInViolation
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testQuotaEnforcementsFromRS
parameter_list|()
throws|throws
name|Exception
block|{
specifier|final
name|long
name|sizeLimit
init|=
literal|1024L
operator|*
literal|8L
decl_stmt|;
comment|// 8KB
specifier|final
name|long
name|tableSize
init|=
literal|1024L
operator|*
literal|10L
decl_stmt|;
comment|// 10KB
specifier|final
name|int
name|numRegions
init|=
literal|10
decl_stmt|;
specifier|final
name|TableName
name|tn
init|=
name|helper
operator|.
name|createTableWithRegions
argument_list|(
name|numRegions
argument_list|)
decl_stmt|;
comment|// Define the quota
name|QuotaSettings
name|settings
init|=
name|QuotaSettingsFactory
operator|.
name|limitTableSpace
argument_list|(
name|tn
argument_list|,
name|sizeLimit
argument_list|,
name|SpaceViolationPolicy
operator|.
name|NO_INSERTS
argument_list|)
decl_stmt|;
name|TEST_UTIL
operator|.
name|getAdmin
argument_list|()
operator|.
name|setQuota
argument_list|(
name|settings
argument_list|)
expr_stmt|;
comment|// Write at least `tableSize` data
try|try
block|{
name|helper
operator|.
name|writeData
argument_list|(
name|tn
argument_list|,
name|tableSize
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|RetriesExhaustedWithDetailsException
decl||
name|SpaceLimitingException
name|e
parameter_list|)
block|{
comment|// Pass
block|}
specifier|final
name|HRegionServer
name|rs
init|=
name|TEST_UTIL
operator|.
name|getMiniHBaseCluster
argument_list|()
operator|.
name|getRegionServer
argument_list|(
literal|0
argument_list|)
decl_stmt|;
specifier|final
name|RegionServerSpaceQuotaManager
name|manager
init|=
name|rs
operator|.
name|getRegionServerSpaceQuotaManager
argument_list|()
decl_stmt|;
name|Waiter
operator|.
name|waitFor
argument_list|(
name|TEST_UTIL
operator|.
name|getConfiguration
argument_list|()
argument_list|,
literal|30
operator|*
literal|1000
argument_list|,
operator|new
name|Predicate
argument_list|<
name|Exception
argument_list|>
argument_list|()
block|{
annotation|@
name|Override
specifier|public
name|boolean
name|evaluate
parameter_list|()
throws|throws
name|Exception
block|{
name|ActivePolicyEnforcement
name|enforcements
init|=
name|manager
operator|.
name|getActiveEnforcements
argument_list|()
decl_stmt|;
name|SpaceViolationPolicyEnforcement
name|enforcement
init|=
name|enforcements
operator|.
name|getPolicyEnforcement
argument_list|(
name|tn
argument_list|)
decl_stmt|;
comment|// Signifies that we're waiting on the quota snapshot to be fetched
if|if
condition|(
name|enforcement
operator|instanceof
name|MissingSnapshotViolationPolicyEnforcement
condition|)
block|{
return|return
literal|false
return|;
block|}
return|return
name|enforcement
operator|.
name|getQuotaSnapshot
argument_list|()
operator|.
name|getQuotaStatus
argument_list|()
operator|.
name|isInViolation
argument_list|()
return|;
block|}
block|}
argument_list|)
expr_stmt|;
comment|// We obtain the violations for a RegionServer by observing the snapshots
annotation|@
name|SuppressWarnings
argument_list|(
literal|"unchecked"
argument_list|)
name|Map
argument_list|<
name|TableName
argument_list|,
name|SpaceQuotaSnapshot
argument_list|>
name|snapshots
init|=
operator|(
name|Map
argument_list|<
name|TableName
argument_list|,
name|SpaceQuotaSnapshot
argument_list|>
operator|)
name|TEST_UTIL
operator|.
name|getAdmin
argument_list|()
operator|.
name|getRegionServerSpaceQuotaSnapshots
argument_list|(
name|rs
operator|.
name|getServerName
argument_list|()
argument_list|)
decl_stmt|;
name|SpaceQuotaSnapshot
name|snapshot
init|=
name|snapshots
operator|.
name|get
argument_list|(
name|tn
argument_list|)
decl_stmt|;
name|assertNotNull
argument_list|(
literal|"Did not find snapshot for "
operator|+
name|tn
argument_list|,
name|snapshot
argument_list|)
expr_stmt|;
name|assertTrue
argument_list|(
name|snapshot
operator|.
name|getQuotaStatus
argument_list|()
operator|.
name|isInViolation
argument_list|()
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
name|SpaceViolationPolicy
operator|.
name|NO_INSERTS
argument_list|,
name|snapshot
operator|.
name|getQuotaStatus
argument_list|()
operator|.
name|getPolicy
argument_list|()
operator|.
name|get
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testQuotaStatusFromMaster
parameter_list|()
throws|throws
name|Exception
block|{
specifier|final
name|long
name|sizeLimit
init|=
literal|1024L
operator|*
literal|25L
decl_stmt|;
comment|// 25KB
comment|// As of 2.0.0-beta-2, this 1KB of "Cells" actually results in about 15KB on disk (HFiles)
comment|// This is skewed a bit since we're writing such little data, so the test needs to keep
comment|// this in mind; else, the quota will be in violation before the test expects it to be.
specifier|final
name|long
name|tableSize
init|=
literal|1024L
operator|*
literal|1
decl_stmt|;
comment|// 1KB
specifier|final
name|long
name|nsLimit
init|=
name|Long
operator|.
name|MAX_VALUE
decl_stmt|;
specifier|final
name|int
name|numRegions
init|=
literal|10
decl_stmt|;
specifier|final
name|TableName
name|tn
init|=
name|helper
operator|.
name|createTableWithRegions
argument_list|(
name|numRegions
argument_list|)
decl_stmt|;
comment|// Define the quota
name|QuotaSettings
name|settings
init|=
name|QuotaSettingsFactory
operator|.
name|limitTableSpace
argument_list|(
name|tn
argument_list|,
name|sizeLimit
argument_list|,
name|SpaceViolationPolicy
operator|.
name|NO_INSERTS
argument_list|)
decl_stmt|;
name|TEST_UTIL
operator|.
name|getAdmin
argument_list|()
operator|.
name|setQuota
argument_list|(
name|settings
argument_list|)
expr_stmt|;
name|QuotaSettings
name|nsSettings
init|=
name|QuotaSettingsFactory
operator|.
name|limitNamespaceSpace
argument_list|(
name|tn
operator|.
name|getNamespaceAsString
argument_list|()
argument_list|,
name|nsLimit
argument_list|,
name|SpaceViolationPolicy
operator|.
name|NO_INSERTS
argument_list|)
decl_stmt|;
name|TEST_UTIL
operator|.
name|getAdmin
argument_list|()
operator|.
name|setQuota
argument_list|(
name|nsSettings
argument_list|)
expr_stmt|;
comment|// Write at least `tableSize` data
name|helper
operator|.
name|writeData
argument_list|(
name|tn
argument_list|,
name|tableSize
argument_list|)
expr_stmt|;
specifier|final
name|Connection
name|conn
init|=
name|TEST_UTIL
operator|.
name|getConnection
argument_list|()
decl_stmt|;
comment|// Make sure the master has a snapshot for our table
name|Waiter
operator|.
name|waitFor
argument_list|(
name|TEST_UTIL
operator|.
name|getConfiguration
argument_list|()
argument_list|,
literal|30
operator|*
literal|1000
argument_list|,
operator|new
name|Predicate
argument_list|<
name|Exception
argument_list|>
argument_list|()
block|{
annotation|@
name|Override
specifier|public
name|boolean
name|evaluate
parameter_list|()
throws|throws
name|Exception
block|{
name|SpaceQuotaSnapshot
name|snapshot
init|=
operator|(
name|SpaceQuotaSnapshot
operator|)
name|conn
operator|.
name|getAdmin
argument_list|()
operator|.
name|getCurrentSpaceQuotaSnapshot
argument_list|(
name|tn
argument_list|)
decl_stmt|;
name|LOG
operator|.
name|info
argument_list|(
literal|"Table snapshot after initial ingest: "
operator|+
name|snapshot
argument_list|)
expr_stmt|;
if|if
condition|(
name|snapshot
operator|==
literal|null
condition|)
block|{
return|return
literal|false
return|;
block|}
return|return
name|snapshot
operator|.
name|getLimit
argument_list|()
operator|==
name|sizeLimit
operator|&&
name|snapshot
operator|.
name|getUsage
argument_list|()
operator|>
literal|0L
return|;
block|}
block|}
argument_list|)
expr_stmt|;
specifier|final
name|AtomicReference
argument_list|<
name|Long
argument_list|>
name|nsUsage
init|=
operator|new
name|AtomicReference
argument_list|<>
argument_list|()
decl_stmt|;
comment|// If we saw the table snapshot, we should also see the namespace snapshot
name|Waiter
operator|.
name|waitFor
argument_list|(
name|TEST_UTIL
operator|.
name|getConfiguration
argument_list|()
argument_list|,
literal|30
operator|*
literal|1000
operator|*
literal|1000
argument_list|,
operator|new
name|Predicate
argument_list|<
name|Exception
argument_list|>
argument_list|()
block|{
annotation|@
name|Override
specifier|public
name|boolean
name|evaluate
parameter_list|()
throws|throws
name|Exception
block|{
name|SpaceQuotaSnapshot
name|snapshot
init|=
operator|(
name|SpaceQuotaSnapshot
operator|)
name|conn
operator|.
name|getAdmin
argument_list|()
operator|.
name|getCurrentSpaceQuotaSnapshot
argument_list|(
name|tn
operator|.
name|getNamespaceAsString
argument_list|()
argument_list|)
decl_stmt|;
name|LOG
operator|.
name|debug
argument_list|(
literal|"Namespace snapshot after initial ingest: "
operator|+
name|snapshot
argument_list|)
expr_stmt|;
if|if
condition|(
name|snapshot
operator|==
literal|null
condition|)
block|{
return|return
literal|false
return|;
block|}
name|nsUsage
operator|.
name|set
argument_list|(
name|snapshot
operator|.
name|getUsage
argument_list|()
argument_list|)
expr_stmt|;
return|return
name|snapshot
operator|.
name|getLimit
argument_list|()
operator|==
name|nsLimit
operator|&&
name|snapshot
operator|.
name|getUsage
argument_list|()
operator|>
literal|0
return|;
block|}
block|}
argument_list|)
expr_stmt|;
comment|// Sanity check: the below assertions will fail if we somehow write too much data
comment|// and force the table to move into violation before we write the second bit of data.
name|SpaceQuotaSnapshot
name|snapshot
init|=
operator|(
name|SpaceQuotaSnapshot
operator|)
name|conn
operator|.
name|getAdmin
argument_list|()
operator|.
name|getCurrentSpaceQuotaSnapshot
argument_list|(
name|tn
argument_list|)
decl_stmt|;
name|assertTrue
argument_list|(
literal|"QuotaSnapshot for "
operator|+
name|tn
operator|+
literal|" should be non-null and not in violation"
argument_list|,
name|snapshot
operator|!=
literal|null
operator|&&
operator|!
name|snapshot
operator|.
name|getQuotaStatus
argument_list|()
operator|.
name|isInViolation
argument_list|()
argument_list|)
expr_stmt|;
try|try
block|{
name|helper
operator|.
name|writeData
argument_list|(
name|tn
argument_list|,
name|tableSize
operator|*
literal|2L
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|RetriesExhaustedWithDetailsException
decl||
name|SpaceLimitingException
name|e
parameter_list|)
block|{
comment|// Pass
block|}
comment|// Wait for the status to move to violation
name|Waiter
operator|.
name|waitFor
argument_list|(
name|TEST_UTIL
operator|.
name|getConfiguration
argument_list|()
argument_list|,
literal|30
operator|*
literal|1000
argument_list|,
operator|new
name|Predicate
argument_list|<
name|Exception
argument_list|>
argument_list|()
block|{
annotation|@
name|Override
specifier|public
name|boolean
name|evaluate
parameter_list|()
throws|throws
name|Exception
block|{
name|SpaceQuotaSnapshot
name|snapshot
init|=
operator|(
name|SpaceQuotaSnapshot
operator|)
name|conn
operator|.
name|getAdmin
argument_list|()
operator|.
name|getCurrentSpaceQuotaSnapshot
argument_list|(
name|tn
argument_list|)
decl_stmt|;
name|LOG
operator|.
name|info
argument_list|(
literal|"Table snapshot after second ingest: "
operator|+
name|snapshot
argument_list|)
expr_stmt|;
if|if
condition|(
name|snapshot
operator|==
literal|null
condition|)
block|{
return|return
literal|false
return|;
block|}
return|return
name|snapshot
operator|.
name|getQuotaStatus
argument_list|()
operator|.
name|isInViolation
argument_list|()
return|;
block|}
block|}
argument_list|)
expr_stmt|;
comment|// The namespace should still not be in violation, but have a larger usage than previously
name|Waiter
operator|.
name|waitFor
argument_list|(
name|TEST_UTIL
operator|.
name|getConfiguration
argument_list|()
argument_list|,
literal|30
operator|*
literal|1000
argument_list|,
operator|new
name|Predicate
argument_list|<
name|Exception
argument_list|>
argument_list|()
block|{
annotation|@
name|Override
specifier|public
name|boolean
name|evaluate
parameter_list|()
throws|throws
name|Exception
block|{
name|SpaceQuotaSnapshot
name|snapshot
init|=
operator|(
name|SpaceQuotaSnapshot
operator|)
name|conn
operator|.
name|getAdmin
argument_list|()
operator|.
name|getCurrentSpaceQuotaSnapshot
argument_list|(
name|tn
operator|.
name|getNamespaceAsString
argument_list|()
argument_list|)
decl_stmt|;
name|LOG
operator|.
name|debug
argument_list|(
literal|"Namespace snapshot after second ingest: "
operator|+
name|snapshot
argument_list|)
expr_stmt|;
if|if
condition|(
name|snapshot
operator|==
literal|null
condition|)
block|{
return|return
literal|false
return|;
block|}
return|return
name|snapshot
operator|.
name|getUsage
argument_list|()
operator|>
name|nsUsage
operator|.
name|get
argument_list|()
operator|&&
operator|!
name|snapshot
operator|.
name|getQuotaStatus
argument_list|()
operator|.
name|isInViolation
argument_list|()
return|;
block|}
block|}
argument_list|)
expr_stmt|;
block|}
specifier|private
name|int
name|countRegionsForTable
parameter_list|(
name|TableName
name|tn
parameter_list|,
name|Map
argument_list|<
name|RegionInfo
argument_list|,
name|Long
argument_list|>
name|regionSizes
parameter_list|)
block|{
name|int
name|size
init|=
literal|0
decl_stmt|;
for|for
control|(
name|RegionInfo
name|regionInfo
range|:
name|regionSizes
operator|.
name|keySet
argument_list|()
control|)
block|{
if|if
condition|(
name|tn
operator|.
name|equals
argument_list|(
name|regionInfo
operator|.
name|getTable
argument_list|()
argument_list|)
condition|)
block|{
name|size
operator|++
expr_stmt|;
block|}
block|}
return|return
name|size
return|;
block|}
specifier|private
name|int
name|getTableSize
parameter_list|(
name|TableName
name|tn
parameter_list|,
name|Map
argument_list|<
name|RegionInfo
argument_list|,
name|Long
argument_list|>
name|regionSizes
parameter_list|)
block|{
name|int
name|tableSize
init|=
literal|0
decl_stmt|;
for|for
control|(
name|Entry
argument_list|<
name|RegionInfo
argument_list|,
name|Long
argument_list|>
name|entry
range|:
name|regionSizes
operator|.
name|entrySet
argument_list|()
control|)
block|{
name|RegionInfo
name|regionInfo
init|=
name|entry
operator|.
name|getKey
argument_list|()
decl_stmt|;
name|long
name|regionSize
init|=
name|entry
operator|.
name|getValue
argument_list|()
decl_stmt|;
if|if
condition|(
name|tn
operator|.
name|equals
argument_list|(
name|regionInfo
operator|.
name|getTable
argument_list|()
argument_list|)
condition|)
block|{
name|tableSize
operator|+=
name|regionSize
expr_stmt|;
block|}
block|}
return|return
name|tableSize
return|;
block|}
block|}
end_class
end_unit
|
package com.ljq1.house.autoconfig;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.annotation.Import;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(HttpClientAutoConfiguration.class)
public @interface EnableHttpClient {
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.rappsilber.gui.components;
import java.awt.AWTEvent;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.ItemEvent;
import javax.swing.ButtonGroup;
import javax.swing.DefaultButtonModel;
import static javax.swing.DefaultButtonModel.PRESSED;
import static javax.swing.DefaultButtonModel.SELECTED;
import javax.swing.Icon;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JToggleButton;
import javax.swing.LayoutStyle;
import javax.swing.UIManager;
/**
* Extends a JCheckBox to have a third state (null)
* @author Lutz Fischer <lfischer@staffmail.ed.ac.uk>
*/
public class TriStateCheckBox extends JCheckBox{
boolean mid_is_seelcted = true;
Boolean state = null;
Icon icon = UIManager.getIcon("CheckBox.icon");
Icon nullIcon = new NullIcon();
private class NullIcon implements Icon {
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
icon.paintIcon(c, g, x, y);
int w = getIconWidth();
int h = getIconHeight();
g.setColor(c.isEnabled() ? new Color(51, 51, 51) : new Color(122, 138, 153));
g.fillRect(x+4, y+4, w-8, h-8);
if (!c.isEnabled()) return;
g.setColor(new Color(81, 81, 81));
g.drawRect(x+4, y+4, w-9, h-9);
}
@Override
public int getIconWidth() {
return icon.getIconWidth();
}
@Override
public int getIconHeight() {
return icon.getIconHeight();
}
}
private class TristateButtonModel extends JToggleButton.ToggleButtonModel {
// shamlessly ripped of from ToggleButtonModel
@Override
public void setPressed(boolean b) {
if ((isPressed() == b) || !isEnabled()) {
return;
}
if (b == false && isArmed()) {
if (getSelectionState() == Boolean.FALSE) {
setSelectionState((Boolean)null);
setSelected(mid_is_seelcted);
} else if (getSelectionState() == null) {
setSelectionState(Boolean.TRUE);
setSelected(true);
} else {
setSelectionState(Boolean.FALSE);
setSelected(false);
}
}
if (b) {
stateMask |= PRESSED;
} else {
stateMask &= ~PRESSED;
}
fireStateChanged();
if(!isPressed() && isArmed()) {
int modifiers = 0;
AWTEvent currentEvent = EventQueue.getCurrentEvent();
if (currentEvent instanceof InputEvent) {
modifiers = ((InputEvent)currentEvent).getModifiers();
} else if (currentEvent instanceof ActionEvent) {
modifiers = ((ActionEvent)currentEvent).getModifiers();
}
fireActionPerformed(
new ActionEvent(this, ActionEvent.ACTION_PERFORMED,
getActionCommand(),
EventQueue.getMostRecentEventTime(),
modifiers));
}
}
public void setSelected(Boolean b) {
ButtonGroup group = getGroup();
if (group != null) {
// use the group model instead
group.setSelected(this, b);
b = group.isSelected(this);
}
if (state == b) {
return;
}
if (b) {
stateMask |= SELECTED;
} else {
stateMask &= ~SELECTED;
}
// Send ChangeEvent
fireStateChanged();
// Send ItemEvent
fireItemStateChanged(
new ItemEvent(this,
ItemEvent.ITEM_STATE_CHANGED,
this,
this.isSelected() ? ItemEvent.SELECTED : ItemEvent.DESELECTED));
}
}
public TriStateCheckBox() {
super();
putClientProperty("SelectionState", (Boolean)null);
// setIcon(new TriStateIcon());
setModel(new TristateButtonModel());
}
@Override
public void paint(Graphics g) {
if (state == null) {
setIcon(nullIcon);
}else {
setIcon(null);
}
super.paint(g);
}
public Boolean getSelectionState() {
return this.state;
}
@Override
public void setSelected(boolean b) {
throw new UnsupportedOperationException("don't call this");
}
public void setSelected(Boolean b) {
((TristateButtonModel)model).setSelected(b);
this.repaint();
}
public void setSelectionState(Boolean state) {
this.state = state;
if (state == null) {
super.setSelected(mid_is_seelcted);
} else {
super.setSelected((boolean)state);
}
}
}
|
package com.example.springdemo.springdemo.selenium;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @program: springBootPractice
* @description: 内容本身
* @author: hu_pf
* @create: 2020-07-13 17:36
**/
@Service("content")
public class Content implements FeiDian{
@Autowired
private SeleiumService seleiumService;
@Autowired
@Qualifier("xPath")
private ClickByXpath clickByXpath;
@Override
public Integer invoke(String name, Integer maxNum) {
clickByXpath.click("//div[@class='like-action action']",SeleiumService.driver);
maxNum++;
return maxNum;
}
}
|
// Copyright (C) 2009 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 com.google.gerrit.server.query;
import static com.google.gerrit.server.query.Predicate.and;
import static com.google.gerrit.server.query.Predicate.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
public class NotPredicateTest extends PredicateTest {
@Test
public void notNot() {
final TestPredicate p = f("author", "bob");
final Predicate<String> n = not(p);
assertTrue(n instanceof NotPredicate);
assertNotSame(p, n);
assertSame(p, not(n));
}
@Test
public void children() {
final TestPredicate p = f("author", "bob");
final Predicate<String> n = not(p);
assertEquals(1, n.getChildCount());
assertSame(p, n.getChild(0));
}
@Test
public void childrenUnmodifiable() {
final TestPredicate p = f("author", "bob");
final Predicate<String> n = not(p);
exception.expect(UnsupportedOperationException.class);
n.getChildren().clear();
assertOnlyChild("clear", p, n);
exception.expect(UnsupportedOperationException.class);
n.getChildren().remove(0);
assertOnlyChild("remove(0)", p, n);
exception.expect(UnsupportedOperationException.class);
n.getChildren().iterator().remove();
assertOnlyChild("remove(0)", p, n);
}
private static void assertOnlyChild(String o, Predicate<String> c, Predicate<String> p) {
assertEquals(o + " did not affect child", 1, p.getChildCount());
assertSame(o + " did not affect child", c, p.getChild(0));
}
@Test
public void testToString() {
assertEquals("-author:bob", not(f("author", "bob")).toString());
}
@SuppressWarnings("unlikely-arg-type")
@Test
public void testEquals() {
assertTrue(not(f("author", "bob")).equals(not(f("author", "bob"))));
assertFalse(not(f("author", "bob")).equals(not(f("author", "alice"))));
assertFalse(not(f("author", "bob")).equals(f("author", "bob")));
assertFalse(not(f("author", "bob")).equals("author"));
}
@Test
public void testHashCode() {
assertTrue(not(f("a", "b")).hashCode() == not(f("a", "b")).hashCode());
assertFalse(not(f("a", "b")).hashCode() == not(f("a", "a")).hashCode());
}
@Test
@SuppressWarnings({"rawtypes", "unchecked"})
public void testCopy() {
final TestPredicate a = f("author", "alice");
final TestPredicate b = f("author", "bob");
final List<TestPredicate> sa = Collections.singletonList(a);
final List<TestPredicate> sb = Collections.singletonList(b);
final Predicate n = not(a);
assertNotSame(n, n.copy(sa));
assertEquals(sa, n.copy(sa).getChildren());
assertNotSame(n, n.copy(sb));
assertEquals(sb, n.copy(sb).getChildren());
try {
n.copy(Collections.<Predicate>emptyList());
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertEquals("Expected exactly one child", e.getMessage());
}
try {
n.copy(and(a, b).getChildren());
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertEquals("Expected exactly one child", e.getMessage());
}
}
}
|
package io.mykit.data.monitor.mysql.binlog.impl.variable.status;
import io.mykit.data.monitor.mysql.common.util.MySQLConstants;
import io.mykit.data.monitor.mysql.common.util.ToStringBuilder;
import io.mykit.data.monitor.mysql.io.XInputStream;
import java.io.IOException;
public class QMicroseconds extends AbstractStatusVariable {
public static final int TYPE = MySQLConstants.Q_MICROSECONDS;
private final int startUsec;
public QMicroseconds(int startUsec) {
super(TYPE);
this.startUsec = startUsec;
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("startUsec", startUsec).toString();
}
public int getStartUsec() {
return startUsec;
}
public static QMicroseconds valueOf(XInputStream tis) throws IOException {
return new QMicroseconds(tis.readInt(3));
}
}
|
package com.cg.spring.boot.demo.controller;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class EmployeeControllerTests {
private static Logger LOG = LoggerFactory.getLogger(EmployeeControllerTests.class);
@Test
public void testMethod() {
LOG.info("testMethod");
assertEquals(10, 10);
}
}
|
/* */ package classes.lrg.insider.plugins.tools.memoria.graphgen;
/* */
/* */ import cdc.clusters.ExtendedWeightedEdge;
/* */ import cdc.clusters.Node;
/* */ import lrg.insider.plugins.tools.memoria.graphgen.GraphvizExporter;
/* */ import lrg.insider.plugins.tools.memoria.graphgen.SystemGraph;
/* */ import org.jgrapht.EdgeFactory;
/* */ import org.jgrapht.graph.DirectedWeightedMultigraph;
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public class SystemGraph<V, E>
/* */ extends DirectedWeightedMultigraph<Node, ExtendedWeightedEdge>
/* */ {
/* */ private static final long serialVersionUID = -8496579278148059150L;
/* */
/* 20 */ public SystemGraph(Class<? extends ExtendedWeightedEdge> arg0) { super(arg0); }
/* */
/* */
/* */
/* */
/* 25 */ public SystemGraph(EdgeFactory<Node, ExtendedWeightedEdge> arg0) { super(arg0); }
/* */
/* */
/* */
/* */
/* 30 */ public void exportAsGraphviz(String graphName, String dirName, String fileName) { GraphvizExporter.exportGraph(this, graphName, dirName, fileName); }
/* */ }
/* Location: C:\Users\emill\Dropbox\slimmerWorden\2018-2019-Semester2\THESIS\iPlasma6\tools\iPlasma\classes.zip!\classes\lrg\insider\plugins\tools\memoria\graphgen\SystemGraph.class
* Java compiler version: 5 (49.0)
* JD-Core Version: 1.0.7
*/
|
package Programs;
import java.util.Scanner;
public class Pattern_8 {
public static void main(String[] args) {
Scanner obj = new Scanner(System.in);
System.out.print("Enter Number of Rows :");
int n = obj.nextInt();
int number = 1;
for(int i =1;i<=n;i++){
for(int j =1;j<=n-i;j++) {
System.out.print(" ");
}
for(int j =1;j<=i;j++) {
System.out.print(number++ +" ");
}
System.out.println();
}
}
}
|
// RobotBuilder Version: 1.5BB
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc330.commands;
import org.usfirst.frc330.Robot;
import edu.wpi.first.wpilibj.command.BBCommand;
import edu.wpi.first.wpilibj.command.Scheduler;
/**
*
*/
public class KillAll extends BBCommand {
public KillAll() {
// Use requires() here to declare subsystem dependencies
// eg. requires(chassis);
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
requires(Robot.chassis);
requires(Robot.arm);
requires(Robot.mast);
requires(Robot.hand);
requires(Robot.frills);
requires(Robot.powerDP);
requires(Robot.lift);
this.setRunWhenDisabled(true);
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
Robot.hand.setHandLevelActivated(false);
Scheduler.getInstance().removeAll();
Robot.chassis.stopDrive();
Robot.arm.stopArm();
Robot.lift.stopLift();
Robot.hand.stopHand();
Robot.mast.stopMast();
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return true;
}
// Called once after isFinished returns true
protected void end() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
}
}
|
/*
* Copyright 2014+ Carnegie Mellon University
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.cmu.lti.oaqa.flexneuart.utils;
import java.util.HashMap;
/**
*
* Provides mapping of PennTree bank tags to WordNet tags.
* This mapping makes sense only for a subset of WordNet tags.
*
* @author Leonid Boytsov
*
*/
public class POSUtil {
HashMap<String, Character> mMap = new HashMap<String, Character>();
public POSUtil() {
// 1. CC Coordinating conjunction
// 2. CD Cardinal number
// 3. DT Determiner
// 4. EX Existential there
// 5. FW Foreign word
// 6. IN Preposition or subordinating conjunction
mMap.put("JJ", 'A'); // 7. JJ Adjective
mMap.put("JJR", 'A'); // 8. JJR Adjective, comparative
mMap.put("JJS", 'A'); // 9. JJS Adjective, superlative
// 10. LS List item marker
// 11. MD Modal
mMap.put("NN", 'N'); // 12. NN Noun, singular or mass
mMap.put("NNS", 'N'); // 13. NNS Noun, plural
mMap.put("NNP", 'N'); // 14. NNP Proper noun, singular
mMap.put("NNPS", 'N');// 15. NNPS Proper noun, plural
// 16. PDT Predeterminer
// 17. POS Possessive ending
// 18. PRP Personal pronoun
// 19. PRP$ Possessive pronoun
mMap.put("RB", 'R'); // 20. RB Adverb
mMap.put("RBR", 'R'); // 21. RBR Adverb, comparative
mMap.put("RBS", 'R'); // 22. RBS Adverb, superlative
// 23. RP Particle
// 24. SYM Symbol
// 25. TO to
// 26. UH Interjection
mMap.put("VB", 'V'); // 27. VB Verb, base form
mMap.put("VBD", 'V'); // 28. VBD Verb, past tense
mMap.put("VBG", 'V'); // 29. VBG Verb, gerund or present participle
mMap.put("VBN", 'V'); // 30. VBN Verb, past participle
mMap.put("VBP", 'V'); // 31. VBP Verb, non-3rd person singular present
mMap.put("VBZ", 'V'); // 32. VBZ Verb, 3rd person singular present
// 33. WDT Wh-determiner
// 34. WP Wh-pronoun
// 35. WP$ Possessive wh-pronoun
// 36. WRB Wh-adverb
String keys[] = new String[mMap.size()];
int n = 0;
for (String k:mMap.keySet()) {
keys[n++] = k;
}
for (int i = 0; i < n; ++i) {
String k = keys[i];
mMap.put(k.toLowerCase(), mMap.get(k));
}
}
public Character get(String pos) {
return mMap.get(pos);
}
}
|
/**
* Copyright (C) 2019 Patrice Brend'amour <patrice@brendamour.net>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.brendamour.jpasskit.signing;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.nio.file.Paths;
import java.util.Locale;
import org.apache.commons.io.IOUtils;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.brendamour.jpasskit.PKPass;
import de.brendamour.jpasskit.enums.PKPassPersonalizationField;
import de.brendamour.jpasskit.personalization.PKPersonalization;
public class PKInMemorySigningUtilTest {
private static final String PASS_TEMPLATE_FOLDER = PKPassTemplateFolderTest.class.getClassLoader().getResource("StoreCard.raw").getPath();
private static final String APPLE_WWDRCA = "passbook/ca-chain.cert.pem";
private static final String KEYSTORE_PATH = "passbook/jpasskittest.p12";
private static final String KEYSTORE_PASSWORD = "password";
private PKInMemorySigningUtil pkInMemorySigningUtil;
@BeforeMethod
public void prepare() {
pkInMemorySigningUtil = new PKInMemorySigningUtil();
}
@Test
public void testWithFolderBasedTemplate() throws Exception {
PKPassTemplateFolder pkPassTemplateFolder = new PKPassTemplateFolder(PASS_TEMPLATE_FOLDER);
PKPass pass = new ObjectMapper().readValue(new File(getPathFromClasspath("pass2.json")), PKPass.class);
createZipAndAssert(pkPassTemplateFolder, pass, "target/passInMemoryFolder.zip");
}
@Test
public void testWithInMemoryTemplate() throws Exception {
PKPassTemplateInMemory pkPassTemplateInMemory = new PKPassTemplateInMemory();
// icon
URL iconFileURL = PKInMemorySigningUtilTest.class.getClassLoader().getResource("StoreCard.raw/icon@2x.png");
File iconFile = new File(iconFileURL.getFile());
pkPassTemplateInMemory.addFile(PKPassTemplateInMemory.PK_ICON_RETINA, iconFile);
// icon for language
pkPassTemplateInMemory.addFile(PKPassTemplateInMemory.PK_ICON_RETINA, Locale.ENGLISH, iconFile);
PKPass pass = new ObjectMapper().readValue(new File(getPathFromClasspath("pass2.json")), PKPass.class);
createZipAndAssert(pkPassTemplateInMemory, pass, "target/passInMemoryStream.zip");
}
@Test
public void testWithInMemoryTemplateAndPersonalization() throws Exception {
PKPassTemplateInMemory pkPassTemplateInMemory = new PKPassTemplateInMemory();
// icon
URL iconFileURL = PKInMemorySigningUtilTest.class.getClassLoader().getResource("StoreCard.raw/icon@2x.png");
File iconFile = new File(iconFileURL.getFile());
pkPassTemplateInMemory.addFile(PKPassTemplateInMemory.PK_ICON_RETINA, iconFile);
// icon for language
pkPassTemplateInMemory.addFile(PKPassTemplateInMemory.PK_ICON_RETINA, Locale.ENGLISH, iconFile);
PKPass pass = new ObjectMapper().readValue(new File(getPathFromClasspath("pass2.json")), PKPass.class);
PKPersonalization personalization = new PKPersonalization();
personalization.setDescription("desc");
personalization.setTermsAndConditions("T&C");
personalization.addRequiredPersonalizationField(PKPassPersonalizationField.PKPassPersonalizationFieldName);
createZipAndAssert(pkPassTemplateInMemory, pass, personalization, "target/passInMemoryStream.zip");
}
private void createZipAndAssert(IPKPassTemplate pkPassTemplate, PKPass pkPass, String fileName) throws Exception {
createZipAndAssert(pkPassTemplate, pkPass, null, fileName);
}
private void createZipAndAssert(IPKPassTemplate pkPassTemplate, PKPass pkPass, PKPersonalization personalization, String fileName)
throws Exception {
PKSigningInformation pkSigningInformation = new PKSigningInformationUtil().loadSigningInformationFromPKCS12AndIntermediateCertificate(
KEYSTORE_PATH, KEYSTORE_PASSWORD, APPLE_WWDRCA);
byte[] signedAndZippedPkPassArchive;
if (personalization != null) {
signedAndZippedPkPassArchive = pkInMemorySigningUtil.createSignedAndZippedPersonalizedPkPassArchive(pkPass, personalization,
pkPassTemplate, pkSigningInformation);
} else {
signedAndZippedPkPassArchive = pkInMemorySigningUtil
.createSignedAndZippedPkPassArchive(pkPass, pkPassTemplate, pkSigningInformation);
}
ByteArrayInputStream inputStream = new ByteArrayInputStream(signedAndZippedPkPassArchive);
File passZipFile = new File(fileName);
if (passZipFile.exists()) {
passZipFile.delete();
}
IOUtils.copy(inputStream, new FileOutputStream(passZipFile));
Assert.assertTrue(passZipFile.exists());
Assert.assertTrue(passZipFile.length() > 0);
AssertZip.assertValid(passZipFile);
}
private String getPathFromClasspath(String path) throws Exception {
return Paths.get(ClassLoader.getSystemResource(path).toURI()).toString();
}
}
|
/*
* Copyright 2021 The Flink Remote Shuffle 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 com.alibaba.flink.shuffle.storage.partition;
import com.alibaba.flink.shuffle.common.config.ConfigOption;
import com.alibaba.flink.shuffle.common.config.Configuration;
import com.alibaba.flink.shuffle.common.exception.ShuffleException;
import com.alibaba.flink.shuffle.common.utils.CommonUtils;
import com.alibaba.flink.shuffle.common.utils.ExceptionUtils;
import com.alibaba.flink.shuffle.core.config.StorageOptions;
import com.alibaba.flink.shuffle.core.executor.SingleThreadExecutor;
import com.alibaba.flink.shuffle.core.ids.DataSetID;
import com.alibaba.flink.shuffle.core.ids.JobID;
import com.alibaba.flink.shuffle.core.ids.MapPartitionID;
import com.alibaba.flink.shuffle.core.listener.BacklogListener;
import com.alibaba.flink.shuffle.core.listener.DataListener;
import com.alibaba.flink.shuffle.core.listener.DataRegionCreditListener;
import com.alibaba.flink.shuffle.core.listener.FailureListener;
import com.alibaba.flink.shuffle.core.storage.DataPartition;
import com.alibaba.flink.shuffle.core.storage.DataPartitionMeta;
import com.alibaba.flink.shuffle.core.storage.DataPartitionReader;
import com.alibaba.flink.shuffle.core.storage.DataPartitionStatistics;
import com.alibaba.flink.shuffle.core.storage.DataPartitionWriter;
import com.alibaba.flink.shuffle.core.storage.PartitionedDataStore;
import com.alibaba.flink.shuffle.core.storage.StorageMeta;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
/** A {@link DataPartition} implementation which writes data to and read data from local file. */
public class LocalFileMapPartition extends BaseMapPartition {
private static final Logger LOG = LoggerFactory.getLogger(LocalFileMapPartition.class);
/** {@link DataPartitionMeta} of this data partition. */
private final LocalFileMapPartitionMeta partitionMeta;
/** Local file storing all data of this data partition. */
private final LocalMapPartitionFile partitionFile;
public LocalFileMapPartition(
StorageMeta storageMeta,
PartitionedDataStore dataStore,
JobID jobID,
DataSetID dataSetID,
MapPartitionID partitionID,
int numReducePartitions) {
super(dataStore, getSingleThreadExecutor(dataStore, storageMeta));
String storagePath = storageMeta.getStoragePath();
File storageDir = new File(storagePath);
CommonUtils.checkArgument(storagePath.endsWith("/"), "Illegal storage path.");
CommonUtils.checkArgument(storageDir.exists(), "Storage path does not exist.");
CommonUtils.checkArgument(storageDir.isDirectory(), "Storage path is not a directory.");
Configuration configuration = dataStore.getConfiguration();
ConfigOption<Integer> configOption = StorageOptions.STORAGE_FILE_TOLERABLE_FAILURES;
int tolerableFailures = CommonUtils.checkNotNull(configuration.getInteger(configOption));
String fileName = CommonUtils.randomHexString(32);
LocalMapPartitionFileMeta fileMeta =
new LocalMapPartitionFileMeta(
storagePath + fileName,
numReducePartitions,
LocalMapPartitionFile.LATEST_STORAGE_VERSION);
this.partitionFile = new LocalMapPartitionFile(fileMeta, tolerableFailures, true);
this.partitionMeta =
new LocalFileMapPartitionMeta(jobID, dataSetID, partitionID, fileMeta, storageMeta);
}
/**
* Used to construct data partition instances when adding a finished external data partition or
* recovering after failure.
*/
public LocalFileMapPartition(
PartitionedDataStore dataStore, LocalFileMapPartitionMeta partitionMeta) {
super(dataStore, getSingleThreadExecutor(dataStore, partitionMeta.getStorageMeta()));
this.partitionMeta = partitionMeta;
LocalMapPartitionFileMeta fileMeta = partitionMeta.getPartitionFileMeta();
this.partitionFile = fileMeta.createPersistentFile(dataStore.getConfiguration());
if (!partitionFile.isConsumable()) {
partitionFile.setConsumable(false);
throw new ShuffleException("Partition data is not consumable.");
}
}
private static SingleThreadExecutor getSingleThreadExecutor(
PartitionedDataStore dataStore, StorageMeta storageMeta) {
CommonUtils.checkArgument(dataStore != null, "Must be not null.");
CommonUtils.checkArgument(storageMeta != null, "Must be not null.");
return dataStore.getExecutorPool(storageMeta).getSingleThreadExecutor();
}
@Override
public boolean isConsumable() {
return partitionFile.isConsumable();
}
@Override
public DataPartitionStatistics getDataPartitionStatistics() {
PersistentFileStatistics fileStatistics = partitionFile.getPersistentFileStatistics();
return new DataPartitionStatistics(
fileStatistics.getNumDataRegions(),
fileStatistics.getIndexFileBytes(),
fileStatistics.getDataFileBytes());
}
@Override
protected DataPartitionReader getDataPartitionReader(
int startPartitionIndex,
int endPartitionIndex,
DataListener dataListener,
BacklogListener backlogListener,
FailureListener failureListener) {
// for different storage versions and formats, different file reader implementations are
// needed for backward compatibility, we must keep backward compatibility when upgrading
int storageVersion = partitionFile.getFileMeta().getStorageVersion();
if (storageVersion <= 1) {
boolean dataChecksumEnabled =
dataStore
.getConfiguration()
.getBoolean(StorageOptions.STORAGE_ENABLE_DATA_CHECKSUM);
LocalMapPartitionFileReader fileReader =
new LocalMapPartitionFileReader(
dataChecksumEnabled,
startPartitionIndex,
endPartitionIndex,
partitionFile);
return new LocalFileMapPartitionReader(
fileReader, dataListener, backlogListener, failureListener);
}
throw new ShuffleException(
String.format(
"Illegal storage version, current: %d, supported: %d.",
storageVersion, partitionFile.getLatestStorageVersion()));
}
@Override
protected DataPartitionWriter getDataPartitionWriter(
MapPartitionID mapPartitionID,
DataRegionCreditListener dataRegionCreditListener,
FailureListener failureListener) {
boolean dataChecksumEnabled =
dataStore
.getConfiguration()
.getBoolean(StorageOptions.STORAGE_ENABLE_DATA_CHECKSUM);
return new LocalFileMapPartitionWriter(
dataChecksumEnabled,
mapPartitionID,
this,
dataRegionCreditListener,
failureListener,
partitionFile);
}
@Override
protected void releaseInternal(Throwable releaseCause) throws Exception {
Throwable exception = null;
try {
super.releaseInternal(releaseCause);
} catch (Throwable throwable) {
exception = throwable;
LOG.error("Fatal: failed to release base map partition.", throwable);
}
try {
partitionFile.deleteFile();
} catch (Throwable throwable) {
exception = throwable;
LOG.error("Fatal: failed to delete the partition file.", throwable);
}
if (exception != null) {
ExceptionUtils.rethrowException(exception);
}
}
@Override
public LocalFileMapPartitionMeta getPartitionMeta() {
return partitionMeta;
}
}
|
// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package dfp.axis.v201611.teamservice;
import com.google.api.ads.common.lib.auth.OfflineCredentials;
import com.google.api.ads.common.lib.auth.OfflineCredentials.Api;
import com.google.api.ads.dfp.axis.factory.DfpServices;
import com.google.api.ads.dfp.axis.utils.v201611.StatementBuilder;
import com.google.api.ads.dfp.axis.v201611.Team;
import com.google.api.ads.dfp.axis.v201611.TeamPage;
import com.google.api.ads.dfp.axis.v201611.TeamServiceInterface;
import com.google.api.ads.dfp.lib.client.DfpSession;
import com.google.api.client.auth.oauth2.Credential;
import com.google.common.collect.Iterables;
import java.util.Arrays;
/**
* This example updates a team's description.
*
* Credentials and properties in {@code fromFile()} are pulled from the
* "ads.properties" file. See README for more info.
*/
public class UpdateTeams {
// Set the ID of the team to update.
private static final String TEAM_ID = "INSERT_TEAM_ID_HERE";
public static void runExample(
DfpServices dfpServices, DfpSession session, long teamId) throws Exception {
// Get the TeamService.
TeamServiceInterface teamService =
dfpServices.get(session, TeamServiceInterface.class);
// Create a statement to only select a single team by ID.
StatementBuilder statementBuilder = new StatementBuilder()
.where("id = :id")
.orderBy("id ASC")
.limit(1)
.withBindVariableValue("id", teamId);
// Get the team.
TeamPage page =
teamService.getTeamsByStatement(statementBuilder.toStatement());
Team team = Iterables.getOnlyElement(Arrays.asList(page.getResults()));
String newDescription = team.getDescription() + " - UPDATED";
team.setDescription(newDescription);
// Update the team on the server.
Team[] teams = teamService.updateTeams(new Team[] {team});
for (Team updatedTeam : teams) {
System.out.printf("Team with ID %d and name '%s' was updated.%n", updatedTeam.getId(),
updatedTeam.getName());
}
}
public static void main(String[] args) throws Exception {
// Generate a refreshable OAuth2 credential.
Credential oAuth2Credential = new OfflineCredentials.Builder()
.forApi(Api.DFP)
.fromFile()
.build()
.generateCredential();
// Construct a DfpSession.
DfpSession session = new DfpSession.Builder()
.fromFile()
.withOAuth2Credential(oAuth2Credential)
.build();
DfpServices dfpServices = new DfpServices();
runExample(dfpServices, session, Long.parseLong(TEAM_ID));
}
}
|
package org.moparscape.elysium.def;
/**
* The definition wrapper for items
*/
public class ItemBowStringDef {
/**
* The ID of the bow created
*/
public int bowID;
/**
* The exp given by attaching this bow string
*/
public int exp;
/**
* The level required to attach this bow string
*/
public int requiredLvl;
public int getBowID() {
return bowID;
}
public int getExp() {
return exp;
}
public int getReqLevel() {
return requiredLvl;
}
}
|
package com.sequenceiq.cloudbreak.converter.stack.cluster.host;
import org.springframework.stereotype.Component;
import com.sequenceiq.cloudbreak.api.model.stack.cluster.host.HostMetadataResponse;
import com.sequenceiq.cloudbreak.converter.AbstractConversionServiceAwareConverter;
import com.sequenceiq.cloudbreak.domain.stack.cluster.host.HostMetadata;
@Component
public class HostMetadataToHostMetadataResponseConverter extends AbstractConversionServiceAwareConverter<HostMetadata, HostMetadataResponse> {
@Override
public HostMetadataResponse convert(HostMetadata source) {
HostMetadataResponse hostMetadataResponse = new HostMetadataResponse();
hostMetadataResponse.setId(source.getId());
hostMetadataResponse.setGroupName(source.getHostGroup().getName());
hostMetadataResponse.setName(source.getHostName());
hostMetadataResponse.setState(source.getHostMetadataState().name());
return hostMetadataResponse;
}
}
|
package org.springframework.roo.addon.test.addon.integration;
import static org.springframework.roo.model.RooJavaType.ROO_DATA_ON_DEMAND;
import static org.springframework.roo.model.RooJavaType.ROO_INTEGRATION_TEST;
import org.apache.commons.lang3.Validate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Service;
import org.osgi.service.component.ComponentContext;
import org.springframework.roo.addon.configurable.addon.ConfigurableMetadataProvider;
import org.springframework.roo.classpath.PhysicalTypeIdentifier;
import org.springframework.roo.classpath.PhysicalTypeMetadata;
import org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails;
import org.springframework.roo.classpath.details.MemberFindingUtils;
import org.springframework.roo.classpath.details.MemberHoldingTypeDetails;
import org.springframework.roo.classpath.details.MethodMetadata;
import org.springframework.roo.classpath.details.annotations.AnnotationAttributeValue;
import org.springframework.roo.classpath.details.annotations.AnnotationMetadata;
import org.springframework.roo.classpath.itd.AbstractItdMetadataProvider;
import org.springframework.roo.classpath.itd.ItdTriggerBasedMetadataProviderTracker;
import org.springframework.roo.classpath.itd.ItdTypeDetailsProvidingMetadataItem;
import org.springframework.roo.classpath.scanner.MemberDetails;
import org.springframework.roo.metadata.MetadataDependencyRegistry;
import org.springframework.roo.metadata.internal.MetadataDependencyRegistryTracker;
import org.springframework.roo.model.JavaType;
import org.springframework.roo.model.RooJavaType;
import org.springframework.roo.project.LogicalPath;
import org.springframework.roo.support.logging.HandlerUtils;
import org.springframework.roo.support.osgi.ServiceInstaceManager;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
/**
* Implementation of {@link IntegrationTestMetadataProvider}.
*
* @author Ben Alex
* @author Enrique Ruiz at DISID Corporation S.L.
* @author Juan Carlos García
* @author Manuel Iborra
* @since 1.0
*/
@Component
@Service
public class IntegrationTestMetadataProviderImpl extends AbstractItdMetadataProvider implements
IntegrationTestMetadataProvider {
protected final static Logger LOGGER = HandlerUtils
.getLogger(IntegrationTestMetadataProviderImpl.class);
protected MetadataDependencyRegistryTracker registryTracker = null;
private ServiceInstaceManager serviceInstaceManager = new ServiceInstaceManager();
/**
* This service is being activated so setup it:
* <ul>
* <li>Create and open the {@link MetadataDependencyRegistryTracker}.</li>
* <li>Create and open the {@link ItdTriggerBasedMetadataProviderTracker} to
* track for {@link ConfigurableMetadataProvider} service.</li>
* <li>Registers {@link RooJavaType#ROO_INTEGRATION_TEST} as additional
* JavaType that will trigger metadata registration.</li>
* </ul>
*/
@Override
protected void activate(final ComponentContext cContext) {
context = cContext.getBundleContext();
this.serviceInstaceManager.activate(this.context);
this.registryTracker =
new MetadataDependencyRegistryTracker(context, this,
PhysicalTypeIdentifier.getMetadataIdentiferType(), getProvidesType());
this.registryTracker.open();
addMetadataTrigger(ROO_INTEGRATION_TEST);
}
/**
* This service is being deactivated so unregister upstream-downstream
* dependencies, triggers, matchers and listeners.
*
* @param context
*/
protected void deactivate(final ComponentContext context) {
MetadataDependencyRegistry registry = this.registryTracker.getService();
registry.removeNotificationListener(this);
registry.deregisterDependency(PhysicalTypeIdentifier.getMetadataIdentiferType(),
getProvidesType());
this.registryTracker.close();
removeMetadataTrigger(ROO_INTEGRATION_TEST);
}
@Override
protected String createLocalIdentifier(final JavaType javaType, final LogicalPath path) {
return IntegrationTestMetadata.createIdentifier(javaType, path);
}
@Override
protected String getGovernorPhysicalTypeIdentifier(final String metadataIdentificationString) {
final JavaType javaType = IntegrationTestMetadata.getJavaType(metadataIdentificationString);
final LogicalPath path = IntegrationTestMetadata.getPath(metadataIdentificationString);
return PhysicalTypeIdentifier.createIdentifier(javaType, path);
}
public String getItdUniquenessFilenameSuffix() {
return "IT";
}
@Override
protected ItdTypeDetailsProvidingMetadataItem getMetadata(
final String metadataIdentificationString, final JavaType aspectName,
final PhysicalTypeMetadata governorPhysicalTypeMetadata, final String itdFilename) {
// Get repository
IntegrationTestAnnotationValues integrationTestValues =
new IntegrationTestAnnotationValues(governorPhysicalTypeMetadata);
JavaType repository = integrationTestValues.getSource();
// Obtain target type complete details
final ClassOrInterfaceTypeDetails cidRepository =
getTypeLocationService().getTypeDetails(repository);
// Get entity related
AnnotationMetadata annotationRepository =
cidRepository.getAnnotation(RooJavaType.ROO_REPOSITORY_JPA);
AnnotationAttributeValue<Object> entityAttribute = annotationRepository.getAttribute("entity");
JavaType entity = (JavaType) entityAttribute.getValue();
// Get DataOnDemand
final JavaType dataOnDemandType = getDataOnDemandType(entity, governorPhysicalTypeMetadata);
Validate.notNull(dataOnDemandType, "DataOnDemand of entity %s is necessary.",
entity.getSimpleTypeName());
List<MethodMetadata> methods = getAllMethods(repository);
return new IntegrationTestMetadata(metadataIdentificationString, aspectName,
governorPhysicalTypeMetadata, repository, dataOnDemandType, methods);
}
/**
* Get all methods of JavaType and the classes that it extends
*
* @param type JavaType on which obtaining the methods
* @return list of methods
*/
private List<MethodMetadata> getAllMethods(JavaType type) {
List<MethodMetadata> methodsList = new ArrayList<MethodMetadata>();
final ClassOrInterfaceTypeDetails cid = getTypeLocationService().getTypeDetails(type);
if (cid != null) {
final MemberDetails memberDetails =
getMemberDetailsScanner().getMemberDetails(this.getClass().getName(), cid);
List<MemberHoldingTypeDetails> details = memberDetails.getDetails();
for (MemberHoldingTypeDetails detail : details) {
// Set methods of extended JavaTypes
List<JavaType> extendsTypes = detail.getExtendsTypes();
for (JavaType extendJavaType : extendsTypes) {
for (MethodMetadata method : getAllMethods(extendJavaType)) {
if (!methodsList.contains(method)) {
methodsList.add(method);
}
}
}
}
// Set methods of actual JavaType
for (MethodMetadata method : memberDetails.getMethods()) {
if (!methodsList.contains(method)) {
methodsList.add(method);
}
}
}
return methodsList;
}
/**
* Returns the {@link JavaType} for the given entity's "data on demand"
* class.
*
* @param entity
* the entity for which to get the DoD type
* @return a non-<code>null</code> type (which may or may not exist yet)
*/
private JavaType getDataOnDemandType(final JavaType entity,
final PhysicalTypeMetadata governorPhysicalTypeMetadata) {
for (final ClassOrInterfaceTypeDetails dodType : getTypeLocationService()
.findClassesOrInterfaceDetailsWithAnnotation(ROO_DATA_ON_DEMAND)) {
final AnnotationMetadata dodAnnotation =
MemberFindingUtils.getFirstAnnotation(dodType, ROO_DATA_ON_DEMAND);
if (dodAnnotation != null
&& dodAnnotation.getAttribute("entity").getValue().equals(entity)
&& governorPhysicalTypeMetadata.getType().getModule()
.equals(dodType.getType().getModule())) {
return dodType.getName();
}
}
return null;
}
public String getProvidesType() {
return IntegrationTestMetadata.getMetadataIdentiferType();
}
}
|
package com.atguigu.gulimall.order.controller;
import java.util.Arrays;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.atguigu.gulimall.order.entity.OrderReturnReasonEntity;
import com.atguigu.gulimall.order.service.OrderReturnReasonService;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.R;
/**
* 退货原因
*
* @author sxq
* @email 2191567886@gmail.com
* @date 2020-11-19 22:22:33
*/
@RestController
@RequestMapping("order/orderreturnreason")
public class OrderReturnReasonController {
@Autowired
private OrderReturnReasonService orderReturnReasonService;
/**
* 列表
*/
@RequestMapping("/list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = orderReturnReasonService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 信息
*/
@RequestMapping("/info/{id}")
public R info(@PathVariable("id") Long id){
OrderReturnReasonEntity orderReturnReason = orderReturnReasonService.getById(id);
return R.ok().put("orderReturnReason", orderReturnReason);
}
/**
* 保存
*/
@RequestMapping("/save")
public R save(@RequestBody OrderReturnReasonEntity orderReturnReason){
orderReturnReasonService.save(orderReturnReason);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
public R update(@RequestBody OrderReturnReasonEntity orderReturnReason){
orderReturnReasonService.updateById(orderReturnReason);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
public R delete(@RequestBody Long[] ids){
orderReturnReasonService.removeByIds(Arrays.asList(ids));
return R.ok();
}
}
|
package Game.Creatures;
import Game.Actions.Dialog;
import Game.Quests.Quest;
import Game.Stuffs.StuffSubs.Equipments.Armor;
import Game.Stuffs.StuffSubs.Equipments.Weapon;
public class NPC extends Creature {
private String name;
private Quest quest;
private Dialog dialog;
public NPC(String name, int hitPoints, int manaPoints, int staminaPoints, Weapon weapon, Armor armor, Quest quest, Dialog dialog) {
super(hitPoints, manaPoints, staminaPoints, weapon, armor);
this.name=name;
this.quest = quest;
this.dialog = dialog;
}
public Quest getQuest() {
return quest;
}
public void setQuest(Quest quest) {
this.quest = quest;
}
public Dialog getDialog() {
return dialog;
}
public void setDialog(Dialog dialog) {
this.dialog = dialog;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
package com.example.bot.spring;
import com.example.bot.spring.DietbotController.DownloadedContent;
import com.rivescript.RiveScript;
import java.util.Set;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.nio.file.Paths;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
public class AdminState extends State {
// Constant values
private static final String ADMIN_TRIGGER = "admin:upload_coupon";
private static String couponImageUrl = null;
/**
* Default constructor for AdminState
*/
public AdminState() {
}
/**
* Match trigger of this state
* @param text String data type as input text
* @return int data type as binary boolean value
*/
public int matchTrigger(String text) {
if(text.toLowerCase().equals(ADMIN_TRIGGER)) {
return 1;
}
return 0;
}
/**
* Reply a message for input image in this state
* @param userId String data type
* @param jpg DownloadedContent data type as the image
* @param bot RiveScript data type
* @return String data type as the reply
*/
public String replyImage(String userId, DownloadedContent jpg, RiveScript bot) {
sql.setCouponUrl(jpg.getUrl());
return "Hi Admin, your image has been well received!";
}
/**
* Get url for coupon image
* @return String data type
*/
public static String getImageUrl() {
return sql.getCouponUrl();
}
/**
* Reply a message for input text in this state
* @param userId String data type
* @param text String data type
* @param bot RiveScript data type
* @return String data type as the reply
*/
public String reply(String userId, String text, RiveScript bot) {
if(matchTrigger(text) == 1) {
return "Hi admin, please input a coupon image!";
}
else {
// Still in this state, but user doesn't want to input image
return "You should input a coupon image!";
}
}
}
|
package com.google.devrel.training.conference.domain;
import java.util.ArrayList;
import java.util.List;
import com.google.appengine.repackaged.com.google.common.collect.ImmutableList;
import com.google.devrel.training.conference.form.ProfileForm.TeeShirtSize;
import com.googlecode.objectify.annotation.Cache;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
// TODO indicate that this class is an Entity
@Cache
@Entity
public class Profile {
String displayName;
String mainEmail;
TeeShirtSize teeShirtSize;
private List<String> conferenceKeysToAttend = new ArrayList<>(0);
// TODO indicate that the userId is to be used in the Entity's key
@Id
String userId;
/**
* Public constructor for Profile.
*
* @param userId
* The user id, obtained from the email
* @param displayName
* Any string user wants us to display him/her on this system.
* @param mainEmail
* User's main e-mail address.
* @param teeShirtSize
* The User's tee shirt size
*
*/
public Profile(String userId, String displayName, String mainEmail, TeeShirtSize teeShirtSize) {
this.userId = userId;
this.displayName = displayName;
this.mainEmail = mainEmail;
this.teeShirtSize = teeShirtSize;
}
public String getDisplayName() {
return displayName;
}
public String getMainEmail() {
return mainEmail;
}
public TeeShirtSize getTeeShirtSize() {
return teeShirtSize;
}
public String getUserId() {
return userId;
}
public void update(String displayName, TeeShirtSize teeShirtSize) {
this.displayName = displayName;
this.teeShirtSize = teeShirtSize;
// this.teeShirtSize = TeeShirtSize.L; // !!!! to break a single test in each
// test suite
}
/**
* Just making the default constructor private.
*/
private Profile() {
}
public List<String> getConferenceKeysToAttend() {
return ImmutableList.copyOf(conferenceKeysToAttend);
}
public void addToConferenceKeysToAttend(String confKey) {
conferenceKeysToAttend.add(confKey);
}
/**
* Remove the conferenceId from conferenceIdsToAttend.
*
* @param conferenceKey
* a websafe String representation of the Conference Key.
*/
public void unregisterFromConference(String conferenceKey) {
if (conferenceKeysToAttend.contains(conferenceKey)) {
conferenceKeysToAttend.remove(conferenceKey);
} else {
throw new IllegalArgumentException("Invalid conferenceKey: " + conferenceKey);
}
}
}
|
package org.innovateuk.ifs.management.competition.setup.organisationaleligibility.controller;
import org.innovateuk.ifs.BaseControllerMockMVCTest;
import org.innovateuk.ifs.competition.resource.CompetitionOrganisationConfigResource;
import org.innovateuk.ifs.competition.resource.CompetitionResource;
import org.innovateuk.ifs.competition.service.CompetitionOrganisationConfigRestService;
import org.innovateuk.ifs.competition.service.CompetitionRestService;
import org.innovateuk.ifs.management.competition.setup.core.form.CompetitionSetupForm;
import org.innovateuk.ifs.management.competition.setup.core.service.CompetitionSetupService;
import org.innovateuk.ifs.management.competition.setup.organisationaleligibility.form.LeadInternationalOrganisationForm;
import org.innovateuk.ifs.management.competition.setup.organisationaleligibility.form.OrganisationalEligibilityForm;
import org.innovateuk.ifs.management.competition.setup.organisationaleligibility.populator.LeadInternationalOrganisationFormPopulator;
import org.innovateuk.ifs.management.competition.setup.organisationaleligibility.populator.LeadInternationalOrganisationViewModelPopulator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static java.lang.String.format;
import static org.innovateuk.ifs.commons.rest.RestResult.restSuccess;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess;
import static org.innovateuk.ifs.competition.builder.CompetitionOrganisationConfigResourceBuilder.newCompetitionOrganisationConfigResource;
import static org.innovateuk.ifs.competition.builder.CompetitionResourceBuilder.newCompetitionResource;
import static org.innovateuk.ifs.competition.resource.CompetitionSetupSection.ORGANISATIONAL_ELIGIBILITY;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@RunWith(MockitoJUnitRunner.Silent.class)
public class CompetitionSetupOrganisationalEligibilityControllerTest extends BaseControllerMockMVCTest<CompetitionSetupOrganisationalEligibilityController> {
private static final String URL = "/competition/setup/{competitionId}/section/organisational-eligibility";
private CompetitionResource competition;
private long competitionId;
@Mock
private CompetitionRestService competitionRestService;
@Mock
private CompetitionSetupService competitionSetupService;
@Mock
private CompetitionOrganisationConfigRestService competitionOrganisationConfigRestService;
@Mock
private LeadInternationalOrganisationViewModelPopulator leadInternationalOrganisationViewModelPopulator;
@Mock
private LeadInternationalOrganisationFormPopulator leadInternationalOrganisationFormPopulator;
@Override
protected CompetitionSetupOrganisationalEligibilityController supplyControllerUnderTest() {
return new CompetitionSetupOrganisationalEligibilityController();
}
@Before
public void setup() {
competitionId = 100L;
competition = newCompetitionResource().withId(competitionId).build();
when(competitionRestService.getCompetitionById(competitionId)).thenReturn(restSuccess(competition));
}
@Test
public void organisationalEligibilityPageDetails() throws Exception {
when(competitionSetupService.hasInitialDetailsBeenPreviouslySubmitted(competitionId)).thenReturn(true);
mockMvc.perform(get(URL, competitionId))
.andExpect(status().isOk())
.andExpect(view().name("competition/setup"));
}
@Test
public void submitTrueOrganisationalEligibilitySectionDetails() throws Exception {
OrganisationalEligibilityForm organisationalEligibilityForm = new OrganisationalEligibilityForm();
organisationalEligibilityForm.setInternationalOrganisationsApplicable(true);
CompetitionOrganisationConfigResource configResource = newCompetitionOrganisationConfigResource()
.withInternationalOrganisationsAllowed(true)
.build();
when(competitionOrganisationConfigRestService.findByCompetitionId(competitionId)).thenReturn(restSuccess(configResource));
when(competitionOrganisationConfigRestService.update(competitionId, configResource)).thenReturn(restSuccess(configResource));
mockMvc.perform(post(URL, competitionId)
.param("internationalOrganisationsApplicable", "true"))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl(format("/competition/setup/%d/section/%s/lead-international-organisation", competition.getId(), ORGANISATIONAL_ELIGIBILITY.getPostMarkCompletePath())));
}
@Test
public void submitFalseOrganisationalEligibilitySectionDetails() throws Exception {
OrganisationalEligibilityForm organisationalEligibilityForm = new OrganisationalEligibilityForm();
organisationalEligibilityForm.setInternationalOrganisationsApplicable(false);
when(competitionSetupService.saveCompetitionSetupSection(isA(CompetitionSetupForm.class), eq(competition), eq(ORGANISATIONAL_ELIGIBILITY))).thenReturn(serviceSuccess());
mockMvc.perform(post(URL, competitionId)
.param("internationalOrganisationsApplicable", "false"))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl(format("/competition/setup/%d/section/%s", competition.getId(), ORGANISATIONAL_ELIGIBILITY.getPostMarkCompletePath())));
}
@Test
public void viewLeadInternationalOrganisationDetails() throws Exception {
CompetitionOrganisationConfigResource configResource = newCompetitionOrganisationConfigResource()
.withInternationalOrganisationsAllowed(true)
.build();
when(competitionOrganisationConfigRestService.findByCompetitionId(competitionId)).thenReturn(restSuccess(configResource));
mockMvc.perform(get(URL + "/lead-international-organisation", competitionId))
.andExpect(status().isOk())
.andExpect(view().name("competition/setup/lead-international-organisation"));
}
@Test
public void submitLeadInternationalOrganisationDetails() throws Exception {
LeadInternationalOrganisationForm leadInternationalOrganisationForm = new LeadInternationalOrganisationForm();
leadInternationalOrganisationForm.setLeadInternationalOrganisationsApplicable(true);
OrganisationalEligibilityForm organisationalEligibilityForm = new OrganisationalEligibilityForm();
organisationalEligibilityForm.setInternationalOrganisationsApplicable(true);
organisationalEligibilityForm.setLeadInternationalOrganisationsApplicable(true);
CompetitionOrganisationConfigResource configResource = newCompetitionOrganisationConfigResource()
.withInternationalOrganisationsAllowed(organisationalEligibilityForm.getInternationalOrganisationsApplicable())
.withInternationalLeadOrganisationAllowed(organisationalEligibilityForm.getLeadInternationalOrganisationsApplicable())
.build();
when(competitionOrganisationConfigRestService.findByCompetitionId(competitionId)).thenReturn(restSuccess(configResource));
when(competitionSetupService.saveCompetitionSetupSection(isA(CompetitionSetupForm.class), eq(competition), eq(ORGANISATIONAL_ELIGIBILITY))).thenReturn(serviceSuccess());
mockMvc.perform(post(URL + "/lead-international-organisation", competitionId)
.param("leadInternationalOrganisationsApplicable", "true"))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl(format("/competition/setup/%d/section/%s", competition.getId(), ORGANISATIONAL_ELIGIBILITY.getPostMarkCompletePath())));
}
@Test
public void submitNullLeadInternationalOrganisationDetails() throws Exception {
LeadInternationalOrganisationForm leadInternationalOrganisationForm = new LeadInternationalOrganisationForm();
leadInternationalOrganisationForm.setLeadInternationalOrganisationsApplicable(null);
OrganisationalEligibilityForm organisationalEligibilityForm = new OrganisationalEligibilityForm();
organisationalEligibilityForm.setInternationalOrganisationsApplicable(true);
CompetitionOrganisationConfigResource configResource = newCompetitionOrganisationConfigResource()
.withInternationalOrganisationsAllowed(organisationalEligibilityForm.getInternationalOrganisationsApplicable())
.build();
when(competitionOrganisationConfigRestService.findByCompetitionId(competitionId)).thenReturn(restSuccess(configResource));
mockMvc.perform(post(URL + "/lead-international-organisation", competitionId)
.param("leadInternationalOrganisationsApplicable", "null"))
.andExpect(status().isOk())
.andExpect(view().name("competition/setup/lead-international-organisation"));
}
}
|
package org.simpleflatmapper.reflect.meta;
import org.simpleflatmapper.util.Consumer;
import org.simpleflatmapper.util.ProducerServiceLoader;
import java.util.ArrayList;
import java.util.ServiceLoader;
public final class AliasProviderService {
private AliasProviderService() { }
private static final AliasProvider aliasProvider = findAliasProviders();
private static AliasProvider findAliasProviders() {
final ArrayList<AliasProvider> providers = new ArrayList<AliasProvider>();
ProducerServiceLoader.produceFromServiceLoader(ServiceLoader.load(AliasProviderProducer.class), new Consumer<AliasProvider>() {
@Override
public void accept(AliasProvider t) {
providers.add(t);
}
});
return aggregateAliasProvider(providers.toArray(new AliasProvider[0]));
}
public static AliasProvider getAliasProvider() {
return aliasProvider;
}
private static AliasProvider aggregateAliasProvider(AliasProvider[] registered) {
if (registered.length == 0) {
return new DefaultAliasProvider();
} else if (registered.length == 1) {
return registered[0];
} else {
return new ArrayAliasProvider(registered);
}
}
}
|
package com.auth.rest.api.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.NoRepositoryBean;
/**
*
*
* Interface that extends the {@link JpaRepository} and {@link JpaSpecificationExecutor} to be inherited by entity daos
* we fixed the type of the id of the entity the repository manages to {@link Integer}
*
* @author mmerabti
* @since 12 mai 2016. API version : 1.0
* @version 1.0
*
* @param <T>
* the type of the enity
*/
@NoRepositoryBean
public interface AbstractDao<T> extends JpaRepository<T, Integer> {
}
|
package com.klinker.android.twitter_l.activities;
/*
* Copyright 2014 Luke Klinker
*
* 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.
*/
import android.app.ActivityOptions;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import androidx.viewpager.widget.ViewPager;
import android.transition.ChangeBounds;
import android.util.Log;
import android.view.*;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import com.klinker.android.twitter_l.R;
import com.klinker.android.twitter_l.adapters.MainDrawerArrayAdapter;
import com.klinker.android.twitter_l.adapters.TimelinePagerAdapter;
import com.klinker.android.twitter_l.data.sq_lite.DMDataSource;
import com.klinker.android.twitter_l.data.sq_lite.FavoriteUsersDataSource;
import com.klinker.android.twitter_l.data.sq_lite.FollowersDataSource;
import com.klinker.android.twitter_l.data.sq_lite.HomeDataSource;
import com.klinker.android.twitter_l.data.sq_lite.InteractionsDataSource;
import com.klinker.android.twitter_l.data.sq_lite.ListDataSource;
import com.klinker.android.twitter_l.data.sq_lite.MentionsDataSource;
import com.klinker.android.twitter_l.services.SendScheduledTweet;
import com.klinker.android.twitter_l.settings.AppSettings;
import com.klinker.android.twitter_l.activities.compose.ComposeActivity;
import com.klinker.android.twitter_l.activities.drawer_activities.DrawerActivity;
import com.klinker.android.twitter_l.activities.main_fragments.MainFragment;
import com.klinker.android.twitter_l.activities.setup.material_login.MaterialLogin;
import com.klinker.android.twitter_l.activities.setup.TutorialActivity;
import com.klinker.android.twitter_l.utils.NotificationUtils;
import com.klinker.android.twitter_l.utils.PermissionModelUtils;
import com.klinker.android.twitter_l.utils.UpdateUtils;
import com.klinker.android.twitter_l.utils.Utils;
public class MainActivity extends DrawerActivity {
public static boolean isPopup;
public static Context sContext;
public static FloatingActionButton sendButton;
public static boolean showIsRunning = false;
public static boolean hideIsRunning = false;
public static Handler sendHandler;
public static Runnable showSend = new Runnable() {
@Override
public void run() {
if (sendButton.getVisibility() == View.GONE && !showIsRunning) {
Animation anim = AnimationUtils.loadAnimation(sContext, R.anim.fab_in);
anim.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
showIsRunning = true;
}
@Override
public void onAnimationEnd(Animation animation) {
sendButton.setVisibility(View.VISIBLE);
showIsRunning = false;
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
sendButton.startAnimation(anim);
}
}
};
public static Runnable hideSend = new Runnable() {
@Override
public void run() {
if (sendButton.getVisibility() == View.VISIBLE && !hideIsRunning) {
Animation anim = AnimationUtils.loadAnimation(sContext, R.anim.fab_out);
anim.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
hideIsRunning = true;
}
@Override
public void onAnimationEnd(Animation animation) {
sendButton.setVisibility(View.GONE);
hideIsRunning = false;
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
anim.setDuration(ANIM_DURATION);
sendButton.startAnimation(anim);
}
}
};
public void topCurrentFragment() {
Intent top = new Intent("com.klinker.android.twitter.TOP_TIMELINE");
top.putExtra("fragment_number", mViewPager.getCurrentItem());
sendBroadcast(top);
}
public void showAwayFromTopToast() {
Intent toast = new Intent("com.klinker.android.twitter.SHOW_TOAST");
toast.putExtra("fragment_number", mViewPager.getCurrentItem());
sendBroadcast(toast);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AppSettings settings = AppSettings.getInstance(this);
if (settings.myScreenName == null || settings.myScreenName.isEmpty()) {
if (settings.currentAccount == 1) {
settings.sharedPrefs.edit().putInt("current_account", 2).commit();
} else {
settings.sharedPrefs.edit().putInt("current_account", 1).commit();
}
AppSettings.invalidate();
}
UpdateUtils.checkUpdate(this);
MainActivity.sendHandler = new Handler();
context = this;
sContext = this;
sharedPrefs = AppSettings.getSharedPreferences(context);
DrawerActivity.settings = AppSettings.getInstance(context);
try {
requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
} catch (Exception e) {
}
sharedPrefs.edit().putBoolean("refresh_me", getIntent().getBooleanExtra("from_notification", false)).apply();
setUpTheme();
setUpWindow();
setContentView(R.layout.main_activity);
mViewPager = (ViewPager) findViewById(R.id.pager);
setUpDrawer(0, getResources().getString(R.string.timeline));
MainActivity.sendButton = (FloatingActionButton) findViewById(R.id.send_button);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setSharedElementExitTransition(new ChangeBounds());
}
MainActivity.sendButton.setBackgroundTintList(ColorStateList.valueOf(settings.themeColors.accentColor));
MainActivity.sendHandler.postDelayed(showSend, 1000);
MainActivity.sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent compose = new Intent(context, ComposeActivity.class);
ActivityOptions opts = ActivityOptions.makeScaleUpAnimation(v, 0, 0,
v.getMeasuredWidth(), v.getMeasuredHeight());
compose.putExtra("already_animated", true);
startActivity(compose, opts.toBundle());
}
});
if (!Utils.hasNavBar(this) ||
(!getResources().getBoolean(R.bool.isTablet) &&
getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) ||
(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && isInMultiWindowMode())) {
MainActivity.sendButton.setTranslationY(Utils.toDP(48, this));
}
if (!settings.isTwitterLoggedIn) {
Intent login = new Intent(context, MaterialLogin.class);
startActivity(login);
}
mSectionsPagerAdapter = new TimelinePagerAdapter(getFragmentManager(), context, sharedPrefs, getIntent().getBooleanExtra("from_launcher", false));
int currAccount = sharedPrefs.getInt("current_account", 1);
int defaultPage = sharedPrefs.getInt("default_timeline_page_" + currAccount, 0);
actionBar.setTitle(mSectionsPagerAdapter.getPageTitle(defaultPage));
mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_DRAGGING) {
int count = mSectionsPagerAdapter.getCount();
for (int i = 0; i < count; i++) {
MainFragment f = (MainFragment) mSectionsPagerAdapter.getRealFrag(i);
f.allowBackPress();
f.resetVideoHandler();
}
}
}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
showBars();
}
public void onPageSelected(int position) {
MainFragment f = (MainFragment) mSectionsPagerAdapter.getRealFrag(position);
f.playCurrentVideos();
String title = "" + mSectionsPagerAdapter.getPageTitle(position);
MainDrawerArrayAdapter.setCurrent(context, position);
drawerList.invalidateViews();
actionBar.setTitle(title);
}
});
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOverScrollMode(View.OVER_SCROLL_NEVER);
mViewPager.setCurrentItem(defaultPage);
MainDrawerArrayAdapter.setCurrent(this, defaultPage);
drawerList.invalidateViews();
if (getIntent().getBooleanExtra("from_launcher", false)) {
actionBar.setTitle(mSectionsPagerAdapter.getPageTitle(getIntent().getIntExtra("launcher_page", 0)));
}
mViewPager.setOffscreenPageLimit(TimelinePagerAdapter.MAX_EXTRA_PAGES);
final PermissionModelUtils permissionUtils = new PermissionModelUtils(this);
if (getIntent().getBooleanExtra("tutorial", false) && !sharedPrefs.getBoolean("done_tutorial", true)) {
getIntent().putExtra("tutorial", false);
sharedPrefs.edit().putBoolean("done_tutorial", true).apply();
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
try {
Log.v("tutorial_activity", "close drawer");
mDrawerLayout.closeDrawer(Gravity.LEFT);
unregisterReceiver(this);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new IntentFilter(TutorialActivity.ACTION_CLOSE_DRAWER));
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
try {
Log.v("tutorial_activity", "open drawer");
mDrawerLayout.openDrawer(Gravity.LEFT);
unregisterReceiver(this);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new IntentFilter(TutorialActivity.ACTION_OPEN_DRAWER));
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
try {
Log.v("tutorial_activity", "page left");
mViewPager.setCurrentItem(mViewPager.getCurrentItem() - 1, true);
unregisterReceiver(this);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new IntentFilter(TutorialActivity.ACTION_PAGE_LEFT));
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
try {
Log.v("tutorial_activity", "page right");
mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1, true);
unregisterReceiver(this);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new IntentFilter(TutorialActivity.ACTION_PAGE_RIGHT));
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
try {
Log.v("tutorial_activity", "tap app bar");
toolbar.performClick();
unregisterReceiver(this);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new IntentFilter(TutorialActivity.ACTION_TAP_APP_BAR));
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
try {
Log.v("tutorial_activity", "long click app bar");
toolbar.performLongClick();
unregisterReceiver(this);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new IntentFilter(TutorialActivity.ACTION_LONG_CLICK_APP_BAR));
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
try {
Log.v("tutorial_activity", "finished");
if (permissionUtils.needPermissionCheck()) {
permissionUtils.showPermissionExplanationThenAuthorization();
}
unregisterReceiver(this);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new IntentFilter(TutorialActivity.ACTION_FINISH_TUTORIAL));
startActivity(new Intent(context, TutorialActivity.class));
overridePendingTransition(0, 0);
} else {
if (permissionUtils.needPermissionCheck()) {
permissionUtils.showPermissionExplanationThenAuthorization();
}
}
setLauncherPage();
if (getIntent().getBooleanExtra("from_drawer", false)) {
mViewPager.setCurrentItem(getIntent().getIntExtra("page_to_open", 1));
}
Log.v("talon_starting", "ending on create");
}
public void setLauncherPage() {
// do nothing here
}
public void setUpWindow() {
// nothing here, will be overrode
MainActivity.isPopup = false;
if ((getIntent().getFlags() & 0x00002000) != 0) {
MainActivity.isPopup = true;
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
recreate();
}
@Override
public void onBackPressed() {
// this will go through all the current fragments and check if one has an expanded item
int count = mSectionsPagerAdapter.getCount();
boolean clicked = false;
for (int i = 0; i < count; i++) {
MainFragment f = (MainFragment) mSectionsPagerAdapter.getRealFrag(i);
// we only want it to quit if there is an expanded item and the view pager is currently looking at the
// page with that expanded item. If they swipe to mentions while something is expanded on the main
// timeline , then it should still quit if the back button is pressed
if (!f.allowBackPress() && mViewPager.getCurrentItem() == i) {
clicked = true;
}
}
if (!clicked) {
super.onBackPressed();
}
}
private void handleOpenPage() {
if (sharedPrefs.getBoolean("open_a_page", false)) {
sharedPrefs.edit().putBoolean("open_a_page", false).apply();
int page = sharedPrefs.getInt("open_what_page", 1);
String title = "" + mSectionsPagerAdapter.getPageTitle(page);
actionBar.setTitle(title);
mViewPager.setCurrentItem(page);
}
if (sharedPrefs.getBoolean("open_interactions", false)) {
sharedPrefs.edit().putBoolean("open_interactions", false).apply();
mDrawerLayout.openDrawer(Gravity.END);
}
}
@Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
handleOpenPage();
}
@Override
public void onResume() {
super.onResume();
handleOpenPage();
try {
int current = mViewPager.getCurrentItem();
MainFragment currentFragment = (MainFragment) mSectionsPagerAdapter.getRealFrag(current);
currentFragment.scrollDown();
} catch (Exception e) {
}
}
@Override
public void onDestroy() {
try {
HomeDataSource.getInstance(context).close();
} catch (Exception e) { }
try {
MentionsDataSource.getInstance(context).close();
} catch (Exception e) { }
try {
DMDataSource.getInstance(context).close();
} catch (Exception e) { }
try {
ListDataSource.getInstance(context).close();
} catch (Exception e) { }
try {
FollowersDataSource.getInstance(context).close();
} catch (Exception e) { }
try {
FavoriteUsersDataSource.getInstance(context).close();
} catch (Exception e) { }
try {
InteractionsDataSource.getInstance(context).close();
} catch (Exception e) { }
super.onDestroy();
}
public static boolean caughtstarting = false;
@Override
public void onStart() {
super.onStart();
MainActivity.isPopup = false;
Log.v("talon_starting", "main activity starting");
sharedPrefs = AppSettings.getSharedPreferences(this);
// check for night mode switching
int theme = AppSettings.getCurrentTheme(sharedPrefs);
if (sharedPrefs.getBoolean("launcher_frag_switch", false) ||
(theme != settings.baseTheme)) {
sharedPrefs.edit().putBoolean("launcher_frag_switch", false)
.putBoolean("dont_refresh", true).apply();
AppSettings.invalidate();
Log.v("talon_theme", "no action bar overlay found, recreating");
finish();
overridePendingTransition(0, 0);
startActivity(getRestartIntent());
overridePendingTransition(0, 0);
MainActivity.caughtstarting = true;
// return so that it doesn't start the background refresh, that is what caused the dups.
sharedPrefs.edit().putBoolean("dont_refresh_on_start", true).apply();
return;
} else {
sharedPrefs.edit().putBoolean("dont_refresh", false)
.putBoolean("should_refresh", true).apply();
MainActivity.caughtstarting = false;
}
UpdateUtils.checkUpdate(this);
if (sharedPrefs.getBoolean("force_reverse_click", true)) {
sharedPrefs.edit().putBoolean("reverse_click_option", false)
.putBoolean("force_reverse_click", false)
.apply();
}
new Handler().postDelayed(() -> {
NotificationUtils.sendTestNotification(MainActivity.this);
SendScheduledTweet.scheduleNextRun(context);
}, 1000);
}
public Intent getRestartIntent() {
return new Intent(context, MainActivity.class);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if (settings.floatingCompose) {
menu.getItem(2).setVisible(false); // hide the compose button here
}
if (settings.tweetmarkerManualOnly) {
menu.getItem(7).setVisible(true);
}
return true;
}
}
|
/*
* Copyright (c) 2019 Baidu.com, Inc. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.baidubce.services.cnap.model.deploygroup;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
/**
* The model for lama config.
*/
public class LamaConfigModel {
/**
* The list of data source.
*/
private List<DataSourceModel> dataSources;
/**
* The config of pod log.
*/
private PodLogsConfigModel podLogsConfig;
/**
* The config of pod metrics.
*/
private PodMetricsConfigModel podMetricsConfig;
public List<DataSourceModel> getDataSources() {
return dataSources;
}
public void setDataSources(List<DataSourceModel> dataSources) {
this.dataSources = dataSources;
}
public PodLogsConfigModel getPodLogsConfig() {
return podLogsConfig;
}
public void setPodLogsConfig(PodLogsConfigModel podLogsConfig) {
this.podLogsConfig = podLogsConfig;
}
public PodMetricsConfigModel getPodMetricsConfig() {
return podMetricsConfig;
}
public void setPodMetricsConfig(PodMetricsConfigModel podMetricsConfig) {
this.podMetricsConfig = podMetricsConfig;
}
public LamaConfigModel addDatasourceModel(DataSourceModel dataSourceModel) {
if (CollectionUtils.isEmpty(dataSources)) {
dataSources = new LinkedList<DataSourceModel>();
}
dataSources.add(dataSourceModel);
return this;
}
public LamaConfigModel withPodLogsConfig(PodLogsConfigModel podLogsConfig) {
this.setPodLogsConfig(podLogsConfig);
return this;
}
public LamaConfigModel withPodMetricsConfigModel(PodMetricsConfigModel podMetricsConfig) {
this.setPodMetricsConfig(podMetricsConfig);
return this;
}
}
|
/*
* MIT License
* <p>
* Copyright (c) 2017 David Krebs
* <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 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.dkarv.jdcallgraph.util.log;
import java.io.IOException;
public interface LogTarget {
void print(String msg, int level) throws IOException;
void printTrace(Throwable e, int level) throws IOException;
void flush() throws IOException;
}
|
package org.ovirt.engine.core.bll;
import javax.inject.Inject;
import org.ovirt.engine.core.common.businessentities.network.NetworkFilter;
import org.ovirt.engine.core.common.queries.IdQueryParameters;
import org.ovirt.engine.core.dao.network.NetworkFilterDao;
public class GetNetworkFilterByIdQuery extends QueriesCommandBase<IdQueryParameters> {
@Inject
private NetworkFilterDao networkFilterDao;
public GetNetworkFilterByIdQuery(IdQueryParameters parameters) {
super(parameters);
}
@Override
protected void executeQueryCommand() {
final NetworkFilter networkFilter = networkFilterDao.getNetworkFilterById(getParameters().getId());
getQueryReturnValue().setReturnValue(networkFilter);
}
}
|
/*
* System Interface Library for games
* Copyright (c) 2007-2020 Andrew Church <achurch@achurch.org>
* Released under the GNU GPL version 3 or later; NO WARRANTY is provided.
* See the file COPYING.txt for details.
*
* src/sysdep/android/SysFont.java: Routines for drawing text using the
* Android system font.
*/
/* Replace this with an appropriate package name for your program. */
package com.example.sil_app;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
public class SysFont {
/*************************************************************************/
/****************************** Local data *******************************/
/*************************************************************************/
/* Activity with which this object is associated. */
private Activity activity;
/* Paint object used for text maniplation. */
private Paint text_paint;
/* Current font size applied to text_paint. */
private float cur_size;
/* Font metrics for font size cur_size. */
private Paint.FontMetrics metrics;
/*************************************************************************/
/*************************** Interface methods ***************************/
/*************************************************************************/
/**
* SysFont: Constructor for the SysFont class.
*
* [Parameters]
* activity: Activity with which this object is associated.
*/
SysFont(Activity activity)
{
this.activity = activity;
text_paint = null;
cur_size = 0;
metrics = null;
}
/*-----------------------------------------------------------------------*/
/**
* height, baseline, ascent, descent: Return the line height, baseline
* position, ascent, or descent of the system font at the given size.
*
* [Parameters]
* size: Font size (nominal height), in pixels.
* [Return value]
* Requested font metric, in pixels.
*/
float height(float size)
{
setSize(size);
return Math.abs(metrics.ascent) + Math.abs(metrics.descent)
+ Math.abs(metrics.leading);
}
float baseline(float size) {setSize(size); return Math.abs(metrics.ascent);}
float ascent(float size) {setSize(size); return Math.abs(metrics.top);}
float descent(float size) {setSize(size); return Math.abs(metrics.bottom);}
/*-----------------------------------------------------------------------*/
/**
* textAdvance: Return the horizontal advance for the given text in the
* system font at the given size.
*
* [Parameters]
* text: Text to measure.
* size: Font size.
* [Return value]
* Horizontal advance, in pixels.
*/
float textAdvance(String text, float size)
{
setSize(size);
return internalTextAdvance(text);
}
private float internalTextAdvance(final String text)
{
float[] advances = new float[text.length()];
int num_advances = text_paint.getTextWidths(text, advances);
float ret_advance = 0;
for (int i = 0; i < num_advances; i++) {
ret_advance += advances[i];
}
return ret_advance;
}
/*-----------------------------------------------------------------------*/
/**
* textWidth: Return the width of the given text as it would be rendered
* in the system font at the given size.
*
* [Parameters]
* text: Text to measure.
* size: Font size.
* [Return value]
* Text width, in pixels.
*/
float textWidth(String text, float size)
{
setSize(size);
return internalTextWidth(text);
}
private float internalTextWidth(final String text)
{
return text_paint.measureText(text);
}
/*-----------------------------------------------------------------------*/
/**
* drawText: Return an alpha-only Bitmap object with the given text drawn
* in the given size. The text baseline is located at a Y coordinate of
* ceil(baseline(size)) in the returned bitmap.
*
* [Parameters]
* text: Text to draw.
* size: Font size.
* [Return value]
* Bitmap containing text.
*/
Bitmap drawText(String text, float size)
{
setSize(size);
return internalDrawText(text);
}
private Bitmap internalDrawText(final String text)
{
int width = (int)Math.ceil(text_paint.measureText(text));
int baseline = (int)Math.ceil(Math.abs(metrics.top));
int height = baseline + (int)Math.ceil(Math.abs(metrics.bottom));
Bitmap ret_bitmap =
Bitmap.createBitmap(width, height, Bitmap.Config.ALPHA_8);
ret_bitmap.eraseColor(Color.TRANSPARENT);
Canvas canvas = new Canvas(ret_bitmap);
canvas.drawText(text, 0, baseline, text_paint);
return ret_bitmap;
}
/*************************************************************************/
/***************************** Local methods *****************************/
/*************************************************************************/
/**
* setSize: Set the font size to use for text operations. Does nothing
* if the given size is already the current size (and thus is safe, in
* performance terms, to call repeatedly with the same value).
*
* [Parameters]
* size: Font size, in pixels.
*/
private void setSize(float size)
{
if (cur_size == size) {
return;
}
cur_size = size;
if (text_paint == null) {
text_paint = new Paint(Paint.ANTI_ALIAS_FLAG);
}
text_paint.setTextSize(cur_size);
metrics = text_paint.getFontMetrics();
}
/*************************************************************************/
/*************************************************************************/
} // class SysFont
|
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* 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.intellij.ide.fileTemplates;
import com.intellij.openapi.application.PathManager;
import consulo.logging.Logger;
import com.intellij.openapi.project.Project;
import org.apache.velocity.Template;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.context.Context;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.RuntimeSingleton;
import org.apache.velocity.runtime.parser.ParseException;
import org.apache.velocity.runtime.parser.node.SimpleNode;
import org.apache.velocity.runtime.resource.Resource;
import org.apache.velocity.runtime.resource.ResourceManager;
import org.apache.velocity.runtime.resource.ResourceManagerImpl;
import org.apache.velocity.runtime.resource.loader.ResourceLoader;
import org.apache.velocity.util.ExtProperties;
import javax.annotation.Nullable;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
/**
* Initializes Velocity when it's actually needed. All interaction with Velocity should go through this class.
*
* @author peter
*/
class VelocityWrapper {
private static final Logger LOG = Logger.getInstance(VelocityWrapper.class);
private static final ThreadLocal<FileTemplateManager> ourTemplateManager = new ThreadLocal<>();
static {
try {
final Class<?>[] interfaces = ResourceManagerImpl.class.getInterfaces();
if (interfaces.length != 1 || !interfaces[0].equals(ResourceManager.class)) {
throw new IllegalStateException("Incorrect velocity version in the classpath" +
", ResourceManager in " +
PathManager.getJarPathForClass(ResourceManager.class) +
", ResourceManagerImpl in " +
PathManager.getJarPathForClass(ResourceManagerImpl.class));
}
Velocity.setProperty(RuntimeConstants.INPUT_ENCODING, FileTemplate.ourEncoding);
Velocity.setProperty(RuntimeConstants.PARSER_POOL_SIZE, 3);
Velocity.setProperty(RuntimeConstants.RESOURCE_LOADERS, "includes");
Velocity.setProperty("resource.loader.includes.instance", new ResourceLoader() {
@Override
public void init(ExtProperties extProperties) {
}
@Override
public Reader getResourceReader(String source, String encoding) throws ResourceNotFoundException {
FileTemplateManager templateManager = ourTemplateManager.get();
if (templateManager == null) templateManager = FileTemplateManager.getDefaultInstance();
final FileTemplate include = templateManager.getPattern(source);
if (include == null) {
throw new ResourceNotFoundException("Template not found: " + source);
}
return new StringReader(include.getText());
}
@Override
public boolean isSourceModified(Resource resource) {
return true;
}
@Override
public long getLastModified(Resource resource) {
return 0L;
}
});
Thread thread = Thread.currentThread();
ClassLoader classLoader = thread.getContextClassLoader();
try {
Velocity.init();
}
finally {
thread.setContextClassLoader(classLoader);
}
}
catch (Exception e) {
LOG.error("Unable to init Velocity", e);
}
}
static SimpleNode parse(Reader reader, String templateName) throws ParseException {
Template template = new Template();
template.setName(templateName);
return RuntimeSingleton.parse(reader, template);
}
static boolean evaluate(@Nullable Project project, Context context, Writer writer, String templateContent)
throws ParseErrorException, MethodInvocationException, ResourceNotFoundException {
try {
ourTemplateManager.set(project == null ? FileTemplateManager.getDefaultInstance() : FileTemplateManager.getInstance(project));
return Velocity.evaluate(context, writer, "", templateContent);
}
finally {
ourTemplateManager.set(null);
}
}
}
|
package org.wikipedia.settings.languages;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.ActionMode;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import org.wikipedia.Constants;
import org.wikipedia.R;
import org.wikipedia.WikipediaApp;
import org.wikipedia.language.LanguagesListActivity;
import org.wikipedia.util.ResourceUtil;
import org.wikipedia.views.DefaultViewHolder;
import org.wikipedia.views.MultiSelectActionModeCallback;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import static android.app.Activity.RESULT_OK;
import static org.wikipedia.Constants.ACTIVITY_REQUEST_ADD_A_LANGUAGE;
public class WikipediaLanguagesFragment extends Fragment implements WikipediaLanguagesItemView.Callback {
@BindView(R.id.wikipedia_languages_recycler) RecyclerView recyclerView;
private WikipediaApp app;
private Unbinder unbinder;
private ItemTouchHelper itemTouchHelper;
private List<String> wikipediaLanguages = new ArrayList<>();
private WikipediaLanguageItemAdapter adapter;
private ActionMode actionMode;
private MultiSelectCallback multiSelectCallback = new MultiSelectCallback();
private List<String> selectedCodes = new ArrayList<>();
private static final int NUM_HEADERS = 1;
private static final int NUM_FOOTERS = 1;
public static final String ACTIVITY_RESULT_LANG_POSITION_DATA = "activity_result_lang_position_data";
@NonNull public static WikipediaLanguagesFragment newInstance() {
return new WikipediaLanguagesFragment();
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_wikipedia_languages, container, false);
app = WikipediaApp.getInstance();
unbinder = ButterKnife.bind(this, view);
prepareWikipediaLanguagesList();
setupRecyclerView();
// TODO: add funnel?
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ACTIVITY_REQUEST_ADD_A_LANGUAGE
&& resultCode == RESULT_OK) {
prepareWikipediaLanguagesList();
requireActivity().invalidateOptionsMenu();
adapter.notifyDataSetChanged();
}
}
@Override
public void onDestroyView() {
recyclerView.setAdapter(null);
unbinder.unbind();
unbinder = null;
super.onDestroyView();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_wikipedia_languages, menu);
if (app.language().getAppLanguageCodes().size() <= 1) {
MenuItem overflowMenu = menu.getItem(0);
overflowMenu.setVisible(false);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_wikipedia_languages_remove:
beginRemoveLanguageMode();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void prepareWikipediaLanguagesList() {
wikipediaLanguages.clear();
wikipediaLanguages.addAll(app.language().getAppLanguageCodes());
}
private void setupRecyclerView() {
recyclerView.setHasFixedSize(true);
adapter = new WikipediaLanguageItemAdapter();
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
itemTouchHelper = new ItemTouchHelper(new RearrangeableItemTouchHelperCallback(adapter));
itemTouchHelper.attachToRecyclerView(recyclerView);
}
@Override
public void onCheckedChanged(int position) {
toggleSelectedLanguage(wikipediaLanguages.get(position));
}
private void updateWikipediaLanguages() {
app.language().setAppLanguageCodes(wikipediaLanguages);
adapter.notifyDataSetChanged();
requireActivity().invalidateOptionsMenu();
}
@SuppressWarnings("checkstyle:magicnumber")
private final class WikipediaLanguageItemAdapter extends RecyclerView.Adapter<DefaultViewHolder> {
private static final int VIEW_TYPE_HEADER = 0;
private static final int VIEW_TYPE_ITEM = 1;
private static final int VIEW_TYPE_FOOTER = 2;
private boolean checkboxEnabled;
@Override
public int getItemViewType(int position) {
if (position == 0) {
return VIEW_TYPE_HEADER;
} else if (position == getItemCount() - 1) {
return VIEW_TYPE_FOOTER;
} else {
return VIEW_TYPE_ITEM;
}
}
@Override
public int getItemCount() {
return wikipediaLanguages.size() + NUM_HEADERS + NUM_FOOTERS;
}
@Override
public DefaultViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
if (viewType == VIEW_TYPE_HEADER) {
View view = inflater.inflate(R.layout.view_section_header, parent, false);
return new HeaderViewHolder(view);
} else if (viewType == VIEW_TYPE_FOOTER) {
View view = inflater.inflate(R.layout.view_wikipedia_language_footer, parent, false);
return new FooterViewHolder(view);
} else {
return new WikipediaLanguageItemHolder(new WikipediaLanguagesItemView(getContext()));
}
}
@Override
public void onBindViewHolder(@NonNull DefaultViewHolder holder, int pos) {
if (holder instanceof WikipediaLanguageItemHolder) {
if (launchedFromSearch()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
((WikipediaLanguageItemHolder) holder).getView().setForeground(ContextCompat.getDrawable(requireContext(),
ResourceUtil.getThemedAttributeId(requireContext(), R.attr.selectableItemBackground)));
}
((WikipediaLanguageItemHolder) holder).getView().setOnClickListener(view -> {
Intent resultIntent = new Intent();
resultIntent.putExtra(ACTIVITY_RESULT_LANG_POSITION_DATA, pos - NUM_HEADERS);
requireActivity().setResult(RESULT_OK, resultIntent);
requireActivity().finish();
});
}
((WikipediaLanguageItemHolder) holder).bindItem(wikipediaLanguages.get(pos - NUM_HEADERS), pos - NUM_FOOTERS);
((WikipediaLanguageItemHolder) holder).getView().setDragHandleEnabled(wikipediaLanguages.size() > 1);
((WikipediaLanguageItemHolder) holder).getView().setCheckBoxEnabled(checkboxEnabled);
}
}
@Override public void onViewAttachedToWindow(@NonNull DefaultViewHolder holder) {
super.onViewAttachedToWindow(holder);
if (holder instanceof WikipediaLanguageItemHolder) {
((WikipediaLanguageItemHolder) holder).getView().setDragHandleTouchListener((v, event) -> {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
itemTouchHelper.startDrag(holder);
break;
case MotionEvent.ACTION_UP:
v.performClick();
break;
default:
break;
}
return false;
});
((WikipediaLanguageItemHolder) holder).getView().setCallback(WikipediaLanguagesFragment.this);
} else if (holder instanceof FooterViewHolder) {
holder.getView().setVisibility(checkboxEnabled ? View.GONE : View.VISIBLE);
holder.getView().setOnClickListener(v -> {
startActivityForResult(new Intent(requireActivity(), LanguagesListActivity.class), ACTIVITY_REQUEST_ADD_A_LANGUAGE);
finishActionMode();
});
}
}
@Override public void onViewDetachedFromWindow(@NonNull DefaultViewHolder holder) {
if (holder instanceof WikipediaLanguageItemHolder) {
((WikipediaLanguageItemHolder) holder).getView().setCallback(null);
((WikipediaLanguageItemHolder) holder).getView().setDragHandleTouchListener(null);
}
super.onViewDetachedFromWindow(holder);
}
void onMoveItem(int oldPosition, int newPosition) {
Collections.swap(wikipediaLanguages, oldPosition - NUM_HEADERS, newPosition - NUM_FOOTERS);
notifyItemMoved(oldPosition, newPosition);
}
void onCheckboxEnabled(boolean enabled) {
checkboxEnabled = enabled;
}
}
private final class RearrangeableItemTouchHelperCallback extends ItemTouchHelper.Callback {
private final WikipediaLanguageItemAdapter adapter;
RearrangeableItemTouchHelperCallback(WikipediaLanguageItemAdapter adapter) {
this.adapter = adapter;
}
@Override
public boolean isLongPressDragEnabled() {
return false;
}
@Override
public boolean isItemViewSwipeEnabled() {
return false;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
}
@Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
return viewHolder instanceof WikipediaLanguageItemHolder
? makeMovementFlags(ItemTouchHelper.UP | ItemTouchHelper.DOWN, 0) : -1;
}
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder source, RecyclerView.ViewHolder target) {
if (target instanceof WikipediaLanguageItemHolder) {
adapter.onMoveItem(source.getAdapterPosition(), target.getAdapterPosition());
}
return true;
}
@Override
public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
super.clearView(recyclerView, viewHolder);
updateWikipediaLanguages();
}
}
// TODO: optimize and reuse the header view holder
private class HeaderViewHolder extends DefaultViewHolder<View> {
HeaderViewHolder(View itemView) {
super(itemView);
TextView sectionText = itemView.findViewById(R.id.section_header_text);
sectionText.setText(R.string.wikipedia_languages_your_languages_text);
}
}
private class WikipediaLanguageItemHolder extends DefaultViewHolder<WikipediaLanguagesItemView> {
WikipediaLanguageItemHolder(WikipediaLanguagesItemView itemView) {
super(itemView);
}
void bindItem(String languageCode, int position) {
getView().setContents(app.language().getAppLanguageLocalizedName(languageCode), position);
}
}
private class FooterViewHolder extends DefaultViewHolder<View> {
FooterViewHolder(View itemView) {
super(itemView);
}
}
private boolean launchedFromSearch() {
return requireActivity().getIntent().hasExtra(Constants.INTENT_EXTRA_LAUNCHED_FROM_SEARCH);
}
private void setMultiSelectEnabled(boolean enabled) {
adapter.onCheckboxEnabled(enabled);
adapter.notifyDataSetChanged();
requireActivity().invalidateOptionsMenu();
}
private void finishActionMode() {
if (actionMode != null) {
actionMode.finish();
}
}
private void beginRemoveLanguageMode() {
((AppCompatActivity) requireActivity()).startSupportActionMode(multiSelectCallback);
setMultiSelectEnabled(true);
}
private void toggleSelectedLanguage(String code) {
if (selectedCodes.contains(code)) {
selectedCodes.remove(code);
} else {
selectedCodes.add(code);
}
}
private void unselectAllLanguages() {
selectedCodes.clear();
adapter.notifyDataSetChanged();
}
private void deleteSelectedLanguages() {
app.language().removeAppLanguageCodes(selectedCodes);
prepareWikipediaLanguagesList();
unselectAllLanguages();
}
private class MultiSelectCallback extends MultiSelectActionModeCallback {
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
super.onCreateActionMode(mode, menu);
mode.setTitle(R.string.wikipedia_languages_remove_action_mode_title);
mode.getMenuInflater().inflate(R.menu.menu_action_mode_wikipedia_languages, menu);
actionMode = mode;
selectedCodes.clear();
return super.onCreateActionMode(mode, menu);
}
@Override
protected void onDeleteSelected() {
showRemoveLanguagesDialog();
// TODO: add snackbar for undo action?
}
@Override
public void onDestroyActionMode(ActionMode mode) {
unselectAllLanguages();
setMultiSelectEnabled(false);
actionMode = null;
super.onDestroyActionMode(mode);
}
}
@SuppressWarnings("checkstyle:magicnumber")
public void showRemoveLanguagesDialog() {
if (selectedCodes.size() > 0) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(requireActivity());
if (selectedCodes.size() < wikipediaLanguages.size()) {
alertDialog
.setTitle(getResources().getQuantityString(R.plurals.wikipedia_languages_remove_dialog_title, selectedCodes.size()))
.setMessage(R.string.wikipedia_languages_remove_dialog_content)
.setPositiveButton(android.R.string.ok, (dialog, i) -> {
deleteSelectedLanguages();
finishActionMode();
})
.setNegativeButton(android.R.string.cancel, null);
} else {
alertDialog
.setTitle(R.string.wikipedia_languages_remove_warning_dialog_title)
.setMessage(R.string.wikipedia_languages_remove_warning_dialog_content)
.setPositiveButton(android.R.string.ok, null);
}
AlertDialog dialog = alertDialog.show();
TextView text = dialog.findViewById(android.R.id.message);
text.setLineSpacing(0, 1.3f);
}
}
}
|
/*
* 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.commons.math3.optimization.univariate;
import org.apache.commons.math3.util.FastMath;
import org.apache.commons.math3.exception.NotStrictlyPositiveException;
import org.apache.commons.math3.optimization.AbstractConvergenceChecker;
/**
* Simple implementation of the
* {@link org.apache.commons.math3.optimization.ConvergenceChecker} interface
* that uses only objective function values.
*
* Convergence is considered to have been reached if either the relative
* difference between the objective function values is smaller than a
* threshold or if either the absolute difference between the objective
* function values is smaller than another threshold.
* <br/>
* The {@link #converged(int,UnivariatePointValuePair,UnivariatePointValuePair)
* converged} method will also return {@code true} if the number of iterations
* has been set (see {@link #SimpleUnivariateValueChecker(double,double,int)
* this constructor}).
*
* @version $Id$
* @deprecated As of 3.1 (to be removed in 4.0).
* @since 3.1
*/
@Deprecated
public class SimpleUnivariateValueChecker
extends AbstractConvergenceChecker<UnivariatePointValuePair> {
/**
* If {@link #maxIterationCount} is set to this value, the number of
* iterations will never cause
* {@link #converged(int,UnivariatePointValuePair,UnivariatePointValuePair)}
* to return {@code true}.
*/
private static final int ITERATION_CHECK_DISABLED = -1;
/**
* Number of iterations after which the
* {@link #converged(int,UnivariatePointValuePair,UnivariatePointValuePair)}
* method will return true (unless the check is disabled).
*/
private final int maxIterationCount;
/**
* Build an instance with default thresholds.
* @deprecated See {@link AbstractConvergenceChecker#AbstractConvergenceChecker()}
*/
@Deprecated
public SimpleUnivariateValueChecker() {
maxIterationCount = ITERATION_CHECK_DISABLED;
}
/** Build an instance with specified thresholds.
*
* In order to perform only relative checks, the absolute tolerance
* must be set to a negative value. In order to perform only absolute
* checks, the relative tolerance must be set to a negative value.
*
* @param relativeThreshold relative tolerance threshold
* @param absoluteThreshold absolute tolerance threshold
*/
public SimpleUnivariateValueChecker(final double relativeThreshold,
final double absoluteThreshold) {
super(relativeThreshold, absoluteThreshold);
maxIterationCount = ITERATION_CHECK_DISABLED;
}
/**
* Builds an instance with specified thresholds.
*
* In order to perform only relative checks, the absolute tolerance
* must be set to a negative value. In order to perform only absolute
* checks, the relative tolerance must be set to a negative value.
*
* @param relativeThreshold relative tolerance threshold
* @param absoluteThreshold absolute tolerance threshold
* @param maxIter Maximum iteration count.
* @throws NotStrictlyPositiveException if {@code maxIter <= 0}.
*
* @since 3.1
*/
public SimpleUnivariateValueChecker(final double relativeThreshold,
final double absoluteThreshold,
final int maxIter) {
super(relativeThreshold, absoluteThreshold);
if (maxIter <= 0) {
throw new NotStrictlyPositiveException(maxIter);
}
maxIterationCount = maxIter;
}
/**
* Check if the optimization algorithm has converged considering the
* last two points.
* This method may be called several time from the same algorithm
* iteration with different points. This can be detected by checking the
* iteration number at each call if needed. Each time this method is
* called, the previous and current point correspond to points with the
* same role at each iteration, so they can be compared. As an example,
* simplex-based algorithms call this method for all points of the simplex,
* not only for the best or worst ones.
*
* @param iteration Index of current iteration
* @param previous Best point in the previous iteration.
* @param current Best point in the current iteration.
* @return {@code true} if the algorithm has converged.
*/
@Override
public boolean converged(final int iteration,
final UnivariatePointValuePair previous,
final UnivariatePointValuePair current) {
if (maxIterationCount != ITERATION_CHECK_DISABLED) {
if (iteration >= maxIterationCount) {
return true;
}
}
final double p = previous.getValue();
final double c = current.getValue();
final double difference = FastMath.abs(p - c);
final double size = FastMath.max(FastMath.abs(p), FastMath.abs(c));
return difference <= size * getRelativeThreshold() ||
difference <= getAbsoluteThreshold();
}
}
|
package org.adligo.xml_io_tests.shared;
import org.adligo.models.params.shared.I_XMLBuilder;
import org.adligo.xml_io.shared.Xml_IOConstants;
public class MockConstants {
public static final String HEADER = Xml_IOConstants.HEADER + I_XMLBuilder.DOS_LINE_FEED + "<a:";
public static final String HEADER_2_NOEND = " xmlns:a=\"http://www.adligo.org/xml_io\"" + I_XMLBuilder.DOS_LINE_FEED +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"";
public static final String HEADER_2 = HEADER_2_NOEND + ">";
public static final String CUSTOM_HEADER = Xml_IOConstants.HEADER + I_XMLBuilder.DOS_LINE_FEED + "<b:";
public static final String CUSTOM_HEADER_2_NOEND =
" xmlns:b=\"http://www.adligo.org/xml_io_tests\"" + I_XMLBuilder.DOS_LINE_FEED +
" xmlns:a=\"http://www.adligo.org/xml_io\"" + I_XMLBuilder.DOS_LINE_FEED +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"";
}
|
/*
WARNING: THIS FILE IS AUTO-GENERATED. DO NOT MODIFY.
This file was generated from .idl using "rtiddsgen".
The rtiddsgen tool is part of the RTI Connext distribution.
For more information, type 'rtiddsgen -help' at a command shell
or consult the RTI Connext manual.
*/
package rapid.ext.astrobee;
/** Grab control of an agent */
/** Initialize bias. */
/** Command used to load a nodelet in the system. Doesn't work with nodes running on the HLP. */
/** Type of nodelet (namespace/classname). The type is specified in the system monitor config file so you may not need to specify this. */
/** Name of nodelet manager. This should be unnecessary since the system monitor should have received a heartbeat at startup from the node and the nodelet manager name is in the heartbeat. The system monitor saves it and should be able to use it to load nodelets. If commands fails, you may want to try to specify it. */
/** Can be left blank. */
/** Reset ekf. */
/** This command is used to switch between localization pipelines. */
/** Specify which pipeline to switch to. */
/** Command used to unload a nodelet in the system. Doesn't work with nodes running on the HLP. With great power comes great responsibility! Don't unload a nodelet crucial to the system!! */
/** This should be unnecessary since the system monitor should have received a heartbeat at startup from the node and the heartbeat contains thenodelet manager name. If the command fails, you may want to try to specify it. */
/** This command is used to unterminate the robot. It will only reset the terminate flag but will not start up the pmcs or repower the payloads. */
/** This command wakes astrobee from a hibernated state into a nominal state. */
/** This command wakes astrobee from a hibernated state into a safe state. */
/** Erases everything on the hlp. */
/** Move arm while perched to control camera angle */
/** Whether to perform a pan, tilt, or both. */
/** Open or close gripper */
/** Clear data */
/** Start downloading data */
/** Set data-to-disk configuration to be the data-to-disk file most recently uplinked; the file specifies which data to save to free flyer onboard storage, and at what rates */
/** Starts the recording of the topics configured with the set data to disk command. */
/** Stop downloading data */
/** Stops the recording of the topics configured with the set data to disk command. */
/** Pass data to guest science APK */
/** Specify which guest science APK to send the data to */
/** The data to send (e.g. could be JSON-encoded data structure) */
/** Start guest science APK */
/** Specify which guest science APK to start */
/** Terminate guest science APK */
/** Specify which guest science APK to terminate */
/** Dock Astrobee. Must meet dock approach preconditions (positioned at dock approach point, etc). */
/** Berth number can only be 1 or 2. */
/** Stop propulsion impeller motors */
/** It takes the prop modules a couple of seconds to ramp up to the requested flight mode if not already at that flight mode. This command ramps up the prop modules so that when a move command is issued, it will execute right away. This doesn't need to be used for nominal use but may be used/needed for astrobee synchronization. */
/** Undock Astrobee */
/** Pause the running plan */
/** Run the loaded plan */
/** Set active plan to be the plan file that was most recently uploaded */
/** Skip next trajectory or command in the plan */
/** Pause plan for specified duration. Do nothing if docked/perched, otherwise station keep. */
/** seconds to pause */
/** Power off an item within Astrobee */
/** Any component within Astrobee that can be turned on or off. */
/** Power on an item within Astrobee */
/** Any component within Astrobee that can be turned on or off. */
/** Generic command used to make up a command after the Control Station freeze. */
/** Set camera parameters. */
/** Camera name */
/** Desired camera mode. Either streaming or recording. */
/** Desired frame size in pixels. */
/** Applies to both modes of camera. */
/** Only for sci camera; related to quality, may change name to bitrate. */
/** Set camera to record video. */
/** Camera name */
/** Record camera video. */
/** Set streaming camera video to the ground. */
/** Camera name */
/** Send live video to the ground. */
/** Command to turn on and off the obstacle detector */
/** Command to turn on and off checking keepout zones */
/** Command to allow auto return */
/** This command is only used for segments in a plan. Currently GDS does not handle timestamps since it is so tricky to get them right. So plan timestamps start at 0 and are not used by mobility since the Astrobee's system time is not 0. Thus in the nominal case set enable immediate should be set to true so that every segment sent to the mobility subsystem will be started immediately. If someone wants to do synchronized Astrobee movement, they can create plans by hand and have the timestamps start in the future. They will also have to set enable immediate to false so that the mobility system abides by the timestamp. Please note that these plans need to be started close to the first timestamp. If they are not, you could end up waiting a long time for the robot to start moving. Also the timestamp cannot be in the past or the segment will be skipped. It is probably easier to juse use GDS plan. To do this, you will want to upload the plans to the robots, use the prepare command to get the robots ready to move, and then run the plans. There could be up to a half of a second delay between the robots starting their plans. See the set time sync command. Astrobee to Astrobee communication is in the works and may solve synchronizing Astrobees in a better way. */
/** Specify which flashlight. */
/** Brightness percentage between 0 - 1 */
/** Command to allow blind flying */
/** Set mass and inertia matrix for Astrobee control */
/** The center of mass of Astrobee. */
/** The moment of inertia tensor. Must be a symmetric matrix. */
/** Change the value of Astrobee operating limits */
/** Defines GN&C gains, hard limits, tolerances, etc. */
/** The maximum linear velocity to target while translating */
/** The maximum linear acceleration to target while translating */
/** The maximum angular velocity to target while rotating */
/** The maximum angular acceleration to target while rotating */
/** Minimum distance margin to maintain away from obstacles */
/** This command is used to switch planners. */
/** Specify which planner to switch to. */
/** Change the frequency at which one type of telemetry is sent to GDS */
/** This command is used to help with Astrobee synchronization. It will try to account for the delay in communication between the ground and space and the time it takes to plan and validate a segment. This will hopefully result in two Astrobees starting to move at the same time. */
/** Set active keepout zones to be the zones file that was most recently uploaded */
public class SETTINGS_TELEMETRY_TYPE_EKF_STATE {
public static final String VALUE = "EkfState";
}
|
/*
* Copyright 2014 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 me.cmoz.gradle.snapshot;
import lombok.SneakyThrows;
import org.gradle.api.DefaultTask;
import org.gradle.api.plugins.ExtensionContainer;
import org.gradle.api.tasks.TaskAction;
import org.gradle.api.tasks.OutputFile;
import javax.annotation.Nullable;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Properties;
/**
* A task to extract build information from an SCM repository and generate a
* file with the most recent commit data.
*/
public class SnapshotTask extends DefaultTask {
/** An output label for the properties file. */
private static final String BUILD_LABEL =
"Generated by the Gradle Snapshot Plugin ("
+ SnapshotTask.class.getPackage().getImplementationVersion()
+ ")";
@OutputFile
public File getOutputFile() {
final SnapshotPluginExtension ext = this.getProject().getExtensions().getByType(SnapshotPluginExtension.class);
final File outputDir = new File(this.getProject().getBuildDir(), "snapshot");
return new File(outputDir, ext.getFilename());
}
/**
* The main action for this task.
*
* <p>The task generates metadata from the SCM for the most recent commit
* and stores it to the {@code snapshot} file location for storing with
* JAR and WAR packages.
*/
@TaskAction
@SneakyThrows(IOException.class)
public void action() {
final ExtensionContainer extensions = getProject().getExtensions();
final SnapshotPluginExtension ext = extensions.getByType(SnapshotPluginExtension.class);
final SCMCommand scmCmd = getSCMCommand();
final Properties properties = new Properties();
final File outputFile = this.getOutputFile();
if (scmCmd != null) {
final Map<String, String> commitMap = scmCmd.getLatestCommit(ext.getDateFormat()).asMap();
properties.putAll(commitMap);
} else {
this.getLogger().warn("No supported SCM repository found.");
if (outputFile.canRead()) {
FileReader reader = null;
try {
properties.load(reader = new FileReader(outputFile));
this.getLogger().info("Properties loaded from output file {}.", outputFile);
} finally {
if (reader != null) {
reader.close();
}
}
}
}
/* always set build.time as this is not scm-related */
properties.setProperty(Commit.BUILD_TIME, new SimpleDateFormat(ext.getDateFormat()).format(new Date()));
for (final String propertyName : properties.stringPropertyNames()) {
final String propertyValue = properties.getProperty(propertyName);
// make the build information available to the project properties
extensions.getExtraProperties().set(propertyName, propertyValue);
if (ext.isVerbose()) {
this.getLogger().quiet("Property {}: {}", propertyName, propertyValue);
}
}
FileWriter writer = null;
try {
outputFile.getParentFile().mkdirs();
properties.store(writer = new FileWriter(outputFile), BUILD_LABEL);
} finally {
if (writer != null) {
writer.close();
}
}
}
/**
* Searches the project directory for a repository directory that belongs
* to a supported SCM tool. If one is found the associated {@code SCMCommand}
* will be returned to interact with it.
*
* @return The {@code SCMCommand} to interact with the SCM repository for
* the project, if one could be found.
*/
@Nullable
private SCMCommand getSCMCommand() {
SCMCommand scmCmd = new HgSCMCommand(getProject());
if (scmCmd.getRepositoryDir() != null) {
return scmCmd;
}
scmCmd = new GitSCMCommand(getProject());
if (scmCmd.getRepositoryDir() != null) {
return scmCmd;
}
return null; // no supported SCM directory could be located
}
}
|
package com.interview.linklist;
/**
* Date 03/24/2016
* @author Tushar Roy
*
* A linked list is given such that each node contains an additional random pointer which could point
* to any node in the list or null. Return a deep copy of the list.
*
* Time complexity is O(n)
* Space complexity is O(1)
*
* https://leetcode.com/problems/copy-list-with-random-pointer/
*/
public class CopyLinkListWIthArbitPointer {
static class RandomListNode {
int label;
RandomListNode next, random;
RandomListNode(int x) { this.label = x; }
}
public RandomListNode copyRandomList(RandomListNode head) {
if (head == null) {
return null;
}
RandomListNode current = head;
while (current != null) {
RandomListNode newNode = new RandomListNode(current.label);
newNode.next = current.next;
newNode.random = current.random;
current.next = newNode;
current = newNode.next;
}
current = head;
while (current != null) {
RandomListNode next = current.next;
if (next.random != null) {
next.random = next.random.next;
}
current = current.next.next;
}
current = head;
RandomListNode dummy = new RandomListNode(0);
RandomListNode newCurrent = dummy;
while (current != null) {
newCurrent.next = current.next;
newCurrent = newCurrent.next;
current.next = current.next.next;
current = current.next;
}
return dummy.next;
}
public static void main(String args[]){
CopyLinkListWIthArbitPointer cll = new CopyLinkListWIthArbitPointer();
RandomListNode randomListNode = new RandomListNode(-1);
RandomListNode randomListNode1 = new RandomListNode(4);
RandomListNode randomListNode2 = new RandomListNode(8);
RandomListNode randomListNode3 = new RandomListNode(-3);
RandomListNode randomListNode4 = new RandomListNode(7);
randomListNode.next = randomListNode1;
randomListNode1.next = randomListNode2;
randomListNode2.next = randomListNode3;
randomListNode3.next = randomListNode4;
randomListNode.random = randomListNode1;
randomListNode2.random = randomListNode3;
randomListNode1.random = randomListNode;
cll.copyRandomList(randomListNode);
}
}
|
package com.ebay.dss.zds.rest.error.handler;
import com.ebay.dss.zds.exception.InterpreterExecutionException;
import com.ebay.dss.zds.exception.InterpreterServiceException;
import com.ebay.dss.zds.rest.error.match.ExceptionRuleService;
import com.ebay.dss.zds.rest.ExceptionRuleController;
import com.ebay.dss.zds.rest.error.ErrorDTO;
import com.ebay.dss.zds.websocket.WebSocketResp;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
/**
* This is for test interpreter exception;
*/
@ControllerAdvice(assignableTypes = ExceptionRuleController.class)
public class InterpreterExceptionHandler extends InterpreterExceptionSupport {
public InterpreterExceptionHandler(ExceptionRuleService ruleService) {
super(ruleService);
}
@ExceptionHandler(value = {InterpreterServiceException.class})
public ResponseEntity<WebSocketResp<ErrorDTO>> handleInterpreterConnectionExceptionRest(InterpreterServiceException ise) {
WebSocketResp<ErrorDTO> resp = handleInterpreterConnectionException(ise);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resp);
}
@ExceptionHandler(value = {InterpreterExecutionException.class})
public ResponseEntity<WebSocketResp<ErrorDTO>> handleInterpreterExecutionExceptionRest(InterpreterExecutionException iee) {
WebSocketResp<ErrorDTO> resp = handleInterpreterExecutionException(iee);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resp);
}
}
|
package org.yeastrc.spectral_storage.accept_import_web_app.servlets_upload_scan_file;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.stream.StreamSource;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.output.FileWriterWithEncoding;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory; import org.slf4j.Logger;
import org.yeastrc.spectral_storage.accept_import_web_app.background_thread.A_BackgroundThreads_Containers_Manager;
import org.yeastrc.spectral_storage.accept_import_web_app.config.ConfigData_Directories_ProcessUploadInfo_InWorkDirectory;
import org.yeastrc.spectral_storage.accept_import_web_app.constants_enums.FileUploadConstants;
import org.yeastrc.spectral_storage.accept_import_web_app.constants_enums.ServetResponseFormatEnum;
import org.yeastrc.spectral_storage.accept_import_web_app.constants_enums.UploadProcessingStatusFileConstants;
import org.yeastrc.spectral_storage.accept_import_web_app.exceptions.SpectralFileBadRequestToServletException;
import org.yeastrc.spectral_storage.accept_import_web_app.exceptions.SpectralFileDeserializeRequestException;
import org.yeastrc.spectral_storage.accept_import_web_app.exceptions.SpectralFileFileUploadInternalException;
import org.yeastrc.spectral_storage.accept_import_web_app.exceptions.SpectralFileWebappInternalException;
import org.yeastrc.spectral_storage.accept_import_web_app.import_processing_status_file__read_write.UploadProcessingWriteOrUpdateStatusFile;
import org.yeastrc.spectral_storage.accept_import_web_app.import_scan_filename_local_disk.ImportScanFilename_LocalDisk;
import org.yeastrc.spectral_storage.accept_import_web_app.process_import_request_api_key_value_in_file.ProcessImportRequest_APIKey_Value_InFile;
import org.yeastrc.spectral_storage.accept_import_web_app.servlets_common.GetRequestObjectFromInputStream;
import org.yeastrc.spectral_storage.accept_import_web_app.servlets_common.Get_ServletResultDataFormat_FromServletInitParam;
import org.yeastrc.spectral_storage.accept_import_web_app.servlets_common.WriteResponseObjectToOutputStream;
import org.yeastrc.spectral_storage.accept_import_web_app.servlets_common.WriteResponseStringToOutputStream;
import org.yeastrc.spectral_storage.accept_import_web_app.shared_server_client.webservice_request_response.main.UploadScanFile_Submit_Request;
import org.yeastrc.spectral_storage.accept_import_web_app.shared_server_client.webservice_request_response.main.UploadScanFile_Submit_Response;
import org.yeastrc.spectral_storage.accept_import_web_app.upload_scan_file.CreateProcessScanFileDir;
import org.yeastrc.spectral_storage.accept_import_web_app.upload_scan_file.ValidateTempDirToUploadScanFileTo;
import org.yeastrc.spectral_storage.accept_import_web_app.upload_scan_file.ValidateTempDirToUploadScanFileTo.ValidationResponse;
import org.yeastrc.spectral_storage.shared_server_importer.constants_enums.ScanFileToProcessConstants;
import org.yeastrc.spectral_storage.shared_server_importer.create__xml_input_factory__xxe_safe.Create_XMLInputFactory_XXE_Safe;
import org.yeastrc.spectral_storage.spectral_file_common.spectral_file.constants_enums.UploadProcessing_InputScanfileS3InfoConstants;
import org.yeastrc.spectral_storage.spectral_file_common.spectral_file.exceptions.SpectralStorageProcessingException;
import org.yeastrc.spectral_storage.spectral_file_common.spectral_file.storage_files_on_disk.common_reader_file_and_s3.CommonReader_File_And_S3_Holder;
import org.yeastrc.spectral_storage.spectral_file_common.spectral_file.upload_scanfile_s3_location.UploadScanfileS3Location;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.ObjectMetadata;
/**
* Submit the Upload Scan Process
* and returning the scanProcessStatusKey
*
* This Servlet should be considered a webservice as it returns JSON or XML
*/
public class UploadScanFile_Submit_Servlet extends HttpServlet {
private static final Logger log = LoggerFactory.getLogger( UploadScanFile_Submit_Servlet.class );
private static final long serialVersionUID = 1L;
private ServetResponseFormatEnum servetResponseFormat;
/* (non-Javadoc)
* @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)
*/
@Override
public void init(ServletConfig config)
throws ServletException {
super.init(config); // Must call this first
servetResponseFormat =
Get_ServletResultDataFormat_FromServletInitParam.getInstance()
.get_ServletResultDataFormat_FromServletInitParam( config );
log.warn( "INFO: servetResponseFormat: " + servetResponseFormat );
}
/* (non-Javadoc)
* @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
log.info( "INFO: doPost called");
UploadScanFile_Submit_Request uploadScanFile_Submit_Request = null;
try {
Object requestObj = null;
try {
requestObj = GetRequestObjectFromInputStream.getSingletonInstance().getRequestObjectFromStream( request );
} catch ( SpectralFileDeserializeRequestException e ) {
throw e;
} catch (Exception e) {
String msg = "Failed to deserialize request";
log.error( msg, e );
throw new SpectralFileBadRequestToServletException( e );
}
try {
uploadScanFile_Submit_Request = (UploadScanFile_Submit_Request) requestObj;
} catch (Exception e) {
String msg = "Failed to cast requestObj to UploadScanFile_Submit_Request";
log.error( msg, e );
throw new SpectralFileBadRequestToServletException( e );
}
} catch (SpectralFileBadRequestToServletException e) {
response.setStatus( HttpServletResponse.SC_BAD_REQUEST /* 400 */ );
if ( StringUtils.isNotEmpty( e.getMessage() ) ) {
WriteResponseStringToOutputStream.getInstance()
.writeResponseStringToOutputStream( e.getMessage(), response);
}
return; // EARLY EXIT
} catch (Throwable e) {
String msg = "Failed to process request";
log.error( msg, e );
response.setStatus( HttpServletResponse.SC_INTERNAL_SERVER_ERROR /* 500 */ );
return; // EARLY EXIT
}
processRequest( uploadScanFile_Submit_Request, request, response );
}
/**
* @param uploadScanFile_Submit_Request
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
private void processRequest(
UploadScanFile_Submit_Request uploadScanFile_Submit_Request,
HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
if ( log.isInfoEnabled() ) {
log.info("INFO: processRequest(...) Start: NEW: uploadScanFile_Submit_Request.getUploadScanFileTempKey(): " + uploadScanFile_Submit_Request.getUploadScanFileTempKey() );
}
long startTime = System.currentTimeMillis();
String uploadScanFileTempKey = null;
try {
uploadScanFileTempKey = uploadScanFile_Submit_Request.getUploadScanFileTempKey();
if ( StringUtils.isEmpty( uploadScanFileTempKey ) ) {
String msg = "request is missing uploadScanFileTempKey ";
log.warn( msg );
throw new SpectralFileBadRequestToServletException( msg );
}
UploadScanFile_Submit_Response webserviceResponse = new UploadScanFile_Submit_Response();
File uploadBaseDir = ConfigData_Directories_ProcessUploadInfo_InWorkDirectory.getSingletonInstance().getTempScanUploadBaseDirectory();
String uploadFileTempDirString = FileUploadConstants.UPLOAD_FILE_TEMP_BASE_DIR;
File uploadFileTempDir = new File( uploadBaseDir, uploadFileTempDirString );
File uploadScanFileTempKey_Dir = new File( uploadFileTempDir, uploadScanFileTempKey );
if ( ! uploadScanFileTempKey_Dir.exists() ) {
String msg = "uploadScanFileTempKey_Dir does not exist for uploadScanFileTempKey. uploadScanFileTempKey: "
+ uploadScanFileTempKey
+ ", uploadScanFileTempKey_Dir: "
+ uploadScanFileTempKey_Dir.getAbsolutePath();
log.warn( msg );
webserviceResponse.setUploadScanFileTempKey_NotFound( true );
WriteResponseObjectToOutputStream.getSingletonInstance()
.writeResponseObjectToOutputStream( webserviceResponse, servetResponseFormat, response );
return; // EARLY EXIT
}
if ( ! uploadScanFileTempKey_Dir.getName().equals( uploadScanFileTempKey ) ) {
// Return not found but actually problem with provided key, contains Operating System path separator or something
String msg = "uploadScanFileTempKey value is not same as directory name when put into Java File object. "
+ "uploadScanFileTempKey from request: '" + uploadScanFileTempKey + "'"
+ ", uploadScanFileTempKey directory name from Java File object: '"
+ uploadScanFileTempKey_Dir.getName()
+ "'";
log.warn( msg );
webserviceResponse.setUploadScanFileTempKey_NotFound( true );
WriteResponseObjectToOutputStream.getSingletonInstance()
.writeResponseObjectToOutputStream( webserviceResponse, servetResponseFormat, response );
return; // EARLY EXIT
}
{
ValidationResponse validationResponse =
ValidateTempDirToUploadScanFileTo.getInstance()
.validateTempDirToUploadScanFileTo( uploadScanFileTempKey_Dir );
if ( validationResponse != ValidationResponse.VALID ) {
if ( validationResponse == ValidationResponse.KEY_NOT_FOUND ) {
String msg = "ValidateTempDirToUploadScanFileTo.getInstance().validateTempDirToUploadScanFileTo(...) returns KEY_NOT_FOUND. uploadScanFileTempKey from request: '"
+ uploadScanFileTempKey
+ "', uploadScanFileTempKey_Dir: "
+ uploadScanFileTempKey_Dir.getAbsolutePath();
log.warn( msg );
webserviceResponse.setStatusSuccess(false);
webserviceResponse.setUploadScanFileTempKey_NotFound(true);
WriteResponseObjectToOutputStream.getSingletonInstance()
.writeResponseObjectToOutputStream( webserviceResponse, servetResponseFormat, response );
return; // EARLY EXIT
} else if ( validationResponse == ValidationResponse.KEY_EXPIRED ) {
String msg = "ValidateTempDirToUploadScanFileTo.getInstance().validateTempDirToUploadScanFileTo(...) returns KEY_EXPIRED. uploadScanFileTempKey from request: '"
+ uploadScanFileTempKey
+ "', uploadScanFileTempKey_Dir: "
+ uploadScanFileTempKey_Dir.getAbsolutePath();
log.warn( msg );
webserviceResponse.setStatusSuccess(false);
webserviceResponse.setUploadScanFileTempKey_Expired(true);
WriteResponseObjectToOutputStream.getSingletonInstance()
.writeResponseObjectToOutputStream( webserviceResponse, servetResponseFormat, response );
return; // EARLY EXIT
} else {
String msg = "validationResponse is not an expected value. is: " + validationResponse;
log.error( msg );
throw new SpectralFileFileUploadInternalException( msg );
}
}
}
String scanProcessStatusKey = null;
if ( StringUtils.isNotEmpty( ConfigData_Directories_ProcessUploadInfo_InWorkDirectory.getSingletonInstance().getS3Bucket() ) ) {
// Scan File on S3
// throws exceptions if errors
scanProcessStatusKey =
moveUpload_S3_ScanFileTempKey_Dir_To_scanProcessStatusKey_Dir( uploadScanFileTempKey_Dir );
} else {
// Scan File on local disk
// Find the scan file
String scanFilenameToMove = ImportScanFilename_LocalDisk.getInstance().getImportScanFilename_LocalDisk( uploadScanFileTempKey_Dir );
if ( scanFilenameToMove == null ) {
String msg = "No Scan file uploaded. uploadScanFileTempKey: "
+ uploadScanFileTempKey
+ ", uploadScanFileTempKey_Dir: "
+ uploadScanFileTempKey_Dir.getAbsolutePath();
log.warn( msg );
webserviceResponse.setNoUploadedScanFile(true);
WriteResponseObjectToOutputStream.getSingletonInstance()
.writeResponseObjectToOutputStream( webserviceResponse, servetResponseFormat, response );
return; // EARLY EXIT
}
// throws exceptions if errors
scanProcessStatusKey =
moveUpload_LocalDisk_ScanFileTempKey_Dir_To_scanProcessStatusKey_Dir(
scanFilenameToMove,
uploadScanFileTempKey_Dir );
log.warn("INFO: processRequest(...) processed uploadScanFile_Submit_Request.getUploadScanFileTempKey(): "
+ uploadScanFile_Submit_Request.getUploadScanFileTempKey()
+ ", and returned scanProcessStatusKey: "
+ scanProcessStatusKey );
}
webserviceResponse.setScanProcessStatusKey( scanProcessStatusKey );
webserviceResponse.setStatusSuccess(true);
WriteResponseObjectToOutputStream.getSingletonInstance()
.writeResponseObjectToOutputStream( webserviceResponse, servetResponseFormat, response );
} catch (SpectralFileBadRequestToServletException e) {
String msg = "SpectralFileBadRequestToServletException caught: scanFilenameToMove == null. uploadScanFileTempKey: "
+ uploadScanFileTempKey ;
log.warn( msg, e );
response.setStatus( HttpServletResponse.SC_BAD_REQUEST /* 400 */ );
if ( StringUtils.isNotEmpty( e.getMessage() ) ) {
WriteResponseStringToOutputStream.getInstance()
.writeResponseStringToOutputStream( e.getMessage(), response);
}
} catch (Throwable e) {
String msg = "Failed to process request, uploadScanFileTempKey: " + uploadScanFileTempKey;
log.error( msg, e );
response.setStatus( HttpServletResponse.SC_INTERNAL_SERVER_ERROR /* 500 */ );
}
long endTime = System.currentTimeMillis();
long timeForMethod = endTime - startTime;
if ( log.isInfoEnabled() ) {
log.info("INFO: processRequest(...) took " + timeForMethod + " millseconds for uploadScanFile_Submit_Request.getUploadScanFileTempKey(): "
+ uploadScanFile_Submit_Request.getUploadScanFileTempKey() );
}
long timeTaken = endTime - startTime;
if ( timeTaken > 7000 ) {
log.warn( "Time taken in processRequest(...) > 7 seconds for for Submit Upload. timeTaken (milliseconds): " + timeTaken
+ ", uploadScanFileTempKey: " + uploadScanFile_Submit_Request.getUploadScanFileTempKey() );
}
}
/**
* @param scanFilenameToMove
* @param uploadFileTempDir
* @return scanProcessStatusKey
* @throws Exception
*/
private String moveUpload_S3_ScanFileTempKey_Dir_To_scanProcessStatusKey_Dir( File uploadFileTempDir ) throws Exception {
File dirToProcessScanFile =
CreateProcessScanFileDir.getInstance().createDirToProcessScanFile();
String scanProcessStatusKey = dirToProcessScanFile.getName();
// Change to have a single S3 object path for uploaded scan files
// since cannot change the S3 object key for a S3 object
// Not practical to copy a multi-gigabyte scan file just to change the object key
// IMPORTANT. If decide that changing the object key is a must,
// must use "Copy an Object Using the AWS SDK for Java Multipart Upload API"
// https://docs.aws.amazon.com/AmazonS3/latest/dev/CopyingObjctsUsingLLJavaMPUapi.html
createScanFileS3Location_File( scanProcessStatusKey, uploadFileTempDir, dirToProcessScanFile );
commonProcessingOfUploadedScanFile( uploadFileTempDir, dirToProcessScanFile, scanProcessStatusKey );
return scanProcessStatusKey;
}
/**
* @param scanProcessStatusKey
* @param uploadFileTempDir
* @param dirToProcessScanFile
*/
private void createScanFileS3Location_File(
String scanProcessStatusKey,
File uploadFileTempDir,
File dirToProcessScanFile ) throws Exception {
JAXBContext jaxbContext = JAXBContext.newInstance( UploadScanfileS3Location.class );
UploadScanfileS3Location uploadScanfileS3Location_InUploadTemp =
getTempUpload_UploadScanfileS3Location( uploadFileTempDir, jaxbContext );
write_scanfileS3Location_InDirToProcessScanFile( uploadScanfileS3Location_InUploadTemp, dirToProcessScanFile, jaxbContext );
if ( ! uploadScanfileS3Location_InUploadTemp.isS3_infoFrom_RemoteSystem() ) {
createScanFileS3_Submitted_S3_Object( uploadScanfileS3Location_InUploadTemp );
}
}
/**
* @param scanProcessStatusKey
* @param uploadFileTempDir
* @param dirToProcessScanFile
*/
private void createScanFileS3_Submitted_S3_Object( UploadScanfileS3Location uploadScanfileS3Location_InUploadTemp ) throws Exception {
final AmazonS3 amazonS3 = CommonReader_File_And_S3_Holder.getSingletonInstance().getCommonReader_File_And_S3().getS3_Client();
// PutObjectResult putObject(String bucketName, String key, InputStream input, ObjectMetadata metadata)
// Uploads the specified input stream and object metadata to Amazon S3 under the specified bucket and key name.
String objectKey = uploadScanfileS3Location_InUploadTemp.getS3_objectName()
+ ScanFileToProcessConstants.SCAN_FILE_TO_PROCESS_FILENAME_SUBMITTED_FILE_SUFFIX;
byte[] dummyBytes = { 0 };
ByteArrayInputStream bais = new ByteArrayInputStream(dummyBytes);
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength( dummyBytes.length );
amazonS3.putObject(
uploadScanfileS3Location_InUploadTemp.getS3_bucketName(),
objectKey,
bais,
objectMetadata );
}
/**
* @param scanfileS3Location_InDirToProcessScanFile
* @param dirToProcessScanFile
* @param jaxbContext
* @throws Exception
*/
private void write_scanfileS3Location_InDirToProcessScanFile( UploadScanfileS3Location scanfileS3Location_InDirToProcessScanFile, File dirToProcessScanFile, JAXBContext jaxbContext ) throws Exception {
File scanfileS3InfoFile = new File( dirToProcessScanFile, UploadProcessing_InputScanfileS3InfoConstants.SCANFILE_S3_LOCATION_FILENAME );
Marshaller marshaller = jaxbContext.createMarshaller();
try ( OutputStream os = new FileOutputStream(scanfileS3InfoFile) ) {
marshaller.marshal( scanfileS3Location_InDirToProcessScanFile, os );
} catch (Exception e) {
String msg = "Failed to Marshal XML. Should be type UploadScanfileS3Location. File: " +
scanfileS3InfoFile.getAbsolutePath();
log.error( msg, e );
throw new SpectralFileWebappInternalException(msg, e);
}
}
/**
* @param uploadFileTempDir
* @param jaxbContext
* @return
* @throws Exception
*/
private UploadScanfileS3Location getTempUpload_UploadScanfileS3Location( File uploadFileTempDir, JAXBContext jaxbContext ) throws Exception {
File scanfileS3InfoFile = new File( uploadFileTempDir, UploadProcessing_InputScanfileS3InfoConstants.SCANFILE_S3_LOCATION_FILENAME );
if ( ! scanfileS3InfoFile.exists() ) {
String msg = "Input file of type UploadScanfileS3Location is missing. File: " +
scanfileS3InfoFile.getAbsolutePath();
log.error( msg );
throw new SpectralFileWebappInternalException(msg);
}
try ( InputStream is = new FileInputStream( scanfileS3InfoFile) ) {
XMLInputFactory xmlInputFactory = Create_XMLInputFactory_XXE_Safe.create_XMLInputFactory_XXE_Safe();
XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader( new StreamSource( is ) );
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Object uploadScanfileS3LocationObj = unmarshaller.unmarshal( xmlStreamReader );
if ( ! ( uploadScanfileS3LocationObj instanceof UploadScanfileS3Location ) ) {
String msg = "Unmarshaled object is not type UploadScanfileS3Location. Source file: " +
scanfileS3InfoFile.getAbsolutePath();
log.error( msg );
throw new SpectralFileWebappInternalException(msg);
}
UploadScanfileS3Location uploadScanfileS3Location = (UploadScanfileS3Location) uploadScanfileS3LocationObj;
return uploadScanfileS3Location;
} catch (Exception e) {
String msg = "Failed to Unmarshal XML. Should be type UploadScanfileS3Location. File: " +
scanfileS3InfoFile.getAbsolutePath();
log.error( msg, e );
throw new SpectralFileWebappInternalException(msg, e);
}
}
/**
* @param scanFilenameToMove
* @param uploadFileTempDir
* @return scanProcessStatusKey
* @throws Exception
*/
private String moveUpload_LocalDisk_ScanFileTempKey_Dir_To_scanProcessStatusKey_Dir(
String scanFilenameToMove,
File uploadFileTempDir ) throws Exception {
File dirToProcessScanFile =
CreateProcessScanFileDir.getInstance().createDirToProcessScanFile();
String scanProcessStatusKey = dirToProcessScanFile.getName();
/// move the uploaded Scan file into processing dir.
moveFileToScanProcessDir( scanFilenameToMove, uploadFileTempDir, dirToProcessScanFile );
commonProcessingOfUploadedScanFile( uploadFileTempDir, dirToProcessScanFile, scanProcessStatusKey );
return scanProcessStatusKey;
}
/**
* @param uploadFileTempDir
* @param dirToProcessScanFile
* @param scanProcessStatusKey
* @throws Exception
*/
private void commonProcessingOfUploadedScanFile(
File uploadFileTempDir,
File dirToProcessScanFile,
String scanProcessStatusKey
) throws Exception {
boolean apiKeyComputed = false;
{ /// If exists, move the computed API Key from hash into processing dir.
File computedAPIKeyFromhashFile = new File( uploadFileTempDir, ScanFileToProcessConstants.SCAN_FILE_TO_PROCESS_HASH_STRING_API_KEY_FILENAME );
if ( computedAPIKeyFromhashFile.exists() ) {
moveFileToScanProcessDir( ScanFileToProcessConstants.SCAN_FILE_TO_PROCESS_HASH_STRING_API_KEY_FILENAME, uploadFileTempDir, dirToProcessScanFile );
apiKeyComputed = true;
}
}
{ // Move file containing submitted filename with path, if exists. Only exists if filename with path submitted
File file = new File( uploadFileTempDir, ScanFileToProcessConstants.SCAN_FILE_TO_PROCESS_SUBMITTED_SCAN_FILENAME_WITH_PATH );
if ( file.exists() ) {
moveFileToScanProcessDir( ScanFileToProcessConstants.SCAN_FILE_TO_PROCESS_SUBMITTED_SCAN_FILENAME_WITH_PATH, uploadFileTempDir, dirToProcessScanFile );
}
}
// Empty and delete temp upload directory uploadFileTempDir
try {
File[] uploadFileTempDir_Files = uploadFileTempDir.listFiles();
for ( File dirEntry : uploadFileTempDir_Files ) {
if ( ! dirEntry.delete() ) {
String msg = "Failed to delete temp dir entry for uploaded file, file failed to delete: " + dirEntry.getAbsolutePath()
+ ", uploadFileTempDir: " + uploadFileTempDir.getAbsolutePath();
log.error( msg );
throw new Exception( msg );
}
{
if ( log.isInfoEnabled() ) {
String msg = "INFO: commonProcessingOfUploadedScanFile: Deleted temp dir entry for uploaded file. Entry: "
+ dirEntry.getAbsolutePath()
+ ", uploadFileTempDir: "
+ uploadFileTempDir.getAbsolutePath();
log.info( msg );
}
}
}
if ( ! uploadFileTempDir.delete() ) {
String msg = "Failed to delete temp dir for uploaded file, uploadFileTempDir: " + uploadFileTempDir.getAbsolutePath();
log.error( msg );
throw new Exception( msg );
}
{
if ( log.isInfoEnabled() ) {
String msg = "INFO: commonProcessingOfUploadedScanFile: Deleted temp dir for uploaded file. uploadFileTempDir: "
+ uploadFileTempDir.getAbsolutePath();
log.info( msg );
}
}
} catch ( Exception e ) {
String msg = "Failed to delete temp dir for uploaded file, uploadFileTempDir: " + uploadFileTempDir.getAbsolutePath();
log.error( msg, e );
throw new Exception(msg, e);
}
// Key returned to client, store in file
{
File scanProcessStatusKeyFile = new File( dirToProcessScanFile, ScanFileToProcessConstants.SCAN_PROCESS_STATUS_KEY_FILENAME );
try ( BufferedWriter writer = new BufferedWriter( new FileWriterWithEncoding( scanProcessStatusKeyFile, StandardCharsets.UTF_8 ) ) ) {
writer.write( scanProcessStatusKey );
} catch ( Exception e ) {
String msg = "Failed to write scanProcessStatusKey to file: " + scanProcessStatusKeyFile.getAbsolutePath();
log.error( msg );
throw new Exception(msg);
}
}
if ( apiKeyComputed ) {
// API Key computed
ProcessImportRequest_APIKey_Value_InFile.getInstance().
processImportRequest_APIKey_Value_InFile( dirToProcessScanFile );
} else {
// API Key NOT computed
compute_API_Key_InProcessingDir( dirToProcessScanFile );
}
}
/**
* @param dirToProcessScanFile
* @throws Exception
*/
private void compute_API_Key_InProcessingDir( File dirToProcessScanFile ) throws Exception {
try {
// Create status file for pending
UploadProcessingWriteOrUpdateStatusFile.getInstance()
.uploadProcessingWriteOrUpdateStatusFile(
UploadProcessingStatusFileConstants.STATUS_COMPUTE_API_KEY,
dirToProcessScanFile,
UploadProcessingStatusFileConstants.STATUS_PROCESSING_CALLER_LABEL__ACCEPT_IMPORT_WEBAPP );
} catch ( Exception e ) {
String msg = "Failed to create status file, dirToProcessScanFile: " + dirToProcessScanFile.getAbsolutePath();
log.error( msg, e );
throw new SpectralStorageProcessingException( msg, e );
}
A_BackgroundThreads_Containers_Manager.getSingletonInstance().getComputeAPIKeyForScanFile_Thread_Container().awakenToProcessAScanFile();
}
/**
* @param filenameToMove
* @param uploadFileTempDir
* @param dirToProcessScanFile
* @throws Exception
*/
private void moveFileToScanProcessDir( String filenameToMove, File uploadFileTempDir, File dirToProcessScanFile ) throws Exception {
File uploadedFile_In_uploadFileTempDir = new File( uploadFileTempDir, filenameToMove );
File uploadedFile_In_dirForProcessingScan = new File( dirToProcessScanFile, filenameToMove );
try {
FileUtils.moveFile( uploadedFile_In_uploadFileTempDir, uploadedFile_In_dirForProcessingScan );
} catch ( Exception e ) {
String msg = "Failed to move uploaded file to dirToProcessScanFile. Src file: " + uploadedFile_In_uploadFileTempDir.getAbsolutePath()
+ ", dest file: " + uploadedFile_In_dirForProcessingScan.getAbsolutePath();
log.error( msg, e );
throw new Exception(msg, e);
}
}
}
|
package com.google.android.gms.common.api.internal;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.PendingResult.zza;
import com.google.android.gms.common.api.Result;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.ResultTransform;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.common.api.TransformedResult;
import com.google.android.gms.common.internal.zzbq;
import java.util.concurrent.TimeUnit;
public final class zzcw<R extends Result> extends PendingResult<R> {
private final Status mStatus;
public zzcw(Status status) {
zzbq.checkNotNull(status, "Status must not be null");
zzbq.checkArgument(!status.isSuccess(), "Status must not be success");
this.mStatus = status;
}
@NonNull
public final R await() {
throw new UnsupportedOperationException("Operation not supported on PendingResults generated by ResultTransform.createFailedResult()");
}
@NonNull
public final R await(long j, @NonNull TimeUnit timeUnit) {
throw new UnsupportedOperationException("Operation not supported on PendingResults generated by ResultTransform.createFailedResult()");
}
public final void cancel() {
throw new UnsupportedOperationException("Operation not supported on PendingResults generated by ResultTransform.createFailedResult()");
}
@NonNull
final Status getStatus() {
return this.mStatus;
}
public final boolean isCanceled() {
throw new UnsupportedOperationException("Operation not supported on PendingResults generated by ResultTransform.createFailedResult()");
}
public final void setResultCallback(@NonNull ResultCallback<? super R> resultCallback) {
throw new UnsupportedOperationException("Operation not supported on PendingResults generated by ResultTransform.createFailedResult()");
}
public final void setResultCallback(@NonNull ResultCallback<? super R> resultCallback, long j, @NonNull TimeUnit timeUnit) {
throw new UnsupportedOperationException("Operation not supported on PendingResults generated by ResultTransform.createFailedResult()");
}
@NonNull
public final <S extends Result> TransformedResult<S> then(@NonNull ResultTransform<? super R, ? extends S> resultTransform) {
throw new UnsupportedOperationException("Operation not supported on PendingResults generated by ResultTransform.createFailedResult()");
}
public final void zza(@NonNull zza com_google_android_gms_common_api_PendingResult_zza) {
throw new UnsupportedOperationException("Operation not supported on PendingResults generated by ResultTransform.createFailedResult()");
}
@Nullable
public final Integer zzagi() {
throw new UnsupportedOperationException("Operation not supported on PendingResults generated by ResultTransform.createFailedResult()");
}
}
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE90_LDAP_Injection__connect_tcp_52a.java
Label Definition File: CWE90_LDAP_Injection.label.xml
Template File: sources-sink-52a.tmpl.java
*/
/*
* @description
* CWE: 90 LDAP Injection
* BadSource: connect_tcp Read data using an outbound tcp connection
* GoodSource: A hardcoded string
* Sinks:
* BadSink : data concatenated into LDAP search, which could result in LDAP Injection
* Flow Variant: 52 Data flow: data passed as an argument from one method to another to another in three different classes in the same package
*
* */
package testcases.CWE90_LDAP_Injection;
import testcasesupport.*;
import javax.servlet.http.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.Socket;
import java.util.logging.Level;
public class CWE90_LDAP_Injection__connect_tcp_52a extends AbstractTestCase
{
public void bad() throws Throwable
{
String data;
data = ""; /* Initialize data */
/* Read data using an outbound tcp connection */
{
Socket socket = null;
BufferedReader readerBuffered = null;
InputStreamReader readerInputStream = null;
try
{
/* Read data using an outbound tcp connection */
socket = new Socket("host.example.org", 39544);
/* read input from socket */
readerInputStream = new InputStreamReader(socket.getInputStream(), "UTF-8");
readerBuffered = new BufferedReader(readerInputStream);
/* POTENTIAL FLAW: Read data using an outbound tcp connection */
data = readerBuffered.readLine();
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
}
finally
{
/* clean up stream reading objects */
try
{
if (readerBuffered != null)
{
readerBuffered.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
}
try
{
if (readerInputStream != null)
{
readerInputStream.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
}
/* clean up socket objects */
try
{
if (socket != null)
{
socket.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing Socket", exceptIO);
}
}
}
(new CWE90_LDAP_Injection__connect_tcp_52b()).badSink(data );
}
public void good() throws Throwable
{
goodG2B();
}
/* goodG2B() - use goodsource and badsink */
private void goodG2B() throws Throwable
{
String data;
/* FIX: Use a hardcoded string */
data = "foo";
(new CWE90_LDAP_Injection__connect_tcp_52b()).goodG2BSink(data );
}
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
public static void main(String[] args) throws ClassNotFoundException,
InstantiationException, IllegalAccessException
{
mainFromParent(args);
}
}
|
package com.boomi.flow.services.boomi.mdh.common;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.util.*;
@XmlRootElement(name = "batch")
public class BatchUpdateRequest {
private String source;
private List<Entity> entities = new ArrayList<>();
@XmlAttribute(name = "src")
public String getSource() {
return source;
}
public BatchUpdateRequest setSource(String source) {
this.source = source;
return this;
}
@XmlAnyElement()
public List<Entity> getEntities() {
return entities;
}
public BatchUpdateRequest setEntities(List<Entity> entities) {
this.entities = entities;
return this;
}
@XmlJavaTypeAdapter(BatchUpdateRequestEntityAdapter.class)
public static class Entity {
private String op;
private String name;
private Map<String, Object> fields = new HashMap<>();
@XmlAttribute
public String getOp() {
return op;
}
public Entity setOp(String op) {
this.op = op;
return this;
}
public String getName() {
return name;
}
public Entity setName(String name) {
this.name = name;
return this;
}
public Map<String, Object> getFields() {
return fields;
}
public Entity setFields(Map<String, Object> fields) {
this.fields = fields;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Entity entity = (Entity) o;
return Objects.equals(op, entity.op) &&
Objects.equals(name, entity.name) &&
Objects.equals(fields, entity.fields);
}
@Override
public int hashCode() {
return Objects.hash(op, name, fields);
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
BatchUpdateRequest that = (BatchUpdateRequest) o;
return Objects.equals(source, that.source) &&
Objects.equals(entities, that.entities);
}
@Override
public int hashCode() {
return Objects.hash(source, entities);
}
}
|
/**
*
*/
package com.thinkgem.jeesite.test.dao;
import com.thinkgem.jeesite.common.persistence.CrudDao;
import com.thinkgem.jeesite.common.persistence.annotation.MyBatisDao;
import com.thinkgem.jeesite.test.entity.TestData;
/**
* 单表生成DAO接口
* @author libn
* @version 2015-04-06
*/
@MyBatisDao
public interface TestDataDao extends CrudDao<TestData> {
}
|
package fr.volax.tutoriel;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class TutorielCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if(!(sender instanceof Player)) return false;
Player player = (Player) sender;
if(TutorielMain.particles.contains(player))
TutorielMain.particles.remove(player);
else
TutorielMain.particles.add(player);
return false;
}
}
|
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered.org <http://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.mod.mixin.core.entity.living.monster;
import net.minecraft.entity.monster.EntityGuardian;
import net.minecraft.entity.monster.EntityMob;
import net.minecraft.world.World;
import org.spongepowered.api.entity.living.monster.Guardian;
import org.spongepowered.api.util.annotation.NonnullByDefault;
import org.spongepowered.asm.mixin.Implements;
import org.spongepowered.asm.mixin.Interface;
import org.spongepowered.asm.mixin.Intrinsic;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
@NonnullByDefault
@Mixin(EntityGuardian.class)
@Implements(@Interface(iface = Guardian.class, prefix = "guardian$"))
public abstract class MixinEntityGuardian extends EntityMob {
@Shadow
public abstract boolean isElder();
@Shadow
public abstract void setElder(boolean elder);
public MixinEntityGuardian(World worldIn) {
super(worldIn);
}
@Intrinsic
public boolean guardian$isElder() {
return this.isElder();
}
@Intrinsic
public void guardian$setElder(boolean elder) {
this.setElder(elder);
}
public boolean isFlowerPot() {
return false;
}
}
|
/**
* Copyright 2017-2018 The OpenTracing Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package io.opentracing.contrib.metrics.spring.autoconfigure;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import io.opentracing.contrib.api.TracerObserver;
import io.opentracing.contrib.metrics.MetricsObserver;
import io.opentracing.contrib.metrics.MetricsReporter;
@Configuration
public class MetricsTracerObserverConfiguration {
@Autowired(required=false)
private Set<MetricsReporter> metricsReporters;
@Bean
public TracerObserver metricsTracerObserver() {
if (metricsReporters != null && !metricsReporters.isEmpty()) {
return new MetricsObserver(metricsReporters);
}
return null;
}
}
|
package io.opensphere.core.cache.jdbc;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import io.opensphere.core.util.collections.CollectionUtilities;
import io.opensphere.core.util.collections.ConcurrentLazyMap;
import io.opensphere.core.util.collections.LazyMap.Factory;
import io.opensphere.core.util.collections.New;
/**
* This keeps track of the current database state.
*/
public class DatabaseState
{
/** The set of indices that have been created. */
private final Set<String> myCreatedIndices = CollectionUtilities.toSetView(new ConcurrentHashMap<String, Object>(),
new Object());
/** The set of tables that have been created. */
private final Map<Integer, Set<String>> myCreatedTables = ConcurrentLazyMap
.create(new ConcurrentHashMap<Integer, Set<String>>(), Integer.class, (Factory<Integer, Set<String>>)key -> Collections.synchronizedSet(New.<String>set()));
/** Counter used to create unique temporary table names. */
private final AtomicInteger myTemporaryTableCounter = new AtomicInteger();
/**
* Clear the cache of created tables and indices.
*/
public void clearCreated()
{
myCreatedTables.clear();
myCreatedIndices.clear();
}
/**
* Access the in-memory cache of the indices that have been created in the
* database. The returned set is read/write and thread-safe.
*
* @return The createdIndices.
*/
public Set<String> getCreatedIndices()
{
return myCreatedIndices;
}
/**
* Access the in-memory cache of the columns that have been created in the
* data table associated with a model group. The returned set is thread-safe
* for put/get but must be externally synchronized for iteration.
*
* @param groupId The group id.
* @return The set of column names.
*/
public Set<String> getExistingColumnsForGroup(int groupId)
{
return myCreatedTables.get(Integer.valueOf(groupId));
}
/**
* Get the next unique name for a temporary table. Temporary tables only
* exist with the scope of the database connection, so this doesn't have to
* be very sophisticated. This is thread-safe.
*
* @return A new temporary table name.
*/
public String getNextTempTableName()
{
return "JOIN_TABLE_" + myTemporaryTableCounter.getAndIncrement();
}
/**
* Remove database state for a group.
*
* @param groupId The group id.
*/
public void removeGroup(int groupId)
{
myCreatedTables.remove(Integer.valueOf(groupId));
String indexPrefix = "INDEX_" + TableNames.getDataTableName(groupId) + "_";
for (Iterator<String> iter = myCreatedIndices.iterator(); iter.hasNext();)
{
if (iter.next().startsWith(indexPrefix))
{
iter.remove();
}
}
}
}
|
package org.embl.mobie.viewer.serialize;
import com.google.gson.*;
import org.embl.mobie.viewer.transform.AffineViewerTransform;
import org.embl.mobie.viewer.transform.NormalizedAffineViewerTransform;
import org.embl.mobie.viewer.transform.PositionViewerTransform;
import org.embl.mobie.viewer.transform.TimepointViewerTransform;
import org.embl.mobie.viewer.transform.ViewerTransform;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.TreeMap;
// TODO: maybe we don't need the serializer?!
public class ViewerTransformAdapter implements JsonSerializer< ViewerTransform >, JsonDeserializer< ViewerTransform >
{
private static Map<String, Class> nameToClass = new TreeMap<>();
private static Map<String, String> classToName = new TreeMap<>();
static {
nameToClass.put("affine", AffineViewerTransform.class);
classToName.put(AffineViewerTransform.class.getName(), "affine");
nameToClass.put("normalizedAffine", NormalizedAffineViewerTransform.class);
classToName.put(NormalizedAffineViewerTransform.class.getName(), "normalizedAffine");
nameToClass.put("position", PositionViewerTransform.class);
classToName.put(PositionViewerTransform.class.getName(), "position");
nameToClass.put("timepoint", TimepointViewerTransform.class);
classToName.put(TimepointViewerTransform.class.getName(), "timepoint");
}
@Override
public ViewerTransform deserialize( JsonElement json, Type typeOfT, JsonDeserializationContext context ) throws JsonParseException
{
final ViewerTransform viewerTransform = ( ViewerTransform ) JsonHelper.createObjectFromJsonObject( context, json, nameToClass );
return viewerTransform;
}
@Override
public JsonElement serialize( ViewerTransform viewerTransform, Type type, JsonSerializationContext context ) {
return context.serialize( viewerTransform );
}
}
|
package com.jetbrains.jsonSchema.impl;
import com.intellij.codeInsight.completion.CompletionTestCase;
import com.intellij.codeInsight.daemon.impl.HighlightInfo;
import com.intellij.json.JsonLanguage;
import com.intellij.lang.LanguageAnnotators;
import com.intellij.lang.annotation.Annotator;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.testFramework.PlatformTestUtil;
import com.intellij.util.concurrency.Semaphore;
import com.jetbrains.jsonSchema.JsonSchemaTestServiceImpl;
import com.jetbrains.jsonSchema.extension.JsonSchemaFileProvider;
import com.jetbrains.jsonSchema.extension.JsonSchemaProjectSelfProviderFactory;
import com.jetbrains.jsonSchema.ide.JsonSchemaService;
import org.junit.Assert;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
/**
* @author Irina.Chernushina on 8/29/2015.
*/
public class JsonSchemaReadTest extends CompletionTestCase {
@Override
protected String getTestDataPath() {
return PlatformTestUtil.getCommunityPath() + "/json/tests/testData/jsonSchema";
}
public void testReadSchemaItself() throws Exception {
final File file = new File(PlatformTestUtil.getCommunityPath(), "json/tests/testData/jsonSchema/schema.json");
final JsonSchemaObject read = getSchemaObject(file);
Assert.assertEquals("http://json-schema.org/draft-04/schema#", read.getId());
Assert.assertTrue(read.getDefinitionsMap().containsKey("positiveInteger"));
Assert.assertTrue(read.getProperties().containsKey("multipleOf"));
Assert.assertTrue(read.getProperties().containsKey("type"));
Assert.assertTrue(read.getProperties().containsKey("additionalProperties"));
Assert.assertEquals(2, read.getProperties().get("additionalItems").getAnyOf().size());
Assert.assertEquals("#", read.getProperties().get("additionalItems").getAnyOf().get(1).getRef());
final JsonSchemaObject required = read.getProperties().get("required");
Assert.assertEquals("#/definitions/stringArray", required.getRef());
final JsonSchemaObject minLength = read.getProperties().get("minLength");
Assert.assertEquals("#/definitions/positiveIntegerDefault0", minLength.getRef());
}
public void testMainSchemaHighlighting() {
final JsonSchemaService service = JsonSchemaService.Impl.get(myProject);
final List<JsonSchemaFileProvider> providers = new JsonSchemaProjectSelfProviderFactory().getProviders(myProject);
Assert.assertEquals(1, providers.size());
final VirtualFile mainSchema = providers.get(0).getSchemaFile();
assertNotNull(mainSchema);
assertTrue(service.isSchemaFile(mainSchema));
final Annotator annotator = new JsonSchemaAnnotator();
LanguageAnnotators.INSTANCE.addExplicitExtension(JsonLanguage.INSTANCE, annotator);
Disposer.register(getTestRootDisposable(), new Disposable() {
@Override
public void dispose() {
LanguageAnnotators.INSTANCE.removeExplicitExtension(JsonLanguage.INSTANCE, annotator);
JsonSchemaTestServiceImpl.setProvider(null);
}
});
configureByExistingFile(mainSchema);
final List<HighlightInfo> infos = doHighlighting();
for (HighlightInfo info : infos) {
if (!HighlightSeverity.INFORMATION.equals(info.getSeverity())) {
assertFalse(String.format("%s in: %s", info.getDescription(),
myEditor.getDocument().getText(new TextRange(info.getStartOffset(), info.getEndOffset()))), true);
}
}
}
private JsonSchemaObject getSchemaObject(File file) throws Exception {
Assert.assertTrue(file.exists());
final VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file);
Assert.assertNotNull(virtualFile);
return JsonSchemaReader.readFromFile(myProject, virtualFile);
}
public void testReadSchemaWithCustomTags() throws Exception {
final File file = new File(PlatformTestUtil.getCommunityPath(), "json/tests/testData/jsonSchema/withNotesCustomTag.json");
final JsonSchemaObject read = getSchemaObject(file);
Assert.assertTrue(read.getDefinitionsMap().get("common").getProperties().containsKey("id"));
}
public void testArrayItemsSchema() throws Exception {
final File file = new File(PlatformTestUtil.getCommunityPath(), "json/tests/testData/jsonSchema/arrayItemsSchema.json");
final JsonSchemaObject read = getSchemaObject(file);
final Map<String, JsonSchemaObject> properties = read.getProperties();
Assert.assertEquals(1, properties.size());
final JsonSchemaObject object = properties.get("color-hex-case");
final List<JsonSchemaObject> oneOf = object.getOneOf();
Assert.assertEquals(2, oneOf.size());
final JsonSchemaObject second = oneOf.get(1);
final List<JsonSchemaObject> list = second.getItemsSchemaList();
Assert.assertEquals(2, list.size());
final JsonSchemaObject firstItem = list.get(0);
Assert.assertEquals("#/definitions/lowerUpper", firstItem.getRef());
final JsonSchemaObject definition = read.findRelativeDefinition(firstItem.getRef());
Assert.assertNotNull(definition);
final List<Object> anEnum = definition.getEnum();
Assert.assertEquals(2, anEnum.size());
Assert.assertTrue(anEnum.contains("\"lower\""));
Assert.assertTrue(anEnum.contains("\"upper\""));
}
public void testReadSchemaWithWrongRequired() throws Exception {
doTestSchemaReadNotHung(new File(PlatformTestUtil.getCommunityPath(), "json/tests/testData/jsonSchema/WithWrongRequired.json"));
}
public void testReadSchemaWithWrongItems() throws Exception {
doTestSchemaReadNotHung(new File(PlatformTestUtil.getCommunityPath(), "json/tests/testData/jsonSchema/WithWrongItems.json"));
}
private void doTestSchemaReadNotHung(final File file) throws Exception {
// because of threading
if (Runtime.getRuntime().availableProcessors() < 2) return;
Assert.assertTrue(file.exists());
final AtomicBoolean done = new AtomicBoolean();
final AtomicReference<Exception> error = new AtomicReference<>();
final Semaphore semaphore = new Semaphore();
semaphore.down();
final Thread thread = new Thread(() -> {
try {
ReadAction.run(() -> getSchemaObject(file));
done.set(true);
}
catch (Exception e) {
error.set(e);
}
finally {
semaphore.up();
}
}, getClass().getName() + ": read test json schema " + file.getName());
thread.setDaemon(true);
try {
thread.start();
semaphore.waitFor(TimeUnit.SECONDS.toMillis(120));
if (error.get() != null) throw error.get();
Assert.assertTrue("Reading test schema hung!", done.get());
} finally {
thread.interrupt();
}
}
}
|
package com.hz;
import com.hz.players.BotPlayer;
import com.hz.players.DummyPlayer;
import com.hz.players.TicTacToe;
public class Main {
public static void main(String[] args) {
GameEngine engine = new GameEngine();
// player 1
TicTacToe playerOne = new DummyPlayer();
playerOne.setSymbol(0);
// player 2
TicTacToe playerTwo = new BotPlayer();
playerOne.setSymbol(1);
// Strategy Design Pattern
engine.setPlayerOne(playerOne);
engine.setPlayerTwo(playerTwo);
engine.startGame();
}
}
|
/*
* ICARUS2 Corpus Modeling Framework
* Copyright (C) 2014-2021 Markus Gärtner <markus.gaertner@ims.uni-stuttgart.de>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.ims.icarus2.model.manifest;
import java.util.function.IntFunction;
import java.util.function.ToIntFunction;
import de.ims.icarus2.test.ErrorCodeTest;
/**
* @author Markus Gärtner
*
*/
class ManifestErrorCodeTest implements ErrorCodeTest<ManifestErrorCode> {
/**
* @see de.ims.icarus2.test.ErrorCodeTest#createErrorCodes()
*/
@Override
public ManifestErrorCode[] createErrorCodes() {
return ManifestErrorCode.values();
}
/**
* @see de.ims.icarus2.test.ErrorCodeTest#createCodeParser()
*/
@Override
public IntFunction<ManifestErrorCode> createCodeParser() {
return ManifestErrorCode::forCode;
}
/**
* @see de.ims.icarus2.test.ErrorCodeTest#createCodeGenerator()
*/
@Override
public ToIntFunction<ManifestErrorCode> createCodeGenerator() {
return ManifestErrorCode::code;
}
}
|
/*
* Origin of the benchmark:
* license: 4-clause BSD (see /java/jbmc-regression/LICENSE)
* repo: https://github.com/diffblue/cbmc.git
* branch: develop
* directory: regression/cbmc-java/ClassCastException3
* The benchmark was taken from the repo: 24 January 2018
*/
class A {}
class B {}
public class Main {
public static void main(String[] args) {
try {
Object a = new A();
B b = (B) a;
} catch (Exception exc) {
assert false;
}
}
}
|
package com.czy.ext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.stereotype.Component;
/* InstantiationAwareBeanPostProcessor后置处理器是spring的一个扩展点,可以控制bean的属性注入 */
@Component
public class MyInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor {
@Override
public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
return true;
}
}
|
package com.zkejid.constructor.managedimplementations.api.v1;
/**
* Attribution of implementation. Developer of the {@link ImplementationProducer} defines
* set of available and required attributions for given producer. User provides
* the set of attributions he desires to get on implementation of requested interface.
* Factory returns the most appropriate implementation according to given set of attributions.
* <p>
* Developer of the {@link ImplementationProducer} may define own implementation of attribution
* or may reuse existing attribution according to it's semantic.
*/
public interface Attribution {
}
|
/*
* Copyright (c) 2016-2017, Adam <Adam@sigterm.info>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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 net.runelite.client;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import com.google.common.annotations.VisibleForTesting;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import java.io.File;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.util.Locale;
import javax.annotation.Nullable;
import javax.inject.Provider;
import javax.inject.Singleton;
import javax.swing.SwingUtilities;
import joptsimple.ArgumentAcceptingOptionSpec;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import joptsimple.util.EnumConverter;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import net.runelite.api.Client;
import net.runelite.client.account.SessionManager;
import net.runelite.client.callback.Hooks;
import net.runelite.client.chat.ChatMessageManager;
import net.runelite.client.chat.CommandManager;
import net.runelite.client.config.ConfigManager;
import net.runelite.client.discord.DiscordService;
import net.runelite.client.eventbus.EventBus;
import net.runelite.client.game.ClanManager;
import net.runelite.client.game.ItemManager;
import net.runelite.client.game.LootManager;
import net.runelite.client.game.chatbox.ChatboxPanelManager;
import net.runelite.client.menus.MenuManager;
import net.runelite.client.plugins.PluginManager;
import net.runelite.client.rs.ClientLoader;
import net.runelite.client.rs.ClientUpdateCheckMode;
import net.runelite.client.ui.ClientUI;
import net.runelite.client.ui.DrawManager;
import net.runelite.client.ui.FatalErrorDialog;
import net.runelite.client.ui.SplashScreen;
import net.runelite.client.ui.overlay.OverlayManager;
import net.runelite.client.ui.overlay.OverlayRenderer;
import net.runelite.client.ui.overlay.WidgetOverlay;
import net.runelite.client.ui.overlay.infobox.InfoBoxManager;
import net.runelite.client.ui.overlay.infobox.InfoBoxOverlay;
import net.runelite.client.ui.overlay.tooltip.TooltipOverlay;
import net.runelite.client.ui.overlay.worldmap.WorldMapOverlay;
import net.runelite.client.ws.PartyService;
import org.slf4j.LoggerFactory;
@Singleton
@Slf4j
public class RuneLite
{
public static final File RUNELITE_DIR = new File(System.getProperty("user.home"), ".runelite");
public static final File CACHE_DIR = new File(RUNELITE_DIR, "cache");
public static final File PROFILES_DIR = new File(RUNELITE_DIR, "profiles");
public static final File SCREENSHOT_DIR = new File(RUNELITE_DIR, "screenshots");
public static final File LOGS_DIR = new File(RUNELITE_DIR, "logs");
@Getter
private static Injector injector;
@Inject
private PluginManager pluginManager;
@Inject
private EventBus eventBus;
@Inject
private ConfigManager configManager;
@Inject
private DrawManager drawManager;
@Inject
private SessionManager sessionManager;
@Inject
private DiscordService discordService;
@Inject
private ClientSessionManager clientSessionManager;
@Inject
private ClientUI clientUI;
@Inject
private InfoBoxManager infoBoxManager;
@Inject
private OverlayManager overlayManager;
@Inject
private Provider<PartyService> partyService;
@Inject
private Provider<ItemManager> itemManager;
@Inject
private Provider<OverlayRenderer> overlayRenderer;
@Inject
private Provider<ClanManager> clanManager;
@Inject
private Provider<ChatMessageManager> chatMessageManager;
@Inject
private Provider<MenuManager> menuManager;
@Inject
private Provider<CommandManager> commandManager;
@Inject
private Provider<InfoBoxOverlay> infoBoxOverlay;
@Inject
private Provider<TooltipOverlay> tooltipOverlay;
@Inject
private Provider<WorldMapOverlay> worldMapOverlay;
@Inject
private Provider<LootManager> lootManager;
@Inject
private Provider<ChatboxPanelManager> chatboxPanelManager;
@Inject
private Provider<Hooks> hooks;
@Inject
@Nullable
private Client client;
public static void main(String[] args) throws Exception
{
Locale.setDefault(Locale.ENGLISH);
final OptionParser parser = new OptionParser();
parser.accepts("developer-mode", "Enable developer tools");
parser.accepts("debug", "Show extra debugging output");
final ArgumentAcceptingOptionSpec<ClientUpdateCheckMode> updateMode = parser
.accepts("rs", "Select client type")
.withRequiredArg()
.ofType(ClientUpdateCheckMode.class)
.defaultsTo(ClientUpdateCheckMode.AUTO)
.withValuesConvertedBy(new EnumConverter<ClientUpdateCheckMode>(ClientUpdateCheckMode.class)
{
@Override
public ClientUpdateCheckMode convert(String v)
{
return super.convert(v.toUpperCase());
}
});
parser.accepts("help", "Show this text").forHelp();
OptionSet options = parser.parse(args);
if (options.has("help"))
{
parser.printHelpOn(System.out);
System.exit(0);
}
if (options.has("debug"))
{
final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
logger.setLevel(Level.DEBUG);
}
Thread.setDefaultUncaughtExceptionHandler((thread, throwable) ->
{
log.error("Uncaught exception:", throwable);
if (throwable instanceof AbstractMethodError)
{
log.error("Classes are out of date; Build with maven again.");
}
});
SplashScreen.init();
SplashScreen.stage(0, "Retrieving client", "");
try
{
final ClientLoader clientLoader = new ClientLoader(options.valueOf(updateMode));
new Thread(() ->
{
clientLoader.get();
ClassPreloader.preload();
}, "Preloader").start();
final boolean developerMode = options.has("developer-mode") && RuneLiteProperties.getLauncherVersion() == null;
if (developerMode)
{
boolean assertions = false;
assert assertions = true;
if (!assertions)
{
SwingUtilities.invokeLater(() ->
new FatalErrorDialog("Developers should enable assertions; Add `-ea` to your JVM arguments`")
.addBuildingGuide()
.open());
return;
}
}
PROFILES_DIR.mkdirs();
final long start = System.currentTimeMillis();
injector = Guice.createInjector(new RuneLiteModule(
clientLoader,
developerMode));
injector.getInstance(RuneLite.class).start();
final long end = System.currentTimeMillis();
final RuntimeMXBean rb = ManagementFactory.getRuntimeMXBean();
final long uptime = rb.getUptime();
log.info("Client initialization took {}ms. Uptime: {}ms", end - start, uptime);
}
catch (Exception e)
{
log.warn("Failure during startup", e);
SwingUtilities.invokeLater(() ->
new FatalErrorDialog("RuneLite has encountered an unexpected error during startup.")
.open());
}
finally
{
SplashScreen.stop();
}
}
public void start() throws Exception
{
// Load RuneLite or Vanilla client
final boolean isOutdated = client == null;
if (!isOutdated)
{
// Inject members into client
injector.injectMembers(client);
}
SplashScreen.stage(.57, null, "Loading configuration");
// Load user configuration
configManager.load();
// Load the session, including saved configuration
sessionManager.loadSession();
// Tell the plugin manager if client is outdated or not
pluginManager.setOutdated(isOutdated);
// Load the plugins, but does not start them yet.
// This will initialize configuration
pluginManager.loadCorePlugins();
SplashScreen.stage(.70, null, "Finalizing configuration");
// Plugins have provided their config, so set default config
// to main settings
pluginManager.loadDefaultPluginConfiguration();
// Start client session
clientSessionManager.start();
SplashScreen.stage(.75, null, "Starting core interface");
// Initialize UI
clientUI.init(this);
// Initialize Discord service
discordService.init();
// Register event listeners
eventBus.register(clientUI);
eventBus.register(pluginManager);
eventBus.register(overlayManager);
eventBus.register(drawManager);
eventBus.register(infoBoxManager);
if (!isOutdated)
{
// Initialize chat colors
chatMessageManager.get().loadColors();
eventBus.register(partyService.get());
eventBus.register(overlayRenderer.get());
eventBus.register(clanManager.get());
eventBus.register(itemManager.get());
eventBus.register(menuManager.get());
eventBus.register(chatMessageManager.get());
eventBus.register(commandManager.get());
eventBus.register(lootManager.get());
eventBus.register(chatboxPanelManager.get());
eventBus.register(hooks.get());
// Add core overlays
WidgetOverlay.createOverlays(client).forEach(overlayManager::add);
overlayManager.add(infoBoxOverlay.get());
overlayManager.add(worldMapOverlay.get());
overlayManager.add(tooltipOverlay.get());
}
// Start plugins
pluginManager.startCorePlugins();
SplashScreen.stop();
clientUI.show();
}
public void shutdown()
{
configManager.sendConfig();
clientSessionManager.shutdown();
discordService.close();
}
@VisibleForTesting
public static void setInjector(Injector injector)
{
RuneLite.injector = injector;
}
}
|
/*
* Copyright Strimzi authors.
* License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html).
*/
package io.strimzi.kafka.bridge.http.base;
import io.strimzi.test.container.StrimziKafkaContainer;
import io.micrometer.core.instrument.MeterRegistry;
import io.strimzi.kafka.bridge.HealthChecker;
import io.strimzi.kafka.bridge.JmxCollectorRegistry;
import io.strimzi.kafka.bridge.MetricsReporter;
import io.strimzi.kafka.bridge.clients.BasicKafkaClient;
import io.strimzi.kafka.bridge.config.BridgeConfig;
import io.strimzi.kafka.bridge.config.KafkaConfig;
import io.strimzi.kafka.bridge.config.KafkaConsumerConfig;
import io.strimzi.kafka.bridge.config.KafkaProducerConfig;
import io.strimzi.kafka.bridge.facades.AdminClientFacade;
import io.strimzi.kafka.bridge.http.HttpBridge;
import io.strimzi.kafka.bridge.http.HttpConfig;
import io.strimzi.kafka.bridge.http.services.BaseService;
import io.strimzi.kafka.bridge.http.services.ConsumerService;
import io.strimzi.kafka.bridge.http.services.ProducerService;
import io.strimzi.kafka.bridge.http.services.SeekService;
import io.strimzi.kafka.bridge.utils.Urls;
import io.vertx.core.Vertx;
import io.vertx.ext.web.client.WebClient;
import io.vertx.ext.web.client.WebClientOptions;
import io.vertx.junit5.VertxExtension;
import io.vertx.junit5.VertxTestContext;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.extension.ExtendWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import static io.strimzi.kafka.bridge.Constants.HTTP_BRIDGE;
@ExtendWith(VertxExtension.class)
@SuppressWarnings({"checkstyle:JavaNCSS"})
@Tag(HTTP_BRIDGE)
public abstract class HttpBridgeITAbstract {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpBridgeITAbstract.class);
protected static Map<String, Object> config = new HashMap<>();
// for periodic/multiple messages test
protected static final int PERIODIC_MAX_MESSAGE = 10;
protected static final int PERIODIC_DELAY = 1000;
protected static final int MULTIPLE_MAX_MESSAGE = 10;
protected static final int TEST_TIMEOUT = 60;
protected int count;
protected String topic;
public static StrimziKafkaContainer kafkaContainer = null;
protected static final String BRIDGE_EXTERNAL_ENV = System.getenv().getOrDefault("EXTERNAL_BRIDGE", "FALSE");
protected static final String KAFKA_EXTERNAL_ENV = System.getenv().getOrDefault("EXTERNAL_KAFKA", "FALSE");
protected static String kafkaUri;
protected static long timeout = 5L;
static {
if ("FALSE".equals(KAFKA_EXTERNAL_ENV)) {
kafkaContainer = new StrimziKafkaContainer();
kafkaContainer.start();
kafkaUri = kafkaContainer.getBootstrapServers();
adminClientFacade = AdminClientFacade.create(kafkaUri);
} else {
// else use external kafka
kafkaUri = "localhost:9092";
}
config.put(KafkaConfig.KAFKA_CONFIG_PREFIX + ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaUri);
config.put(KafkaConsumerConfig.KAFKA_CONSUMER_CONFIG_PREFIX + ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
config.put(KafkaProducerConfig.KAFKA_PRODUCER_CONFIG_PREFIX + ProducerConfig.MAX_BLOCK_MS_CONFIG, "10000");
config.put(HttpConfig.HTTP_CONSUMER_TIMEOUT, timeout);
config.put(BridgeConfig.BRIDGE_ID, "my-bridge");
}
protected static Vertx vertx;
protected static WebClient client;
protected static BasicKafkaClient basicKafkaClient;
protected static AdminClientFacade adminClientFacade;
protected static HttpBridge httpBridge;
protected static BridgeConfig bridgeConfig;
protected static MeterRegistry meterRegistry = null;
protected static JmxCollectorRegistry jmxCollectorRegistry = null;
protected BaseService baseService() {
return BaseService.getInstance(client);
}
protected ConsumerService consumerService() {
return ConsumerService.getInstance(client);
}
protected SeekService seekService() {
return SeekService.getInstance(client);
}
protected ProducerService producerService() {
return ProducerService.getInstance(client);
}
@BeforeAll
static void beforeAll(VertxTestContext context) {
vertx = Vertx.vertx();
adminClientFacade = AdminClientFacade.create(kafkaUri);
basicKafkaClient = new BasicKafkaClient(kafkaUri);
LOGGER.info("Environment variable EXTERNAL_BRIDGE:" + BRIDGE_EXTERNAL_ENV);
if ("FALSE".equals(BRIDGE_EXTERNAL_ENV)) {
bridgeConfig = BridgeConfig.fromMap(config);
httpBridge = new HttpBridge(bridgeConfig, new MetricsReporter(jmxCollectorRegistry, meterRegistry));
httpBridge.setHealthChecker(new HealthChecker());
LOGGER.info("Deploying in-memory bridge");
vertx.deployVerticle(httpBridge, context.succeeding(id -> context.completeNow()));
} else {
context.completeNow();
// else we create external bridge from the OS invoked by `.jar`
}
client = WebClient.create(vertx, new WebClientOptions()
.setDefaultHost(Urls.BRIDGE_HOST)
.setDefaultPort(Urls.BRIDGE_PORT)
);
}
@AfterAll
static void afterAll(VertxTestContext context) {
if ("FALSE".equals(BRIDGE_EXTERNAL_ENV)) {
vertx.close(context.succeeding(arg -> context.completeNow()));
} else {
// if we running external bridge
context.completeNow();
}
}
@BeforeEach
void setUpEach() {
topic = "my-topic-" + new Random().nextInt(Integer.MAX_VALUE);
}
@AfterEach
void cleanUp() throws InterruptedException, ExecutionException {
Collection<String> topics = adminClientFacade.listTopic();
LOGGER.info("Kafka still contains {}", topics);
adminClientFacade.deleteTopics(topics);
}
protected String generateRandomConsumerGroupName() {
int salt = new Random().nextInt(Integer.MAX_VALUE);
return "my-group-" + salt;
}
}
|
package com.cgfay.filterlibrary.glfilter.base;
import android.content.Context;
import android.graphics.Bitmap;
import android.opengl.GLES30;
import com.cgfay.filterlibrary.glfilter.utils.OpenGLUtils;
/**
* 应用查找表(3D LUT)滤镜(512 x 512)
* Created by cain.huang on 2018/3/8.
*/
public class GLImage512LookupTableFilter extends GLImageFilter {
private float mStrength;
private int mStrengthHandle;
private int mLookupTableTextureHandle;
private int mCurveTexture = OpenGLUtils.GL_NOT_INIT;
public GLImage512LookupTableFilter(Context context) {
this(context, VERTEX_SHADER, OpenGLUtils.getShaderFromAssets(context,
"shader/base/fragment_lookup_table_512.glsl"));
}
public GLImage512LookupTableFilter(Context context, String vertexShader, String fragmentShader) {
super(context, vertexShader, fragmentShader);
}
@Override
public void initProgramHandle() {
super.initProgramHandle();
mStrengthHandle = GLES30.glGetUniformLocation(mProgramHandle, "strength");
mLookupTableTextureHandle = GLES30.glGetUniformLocation(mProgramHandle, "lookupTableTexture");
setStrength(1.0f);
}
@Override
public void onDrawFrameBegin() {
super.onDrawFrameBegin();
OpenGLUtils.bindTexture(mLookupTableTextureHandle, mCurveTexture, 1);
GLES30.glUniform1f(mStrengthHandle, mStrength);
}
@Override
public void release() {
GLES30.glDeleteTextures(1, new int[]{ mCurveTexture }, 0);
super.release();
}
/**
* 设置变化值,0.0f ~ 1.0f
* @param value
*/
public void setStrength(float value) {
float opacity;
if (value <= 0) {
opacity = 0.0f;
} else if (value > 1.0f) {
opacity = 1.0f;
} else {
opacity = value;
}
mStrength = opacity;
setFloat(mStrengthHandle, mStrength);
}
public void setLookupBitmap(Bitmap bitmap){
if (mCurveTexture != OpenGLUtils.GL_NOT_INIT){
GLES30.glDeleteTextures(1, new int[]{ mCurveTexture }, 0);
}
mCurveTexture = OpenGLUtils.createTexture(bitmap);
}
}
|
package com.computician.janusclientapi;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by ben.trent on 6/25/2015.
*/
public class JanusCreateSessionTransaction implements ITransactionCallbacks {
private final IJanusSessionCreationCallbacks callbacks;
public JanusCreateSessionTransaction(IJanusSessionCreationCallbacks callbacks) {
this.callbacks = callbacks;
}
public TransactionType getTransactionType() {
return TransactionType.create;
}
@Override
public void reportSuccess(JSONObject obj) {
try {
JanusMessageType type = JanusMessageType.fromString(obj.getString("janus"));
if (type != JanusMessageType.success) {
callbacks.onCallbackError(obj.getJSONObject("error").getString("reason"));
} else {
callbacks.onSessionCreationSuccess((obj));
}
} catch (JSONException ex) {
callbacks.onCallbackError(ex.getMessage());
}
}
}
|
package com.huaweicloud.sdk.ecs.v2.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
import java.util.Objects;
/**
*
*/
public class PrePaidServerEipBandwidth {
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value="size")
private Integer size;
/**
* 带宽的共享类型。 共享类型枚举:PER,表示独享。WHOLE,表示共享。
*/
public static class SharetypeEnum {
/**
* Enum PER for value: "PER"
*/
public static final SharetypeEnum PER = new SharetypeEnum("PER");
/**
* Enum WHOLE for value: "WHOLE"
*/
public static final SharetypeEnum WHOLE = new SharetypeEnum("WHOLE");
public static final Map<String, SharetypeEnum> staticFields = new HashMap<String, SharetypeEnum>() {
{
put("PER", PER);
put("WHOLE", WHOLE);
}
};
private String value;
SharetypeEnum(String value) {
this.value = value;
}
@Override
@JsonValue
public String toString() {
return String.valueOf(value);
}
@JsonCreator
public static SharetypeEnum fromValue(String value) {
if( value == null ){
return null;
}
SharetypeEnum result = staticFields.get(value);
if (result == null) {
result = staticFields.putIfAbsent(value, new SharetypeEnum(value));
if (result == null) {
result = staticFields.get(value);
}
}
return result;
}
public static SharetypeEnum valueOf(String value) {
if( value == null ){
return null;
}
SharetypeEnum result = staticFields.get(value);
if (result != null) {
return result;
}
throw new IllegalArgumentException("Unexpected value '" + value + "'");
}
@Override
public boolean equals(Object obj) {
if (obj != null && obj instanceof SharetypeEnum) {
return this.value.equals(((SharetypeEnum) obj).value);
}
return false;
}
@Override
public int hashCode() {
return this.value.hashCode();
}
}
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value="sharetype")
private SharetypeEnum sharetype;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value="chargemode")
private String chargemode;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value="id")
private String id;
public PrePaidServerEipBandwidth withSize(Integer size) {
this.size = size;
return this;
}
/**
* 功能说明:带宽大小 带宽(Mbit/s),取值范围为[1,2000]。 调整带宽时的最小单位会根据带宽范围不同存在差异。 - 小于等于300Mbit/s:默认最小单位为1Mbit/s。 - 300Mbit/s~1000Mbit/s:默认最小单位为50Mbit/s。 - 大于1000Mbit/s:默认最小单位为500Mbit/s。 > 说明: > > 如果share_type是PER,该参数必选项;如果share_type是WHOLE并且id有值,该参数会忽略。
* minimum: 1
* maximum: 2000
* @return size
*/
public Integer getSize() {
return size;
}
public void setSize(Integer size) {
this.size = size;
}
public PrePaidServerEipBandwidth withSharetype(SharetypeEnum sharetype) {
this.sharetype = sharetype;
return this;
}
/**
* 带宽的共享类型。 共享类型枚举:PER,表示独享。WHOLE,表示共享。
* @return sharetype
*/
public SharetypeEnum getSharetype() {
return sharetype;
}
public void setSharetype(SharetypeEnum sharetype) {
this.sharetype = sharetype;
}
public PrePaidServerEipBandwidth withChargemode(String chargemode) {
this.chargemode = chargemode;
return this;
}
/**
* 带宽的计费类型。 - 未传该字段,表示按带宽计费。 - 字段值为空,表示按带宽计费。 - 字段值为“traffic”,表示按流量计费。 - 字段为其它值,会导致创建云服务器失败。 > 说明: > > 如果share_type是WHOLE并且id有值,该参数会忽略。
* @return chargemode
*/
public String getChargemode() {
return chargemode;
}
public void setChargemode(String chargemode) {
this.chargemode = chargemode;
}
public PrePaidServerEipBandwidth withId(String id) {
this.id = id;
return this;
}
/**
* 带宽ID,创建WHOLE类型带宽的弹性IP时可以指定之前的共享带宽创建。 取值范围:WHOLE类型的带宽ID。 > 说明: > > 当创建WHOLE类型的带宽时,该字段必选。
* @return id
*/
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PrePaidServerEipBandwidth prePaidServerEipBandwidth = (PrePaidServerEipBandwidth) o;
return Objects.equals(this.size, prePaidServerEipBandwidth.size) &&
Objects.equals(this.sharetype, prePaidServerEipBandwidth.sharetype) &&
Objects.equals(this.chargemode, prePaidServerEipBandwidth.chargemode) &&
Objects.equals(this.id, prePaidServerEipBandwidth.id);
}
@Override
public int hashCode() {
return Objects.hash(size, sharetype, chargemode, id);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class PrePaidServerEipBandwidth {\n");
sb.append(" size: ").append(toIndentedString(size)).append("\n");
sb.append(" sharetype: ").append(toIndentedString(sharetype)).append("\n");
sb.append(" chargemode: ").append(toIndentedString(chargemode)).append("\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
package org.aanguita.jtcpserver.clientserver.server;
import java.io.Serializable;
import java.net.Socket;
/**
* Light server interface, for implementing a connection-less server that answers generic client requests
*/
public interface LightServerActionObject {
/**
* A client makes a new request
*
* @param clientSocket the socket of the client
* @param object the generic object sent by the client
* @return the response to the client request
* @throws Exception there was some kind of error while processing the request.
*/
public Serializable newClientRequest(Socket clientSocket, Object object) throws Exception;
/**
* Error in the connection server. The connection server had to be closed due to IO problems opening the tcp server and could not be restarted.
* No new connections will be accepted, although connected clients will remain connected
*
* @param e exception that caused the error
*/
public void TCPServerError(Exception e);
}
|
/**
*
*/
package com.manan.busservice.service.operations;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.manan.busservice.dto.mapper.operations.BookingMapper;
import com.manan.busservice.dto.model.operations.Booking;
import com.manan.busservice.exception.BusAppException;
import com.manan.busservice.jpa.repository.Repositories;
import com.manan.busservice.model.operations.BookingEntity;
import com.manan.busservice.response.ResponseEntity;
import com.manan.busservice.service.Services;
import com.manan.busservice.utility.DateUtils;
/**
* @author Manan Sanghvi
*
*/
@Component
public class BookingServiceImpl implements Services.BookingService {
private Repositories.Container repos;
@Autowired
public BookingServiceImpl(Repositories.Container repos) {
this.repos = repos;
}
private Optional<BookingEntity> optional;
private void findByBookingCode(String bookingCode) {
optional = repos.bookingRepository.findByBookingCode(bookingCode);
}
@Override
public Booking newBooking(Booking booking) {
findByBookingCode(booking.getBookingCode());
if(optional.isEmpty()) {
try {
return BookingMapper.toBooking(repos.bookingRepository.save(new BookingEntity()
.setBookingCode(booking.getBookingCode())
.setCancelled(false)
.setDepartureTime(booking.getDepartureTime())
.setLastUpdate(DateUtils.today())
.setTotalCost(booking.getTotalCost())
.setBus(repos.busRepository.findByBusCode(booking.getBus().getBusCode())
.get())
.setTripCode(repos.tripRepository.findByCode(booking.getTripCode().getCode())
.get())
.setPassenger(repos.userRepository.findByUserName(booking.getPassenger().getUserName())
.get())));
} catch(RuntimeException re) {
throw new BusAppException.BadRequestException(ResponseEntity.BOOKING);
}
}
throw new BusAppException.DuplicateEntityException(ResponseEntity.BOOKING);
}
@Override
public Booking editBooking(Booking booking) {
findByBookingCode(booking.getBookingCode());
if(optional.isPresent()) {
try {
BookingEntity bookingEntity = optional.get();
return BookingMapper.toBooking(repos.bookingRepository.save(bookingEntity
.setDepartureTime(booking.getDepartureTime())
.setLastUpdate(DateUtils.today())
.setTotalCost(booking.getTotalCost())
.setTripCode(repos.tripRepository.findByCode(booking.getTripCode().getCode())
.get())
.setBus(repos.busRepository.findByBusCode(booking.getBus().getBusCode())
.get())
));
} catch(RuntimeException re) {
throw new BusAppException.BadRequestException(ResponseEntity.BOOKING);
}
}
throw new BusAppException.EntityNotFoundException(ResponseEntity.BOOKING);
}
@Override
public void cancelBooking(String bookingCode) {
findByBookingCode(bookingCode);
if(optional.isPresent()) {
BookingEntity bookingEntity = optional.get();
BookingMapper.toBooking(repos.bookingRepository.save(bookingEntity
.setCancelled(true)));
}
throw new BusAppException.EntityNotFoundException(ResponseEntity.BOOKING);
}
@Override
public Booking viewBooking(String bookingCode) {
findByBookingCode(bookingCode);
if(optional.isPresent()) {
return BookingMapper.toBooking(optional.get());
}
throw new BusAppException.EntityNotFoundException(ResponseEntity.BOOKING);
}
@Override
public List<Booking> viewAllBookingByUser(String userName) {
return BookingMapper.toBooking(repos.bookingRepository.findByPassenger(repos.userRepository.findByUserName(userName).get()));
}
@Override
public List<Booking> viewAllBookings() {
return BookingMapper.toBooking(repos.bookingRepository.findAll());
}
@Override
public List<Booking> viewBookingsByTrip(String tripCode) {
return BookingMapper.toBooking(repos.bookingRepository.findByTripCode(repos.tripRepository.findByCode(tripCode)
.get()));
}
}
|
/**
* Copyright 2017 SmartBear Software
*
* <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 io.swagger.v3.oas.annotations.security;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Inherited;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* The annotation may be applied at class or method level, or in {@link
* io.swagger.v3.oas.annotations.Operation#security()} ()} to define security requirements for the
* single operation (when applied at method level) or for all operations of a class (when applied at
* class level).
*
* <p>It can also be used in {@link io.swagger.v3.oas.annotations.OpenAPIDefinition#security()} to
* define spec level security.
*
* @see <a target="_new"
* href="https://github.com/OAI/OpenAPI-Specification/blob/3.0.1/versions/3.0.1.md#securityRequirementObject">Security
* Requirement (OpenAPI specification)</a>
* @see io.swagger.v3.oas.annotations.OpenAPIDefinition
* @see io.swagger.v3.oas.annotations.Operation
*/
@Target({METHOD, TYPE, ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(SecurityRequirements.class)
@Inherited
public @interface SecurityRequirement {
/**
* This name must correspond to a declared SecurityRequirement.
*
* @return String name
*/
String name();
/**
* If the security scheme is of type "oauth2" or "openIdConnect", then the value is a list of
* scope names required for the execution. For other security scheme types, the array must be
* empty.
*
* @return String array of scopes
*/
String[] scopes() default {};
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.