text
stringlengths 7
1.01M
|
|---|
package org.examples.ssh.util;
import java.text.MessageFormat;
import java.util.Iterator;
import java.util.Map;
/**
* @Title: SqlUtil.java
* @Package org.examples.spring.util
* @Description: TODO(用一句话描述该文件做什么)
* @author dusf
* @date 2016年3月25日 上午11:48:35
*/
public class SqlUtil {
public static final String DATABSE_TYPE_MYSQL ="mysql";
public static final String DATABSE_TYPE_ORACLE ="oracle";
public static final String DATABSE_TYPE_SQLSERVER ="sqlserver";
/**
* 分页SQL
*/
public static final String MYSQL_SQL = "select * from ( {0}) sel_tab00 limit {1},{2}"; //mysql
public static final String POSTGRE_SQL = "select * from ( {0}) sel_tab00 limit {2} offset {1}";//postgresql
public static final String ORACLE_SQL = "select * from (select row_.*,rownum rownum_ from ({0}) row_ where rownum <= {1}) where rownum_>{2}"; //oracle
public static final String SQLSERVER_SQL = "select * from ( select row_number() over(order by tempColumn) tempRowNumber, * from (select top {1} tempColumn = 0, {0}) t ) tt where tempRowNumber > {2}"; //sqlserver
//add-begin--Author:luobaoli Date:20150620 for:增加各个数据库获取表的SQL和获取指定表列的SQL
/**
* 获取所有表的SQL
*/
public static final String MYSQL_ALLTABLES_SQL = "select distinct table_name from information_schema.columns where table_schema = {0}";
public static final String POSTGRE__ALLTABLES_SQL = "SELECT distinct c.relname AS table_name FROM pg_class c";
public static final String ORACLE__ALLTABLES_SQL = "select distinct colstable.table_name as table_name from user_tab_cols colstable";
public static final String SQLSERVER__ALLTABLES_SQL= "select distinct c.name as table_name from sys.objects c";
/**
* 获取指定表的所有列名
*/
public static final String MYSQL_ALLCOLUMNS_SQL = "select column_name from information_schema.columns where table_name = {0} and table_schema = {1}";
public static final String POSTGRE_ALLCOLUMNS_SQL = "select table_name from information_schema.columns where table_name = {0}";
public static final String ORACLE_ALLCOLUMNS_SQL = "select column_name from all_tab_columns where table_name ={0}";
public static final String SQLSERVER_ALLCOLUMNS_SQL = "select name from syscolumns where id={0}";
//add-end--Author:luobaoli Date:20150620 for:增加各个数据库获取表的SQL和获取指定表列的SQL
/**
* 获取全sql
* @param sql
* @param params
* @return
*/
public static String getFullSql(String sql,Map params){
StringBuilder sqlB = new StringBuilder();
sqlB.append("SELECT t.* FROM ( ");
sqlB.append(sql+" ");
sqlB.append(") t ");
if (params!=null&¶ms.size() >= 1) {
sqlB.append("WHERE 1=1 ");
Iterator it = params.keySet().iterator();
while (it.hasNext()) {
String key = String.valueOf(it.next());
String value = String.valueOf(params.get(key));
if (!StringUtil.isEmpty(value) && !"null".equals(value)) {
sqlB.append(" AND ");
sqlB.append(" " + key + value );
}
}
}
return sqlB.toString();
}
/**
* 获取求数量sql
* @param sql
* @param params
* @return
*/
public static String getCountSql(String sql, Map params) {
String querySql = getFullSql(sql,params);
querySql = "SELECT COUNT(*) FROM ("+querySql+") t2";
return querySql;
}
private static int getAfterSelectInsertPoint(String sql) {
int selectIndex = sql.toLowerCase().indexOf("select");
int selectDistinctIndex = sql.toLowerCase().indexOf("select distinct");
return selectIndex + (selectDistinctIndex == selectIndex ? 15 : 6);
}
//add-begin--Author:luobaoli Date:20150620 for:增加各个数据库获取表的SQL和获取指定表列的SQL
public static String getAllTableSql(String dbType,String ... param){
if(StringUtil.isNotEmpty(dbType)){
if(dbType.equals(DATABSE_TYPE_MYSQL)){
return MessageFormat.format(MYSQL_ALLTABLES_SQL, param);
}else if(dbType.equals(DATABSE_TYPE_ORACLE)){
return ORACLE__ALLTABLES_SQL;
}else if(dbType.equals(DATABSE_TYPE_SQLSERVER)){
return SQLSERVER__ALLTABLES_SQL;
}
}
return null;
}
public static String getAllCloumnSql(String dbType,String ... param){
if(StringUtil.isNotEmpty(dbType)){
if(dbType.equals(DATABSE_TYPE_MYSQL)){
return MessageFormat.format(MYSQL_ALLCOLUMNS_SQL, param);
}else if(dbType.equals(DATABSE_TYPE_ORACLE)){
return MessageFormat.format(ORACLE_ALLCOLUMNS_SQL, param);
}else if(dbType.equals(DATABSE_TYPE_SQLSERVER)){
return MessageFormat.format(SQLSERVER_ALLCOLUMNS_SQL, param);
}
}
return null;
}
//add-end--Author:luobaoli Date:20150620 for:增加各个数据库获取表的SQL和获取指定表列的SQL
}
|
package collection1;
import java.util.*;
class Student1 {
private int rno;
private String name;
Student1(int rno, String name) {
this.rno = rno;
this.name = name;
}
public int hashCode() {
return rno;
}
public boolean equals(Object o) {
Student1 s = (Student1) o;
if (rno == s.rno)
return true;
else
return false;
}
void printStudent1() {
System.out.println(rno + "" + name);
}
}
public class HashSet2 {
public static void main(String[] args) {
HashSet<Student1> hs = new HashSet<Student1>();
hs.add(new Student1(01, "aamir"));
hs.add(new Student1(02, "khan"));
hs.add(new Student1(03, "David"));
hs.add(new Student1(04, "Sam"));
Iterator<Student1> i = hs.iterator();
while (i.hasNext()) {
System.out.println(i.next());
}
}
}
|
package cn.suniper.mesh.transport.tcp;
import com.netflix.client.RequestSpecificRetryHandler;
import org.junit.Test;
import java.net.SocketException;
import java.net.URI;
import static org.junit.Assert.*;
/**
* @author Rao Mengnan
* on 2018/7/28.
*/
public class AsyncLoadBalancingTcpClientTest {
@Test
public void getRequestSpecificRetryHandler() throws Exception {
TcpRequest request = new TcpRequest.Builder(new URI("http://127.0.0.1"), null, true).build();
AsyncLoadBalancingTcpClient client = new AsyncLoadBalancingTcpClient();
RequestSpecificRetryHandler handler = client.getRequestSpecificRetryHandler(request, null);
assertTrue(handler.isRetriableException(new SocketException(), false));
request = new TcpRequest.Builder(new URI("http://127.0.0.1"), null, false).build();
handler = client.getRequestSpecificRetryHandler(request, null);
assertFalse(handler.isRetriableException(new SocketException(), false));
}
}
|
package eu.bcvsolutions.idm.extras.scheduler.task.impl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import eu.bcvsolutions.idm.acc.dto.SysRoleSystemAttributeDto;
import eu.bcvsolutions.idm.acc.dto.SysRoleSystemDto;
import eu.bcvsolutions.idm.acc.dto.SysSystemDto;
import eu.bcvsolutions.idm.acc.dto.filter.SysRoleSystemAttributeFilter;
import eu.bcvsolutions.idm.acc.dto.filter.SysRoleSystemFilter;
import eu.bcvsolutions.idm.acc.service.api.SysRoleSystemAttributeService;
import eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto;
import eu.bcvsolutions.idm.core.api.dto.IdmRoleCatalogueDto;
import eu.bcvsolutions.idm.core.api.dto.IdmRoleCompositionDto;
import eu.bcvsolutions.idm.core.api.dto.IdmRoleDto;
import eu.bcvsolutions.idm.core.api.dto.IdmRoleFormAttributeDto;
import eu.bcvsolutions.idm.core.api.dto.IdmRoleGuaranteeDto;
import eu.bcvsolutions.idm.core.api.dto.IdmRoleGuaranteeRoleDto;
import eu.bcvsolutions.idm.core.api.dto.filter.IdmRoleFilter;
import eu.bcvsolutions.idm.core.api.dto.filter.IdmRoleFormAttributeFilter;
import eu.bcvsolutions.idm.core.api.dto.filter.IdmRoleGuaranteeFilter;
import eu.bcvsolutions.idm.core.api.dto.filter.IdmRoleGuaranteeRoleFilter;
import eu.bcvsolutions.idm.core.api.service.IdmIdentityService;
import eu.bcvsolutions.idm.core.api.service.IdmRoleCatalogueService;
import eu.bcvsolutions.idm.core.api.service.IdmRoleCompositionService;
import eu.bcvsolutions.idm.core.api.service.IdmRoleFormAttributeService;
import eu.bcvsolutions.idm.core.api.service.IdmRoleGuaranteeRoleService;
import eu.bcvsolutions.idm.core.api.service.IdmRoleGuaranteeService;
import eu.bcvsolutions.idm.core.api.service.IdmRoleService;
import eu.bcvsolutions.idm.core.eav.api.domain.PersistentType;
import eu.bcvsolutions.idm.core.eav.api.dto.IdmCodeListDto;
import eu.bcvsolutions.idm.core.eav.api.dto.IdmCodeListItemDto;
import eu.bcvsolutions.idm.core.eav.api.dto.IdmFormAttributeDto;
import eu.bcvsolutions.idm.core.eav.api.dto.IdmFormValueDto;
import eu.bcvsolutions.idm.core.eav.api.service.FormService;
import eu.bcvsolutions.idm.core.eav.api.service.IdmCodeListItemService;
import eu.bcvsolutions.idm.core.eav.api.service.IdmCodeListService;
import eu.bcvsolutions.idm.core.eav.api.service.IdmFormAttributeService;
import eu.bcvsolutions.idm.core.ecm.api.dto.IdmAttachmentDto;
import eu.bcvsolutions.idm.core.model.entity.IdmRole;
import eu.bcvsolutions.idm.core.scheduler.api.dto.IdmLongRunningTaskDto;
import eu.bcvsolutions.idm.test.api.TestHelper;
@Transactional
public class ImportRolesFromCSVExecutorTest extends AbstractCsvImportTaskTest {
private static final String PATH = System.getProperty("user.dir") + "/src/test/resources/scheduler/task/impl/importRolesTestFile04.csv";
private static final String PATH_TWO = System.getProperty("user.dir") + "/src/test/resources/scheduler/task/impl/importRolesTestFile05.csv";
private static final String PATH_THREE = System.getProperty("user.dir") + "/src/test/resources/scheduler/task/impl/importRolesTestFile06.csv";
private static final String PATH_FOUR = System.getProperty("user.dir") + "/src/test/resources/scheduler/task/impl/importRolesTestFile07.csv";
private static final String ATTRIBUTE = "attr1";
private static final String ATTRIBUTE_TWO = "attr2";
private static final int CRITICALITY = 3;
private static final int CRITICALITY_TWO = 2;
private static final String GUARANTEE = "uzivatel1";
private static final String GUARANTEE_TWO = "uzivatel2";
private static final String GUARANTEE_ROLE = "role1";
private static final String GUARANTEE_ROLE_TWO = "role2";
private static final String SUB_ROLE = "subrole";
private static final String SUB_ROLE_TWO = "subrole2";
private static final String SUB_ROLE_COLUMN = "subroles";
private static final String ENVIRONMENT = "testing env";
private static final String GUARANTEE_TYPE_COLUMN = "guaranteeType";
private static final String GUARANTEE_ROLE_TYPE_COLUMN = "guaranteeRoleType";
private static final String GUARANTEE_TYPE = "type1";
private static final String EAV_CODE_PREFIX = "eavCode";
private static final String EAV_VALUE_PREFIX = "eavValue";
private static final String SYSTEM_NAME_PREFIX = "systemName";
private static final String SYSTEM_ATTRIBUTE_PREFIX = "systemAttribute";
private static final String SYSTEM_ATTRIBUTE_VALUE_PREFIX = "systemValue";
static final String ROLE_ROW = "roles";
static final String MEMBER_OF_NAME = "rights";
static final String CHECK_NAME = "CORE-CLOSE";
static final String DESCRIPTION = "description";
static final String ROLE_ATTRIBUTE = "attribute";
static final String GUARANTEE_COLUMN = "guarantees";
static final String GUARANTEE_ROLE_COLUMN = "guarantee role";
static final String CRITICALITY_COLUMN = "criticality";
static final String CATALOGUES_COLUMN = "catalogue";
static final String DEFINITION = "defin";
@Autowired
private IdmRoleFormAttributeService roleFormAttributeService;
@Autowired
private IdmFormAttributeService formAttributeService;
@Autowired
private TestHelper testHelper;
@Autowired
private IdmRoleGuaranteeService roleGuaranteeService;
@Autowired
private IdmRoleGuaranteeRoleService roleGuaranteeRoleService;
@Autowired
private IdmIdentityService identityService;
@Autowired
private IdmRoleService roleService;
@Autowired
private IdmRoleCatalogueService roleCatalogueService;
@Autowired
private IdmRoleCompositionService roleCompositionService;
@Autowired
private IdmCodeListService codeListService;
@Autowired
private IdmCodeListItemService codeListItemService;
@Autowired
private SysRoleSystemAttributeService roleSystemAttributeService;
@Autowired
private FormService formService;
@Test
public void importRolesTest() {
// prepare LRT configuration
IdmAttachmentDto attachement = createAttachment(PATH, "importRolesTestFile04.csv");
Map<String, Object> configOfLRT = prepareConfig();
configOfLRT.put(AbstractCsvImportTask.PARAM_PATH_TO_CSV, attachement.getId());
// create system
SysSystemDto system = initSystem("systemtest1");
// create guarantee type
IdmCodeListDto codeList = new IdmCodeListDto(UUID.randomUUID());
codeList.setCode("guarantee-type");
codeList.setName("guarantee-type");
codeListService.save(codeList);
IdmCodeListItemDto codeListItem = new IdmCodeListItemDto();
codeListItem.setCode(GUARANTEE_TYPE);
codeListItem.setName(GUARANTEE_TYPE);
codeListItem.setCodeList(codeList.getId());
codeListItemService.save(codeListItem);
// create EAVs
testHelper.createEavAttribute("eav", IdmRole.class, PersistentType.SHORTTEXT);
// creates identity
IdmIdentityDto identity = testHelper.createIdentity(GUARANTEE);
testHelper.createIdentityContact(identity);
// create subrole
testHelper.createRole(SUB_ROLE);
// create role
IdmRoleDto roleToAssing = new IdmRoleDto();
roleToAssing.setCode(GUARANTEE_ROLE);
roleToAssing.setName(GUARANTEE_ROLE);
roleToAssing = roleService.save(roleToAssing);
//
ImportRolesFromCSVExecutor lrt = new ImportRolesFromCSVExecutor();
lrt.init(configOfLRT);
longRunningTaskManager.executeSync(lrt);
IdmLongRunningTaskDto task = longRunningTaskManager.getLongRunningTask(lrt);
while (task.isRunning()) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Long count = task.getCount();
Long total = 4L;
// Assert.assertEquals(task.getCounter(), count);
Assert.assertEquals(total, count);
SysRoleSystemFilter filter = new SysRoleSystemFilter();
filter.setSystemId(system.getId());
List<SysRoleSystemDto> content = roleSystemService.find(filter, null).getContent();
// Assert.assertEquals(4, content.size());
LinkedList<IdmRoleDto> roles = new LinkedList<>();
content.forEach(r -> roles.add(roleService.get(r.getRole())));
boolean contains = false;
IdmRoleDto ourRole = null;
for (IdmRoleDto role : roles) {
if (filterContains(role, CHECK_NAME)) {
ourRole = role;
contains = true;
break;
}
}
assertTrue(contains);
assertNotNull(ourRole);
// test for adding catalogues
List<IdmRoleCatalogueDto> allByRole = roleCatalogueService.findAllByRole(ourRole.getId());
assertEquals(2, allByRole.size());
assertEquals("cat1", allByRole.get(0).getName());
assertEquals("cat3", allByRole.get(1).getName());
// test for adding attributes
IdmRoleFormAttributeFilter roleFormAttributeFilter = new IdmRoleFormAttributeFilter();
roleFormAttributeFilter.setRole(ourRole.getId());
List<IdmRoleFormAttributeDto> allRolesParams = roleFormAttributeService.find(roleFormAttributeFilter, null).getContent();
IdmFormAttributeDto formAttributeDto = new IdmFormAttributeDto();
for (IdmRoleFormAttributeDto p : allRolesParams) {
formAttributeDto = formAttributeService.get(p.getFormAttribute());
}
Assert.assertEquals(ATTRIBUTE, formAttributeDto.getName());
// test for setting criticality
Assert.assertEquals(CRITICALITY, ourRole.getPriority());
// test for setting guarantee, finds the guarantee of the role
IdmRoleGuaranteeFilter filterGuaranteeRole = new IdmRoleGuaranteeFilter();
filterGuaranteeRole.setRole(ourRole.getId());
List<IdmRoleGuaranteeDto> garantLinks = roleGuaranteeService.find(filterGuaranteeRole, null).getContent();
IdmRoleGuaranteeDto garantLink = garantLinks.get(0);
IdmIdentityDto garant = identityService.get(garantLink.getGuarantee());
String guaranteeType = garantLink.getType();
Assert.assertEquals(GUARANTEE, garant.getUsername());
Assert.assertEquals(GUARANTEE_TYPE, guaranteeType);
// test for setting guarantee role
IdmRoleGuaranteeRoleFilter filterRoleGuaranteeRole = new IdmRoleGuaranteeRoleFilter();
filterRoleGuaranteeRole.setRole(ourRole.getId());
List<IdmRoleGuaranteeRoleDto> garantRoleLinks = roleGuaranteeRoleService.find(filterRoleGuaranteeRole, null).getContent();
IdmRoleGuaranteeRoleDto garantRoleLink = garantRoleLinks.get(0);
IdmRoleDto garantRole = roleService.get(garantRoleLink.getGuaranteeRole());
String guaranteeRoleType = garantRoleLink.getType();
Assert.assertEquals(GUARANTEE_ROLE, garantRole.getCode());
Assert.assertEquals(GUARANTEE_TYPE, guaranteeRoleType);
// test for assigning sub roles
List<IdmRoleCompositionDto> subRoles = roleCompositionService.findAllSubRoles(ourRole.getId());
Assert.assertEquals(1, subRoles.size());
Assert.assertEquals(ourRole.getId(), subRoles.get(0).getSuperior());
// test for setting EAV values
List<IdmFormValueDto> values = formService.getValues(ourRole.getId(), IdmRole.class, "eav");
Assert.assertEquals(1, values.size());
IdmFormValueDto value = values.get(0);
Assert.assertEquals("testvalue", value.getShortTextValue());
// ***testing role updates
// create system
// prepare LRT configuration
IdmAttachmentDto attachementUpdate = createAttachment(PATH_TWO, "importRolesTestFile05.csv");
Map<String, Object> configOfLRTUpdate = prepareConfig();
configOfLRTUpdate.put(AbstractCsvImportTask.PARAM_PATH_TO_CSV, attachementUpdate.getId());
// create system
SysSystemDto systemUpdate = initSystem("systemtest2");
// creates identity
IdmIdentityDto identityUpdate = testHelper.createIdentity(GUARANTEE_TWO);
testHelper.createIdentityContact(identityUpdate);
// create subrole
testHelper.createRole(SUB_ROLE_TWO);
// create role
IdmRoleDto roleToAssingUpdate = new IdmRoleDto();
roleToAssingUpdate.setCode(GUARANTEE_ROLE_TWO);
roleToAssingUpdate.setName(GUARANTEE_ROLE_TWO);
roleToAssingUpdate = roleService.save(roleToAssingUpdate);
//
ImportRolesFromCSVExecutor lrtUpdate = new ImportRolesFromCSVExecutor();
lrtUpdate.init(configOfLRTUpdate);
longRunningTaskManager.executeSync(lrtUpdate);
IdmLongRunningTaskDto taskUpdate = longRunningTaskManager.getLongRunningTask(lrtUpdate);
while (taskUpdate.isRunning()) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Long countUpdate = taskUpdate.getCount();
Long totalUpdate = 1L;
Assert.assertEquals(taskUpdate.getCounter(), countUpdate);
Assert.assertEquals(totalUpdate, countUpdate);
SysRoleSystemFilter filterUpdate = new SysRoleSystemFilter();
filterUpdate.setSystemId(systemUpdate.getId());
List<SysRoleSystemDto> contentUpdate = roleSystemService.find(filterUpdate, null).getContent();
Assert.assertEquals(1, contentUpdate.size());
LinkedList<IdmRoleDto> rolesUpdate = new LinkedList<>();
contentUpdate.forEach(r -> rolesUpdate.add(roleService.get(r.getRole())));
boolean containsUpdate = false;
IdmRoleDto ourRoleUpdate = null;
for (IdmRoleDto role : rolesUpdate) {
if (filterContains(role, CHECK_NAME)) {
ourRoleUpdate = role;
containsUpdate = true;
break;
}
}
assertTrue(containsUpdate);
assertNotNull(ourRoleUpdate);
// test for adding attributes
IdmRoleFormAttributeFilter roleFormAttributeFilterUpdate = new IdmRoleFormAttributeFilter();
roleFormAttributeFilterUpdate.setRole(ourRoleUpdate.getId());
List<IdmRoleFormAttributeDto> allRolesParamsUpdate = roleFormAttributeService.find(roleFormAttributeFilterUpdate, null).getContent();
IdmFormAttributeDto formAttributeDtoUpdate = new IdmFormAttributeDto();
for (IdmRoleFormAttributeDto p : allRolesParamsUpdate) {
formAttributeDtoUpdate = formAttributeService.get(p.getFormAttribute());
}
Assert.assertEquals(ATTRIBUTE_TWO, formAttributeDtoUpdate.getName());
// test for setting criticality
Assert.assertEquals(CRITICALITY_TWO, ourRoleUpdate.getPriority());
// test for setting guarantee, finds the guarantee of the role
IdmRoleGuaranteeFilter filterGuaranteeRoleUpdate = new IdmRoleGuaranteeFilter();
filterGuaranteeRoleUpdate.setRole(ourRoleUpdate.getId());
List<IdmRoleGuaranteeDto> garantLinksUpdate = roleGuaranteeService.find(filterGuaranteeRoleUpdate, null).getContent();
Assert.assertEquals(2, garantLinksUpdate.size());
// test for setting guarantee role
IdmRoleGuaranteeRoleFilter filterRoleGuaranteeRoleUpdate = new IdmRoleGuaranteeRoleFilter();
filterRoleGuaranteeRoleUpdate.setRole(ourRoleUpdate.getId());
List<IdmRoleGuaranteeRoleDto> garantRoleLinksUpdate = roleGuaranteeRoleService.find(filterRoleGuaranteeRoleUpdate, null).getContent();
Assert.assertEquals(2, garantRoleLinksUpdate.size());
// test for assigning sub roles
List<IdmRoleCompositionDto> subRolesUpdate = roleCompositionService.findAllSubRoles(ourRoleUpdate.getId());
Assert.assertEquals(2, subRolesUpdate.size());
// test for setting EAV values
List<IdmFormValueDto> valuesUpdated = formService.getValues(ourRoleUpdate.getId(), IdmRole.class, "eav");
Assert.assertEquals(1, valuesUpdated.size());
IdmFormValueDto valueUpdated = valuesUpdated.get(0);
Assert.assertEquals("testvalue2", valueUpdated.getShortTextValue());
}
@Test
public void importRolesTestEnvironment() {
// prepare LRT configuration
IdmAttachmentDto attachement = createAttachment(PATH_THREE, "importRolesTestFile06.csv");
Map<String, Object> configOfLRT = prepareConfig();
configOfLRT.put(AbstractCsvImportTask.PARAM_PATH_TO_CSV, attachement.getId());
configOfLRT.put(ImportRolesFromCSVExecutor.PARAM_ENVIRONMENT, ENVIRONMENT);
ImportRolesFromCSVExecutor lrt = new ImportRolesFromCSVExecutor();
lrt.init(configOfLRT);
longRunningTaskManager.executeSync(lrt);
IdmLongRunningTaskDto task = longRunningTaskManager.getLongRunningTask(lrt);
while (task.isRunning()) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Long count = task.getCount();
Long total = 1L;
Assert.assertEquals(task.getCounter(), count);
Assert.assertEquals(total, count);
IdmRoleFilter rf = new IdmRoleFilter();
rf.setEnvironment(ENVIRONMENT);
List<IdmRoleDto> rolesForEnvironment = roleService.find(rf, null).getContent();
Assert.assertEquals(1, rolesForEnvironment.size());
Assert.assertEquals("testtest3" + "|" + ENVIRONMENT, rolesForEnvironment.get(0).getCode());
Assert.assertEquals(ENVIRONMENT, rolesForEnvironment.get(0).getEnvironment());
}
@Test
public void importMemberOfValue() {
// prepare LRT configuration
IdmAttachmentDto attachement = createAttachment(PATH_FOUR, "importRolesTestFile07.csv");
Map<String, Object> configOfLRT = prepareConfig();
configOfLRT.put(AbstractCsvImportTask.PARAM_PATH_TO_CSV, attachement.getId());
configOfLRT.put(ImportRolesFromCSVExecutor.PARAM_ROLE_CODE_COLUMN_NAME, ROLE_ROW);
initSystem("systemtest4");
ImportRolesFromCSVExecutor lrt = new ImportRolesFromCSVExecutor();
lrt.init(configOfLRT);
longRunningTaskManager.executeSync(lrt);
IdmLongRunningTaskDto task = longRunningTaskManager.getLongRunningTask(lrt);
while (task.isRunning()) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Long count = task.getCount();
Long total = 1L;
Assert.assertEquals(count, total);
// Check existing role
IdmRoleDto roleDto = roleService.getByCode("Admin (14)");
Assert.assertNotNull(roleDto);
// Check mapped system
SysRoleSystemFilter roleSystemFilter = new SysRoleSystemFilter();
roleSystemFilter.setRoleId(roleDto.getId());
List<SysRoleSystemDto> roleSystems = roleSystemService.find(roleSystemFilter, null).getContent();
Assert.assertEquals(1, roleSystems.size());
SysRoleSystemDto roleSystem = roleSystems.get(0);
// Check attribute and value in it
SysRoleSystemAttributeFilter systemAttributeFilter = new SysRoleSystemAttributeFilter();
systemAttributeFilter.setSystemId(roleSystem.getSystem());
systemAttributeFilter.setSchemaAttributeName(MEMBER_OF_NAME);
List<SysRoleSystemAttributeDto> attribute = roleSystemAttributeService.find(systemAttributeFilter, null).getContent();
Assert.assertNotNull(attribute);
String transformToResourceScript = attribute.get(0).getTransformToResourceScript();
Assert.assertEquals("\"Admin1\"", transformToResourceScript);
}
private Map<String, Object> prepareConfig() {
Map<String, Object> configOfLRT = new HashMap<>();
configOfLRT.put(ImportRolesFromCSVExecutor.PARAM_ROLES_COLUMN_NAME, ROLE_ROW);
configOfLRT.put(ImportRolesFromCSVExecutor.PARAM_CAN_BE_REQUESTED, true);
configOfLRT.put(ImportRolesFromCSVExecutor.PARAM_ATTRIBUTES_COLUMN_NAME, ROLE_ATTRIBUTE);
configOfLRT.put(ImportRolesFromCSVExecutor.PARAM_FORM_DEFINITION_CODE, DEFINITION);
configOfLRT.put(ImportRolesFromCSVExecutor.PARAM_DESCRIPTION_COLUMN_NAME, DESCRIPTION);
configOfLRT.put(ImportRolesFromCSVExecutor.PARAM_GUARANTEE_COLUMN_NAME, GUARANTEE_COLUMN);
configOfLRT.put(ImportRolesFromCSVExecutor.PARAM_GUARANTEE_ROLE_COLUMN_NAME, GUARANTEE_ROLE_COLUMN);
configOfLRT.put(ImportRolesFromCSVExecutor.PARAM_CRITICALITY_COLUMN_NAME, CRITICALITY_COLUMN);
configOfLRT.put(ImportRolesFromCSVExecutor.PARAM_CATALOGUES_COLUMN_NAME, CATALOGUES_COLUMN);
configOfLRT.put(ImportRolesFromCSVExecutor.PARAM_SUBROLES_COLUMN_NAME, SUB_ROLE_COLUMN);
configOfLRT.put(ImportRolesFromCSVExecutor.PARAM_GUARANTEE_TYPE_COLUMN_NAME, GUARANTEE_TYPE_COLUMN);
configOfLRT.put(ImportRolesFromCSVExecutor.PARAM_GUARANTEE_ROLE_TYPE_COLUMN_NAME, GUARANTEE_ROLE_TYPE_COLUMN);
configOfLRT.put(ImportRolesFromCSVExecutor.PARAM_EAV_CODE_PREFIX, EAV_CODE_PREFIX);
configOfLRT.put(ImportRolesFromCSVExecutor.PARAM_EAV_VALUE_PREFIX, EAV_VALUE_PREFIX);
configOfLRT.put(ImportRolesFromCSVExecutor.PARAM_SYSTEM_NAME_PREFIX, SYSTEM_NAME_PREFIX);
configOfLRT.put(ImportRolesFromCSVExecutor.PARAM_SYSTEM_ATTRIBUTE_PREFIX, SYSTEM_ATTRIBUTE_PREFIX);
configOfLRT.put(ImportRolesFromCSVExecutor.PARAM_SYSTEM_ATTRIBUTE_VALUE_PREFIX, SYSTEM_ATTRIBUTE_VALUE_PREFIX);
return configOfLRT;
}
}
|
package org.appenders.log4j2.elasticsearch.bulkprocessor;
/*-
* #%L
* log4j2-elasticsearch
* %%
* Copyright (C) 2018 Rafal Foltynski
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.ConfigurationException;
import org.apache.logging.log4j.core.lookup.StrSubstitutor;
import org.appenders.log4j2.elasticsearch.BatchEmitter;
import org.appenders.log4j2.elasticsearch.ClientObjectFactory;
import org.appenders.log4j2.elasticsearch.ClientProvider;
import org.appenders.log4j2.elasticsearch.FailoverPolicy;
import org.appenders.log4j2.elasticsearch.IndexTemplate;
import org.appenders.log4j2.elasticsearch.IndexTemplateTest;
import org.appenders.log4j2.elasticsearch.NoopFailoverPolicy;
import org.appenders.log4j2.elasticsearch.Operation;
import org.appenders.log4j2.elasticsearch.ValueResolver;
import org.appenders.log4j2.elasticsearch.bulkprocessor.BulkProcessorObjectFactory.Builder;
import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkRequestIntrospector;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.LocalTransportAddress;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.Collection;
import java.util.Collections;
import java.util.UUID;
import java.util.function.Function;
import static org.appenders.log4j2.elasticsearch.IndexTemplateTest.createTestIndexTemplateBuilder;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class BulkProcessorObjectFactoryTest {
public static final String TEST_SERVER_URIS = "http://localhost:9300";
public static Builder createTestObjectFactoryBuilder() {
return BulkProcessorObjectFactory.newBuilder()
.withServerUris(TEST_SERVER_URIS)
.withClientSettings(ClientSettings.newBuilder().build());
}
@Test
public void builderFailsIfServerUrisStringIsNull() {
// given
Builder builder = createTestObjectFactoryBuilder()
.withServerUris(null);
// when
final ConfigurationException exception = assertThrows(ConfigurationException.class, builder::build);
// then
assertThat(exception.getMessage(), equalTo("No serverUris provided for " + BulkProcessorObjectFactory.PLUGIN_NAME));
}
@Test
public void configReturnsACopyOfServerUrisList() {
// given
Builder builder = createTestObjectFactoryBuilder();
builder.withServerUris("http://localhost:9200;http://localhost:9201;http://localhost:9202");
ClientObjectFactory<TransportClient, BulkRequest> config = builder.build();
// when
Collection<String> serverUrisList = config.getServerList();
serverUrisList.add("test");
// then
assertNotEquals(serverUrisList.size(), config.getServerList().size());
}
@Test
public void clientIsInitializedOnlyOnce() {
// given
BulkProcessorObjectFactory factory = spy(createTestObjectFactoryBuilder().build());
BulkProcessorObjectFactory.InsecureTransportClientProvider clientProvider =
new BulkProcessorObjectFactory.InsecureTransportClientProvider();
when(factory.getClientProvider()).thenReturn(spy(clientProvider));
// when
TransportClient client1 = factory.createClient();
TransportClient client2 = factory.createClient();
// then
verify(factory, times(1)).getClientProvider();
assertEquals(client1, client2);
}
@Test
public void throwsIfUnknownHostWasProvided() {
// given
Builder builder = createTestObjectFactoryBuilder();
builder.withServerUris("http://unknowntesthost:8080");
BulkProcessorObjectFactory factory = builder.build();
// when
final ConfigurationException exception = assertThrows(ConfigurationException.class, factory::createClient);
// then
assertThat(exception.getMessage(), containsString("unknowntesthost"));
}
@Test
public void secureTransportIsSetupByDefaultWhenAuthIsConfigured() {
// given
Builder builder = createTestObjectFactoryBuilder();
builder.withAuth(XPackAuthTest.createTestBuilder().build());
BulkProcessorObjectFactory factory = builder.build();
// when
ClientProvider clientProvider = factory.getClientProvider();
// then
assertTrue(clientProvider instanceof SecureClientProvider);
}
@Test
public void insecureTransportIsSetupByDefaultWhenAuthIsNotConfigured() {
// given
Builder builder = createTestObjectFactoryBuilder();
builder.withAuth(null);
BulkProcessorObjectFactory factory = builder.build();
// when
ClientProvider clientProvider = factory.getClientProvider();
// then
assertTrue(clientProvider instanceof BulkProcessorObjectFactory.InsecureTransportClientProvider);
}
@Test
public void insecureTransportCanBeSetUpWithMinimalConstructor() {
// given
BulkProcessorObjectFactory factory = new BulkProcessorObjectFactory(Collections.singletonList(TEST_SERVER_URIS), null);
// when
ClientProvider clientProvider = factory.getClientProvider();
// then
assertTrue(clientProvider instanceof BulkProcessorObjectFactory.InsecureTransportClientProvider);
}
@Test
public void minimalSetupUsesClientProviderByDefault() {
// given
Builder builder = createTestObjectFactoryBuilder();
builder.withAuth(null);
BulkProcessorObjectFactory factory = spy(builder.build());
// when
factory.createClient();
// then
verify(factory).getClientProvider();
}
@Test
public void failureHandlerExecutesFailoverForEachBatchItemSeparately() {
// given
Builder builder = createTestObjectFactoryBuilder();
ClientObjectFactory<TransportClient, BulkRequest> config = builder.build();
FailoverPolicy failoverPolicy = spy(new NoopFailoverPolicy());
String payload1 = "test1";
String payload2 = "test2";
BulkRequest bulk = new BulkRequest()
.add(spy(new IndexRequest().source(payload1, XContentType.CBOR)))
.add(spy(new IndexRequest().source(payload2, XContentType.CBOR)));
// when
config.createFailureHandler(failoverPolicy).apply(bulk);
// then
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
verify(failoverPolicy, times(2)).deliver(captor.capture());
assertTrue(captor.getAllValues().contains(payload1));
assertTrue(captor.getAllValues().contains(payload2));
}
@Test
public void clientIsCalledWhenBatchItemIsAdded() {
// given
Builder builder = createTestObjectFactoryBuilder();
ClientObjectFactory<TransportClient, BulkRequest> config = spy(builder.build());
Settings settings = Settings.builder().build();
TransportClient client = spy(new PreBuiltTransportClient(settings));
client.addTransportAddress(new LocalTransportAddress("1"));
when(config.createClient()).thenReturn(client);
FailoverPolicy failoverPolicy = spy(new NoopFailoverPolicy());
BulkProcessorFactory bulkProcessorFactory = new BulkProcessorFactory();
BatchEmitter batchEmitter = bulkProcessorFactory.createInstance(
1,
100,
config,
failoverPolicy);
String payload1 = "test1";
ActionRequest testRequest = createTestRequest(payload1);
// when
batchEmitter.add(testRequest);
// then
ArgumentCaptor<BulkRequest> captor = ArgumentCaptor.forClass(BulkRequest.class);
verify(client, times(1)).bulk(captor.capture(), any());
assertEquals(payload1, new BulkRequestIntrospector().items(captor.getValue()).iterator().next());
}
@Test
public void failoverIsExecutedAfterNonSuccessfulRequest() {
// given
Builder builder = createTestObjectFactoryBuilder();
ClientObjectFactory<TransportClient, BulkRequest> config = spy(builder.build());
FailoverPolicy failoverPolicy = spy(new NoopFailoverPolicy());
Function handler = spy(config.createFailureHandler(failoverPolicy));
when(config.createFailureHandler(any())).thenReturn(handler);
Settings settings = Settings.builder().build();
TransportClient client = spy(new PreBuiltTransportClient(settings));
client.addTransportAddress(new LocalTransportAddress("1"));
when(config.createClient()).thenReturn(client);
BulkProcessorFactory bulkProcessorFactory = new BulkProcessorFactory();
BatchEmitter batchEmitter = bulkProcessorFactory.createInstance(
1,
100,
config,
failoverPolicy);
String payload1 = "test1";
ActionRequest testRequest = createTestRequest(payload1);
// when
batchEmitter.add(testRequest);
// then
ArgumentCaptor<BulkRequest> captor = ArgumentCaptor.forClass(BulkRequest.class);
verify(handler, times(1)).apply(captor.capture());
assertEquals(payload1, new BulkRequestIntrospector().items(captor.getValue()).iterator().next());
}
@Test
public void defaultValueResolverIsUsedWheNoConfigurationOrValueResolverProvided() {
// given
BulkProcessorObjectFactory.Builder builder = createTestObjectFactoryBuilder()
.withValueResolver(null);
BulkProcessorObjectFactory factory = builder.build();
// when
factory.addOperation(factory.setupOperationFactory().create(IndexTemplateTest.createTestIndexTemplateBuilder()
.withSource("${unresolved}")
.withPath(null)
.build()));
}
@Test
public void log4j2ConfigurationBasedValueResolverIsUsedWhenConfigurationProvided() {
// given
Configuration configuration = mock(Configuration.class);
StrSubstitutor strSubstitutor = mock(StrSubstitutor.class);
when(strSubstitutor.replace((String)any())).thenReturn(UUID.randomUUID().toString());
when(configuration.getStrSubstitutor()).thenReturn(strSubstitutor);
BulkProcessorObjectFactory.Builder builder = createTestObjectFactoryBuilder()
.withValueResolver(null)
.withConfiguration(configuration);
BulkProcessorObjectFactory factory = builder.build();
String expectedSource = UUID.randomUUID().toString();
IndexTemplate indexTemplate = createTestIndexTemplateBuilder()
.withName(UUID.randomUUID().toString())
.withSource(expectedSource)
.withPath(null)
.build();
// when
factory.setupOperationFactory().create(indexTemplate);
// then
verify(configuration).getStrSubstitutor();
verify(strSubstitutor).replace(eq(expectedSource));
}
@Test
public void providedValueResolverIsUsedWhenBothConfigurationAndValueResolverProvided() {
// given
ValueResolver valueResolver = mock(ValueResolver.class);
when(valueResolver.resolve(anyString())).thenReturn(UUID.randomUUID().toString());
BulkProcessorObjectFactory.Builder builder = createTestObjectFactoryBuilder()
.withConfiguration(mock(Configuration.class))
.withValueResolver(valueResolver);
BulkProcessorObjectFactory factory = builder.build();
String expectedSource = UUID.randomUUID().toString();
IndexTemplate indexTemplate = createTestIndexTemplateBuilder()
.withName(UUID.randomUUID().toString())
.withSource(expectedSource)
.withPath(null)
.build();
// when
factory.setupOperationFactory().create(indexTemplate);
// then
verify(valueResolver).resolve(eq(expectedSource));
}
@Test
public void defaultBatchListenerDoesntThrow() {
// given
BulkProcessorObjectFactory factory = createTestObjectFactoryBuilder().build();
Function<BulkRequest, Boolean> batchListener = factory.createBatchListener(failedPayload -> {
throw new ConfigurationException("test exception");
});
// when
batchListener.apply(null);
}
@Test
public void addAdminOperationExecutesImmediately() throws Exception {
// given
BulkProcessorObjectFactory factory = createTestObjectFactoryBuilder().build();
Operation operation = mock(Operation.class);
// when
factory.addOperation(operation);
// then
verify(operation).execute();
}
@Test
public void addAdminOperationExceptinsAreNotRethrown() throws Exception {
// given
BulkProcessorObjectFactory factory = createTestObjectFactoryBuilder().build();
Operation operation = spy(new Operation() {
@Override
public void execute() throws Exception {
throw new Exception("test exception");
}
});
// when
factory.addOperation(operation);
// then
verify(operation).execute();
}
private ActionRequest createTestRequest(String payload) {
return spy(new IndexRequest().source(payload, XContentType.CBOR));
}
}
|
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.activiti.engine.impl.persistence.entity;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.db.PersistentObject;
import org.activiti.engine.impl.util.ClockUtil;
/**
* @author Tom Baeyens
*/
public class HistoricTaskInstanceEntity extends HistoricScopeInstanceEntity implements HistoricTaskInstance, PersistentObject {
private static final long serialVersionUID = 1L;
protected String executionId;
protected String name;
protected String parentTaskId;
protected String description;
protected String assignee;
protected String taskDefinitionKey;
protected String formKey;
protected int priority;
protected Date dueDate;
/**
* 超时是否已经发送
*/
protected int OVERTIMESEND;
/**
* '任务持续时间限制
*/
protected long DURATION_NODE;
/**
* 预警是否已发送
*/
protected int ADVANCESEND;
/**
* 提前预警时间
*/
protected Timestamp ALERTTIME;
/**
* 超时告警时间
*/
protected Timestamp OVERTIME;
/**
* 预警时间率
*/
protected int NOTICERATE;
/**
* 节假日策略
* '节假日策略,0-考虑节假日,不考虑作息时间,1-不考虑节假日,不考虑作息时间,2-考虑节假日,考虑作息时间,默认值为1';
*/
protected int IS_CONTAIN_HOLIDAY;
public HistoricTaskInstanceEntity() {
}
public HistoricTaskInstanceEntity(TaskEntity task, ExecutionEntity execution) {
this.id = task.getId();
if (execution != null) {
this.processDefinitionId = execution.getProcessDefinitionId();
this.processInstanceId = execution.getProcessInstanceId();
this.executionId = execution.getId();
}
this.name = task.getName();
this.parentTaskId = task.getParentTaskId();
this.description = task.getDescription();
this.owner = task.getOwner();
this.assignee = task.getAssignee();
this.startTime = ClockUtil.getCurrentTime();
this.startTimeLong = this.startTime.getTime();
this.taskDefinitionKey = task.getTaskDefinitionKey();
this.setPriority(task.getPriority());
this.setDueDate(task.getDueDate());
task.setHistoricTaskInstanceEntity(this);
}
// persistence //////////////////////////////////////////////////////////////
public Object getPersistentState() {
Map<String, Object> persistentState = new HashMap<String, Object>();
persistentState.put("name", name);
persistentState.put("owner", owner);
persistentState.put("assignee", assignee);
persistentState.put("endTime", endTime);
persistentState.put("endTimeLong", endTimeLong);
persistentState.put("durationInMillis", durationInMillis);
persistentState.put("description", description);
persistentState.put("deleteReason", deleteReason);
persistentState.put("taskDefinitionKey", taskDefinitionKey);
persistentState.put("formKey", formKey);
persistentState.put("priority", priority);
if(parentTaskId != null) {
persistentState.put("parentTaskId", parentTaskId);
}
if(dueDate != null) {
persistentState.put("dueDate", dueDate);
}
if (claimTime != null) {
persistentState.put("claimTime", claimTime);
}
if(this.bussinessOperation != null)
persistentState.put("bussinessOperation", bussinessOperation);
if(this.bussinessRemark != null)
{
persistentState.put("bussinessRemark", bussinessRemark);
}
return persistentState;
}
// getters and setters //////////////////////////////////////////////////////
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getAssignee() {
return assignee;
}
public void setAssignee(String assignee) {
this.assignee = assignee;
}
public String getTaskDefinitionKey() {
return taskDefinitionKey;
}
public void setTaskDefinitionKey(String taskDefinitionKey) {
this.taskDefinitionKey = taskDefinitionKey;
}
public String getFormKey() {
return formKey;
}
public void setFormKey(String formKey) {
this.formKey = formKey;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
public Date getDueDate() {
return dueDate;
}
public void setDueDate(Date dueDate) {
this.dueDate = dueDate;
}
public String getParentTaskId() {
return parentTaskId;
}
public void setParentTaskId(String parentTaskId) {
this.parentTaskId = parentTaskId;
}
public Long getWorkTimeInMillis() {
if (endTime == null || claimTime == null) {
return null;
}
return endTime.getTime() - claimTime.getTime();
}
public int getOVERTIMESEND() {
return OVERTIMESEND;
}
public void setOVERTIMESEND(int oVERTIMESEND) {
OVERTIMESEND = oVERTIMESEND;
}
public long getDURATION_NODE() {
return DURATION_NODE;
}
public void setDURATION_NODE(long dURATION_NODE) {
DURATION_NODE = dURATION_NODE;
}
public int getADVANCESEND() {
return ADVANCESEND;
}
public void setADVANCESEND(int aDVANCESEND) {
ADVANCESEND = aDVANCESEND;
}
public Timestamp getALERTTIME() {
return ALERTTIME;
}
public void setALERTTIME(Timestamp aLERTTIME) {
ALERTTIME = aLERTTIME;
}
public Timestamp getOVERTIME() {
return OVERTIME;
}
public void setOVERTIME(Timestamp oVERTIME) {
OVERTIME = oVERTIME;
}
public int getNOTICERATE() {
return NOTICERATE;
}
public void setNOTICERATE(int nOTICERATE) {
NOTICERATE = nOTICERATE;
}
public int getIS_CONTAIN_HOLIDAY() {
return IS_CONTAIN_HOLIDAY;
}
public void setIS_CONTAIN_HOLIDAY(int iS_CONTAIN_HOLIDAY) {
IS_CONTAIN_HOLIDAY = iS_CONTAIN_HOLIDAY;
}
}
|
/*
* Copyright (C) 2016 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 com.google.android.apps.santatracker.doodles.pursuit;
import android.content.res.Resources;
import com.google.android.apps.santatracker.doodles.shared.AnimatedSprite;
import com.google.android.apps.santatracker.doodles.shared.Sprites;
/**
* The player actor that has two more animation states than runner actor: celebrating running and
* sweating running.
*/
public class PlayerActor extends RunnerActor {
boolean isSweating;
boolean isCelebrating;
protected AnimatedSprite celebrateSprite;
protected AnimatedSprite sweatSprite;
public PlayerActor(Resources resources, int lane) {
super(resources, RunnerType.STRAWBERRY, lane);
isSweating = false;
isCelebrating = false;
sweatSprite = AnimatedSprite.fromFrames(resources, Sprites.snowballrun_running_losing);
celebrateSprite = AnimatedSprite.fromFrames(resources, Sprites.snowballrun_running_normal);
setSpriteAnchorUpright(sweatSprite);
setSpriteAnchorUpright(celebrateSprite);
}
@Override
public void setRunnerState(RunnerState state) {
super.setRunnerState(state);
if (state == RunnerState.RUNNING) {
if (isCelebrating) {
currentSprite = celebrateSprite;
} else if (isSweating) {
currentSprite = sweatSprite;
} else {
currentSprite = runningSprite;
}
}
}
public void setSweat(boolean sweat) {
if (this.isSweating == sweat) {
return;
}
this.isSweating = sweat;
if (state != RunnerState.RUNNING || isCelebrating) {
return;
}
if (sweat) {
sweatSprite.setFrameIndex(runningSprite.getFrameIndex());
currentSprite = sweatSprite;
} else {
runningSprite.setFrameIndex(sweatSprite.getFrameIndex() % runningSprite.getNumFrames());
currentSprite = runningSprite;
}
}
public void setCelebrate(boolean celebrate) {
if (this.isCelebrating == celebrate) {
return;
}
this.isCelebrating = celebrate;
if (state != RunnerState.RUNNING) {
return;
}
if (celebrate) {
celebrateSprite.setFrameIndex(runningSprite.getFrameIndex());
currentSprite = celebrateSprite;
} else {
runningSprite.setFrameIndex(celebrateSprite.getFrameIndex() % runningSprite.getNumFrames());
currentSprite = runningSprite;
}
}
}
|
package com.cloudrain.derecho.fundamental.echo;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
/**
* Created by lugan on 12/29/2016.
*/
public class EchoClient {
public static void main(String ...argv) throws Exception{
int port = 5555;
String host = "localhost";
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast(new EchoClientHandler());
}
});
ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
channelFuture.channel().closeFuture().sync();
}finally {
group.shutdownGracefully();
}
}
}
|
package com.goufn.permission.common.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import java.util.Properties;
@EnableTransactionManagement(proxyTargetClass = true)
@Configuration
public class MybatisPlusConfig {
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
/**
* 打印 sql
*/
@Bean
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
//格式化sql语句
Properties properties = new Properties();
properties.setProperty("format", "true");
performanceInterceptor.setProperties(properties);
return performanceInterceptor;
}
}
|
package com.ggbwallet.app.web3;
import com.ggbwallet.token.entity.EthereumTypedMessage;
public interface OnSignTypedMessageListener {
void onSignTypedMessage(EthereumTypedMessage message);
}
|
/*
* Copyright (C) 2015 Inderjeet Singh
*
* 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.singhinderjeet.geocoding.model;
/**
* The Location class
*
* @author Inderjeet Singh
*/
public class Location {
private final double lat;
private final double lng;
public Location(double lat, double lng) {
this.lat = lat;
this.lng = lng;
}
public double getLat() {
return lat;
}
public double getLng() {
return lng;
}
}
|
package com.bjghhnt.app.treatmentdevice.activities;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.StatFs;
import android.os.storage.StorageManager;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v7.app.AppCompatActivity;
import android.text.format.Formatter;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.bjghhnt.app.treatmentdevice.Adapters.PropagandaListViewAdapter;
import com.bjghhnt.app.treatmentdevice.R;
import com.bjghhnt.app.treatmentdevice.service.PropagandaMusicService;
import com.bjghhnt.app.treatmentdevice.TreatmentApplication;
import com.bjghhnt.app.treatmentdevice.activities.fragment.propaganda.PropagandaAudioFragment;
import com.bjghhnt.app.treatmentdevice.activities.fragment.propaganda.PropagandaTxtFragment;
import com.bjghhnt.app.treatmentdevice.activities.fragment.propaganda.PropagandaVideoFragment;
import com.bjghhnt.app.treatmentdevice.bean.MediaBean;
import com.bjghhnt.app.treatmentdevice.utils.MusicUtils;
import com.bjghhnt.app.treatmentdevice.utils.serials.SerialHandler;
import com.bjghhnt.app.treatmentdevice.utils.serials.SimpleHandler;
import com.bjghhnt.app.treatmentdevice.views.NoScrollViewPager;
import com.squareup.otto.Subscribe;
import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import rx.Observable;
import rx.Observable.OnSubscribe;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
/**
* 宣传片界面
*
*/
public class PropagandaActivity extends MinorActivity implements
RadioGroup.OnCheckedChangeListener, AdapterView.OnItemClickListener {
private static final int BOOKS_SUCCESS = 500;
@BindView(R.id.rb_propaganda_music)
RadioButton mRbPropagandaMusic;
@BindView(R.id.rb_propaganda_video)
RadioButton mRbPropagandaVideo;
@BindView(R.id.rb_propaganda_books)
RadioButton mRbPropagandaBooks;
@BindView(R.id.rb_propaganda_back)
RadioButton mRbPropagandaBack;
@BindView(R.id.rg_propaganda)
RadioGroup mRgPropaganda;
@BindView(R.id.vp_propaganda_detail)
NoScrollViewPager mVpPropagandaDetail;
@BindView(R.id.lv_propaganda_list)
ListView mLvPropagandaList;
@BindView(R.id.ll_propaganda)
LinearLayout mLlPropaganda;
@BindView(R.id.tv_time)
TextView tvTimePropaganda;
private List<MediaBean> mAudioList = new ArrayList<>();
private List<MediaBean> mVideoList = new ArrayList<>();
private List<File> mFileList = new ArrayList<>();
private List<File> mBooksList = new ArrayList<>();
private List<Fragment> mFragmentList = new ArrayList<>();
private PropagandaListViewAdapter mPropagandaAdapter;
private ProgressDialog mProgressDialog;
private PropagandaAudioFragment mPropagandaAudioFragment;
private PropagandaMusicService mPropagandaMusicService;
private PropagandaVideoFragment mPropagandaVideoFragment;
private static final int VIDEO_SUCCESS = 101;
private PropagandaTxtFragment mPropagandaTxtFragment;
private static int FIRST_START = 1;
private final SimpleHandler mSimHandler = new SimpleHandler(this);
private Observer<Integer> obHandler = new Observer<Integer>() {
@Override
public void onNext(Integer integer) {
if (integer.equals(FIRST_START)){
mPropagandaAdapter.setList(PropagandaListViewAdapter.PropagandaChecked.CHECKED_MUSIC,
mAudioList);
mPropagandaMusicService.setMusicListAndInitMediaPlayer(mAudioList);
mPropagandaAudioFragment.setmAudioList(mAudioList);
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
if (integer.equals(VIDEO_SUCCESS)){
mPropagandaVideoFragment.setVideoList(mVideoList);
}
if (integer.equals(BOOKS_SUCCESS)){
mPropagandaTxtFragment.setBooksList(mBooksList);
}
}
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable t) {
}
};
//更新时间
@Override
protected void upDateTime() {
tvTimePropaganda.setText(formatTime);
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_propaganda);
ButterKnife.bind(this);
init();
}
@Override
protected SerialHandler setHandler() {
return mSimHandler;
}
private void init() {
TreatmentApplication.getBusInstance().register(this);
Intent intent = new Intent(PropagandaActivity.this, PropagandaMusicService.class);
startService(intent);
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("正在加载....");
mProgressDialog.show();
mProgressDialog.setCanceledOnTouchOutside(false);
mVpPropagandaDetail.setOffscreenPageLimit(3);
mPropagandaAdapter = new PropagandaListViewAdapter(PropagandaActivity.this);
mRgPropaganda.setOnCheckedChangeListener(this);
mRbPropagandaMusic.setChecked(true);
FIRST_START = 1;
mLvPropagandaList.setAdapter(mPropagandaAdapter);
mLvPropagandaList.setOnItemClickListener(this);
initBackground();
}
private void initBackground() {
Observable
.create((OnSubscribe<Bitmap>) e -> {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inSampleSize = 8;
Bitmap backgroundBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.propaganda_background, options);
e.onNext(backgroundBitmap);
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Bitmap>() {
@Override
public void onNext(Bitmap bitmap) {
mLlPropaganda.setBackground(new BitmapDrawable(getResources()
, bitmap));
initDate();
}
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
});
}
private void initDate() {
Observable
.create((OnSubscribe<Integer>) e -> {
initAudio();
e.onNext(FIRST_START);
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(obHandler);
Observable
.create((OnSubscribe<Integer>) e -> {
initVideo();
e.onNext(VIDEO_SUCCESS);
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(obHandler);
Observable
.create((OnSubscribe<Integer>) e -> {
initBooks();
e.onNext(BOOKS_SUCCESS);
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(obHandler);
}
private void initBooks() {
//通过反射获取所有可用的储存信息
StorageManager storageManager = (StorageManager) getSystemService(Context.STORAGE_SERVICE);
try {
Class<?>[] paramClasses = {};
Method getVolumePathsMethod = StorageManager.class.getMethod("getVolumePaths", paramClasses);
getVolumePathsMethod.setAccessible(true);
Object[] params = {};
Object invoke = getVolumePathsMethod.invoke(storageManager, params);
for (int i = 0; i < ((String[]) invoke).length; i++) {
// System.out.println(((String[])invoke)[i]);
//获得SD卡空间的信息
// File path=Environment.getExternalStorageDirectory();
// StatFs statFs=new StatFs(path.getPath());
StatFs statFs = new StatFs(((String[]) invoke)[i]);
long blocksize = statFs.getBlockSize();
long totalblocks = statFs.getBlockCount();
long availableblocks = statFs.getAvailableBlocks();
//计算SD卡的空间大小
long totalsize = blocksize * totalblocks;
long availablesize = availableblocks * blocksize;
//转化为可以显示的字符串
String totalsize_str = Formatter.formatFileSize(this, totalsize);
String availablesize_strString = Formatter.formatFileSize(this, availablesize);
if (!totalsize_str.equals("0.00 B")) {
// System.out.println(((String[]) invoke)[i] + ":" + totalsize_str);
getAllFiles(new File(((String[]) invoke)[i]));
}
// System.out.println(((String[]) invoke)[i] + "--;totalsize:" + totalsize_str + "--;availablesize:" + availablesize_strString);
}
for (File file : mFileList) {
if (file.getAbsolutePath().endsWith(".txt")) {
mBooksList.add(file);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void initVideo() {
Cursor cursor = getContentResolver().query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Video.Media.TITLE,
MediaStore.Video.Media.DURATION,
MediaStore.Video.Media.ARTIST,
MediaStore.Video.Media._ID,
MediaStore.Video.Media.DISPLAY_NAME,
MediaStore.Video.Media.DATA}, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
do {
MediaBean mediaBean = new MediaBean();
mediaBean.mMediaTitle = cursor.getString(0);
mediaBean.mMediaDuration = cursor.getString(1);
mediaBean.mMediaArtist = cursor.getString(2);
mediaBean.mMedia_ID = cursor.getLong(3);
mediaBean.mMediaDispalyName = cursor.getString(4);
mediaBean.mMediaData = cursor.getString(5);
mVideoList.add(mediaBean);
} while (cursor.moveToNext());
cursor.close();
}
}
private void initAudio() {
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.ALBUM_ID}, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
do {
MediaBean mediaBean = new MediaBean();
mediaBean.mMediaTitle = cursor.getString(0);
mediaBean.mMediaDuration = cursor.getString(1);
mediaBean.mMediaArtist = cursor.getString(2);
long audio_ID = cursor.getLong(3);
mediaBean.mMedia_ID = audio_ID;
mediaBean.mMediaDispalyName = cursor.getString(4);
mediaBean.mMediaData = cursor.getString(5);
long albumid = cursor.getLong(6);
Bitmap artwork = MusicUtils.getArtwork(PropagandaActivity.this, audio_ID, albumid, true);
if (artwork != null) {
mediaBean.album = artwork;
}
mAudioList.add(mediaBean);
} while (cursor.moveToNext());
cursor.close();
}
}
@Subscribe
public void getMusicService(PropagandaMusicService musicService) {
this.mPropagandaMusicService = musicService;
initFragment(musicService);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
TreatmentApplication.getBusInstance().unregister(this);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (mRgPropaganda.getCheckedRadioButtonId()) {
case R.id.rb_propaganda_music:
mPropagandaAudioFragment.playMusic(position);
mPropagandaAudioFragment.playOrPauseMusic();
break;
case R.id.rb_propaganda_video:
mPropagandaVideoFragment.playVideo(position);
break;
case R.id.rb_propaganda_books:
mPropagandaTxtFragment.setPosition(position);
// Intent intent = new Intent();
// intent.putExtra("bookname", "testbookname");
// intent.putExtra("bookpath", mBooksList.get(position).getAbsolutePath());
// intent.setClass(PropagandaActivity.this, HwReaderPlayActivity.class);
// startActivity(intent);
break;
}
}
private void initFragment(PropagandaMusicService musicService) {
mPropagandaAudioFragment = new PropagandaAudioFragment(musicService);
mPropagandaVideoFragment = new PropagandaVideoFragment();
mPropagandaTxtFragment = new PropagandaTxtFragment();
mFragmentList.add(mPropagandaAudioFragment);
mFragmentList.add(mPropagandaVideoFragment);
mFragmentList.add(mPropagandaTxtFragment);
mVpPropagandaDetail.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
});
}
private void getAllFiles(File root) {
File files[] = root.listFiles();
if (files != null)
for (File f : files) {
if (f.isDirectory()) {
getAllFiles(f);
} else {
this.mFileList.add(f);
}
}
}
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.rb_propaganda_music:
mPropagandaAdapter.setList(PropagandaListViewAdapter.PropagandaChecked.CHECKED_MUSIC,
mAudioList);
mVpPropagandaDetail.setCurrentItem(0);
break;
case R.id.rb_propaganda_video:
mPropagandaAdapter.setList(PropagandaListViewAdapter.PropagandaChecked.CHECKED_VIDEO,
mVideoList);
mVpPropagandaDetail.setCurrentItem(1);
break;
case R.id.rb_propaganda_books:
mPropagandaAdapter.setBooksList(PropagandaListViewAdapter.PropagandaChecked.CHECKED_BOOKS,
mBooksList);
mVpPropagandaDetail.setCurrentItem(2);
break;
case R.id.rb_propaganda_back:
finish();
break;
}
}
}
|
package com.github.joschi.jadconfig.repositories;
import com.github.joschi.jadconfig.RepositoryException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.fail;
/**
* Unit tests for {@link InMemoryRepository}
*
* @author jschalanda
*/public class InMemoryRepositoryTest {
private InMemoryRepository repository;
@Before
public void setUp() {
repository = new InMemoryRepository();
}
@Test
public void testOpen() throws RepositoryException {
repository.open();
Assert.assertEquals(0, repository.size());
}
@Test(expected = IllegalStateException.class)
public void testCloseWithoutOpen() throws RepositoryException {
repository.close();
}
@Test
public void testClose() throws RepositoryException {
repository.open();
Assert.assertEquals(0, repository.size());
repository.close();
try {
repository.size();
fail("repository.size() should throw an IllegalStateException");
} catch (IllegalStateException ex) {
// OK
}
}
@Test(expected = IllegalStateException.class)
public void testReadWithoutOpen() {
repository.read("Test");
}
@Test
public void testRead() throws RepositoryException {
final InMemoryRepository emptyRepository = new InMemoryRepository();
emptyRepository.open();
Assert.assertNull(emptyRepository.read("Test"));
final InMemoryRepository inMemoryRepository = new InMemoryRepository(Collections.singletonMap("Test", "Value"));
inMemoryRepository.open();
Assert.assertEquals("Value", inMemoryRepository.read("Test"));
}
@Test(expected = IllegalStateException.class)
public void testSizeWithoutOpen() {
repository.size();
}
@Test
public void testSize() throws RepositoryException {
final InMemoryRepository emptyRepository = new InMemoryRepository();
emptyRepository.open();
Assert.assertEquals(0, emptyRepository.size());
final InMemoryRepository inMemoryRepository = new InMemoryRepository(Collections.singletonMap("Test", "Value"));
inMemoryRepository.open();
Assert.assertEquals(1, inMemoryRepository.size());
}
@Test
public void testConstructor() {
Map<String, String> map = new HashMap<String, String>();
map.put("one", "one");
map.put("two", "two");
map.put("three", "three");
InMemoryRepository inMemoryRepository = new InMemoryRepository(map);
Assert.assertEquals("one", inMemoryRepository.read("one"));
Assert.assertEquals("two", inMemoryRepository.read("two"));
Assert.assertEquals("three", inMemoryRepository.read("three"));
}
}
|
package io.dropwizard.kubernetes.http.security;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.internal.SSLUtils;
import okhttp3.OkHttpClient;
import okhttp3.TlsVersion;
import java.io.File;
import java.security.GeneralSecurityException;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
public class SecurityFactory {
@JsonProperty
private boolean trustCerts = false;
@Valid
@JsonProperty
private CertAuthorityFactory caCert;
@Valid
@JsonProperty
private ClientCertFactory clientCert;
@Valid
@JsonProperty
private ClientKeyFactory clientKey;
@JsonProperty
private File trustStore;
@JsonProperty
private String trustStorePassword;
@NotNull
@JsonProperty
private TlsVersion tlsVersion = TlsVersion.TLS_1_2;
public boolean isTrustCerts() {
return trustCerts;
}
public void setTrustCerts(final boolean trustCerts) {
this.trustCerts = trustCerts;
}
public CertAuthorityFactory getCaCert() {
return caCert;
}
public void setCaCert(final CertAuthorityFactory caCert) {
this.caCert = caCert;
}
public ClientCertFactory getClientCert() {
return clientCert;
}
public void setClientCert(final ClientCertFactory clientCert) {
this.clientCert = clientCert;
}
public ClientKeyFactory getClientKey() {
return clientKey;
}
public void setClientKey(final ClientKeyFactory clientKey) {
this.clientKey = clientKey;
}
public File getTrustStore() {
return trustStore;
}
public void setTrustStore(final File trustStore) {
this.trustStore = trustStore;
}
public String getTrustStorePassword() {
return trustStorePassword;
}
public void setTrustStorePassword(final String trustStorePassword) {
this.trustStorePassword = trustStorePassword;
}
public TlsVersion getTlsVersion() {
return tlsVersion;
}
public void setTlsVersion(final TlsVersion tlsVersion) {
this.tlsVersion = tlsVersion;
}
public void addSecurityConfigs(final OkHttpClient.Builder builder, final Config config) throws Exception {
config.setTrustCerts(trustCerts);
if (caCert != null) {
caCert.addCertAuthorityConfigs(config);
}
if (clientCert != null) {
clientCert.addClientCertConfig(config);
}
if (clientKey != null) {
clientKey.addClientKeyConfigs(config);
}
if (trustStore != null) {
config.setTrustStoreFile(trustStore.getAbsolutePath());
}
if (trustStorePassword != null) {
config.setTrustStorePassphrase(trustStorePassword);
}
addTlsConfigs(builder, config);
}
protected void addTlsConfigs(final OkHttpClient.Builder builder, final Config config) throws Exception {
final TrustManager[] trustManagers = SSLUtils.trustManagers(config);
final KeyManager[] keyManagers = SSLUtils.keyManagers(config);
if (keyManagers == null && trustManagers == null && !config.isTrustCerts()) {
final SSLContext context = SSLContext.getInstance(tlsVersion.javaName());
context.init(keyManagers, trustManagers, null);
builder.sslSocketFactory(context.getSocketFactory(), (X509TrustManager) trustManagers[0]);
} else {
X509TrustManager trustManager = null;
if (trustManagers != null && trustManagers.length == 1) {
trustManager = (X509TrustManager)trustManagers[0];
}
try {
final SSLContext sslContext = SSLUtils.sslContext(keyManagers, trustManagers, config.isTrustCerts());
builder.sslSocketFactory(sslContext.getSocketFactory(), trustManager);
} catch (final GeneralSecurityException var7) {
throw new AssertionError();
}
}
}
}
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/websecurityscanner/v1alpha/web_security_scanner.proto
package com.google.cloud.websecurityscanner.v1alpha;
/**
*
*
* <pre>
* Request for the `ListCrawledUrls` method.
* </pre>
*
* Protobuf type {@code google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest}
*/
public final class ListCrawledUrlsRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest)
ListCrawledUrlsRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListCrawledUrlsRequest.newBuilder() to construct.
private ListCrawledUrlsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListCrawledUrlsRequest() {
parent_ = "";
pageToken_ = "";
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private ListCrawledUrlsRequest(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
java.lang.String s = input.readStringRequireUtf8();
parent_ = s;
break;
}
case 18:
{
java.lang.String s = input.readStringRequireUtf8();
pageToken_ = s;
break;
}
case 24:
{
pageSize_ = input.readInt32();
break;
}
default:
{
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.websecurityscanner.v1alpha.WebSecurityScannerProto
.internal_static_google_cloud_websecurityscanner_v1alpha_ListCrawledUrlsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.websecurityscanner.v1alpha.WebSecurityScannerProto
.internal_static_google_cloud_websecurityscanner_v1alpha_ListCrawledUrlsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest.class,
com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
private volatile java.lang.Object parent_;
/**
*
*
* <pre>
* Required. The parent resource name, which should be a scan run resource name in the
* format
* 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The parent resource name, which should be a scan run resource name in the
* format
* 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PAGE_TOKEN_FIELD_NUMBER = 2;
private volatile java.lang.Object pageToken_;
/**
*
*
* <pre>
* A token identifying a page of results to be returned. This should be a
* `next_page_token` value returned from a previous List request.
* If unspecified, the first page of results is returned.
* </pre>
*
* <code>string page_token = 2;</code>
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* A token identifying a page of results to be returned. This should be a
* `next_page_token` value returned from a previous List request.
* If unspecified, the first page of results is returned.
* </pre>
*
* <code>string page_token = 2;</code>
*/
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PAGE_SIZE_FIELD_NUMBER = 3;
private int pageSize_;
/**
*
*
* <pre>
* The maximum number of CrawledUrls to return, can be limited by server.
* If not specified or not positive, the implementation will select a
* reasonable value.
* </pre>
*
* <code>int32 page_size = 3;</code>
*/
public int getPageSize() {
return pageSize_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!getParentBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (!getPageTokenBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, pageToken_);
}
if (pageSize_ != 0) {
output.writeInt32(3, pageSize_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!getParentBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (!getPageTokenBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, pageToken_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(3, pageSize_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest)) {
return super.equals(obj);
}
com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest other =
(com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (!getPageToken().equals(other.getPageToken())) return false;
if (getPageSize() != other.getPageSize()) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getPageToken().hashCode();
hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getPageSize();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest
parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Request for the `ListCrawledUrls` method.
* </pre>
*
* Protobuf type {@code google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest)
com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.websecurityscanner.v1alpha.WebSecurityScannerProto
.internal_static_google_cloud_websecurityscanner_v1alpha_ListCrawledUrlsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.websecurityscanner.v1alpha.WebSecurityScannerProto
.internal_static_google_cloud_websecurityscanner_v1alpha_ListCrawledUrlsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest.class,
com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest.Builder.class);
}
// Construct using
// com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}
}
@java.lang.Override
public Builder clear() {
super.clear();
parent_ = "";
pageToken_ = "";
pageSize_ = 0;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.websecurityscanner.v1alpha.WebSecurityScannerProto
.internal_static_google_cloud_websecurityscanner_v1alpha_ListCrawledUrlsRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest
getDefaultInstanceForType() {
return com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest
.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest build() {
com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest buildPartial() {
com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest result =
new com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest(this);
result.parent_ = parent_;
result.pageToken_ = pageToken_;
result.pageSize_ = pageSize_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest) {
return mergeFrom(
(com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest other) {
if (other
== com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest
.getDefaultInstance()) return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
onChanged();
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage =
(com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest)
e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The parent resource name, which should be a scan run resource name in the
* format
* 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The parent resource name, which should be a scan run resource name in the
* format
* 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The parent resource name, which should be a scan run resource name in the
* format
* 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The parent resource name, which should be a scan run resource name in the
* format
* 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The parent resource name, which should be a scan run resource name in the
* format
* 'projects/{projectId}/scanConfigs/{scanConfigId}/scanRuns/{scanRunId}'.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
onChanged();
return this;
}
private java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* A token identifying a page of results to be returned. This should be a
* `next_page_token` value returned from a previous List request.
* If unspecified, the first page of results is returned.
* </pre>
*
* <code>string page_token = 2;</code>
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A token identifying a page of results to be returned. This should be a
* `next_page_token` value returned from a previous List request.
* If unspecified, the first page of results is returned.
* </pre>
*
* <code>string page_token = 2;</code>
*/
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A token identifying a page of results to be returned. This should be a
* `next_page_token` value returned from a previous List request.
* If unspecified, the first page of results is returned.
* </pre>
*
* <code>string page_token = 2;</code>
*/
public Builder setPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
pageToken_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* A token identifying a page of results to be returned. This should be a
* `next_page_token` value returned from a previous List request.
* If unspecified, the first page of results is returned.
* </pre>
*
* <code>string page_token = 2;</code>
*/
public Builder clearPageToken() {
pageToken_ = getDefaultInstance().getPageToken();
onChanged();
return this;
}
/**
*
*
* <pre>
* A token identifying a page of results to be returned. This should be a
* `next_page_token` value returned from a previous List request.
* If unspecified, the first page of results is returned.
* </pre>
*
* <code>string page_token = 2;</code>
*/
public Builder setPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
pageToken_ = value;
onChanged();
return this;
}
private int pageSize_;
/**
*
*
* <pre>
* The maximum number of CrawledUrls to return, can be limited by server.
* If not specified or not positive, the implementation will select a
* reasonable value.
* </pre>
*
* <code>int32 page_size = 3;</code>
*/
public int getPageSize() {
return pageSize_;
}
/**
*
*
* <pre>
* The maximum number of CrawledUrls to return, can be limited by server.
* If not specified or not positive, the implementation will select a
* reasonable value.
* </pre>
*
* <code>int32 page_size = 3;</code>
*/
public Builder setPageSize(int value) {
pageSize_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* The maximum number of CrawledUrls to return, can be limited by server.
* If not specified or not positive, the implementation will select a
* reasonable value.
* </pre>
*
* <code>int32 page_size = 3;</code>
*/
public Builder clearPageSize() {
pageSize_ = 0;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest)
private static final com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest();
}
public static com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListCrawledUrlsRequest> PARSER =
new com.google.protobuf.AbstractParser<ListCrawledUrlsRequest>() {
@java.lang.Override
public ListCrawledUrlsRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new ListCrawledUrlsRequest(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<ListCrawledUrlsRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListCrawledUrlsRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
package com.sparrow.collect.website.handler;
import java.io.File;
import java.io.FilenameFilter;
import java.util.HashMap;
import java.util.Map;
import com.sparrow.collect.website.lucene.creator.IFileCreator;
import com.sparrow.collect.website.utils.PathResolver;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.index.IndexWriter;
public class FileHandlerFactory {
private static final Map<String, FileHandler> cache = new HashMap<String, FileHandler>();
/**
* <p>
* Title: getHandler
* </p>
* <p>
* Description:
* </p>
*
* @param key
* @return
* @author Yzc
*/
private static FileHandler getHandler(String key) {
FileHandler handler = (FileHandler) cache.get(key);
if (handler == null) {
handler = build(key);
if (handler != null) {
handler.setWrite2file(true);
cache.put(key, handler);
}
}
return handler;
}
/**
* <p>
* Title: build
* </p>
* <p>
* Description:
* </p>
*
* @param key
* @return
* @author Yzc
*/
private static FileHandler build(String key) {
if ("txt|text|js|".indexOf(key) != -1) {
return new TextFileHandler();
} else if ("pdf".equals(key)) {
return new PdfFileHandler();
} else if ("html|xml|jsp|asp".indexOf(key) != -1) {
return new HtmlFileHandler();
} else if ("doc".equals(key)) {
return new WordFileHandler();
} else if ("docx".equals(key)) {
return new Word2007FileHandler();
} else if ("xls".equals(key)) {
return new ExcelFileHandler();
} else if ("xlsx".equals(key)) {
return new Excel2007FileHandler();
}
return null;
}
/**
* <p>
* Title: buildFileDocument
* </p>
* <p>
* Description:
* </p>
*
* @param file
* @return
* @author Yzc
*/
public static void buildFileDocument(File file, IndexWriter writer,
IFileCreator creator) {
if (file == null)
return;
FileHandler handler = null;
if (file.isFile()) {
String extension = PathResolver.getExtension(file);
handler = getHandler(extension);
}
if (handler != null)
handler.handle(file, writer, creator);
}
static boolean hasInArray(String v, String array[]) {
if (array == null || array.length == 0)
return false;
for (String str : array) {
if (StringUtils.equalsIgnoreCase(str, v))
return true;
}
return false;
}
public static void parseAllFile(File dir, final String suffix) {
if (dir.exists()) {
final String arr[] = suffix.split(",");
File files[] = dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
String fix = PathResolver.getExtension(name);
return hasInArray(fix, arr);
}
});
for (File file : files) {
System.out.println(file.getPath());
buildFileDocument(file, null, null);
}
}
}
static void formatFile(File file) {
}
public static void main(String args[]) {
System.setProperty("data.store.path", "E:\\_server\\playServer\\config\\data");
parseAllFile(new File("E:\\_server\\playServer\\config\\_src"), "pdf,doc,xls");
}
}
|
/*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.identity.configuration.mgt.endpoint.exception;
import org.wso2.carbon.identity.configuration.mgt.core.constant.ConfigurationConstants;
import org.wso2.carbon.identity.configuration.mgt.endpoint.dto.ErrorDTO;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
public class ConflictRequestException extends WebApplicationException {
private String message;
public ConflictRequestException(ErrorDTO errorDTO) {
super(Response.status(Response.Status.CONFLICT)
.entity(errorDTO)
.header(ConfigurationConstants.HEADER_CONTENT_TYPE,
ConfigurationConstants.DEFAULT_RESPONSE_CONTENT_TYPE)
.build());
message = errorDTO.getDescription();
}
public ConflictRequestException() {
super(Response.Status.CONFLICT);
}
@Override
public String getMessage() {
return message;
}
}
|
package com.hxcf.manager.config;
import com.github.xiaoymin.knife4j.spring.annotations.EnableSwaggerBootstrapUi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
@Configuration
@EnableSwagger2
@EnableSwaggerBootstrapUi
public class Knife4jConfig {
@Resource
private DefinitionProperties definitionProperties;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.enable(!"prod".equals(definitionProperties.getActiveProfile()))//正式环境禁用Swagger
.useDefaultResponseMessages(false)//缺省true,设置false时会把响应状态里除200以外的状态码去掉
.groupName(definitionProperties.getApplicationName())//分组名
.globalOperationParameters(buildGlobalOperationParameters())//全局参数设置
.apiInfo(new ApiInfoBuilder()
.title("Data Manager API")//大标题
.description("数据中心---管理后台---接口文档")//详细描述
.version("1.0")//版本
.build())
.select()
.apis(RequestHandlerSelectors.basePackage("com.hxcf.manager.controller"))
.paths(PathSelectors.any())
.build();
}
private static List<Parameter> buildGlobalOperationParameters() {
List<Parameter> list = new ArrayList<>();
list.add(new ParameterBuilder().name("HX-SERIAL-NUMBER").description("请求流水号,每次请求都不同,每个模块都要记录到log日志,由请求方生成,可以使用UUID")
.modelRef(new ModelRef("string")).parameterType("header").required(true).build());
return list;
}
}
|
/*
* Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.devopsguru.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.devopsguru.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* DescribeResourceCollectionHealthResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeResourceCollectionHealthResultJsonUnmarshaller implements Unmarshaller<DescribeResourceCollectionHealthResult, JsonUnmarshallerContext> {
public DescribeResourceCollectionHealthResult unmarshall(JsonUnmarshallerContext context) throws Exception {
DescribeResourceCollectionHealthResult describeResourceCollectionHealthResult = new DescribeResourceCollectionHealthResult();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return describeResourceCollectionHealthResult;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("CloudFormation", targetDepth)) {
context.nextToken();
describeResourceCollectionHealthResult.setCloudFormation(new ListUnmarshaller<CloudFormationHealth>(CloudFormationHealthJsonUnmarshaller
.getInstance())
.unmarshall(context));
}
if (context.testExpression("NextToken", targetDepth)) {
context.nextToken();
describeResourceCollectionHealthResult.setNextToken(context.getUnmarshaller(String.class).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return describeResourceCollectionHealthResult;
}
private static DescribeResourceCollectionHealthResultJsonUnmarshaller instance;
public static DescribeResourceCollectionHealthResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new DescribeResourceCollectionHealthResultJsonUnmarshaller();
return instance;
}
}
|
/* ***** BEGIN LICENSE BLOCK *****
Version: Apache 2.0/GPL 3.0/LGPL 3.0
CCT - Computational Chemistry Tools
Jamberoo - Java Molecules Editor
Copyright 2008-2015 Dr. Vladislav Vasilyev
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.
Contributor(s):
Dr. Vladislav Vasilyev <vvv900@gmail.com> (original author)
Alternatively, the contents of this file may be used under the terms of
either the GNU General Public License Version 2 or later (the "GPL"), or
the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
in which case the provisions of the GPL or the LGPL are applicable instead
of those above. If you wish to allow use of your version of this file only
under the terms of either the GPL or the LGPL, and not to allow others to
use your version of this file under the terms of the Apache 2.0, indicate your
decision by deleting the provisions above and replace them with the notice
and other provisions required by the GPL or the LGPL. If you do not delete
the provisions above, a recipient may use your version of this file under
the terms of any one of the Apache 2.0, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package cct.amber;
import java.applet.Applet;
import java.awt.BorderLayout;
//import cct.amber.*;
public class AmberApplet
extends Applet {
boolean isStandalone = false;
BorderLayout borderLayout1 = new BorderLayout();
AmberSubmitDialog AmberSubmit;
//String var0;
//Get a parameter value
public String getParameter(String key, String def) {
return isStandalone ? System.getProperty(key, def) :
(getParameter(key) != null ? getParameter(key) : def);
}
//Construct the applet
public AmberApplet() {
}
//Initialize the applet
@Override
public void init() {
/*
try {
var0 = this.getParameter("param0", "");
}
catch (Exception e) {
e.printStackTrace();
}
*/
try {
jbInit();
}
catch (Exception e) {
e.printStackTrace();
}
}
//Component initialization
private void jbInit() throws Exception {
String actionURL;
actionURL = getParameter("actionURL");
AmberSubmit = new AmberSubmitDialog(this, "Submit Amber Job", actionURL);
AmberSubmit.setSize(600, 400);
AmberSubmit.setVisible(true);
}
//Get Applet information
@Override
public String getAppletInfo() {
return "Applet Information";
}
//Get parameter info
@Override
public String[][] getParameterInfo() {
String[][] pinfo = {
{
"param0", "String", ""},
};
return pinfo;
}
}
|
/**
* MIT License
*
* Copyright (c) 2017-2019 Yurii Dubinka
*
* 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
* OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.github.dgroup.dockertest.yml.tag;
import com.github.dgroup.dockertest.yml.Tag;
import com.github.dgroup.dockertest.yml.UncheckedYmlFormatException;
import com.github.dgroup.dockertest.yml.YmlFormatException;
/**
* Tag that doesn't throw checked {@link YmlFormatException}.
*
* @author Yurii Dubinka (yurii.dubinka@gmail.com)
* @version $Id: 792f83cf98093cd7286eb712de4b1c665afd5c6c $
* @param <T> Type of tag.
* @since 1.1
*/
public final class UncheckedTag<T> implements Tag<T> {
/**
* Origin.
*/
private final Tag<T> tag;
/**
* Ctor.
* @param tag Origin.
*/
public UncheckedTag(final Tag<T> tag) {
this.tag = tag;
}
@Override
public String name() {
return this.tag.name();
}
@Override
public T value() {
try {
return this.tag.value();
} catch (final YmlFormatException cause) {
throw new UncheckedYmlFormatException(cause);
}
}
}
|
package io.github.nandandesai.twitterscraper4j.models;
public class Media {
public enum TYPE{
PICTURE, VIDEO, GIF
}
private TYPE type;
private String link;
public Media(TYPE type, String link) {
this.type = type;
this.link = link;
}
public TYPE getType() {
return type;
}
public String getLink() {
return link;
}
@Override
public String toString(){
return "{\n" +
" \"type\": \""+type+"\",\n" +
" \"url\": "+link+"\n" +
"}";
}
}
|
package com.osawaseigo.netty.promises;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
public class MyAppServerHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg)
throws Exception {
System.out.println("[server][in] " + msg);
if (IoClient.MESSAGE_LONG_DELAY.equals(msg)) {
Thread.sleep(3000);
}
String answer = "Response to " + msg;
System.out.println("[server][out] " + answer);
ctx.writeAndFlush(answer);
}
}
|
/*
* 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.axis2.jaxws.handler;
import org.apache.axis2.jaxws.core.MessageContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
/**
* BaseMessageContext is the base class for the two handler message contexts:
* SoapMessageContext and LogicalMessageContext. It delegates everything up to
* the MEPContext, which itself delegates to the requestMC or responseMC, as
* appropriate.
*
*/
public class BaseMessageContext implements javax.xml.ws.handler.MessageContext {
private static final Log log = LogFactory.getLog(BaseMessageContext.class);
protected MessageContext messageCtx;
/**
* @param messageCtx
*/
protected BaseMessageContext(MessageContext messageCtx) {
this.messageCtx = messageCtx;
// Install an an AttachmentsAdapter between the
// jaxws attachment standard properties and the
// MessageContext Attachments implementation.
AttachmentsAdapter.install(messageCtx);
TransportHeadersAdapter.install(messageCtx);
SOAPHeadersAdapter.install(messageCtx);
}
/* (non-Javadoc)
* @see java.util.Map#clear()
*/
public void clear() {
messageCtx.getMEPContext().clear();
}
/* (non-Javadoc)
* @see java.util.Map#containsKey(java.lang.Object)
*/
public boolean containsKey(Object key) {
return messageCtx.getMEPContext().containsKey(key);
}
/* (non-Javadoc)
* @see java.util.Map#containsValue(java.lang.Object)
*/
public boolean containsValue(Object value) {
return messageCtx.getMEPContext().containsValue(value);
}
/* (non-Javadoc)
* @see java.util.Map#entrySet()
*/
public Set<java.util.Map.Entry<String, Object>> entrySet() {
return messageCtx.getMEPContext().entrySet();
}
/* (non-Javadoc)
* @see java.util.Map#get(java.lang.Object)
*/
public Object get(Object key) {
// There are some properties that, in some cases, should not span the message exchange;
// that is, they should come from only the current message context. For others properties,
// they should span the message exchange, meaning a property could be set on the request
// and it will also be available on the response. [JAXWS 2.0, Sec 9.4.1.1, pp. 110-113]
Object returnValue = null;
if (shouldPropertySpanMEP(key)) {
returnValue = messageCtx.getMEPContext().get(key);
} else {
returnValue = messageCtx.getProperty((String) key);
}
// For the HTTP_REQUEST_HEADERS and HTTP_RESPONSE_HEADERS, the CTS tests want a null returned
// if there are no headers. Since we always put an instance of TransportHeadersAdapter,
// which contains the headers, on the message context, return a null if it is empty.
if (returnValue != null && (returnValue instanceof TransportHeadersAdapter)) {
TransportHeadersAdapter adapter = (TransportHeadersAdapter) returnValue;
if (adapter.isEmpty()) {
return null;
}
}
return returnValue;
}
private boolean shouldPropertySpanMEP(Object key) {
boolean shouldSpan = true;
String keyString = (String) key;
// The CTS tests require that HTTP_REQUEST_HEADERS span the request and response contexts
// on the service-provider, but do NOT span the request and response context on the
// service-requester. So, for an INBOUND flow, do not allow HTTP_REQUEST_HEADERS to
// span the request and response contexts. The result is that the service-requester
// inbound handler will not see the request headers while processing a response.
Boolean outbound = (Boolean) messageCtx.getMEPContext().get(MESSAGE_OUTBOUND_PROPERTY);
if (outbound != null && !outbound)
if (javax.xml.ws.handler.MessageContext.HTTP_REQUEST_HEADERS.equals(keyString)) {
shouldSpan = false;
}
return shouldSpan;
}
/* (non-Javadoc)
* @see java.util.Map#isEmpty()
*/
public boolean isEmpty() {
return messageCtx.getMEPContext().isEmpty();
}
/* (non-Javadoc)
* @see java.util.Map#keySet()
*/
public Set<String> keySet() {
return messageCtx.getMEPContext().keySet();
}
/* (non-Javadoc)
* @see java.util.Map#put(java.lang.Object, java.lang.Object)
*/
public Object put(String key, Object value) {
return messageCtx.getMEPContext().put(key, value);
}
/* (non-Javadoc)
* @see java.util.Map#putAll(java.util.Map)
*/
public void putAll(Map<? extends String, ? extends Object> t) {
messageCtx.getMEPContext().putAll(t);
}
/* (non-Javadoc)
* @see java.util.Map#remove(java.lang.Object)
*/
public Object remove(Object key) {
return messageCtx.getMEPContext().remove(key);
}
/* (non-Javadoc)
* @see java.util.Map#size()
*/
public int size() {
return messageCtx.getMEPContext().size();
}
/* (non-Javadoc)
* @see java.util.Map#values()
*/
public Collection<Object> values() {
return messageCtx.getMEPContext().values();
}
/* (non-Javadoc)
* @see javax.xml.ws.handler.MessageContext#getScope(java.lang.String)
*/
public Scope getScope(String s) {
return messageCtx.getMEPContext().getScope(s);
}
/* (non-Javadoc)
* @see javax.xml.ws.handler.MessageContext#setScope(java.lang.String, javax.xml.ws.handler.MessageContext.Scope)
*/
public void setScope(String s, Scope scope) {
messageCtx.getMEPContext().setScope(s, scope);
}
}
|
/**
* CloudMapping - Sistema de Extração de Dados de Mapeamento dos Experimentos em Computação em Nuvem
*
* Copyright (c) AssertLab.
*
* Este software é confidencial e propriedade da AssertLab. Não é permitida sua distribuição ou divulgação
* do seu conteúdo sem expressa autorização do AssertLab. Este arquivo contém informações proprietárias.
*/
package br.ufpe.cin.cloud.mapeamento.negocio.base.validacao;
import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import org.apache.commons.beanutils.PropertyUtils;
import br.ufpe.cin.cloud.mapeamento.negocio.base.camadas.Entidade;
import br.ufpe.cin.cloud.mapeamento.negocio.base.excecao.Erro;
import br.ufpe.cin.cloud.mapeamento.negocio.base.excecao.TipoErro;
import br.ufpe.cin.cloud.mapeamento.negocio.base.util.MapeamentoUtil;
/**
* A classe representa a extensão da implementação do hibernate validator para o projeto.
*
* @author helaine.lins
* @version
* @created 18:33:15
*/
public class ValidadorEntidade<E extends Entidade> {
/**
* Representa o mecanismo validador da entidade.
*/
private Validator validador;
/**
* Lista que matém todas as violações de uma propriedade.
*/
private List<Violacao> violacoes;
/**
* Inicializa o mecanismo de validação de entidades.
*/
public ValidadorEntidade(Class<E> classe) {
this.violacoes = new ArrayList<Violacao>();
this.validador = Validation.buildDefaultValidatorFactory().getValidator();
}
/**
* Aplica todas as validações nas propriedades mapeadas de uma {@link Entidade} com exceção das informadas como
* parâmetro.
*
* @param entidade A instância a ser validada.
* @param propriedadesIgnoradas A lista das propriedades que terão a <strong>validação ignorada</strong>
* @return Um {@link List} de {@link Erro} contendo as validações encontradas.
*/
public List<Erro> validate(E entidade, String... propriedadesIgnoradas) {
List<Erro> erros = new ArrayList<Erro>();
// recupera todas as propriedades declaradas na entidade para que sejam
// validadas.
PropertyDescriptor[] descritores = PropertyUtils.getPropertyDescriptors(entidade);
// aplica as validações respeitando as que devem ser ignoradas.
for (PropertyDescriptor descritor : descritores) {
String propriedade = descritor.getName();
if (!isPropriedadeEmLista(propriedade, propriedadesIgnoradas)) {
erros.addAll(validarPropriedade(entidade, propriedade));
}
}
return erros;
}
/**
* Identifica se a propriedade informada na {@link String} encontra-se na lista de propriedades a serem
* ignoradas.
*
* @param propriedade A instância da string a ser procurada.
* @param propIgnoradas A instância que contém a lista de strings onde a procura será realizada.
* @return <code>true</code> se a "string" estiver contida na lista de "strings", caso contrário
* <code>false</code>.
*/
protected boolean isPropriedadeEmLista(String propriedade, String... propIgnoradas) {
boolean isContida = false;
for (String stringAtual : propIgnoradas) {
if (stringAtual.equals(propriedade)) {
isContida = true;
}
}
return isContida;
}
/**
* Valida todos os atributos de uma {@link Entidade} e retorna uma lista de {@link FaultService} contendo as
* violações encontradas.
*
* @param entidade A instância que contém a propriedade a ser validada.
* @param propriedade O nome da propriedade.
* @return um {@link List} de violações {@link FaultService} contendo as mensagens a serem apresentadas ao
* usuário.
*/
public List<Erro> validarPropriedade(E entidade, String propriedade) {
Erro msgViolacao = null;
this.violacoes.clear();
// realiza a validação da propriedade. Uma propriedade pode retornar
// mais de uma violação.
Set<ConstraintViolation<E>> violacoesEncontradas = this.validador.validateProperty(entidade, propriedade);
List<Erro> violacoes = new ArrayList<Erro>();
String chaveProp = entidade.getClass().getSimpleName() + "." + propriedade;
StringBuilder desErro = new StringBuilder();
for (ConstraintViolation<E> valorInvalido : violacoesEncontradas) {
desErro.append(this.recuperarNomeExibicaoPropriedade(entidade, propriedade, chaveProp));
desErro.append(" ");
desErro.append(valorInvalido.getMessage());
msgViolacao = new Erro(chaveProp, desErro.toString(), TipoErro.HIBERNATE_VALIDATOR);
violacoes.add(msgViolacao);
}
this.violacoes.clear();
return violacoes;
}
/**
* Recupera o nome da propriedade validada para ser exibida ao usuário durante a exibição da exceção.
*
* @param entidade A entidade que está sendo validada.
* @param propriedade A propriedade que está sendo validada.
* @param chaveProp A chave da propriedade a ser procurar no arquivo de propriedades.
* @return Uma {@link String} contendo o nome da propriedade a ser apresentada para o usuário.
*/
private String recuperarNomeExibicaoPropriedade(E entidade, String propriedade, String chaveProp) {
String nomeProp = "O campo " + propriedade;
/*
* Foi montada uma convenção para recperar o nome da propriedade(amigável para o usuário) que está sendo
* validada. A conveção adotada é acrescentar no arquivo de proprieades ValidationMessages.properties a
* chave seguindo a conveção: NomeDaEntity.propriedade.
*
* Ex: Entidade.codEntidade=código da entidade
*
* Caso a conveção não seja satisfeita será retornada a mensagem padrão: 'O campo + propriedade'.
*/
return MapeamentoUtil.recuperarMensagemProperties(chaveProp, nomeProp);
}
}
|
/*
* Copyright 2012 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.uberfire.client.animations;
import com.google.gwt.user.client.ui.Widget;
/**
* A linear animation to fade a Widget from 1.0 to 0.0 opacity
*/
public class LinearFadeOutAnimation extends SequencedAnimation {
private Widget widget;
public LinearFadeOutAnimation(final Widget widget) {
this.widget = widget;
}
@Override
public void onUpdate(double progress) {
this.widget.getElement().getStyle().setOpacity( 1.0 - progress );
}
@Override
public double interpolate(double progress) {
return progress;
}
}
|
package org.nodes.util.bootstrap;
import static nl.peterbloem.kit.Functions.log2;
import static nl.peterbloem.kit.Functions.log2Sum;
import static nl.peterbloem.kit.LogNum.fromDouble;
import static nl.peterbloem.kit.Series.series;
import static org.nodes.util.bootstrap.BCaCI.beta;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.math3.distribution.NormalDistribution;
import nl.peterbloem.kit.Functions;
import nl.peterbloem.kit.LogNum;
public class LogBCaCI extends LogPercentileCI
{
private static final NormalDistribution N = new NormalDistribution();
protected double a, b;
protected LogBCaCI(List<LogNum> bootstraps, List<Double> data, Object blah)
{
super(bootstraps, data, blah);
compute();
}
public LogBCaCI(List<Double> data)
{
this(data, BS_SAMPLES);
}
public LogBCaCI(List<Double> data, int bootstrapSamples)
{
super(data, bootstrapSamples);
compute();
}
private void compute()
{
// * estimate a by the jackknife method
List<LogNum> means = new ArrayList<LogNum>(this.data.size());
for(int i : series(this.data.size()))
{
List<LogNum> fold = Functions.minList(this.data, i);
means.add(LogNum.mean(fold));
}
LogNum a = computeA(means);
// * estimate b
// * estimate b from the number of bootstrap means below the sample mean
int m = 0;
while(bootstraps.get(m).logMag() < dataMean.logMag())
m++;
b = N.inverseCumulativeProbability(m/(double)bootstraps.size());
}
protected static LogNum computeA(List<LogNum> jkEstimates)
{
LogNum mean = LogNum.mean(jkEstimates);
List<LogNum> diffs = new ArrayList<LogNum>(jkEstimates.size());
for(LogNum datum : jkEstimates)
diffs.add(mean.minus(datum));
List<LogNum> diffsTo2 = new ArrayList<LogNum>(jkEstimates.size());
for(LogNum diff : diffs)
diffsTo2.add(diff.pow(2));
List<LogNum> diffsTo3 = new ArrayList<LogNum>(jkEstimates.size());
for(LogNum diff : diffs)
diffsTo3.add(diff.pow(3));
LogNum num = LogNum.sum(diffsTo3);
LogNum den = LogNum.sum(diffsTo2);
den = den.root(2).pow(3).times(fromDouble(6.0, 2.0));
if(den.logMag() == Double.NEGATIVE_INFINITY) // prevent div by zero
return LogNum.fromDouble(0.0, den.base());
return num.divide(den);
}
@Override
public double lowerBound(double alpha)
{
int iBelow = (int) (beta(a, b, alpha) * bootstraps.size());
double rem = ((int) beta(a, b, alpha) * bootstraps.size()) - (double) iBelow;
if(iBelow == bootstraps.size() -1)
return bootstraps.get(iBelow).logMag();
return interpolate(bootstraps.get(iBelow), bootstraps.get(iBelow+1), (1.0 - rem)).logMag();
}
@Override
public double upperBound(double alpha)
{
int iBelow = (int) (beta(a, b, 1.0 - alpha) * bootstraps.size());
double rem = ((int) (beta(a, b, 1.0 - alpha) * bootstraps.size())) - (double) iBelow;
if(iBelow == bootstraps.size() -1)
return bootstraps.get(iBelow).logMag();
return interpolate(bootstraps.get(iBelow), bootstraps.get(iBelow+1), (1.0 - rem)).logMag();
}
/**
* Create a log bca model directly from a sequence of bootstrap values.
*
* This is useful for performing parametric bootstrap.
*
* @param logValues
* @return
*/
public static LogBCaCI fromBootstraps(List<Double> bootstraps, List<Double> data)
{
List<LogNum> bs = new ArrayList<LogNum>(bootstraps.size());
for(double val : bootstraps)
bs.add(new LogNum(val, true, 2.0));
return new LogBCaCI(bs, data, null);
}
}
|
package com.plantserver.service;
import org.apache.log4j.Logger;
import org.influxdb.InfluxDB;
import org.influxdb.dto.BatchPoints;
import org.influxdb.dto.Point;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
@Service
public class MessageConsumerService {
private static final Logger log = Logger.getLogger(MessageConsumerService.class);
@Autowired
private InfluxDB influxDB;
//@JmsListener(destination="${spring.activemq.queue}")
public void receiveMessage(String text) { // 进行消息接收处理
System.out.println("【*** 接收消息 ***】" + text);
String[] textarr = text.split(",");
//System.out.println(datestr+"-------------------");
try {
BatchPoints batchPoints = BatchPoints.database("plantsurv_web").build();
Point tmpPoint = Point.measurement("pt_new_" + textarr[1])
.time(Long.parseLong(textarr[2]),TimeUnit.MILLISECONDS)
.tag("device", textarr[1])
.addField("seq", textarr[3])
.addField("Ax", Float.parseFloat(textarr[4]))
.addField("Ay", Float.parseFloat(textarr[5]))
.addField("Az", Float.parseFloat(textarr[6]))
.addField("Wx", Float.parseFloat(textarr[7]))
.addField("Wy", Float.parseFloat(textarr[8]))
.addField("Wz", Float.parseFloat(textarr[9]))
.build();
batchPoints.point(tmpPoint);
influxDB.write(batchPoints);
System.out.println("============数 据 添 加 成 功==================");
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package protocol.network.messages.game.context.mount;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import protocol.utils.ProtocolTypeManager;
import protocol.network.util.types.BooleanByteWrapper;
import protocol.network.NetworkMessage;
import protocol.network.util.DofusDataReader;
import protocol.network.util.DofusDataWriter;
import protocol.network.Network;
import protocol.network.NetworkMessage;
import protocol.network.types.game.mount.MountClientData;
@SuppressWarnings("unused")
public class MountSetMessage extends NetworkMessage {
public static final int ProtocolId = 5968;
private MountClientData mountData;
public MountClientData getMountData() { return this.mountData; }
public void setMountData(MountClientData mountData) { this.mountData = mountData; };
public MountSetMessage(){
}
public MountSetMessage(MountClientData mountData){
this.mountData = mountData;
}
@Override
public void Serialize(DofusDataWriter writer) {
try {
mountData.Serialize(writer);
} catch (Exception e){
e.printStackTrace();
}
}
@Override
public void Deserialize(DofusDataReader reader) {
try {
this.mountData = new MountClientData();
this.mountData.Deserialize(reader);
} catch (Exception e){
e.printStackTrace();
}
}
}
|
/* MazeMode: A Maze-Solving Game
Copyright (C) 2008-2010 Eric Ahnell
Any questions should be directed to the author via email at: products@puttysoftware.com
*/
package com.puttysoftware.mazemode.objects;
import com.puttysoftware.mazemode.generic.GenericCarpet;
public class RoseCarpet extends GenericCarpet {
// Constructors
public RoseCarpet() {
super("Rose");
}
}
|
/**
* Leetcode - p0104_maximum_depth_of_binary_tree
*/
package com.abc.leetcode.p0104_maximum_depth_of_binary_tree;
// basic util
import java.util.*;
import com.ciaoshen.leetcode.util.*;
// leetcode-helper library
import com.ciaoshen.leetcode.helper.PropertyScanner;
// junit
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
// log4j
import org.apache.log4j.PropertyConfigurator;
// slf4j
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* In most case you DO NOT NEED TO CHANGE ANYTHING in this class.
*/
public class TesterRunner {
// use this Object to print the log (call from slf4j facade)
private static final Logger LOGGER = LoggerFactory.getLogger(TesterRunner.class);
// both log4j and slf4j are included in leetcode-helper.jar
private static final String LOG4J = "log4j.properties";
public static void main(String[] args) {
// use log4j as Logger implementation
Properties log4jProps = PropertyScanner.load(LOG4J); // PropertyScanner load "log4j.properties" for us
PropertyConfigurator.configure(log4jProps);
// run Tester.class
Result result = JUnitCore.runClasses(Tester.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure);
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Pass all JUnit test? {}", result.wasSuccessful());
}
}
}
|
package com.atguigu.gmall.ums.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* 收货地址表
*
* @author fengge
* @email fengge@atguigu.com
* @date 2020-10-13 14:06:30
*/
@Data
@TableName("ums_user_address")
public class UserAddressEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId
private Long id;
/**
* member_id
*/
private Long userId;
/**
* 收货人
*/
private String name;
/**
* 电话
*/
private String phone;
/**
* 右边
*/
private String postCode;
/**
* 省份
*/
private String province;
/**
* 城市
*/
private String city;
/**
* 区
*/
private String region;
/**
* 详细地址
*/
private String address;
/**
* 是否默认地址
*/
private Integer defaultStatus;
}
|
/*
* Copyright 2010-2019 Tim Boudreau
*
* 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.netbeans.validation.api.builtin.stringvalidation;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.netbeans.validation.api.Problems;
/**
*
* @author Tim Boudreau
*/
public class IpAddressValidatorTest {
private IpAddressValidator v = new IpAddressValidator();
@Test
public void testValidate() {
assertValid ("192.168.2.1");
assertValid ("192.168.2.1:2080");
assertValid ("0.0.0.0");
assertValid ("255.255.255.255");
assertInvalid ("192.168.2.1:2080303");
assertInvalid ("1.1.1.256");
assertInvalid ("1.1.1.256:10");
assertInvalid ("1.2");
assertInvalid ("192.168.2.1:");
assertInvalid ("192.168.2.1.");
assertInvalid ("192.168.2 .1");
assertInvalid ("192.168. .1");
assertInvalid ("192.168. 2.1");
assertInvalid (".192.168.2.1");
assertInvalid ("192.168.2.bad");
assertInvalid ("192.168.1");
assertInvalid ("foo.bar.com");
assertInvalid ("foo.bar.com:2080");
assertInvalid ("foo");
assertInvalid ("192.168.2.1::");
assertInvalid (":192.168.2.1");
assertInvalid ("2020:192.168.2.1");
assertInvalid ("192.168.2.1:192.168.2.1");
assertInvalid ("192.168.2.1:202p");
assertInvalid ("192.168.2.1:2080303:3030");
assertInvalid ("192.168.2..1:2080303:3030");
assertInvalid ("192.168.2..1:2080");
assertInvalid ("192.168.2..1::2080");
assertInvalid ("192.168:23.2.1:2080303:3030");
assertInvalid ("192.168:23.2.1:2080 ");
assertInvalid (" 192.168:23.2.1:2080 ");
assertInvalid (" 192.168:23.2.1:2080");
assertInvalid (" 192.168:23.2.1");
assertInvalid (" 192.168:23.2.1 ");
assertInvalid ("192.168:23.2.1 ");
assertInvalid ("192.168.2.1.abc");
assertInvalid ("192.168.2.abc");
assertInvalid ("192.168.2:2020:");
assertInvalid ("");
assertInvalid (".");
}
private void assertValid(String string) {
Problems p = new Problems();
v.validate(p, "X", string);
assertNull(p.getLeadProblem());
}
private void assertInvalid(String string) {
Problems p = new Problems();
v.validate(p, "X", string);
assertTrue(p.hasFatal());
}
}
|
package ex05.pyrmont.valves;
import org.apache.catalina.*;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import java.io.IOException;
public class ClientIPLoggerValve implements Valve, Contained {
protected Container container;
@Override
public void invoke(Request request, Response response, ValveContext valveContext)
throws IOException, ServletException {
// Pass this request on to the next valve in our pipeline
valveContext.invokeNext(request, response);
System.out.println("Client IP Logger Valve");
ServletRequest sreq = request.getRequest();
System.out.println(sreq.getRemoteAddr());
System.out.println("------------------------------------");
}
@Override
public String getInfo() {
return null;
}
@Override
public Container getContainer() {
return container;
}
@Override
public void setContainer(Container container) {
this.container = container;
}
}
|
package net.minecraft.world.entity.animal;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.syncher.EntityDataAccessor;
import net.minecraft.network.syncher.EntityDataSerializers;
import net.minecraft.network.syncher.SynchedEntityData;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.tags.FluidTags;
import net.minecraft.util.Mth;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.EntityDimensions;
import net.minecraft.world.entity.EntitySelector;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.MoverType;
import net.minecraft.world.entity.Pose;
import net.minecraft.world.entity.ai.attributes.AttributeSupplier;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.entity.ai.control.MoveControl;
import net.minecraft.world.entity.ai.goal.AvoidEntityGoal;
import net.minecraft.world.entity.ai.goal.PanicGoal;
import net.minecraft.world.entity.ai.goal.RandomSwimmingGoal;
import net.minecraft.world.entity.ai.navigation.PathNavigation;
import net.minecraft.world.entity.ai.navigation.WaterBoundPathNavigation;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.Vec3;
public abstract class AbstractFish extends WaterAnimal implements Bucketable {
private static final EntityDataAccessor<Boolean> FROM_BUCKET = SynchedEntityData.defineId(AbstractFish.class, EntityDataSerializers.BOOLEAN);
public AbstractFish(EntityType<? extends AbstractFish> p_27461_, Level p_27462_) {
super(p_27461_, p_27462_);
this.moveControl = new AbstractFish.FishMoveControl(this);
}
protected float getStandingEyeHeight(Pose p_27474_, EntityDimensions p_27475_) {
return p_27475_.height * 0.65F;
}
public static AttributeSupplier.Builder createAttributes() {
return Mob.createMobAttributes().add(Attributes.MAX_HEALTH, 3.0D);
}
public boolean requiresCustomPersistence() {
return super.requiresCustomPersistence() || this.fromBucket();
}
public boolean removeWhenFarAway(double p_27492_) {
return !this.fromBucket() && !this.hasCustomName();
}
public int getMaxSpawnClusterSize() {
return 8;
}
protected void defineSynchedData() {
super.defineSynchedData();
this.entityData.define(FROM_BUCKET, false);
}
public boolean fromBucket() {
return this.entityData.get(FROM_BUCKET);
}
public void setFromBucket(boolean p_27498_) {
this.entityData.set(FROM_BUCKET, p_27498_);
}
public void addAdditionalSaveData(CompoundTag p_27485_) {
super.addAdditionalSaveData(p_27485_);
p_27485_.putBoolean("FromBucket", this.fromBucket());
}
public void readAdditionalSaveData(CompoundTag p_27465_) {
super.readAdditionalSaveData(p_27465_);
this.setFromBucket(p_27465_.getBoolean("FromBucket"));
}
protected void registerGoals() {
super.registerGoals();
this.goalSelector.addGoal(0, new PanicGoal(this, 1.25D));
this.goalSelector.addGoal(2, new AvoidEntityGoal<>(this, Player.class, 8.0F, 1.6D, 1.4D, EntitySelector.NO_SPECTATORS::test));
this.goalSelector.addGoal(4, new AbstractFish.FishSwimGoal(this));
}
protected PathNavigation createNavigation(Level p_27480_) {
return new WaterBoundPathNavigation(this, p_27480_);
}
public void travel(Vec3 p_27490_) {
if (this.isEffectiveAi() && this.isInWater()) {
this.moveRelative(0.01F, p_27490_);
this.move(MoverType.SELF, this.getDeltaMovement());
this.setDeltaMovement(this.getDeltaMovement().scale(0.9D));
if (this.getTarget() == null) {
this.setDeltaMovement(this.getDeltaMovement().add(0.0D, -0.005D, 0.0D));
}
} else {
super.travel(p_27490_);
}
}
public void aiStep() {
if (!this.isInWater() && this.onGround && this.verticalCollision) {
this.setDeltaMovement(this.getDeltaMovement().add((double)((this.random.nextFloat() * 2.0F - 1.0F) * 0.05F), (double)0.4F, (double)((this.random.nextFloat() * 2.0F - 1.0F) * 0.05F)));
this.onGround = false;
this.hasImpulse = true;
this.playSound(this.getFlopSound(), this.getSoundVolume(), this.getVoicePitch());
}
super.aiStep();
}
protected InteractionResult mobInteract(Player p_27477_, InteractionHand p_27478_) {
return Bucketable.bucketMobPickup(p_27477_, p_27478_, this).orElse(super.mobInteract(p_27477_, p_27478_));
}
public void saveToBucketTag(ItemStack p_27494_) {
Bucketable.saveDefaultDataToBucketTag(this, p_27494_);
}
public void loadFromBucketTag(CompoundTag p_148708_) {
Bucketable.loadDefaultDataFromBucketTag(this, p_148708_);
}
public SoundEvent getPickupSound() {
return SoundEvents.BUCKET_FILL_FISH;
}
protected boolean canRandomSwim() {
return true;
}
protected abstract SoundEvent getFlopSound();
protected SoundEvent getSwimSound() {
return SoundEvents.FISH_SWIM;
}
protected void playStepSound(BlockPos p_27482_, BlockState p_27483_) {
}
static class FishMoveControl extends MoveControl {
private final AbstractFish fish;
FishMoveControl(AbstractFish p_27501_) {
super(p_27501_);
this.fish = p_27501_;
}
public void tick() {
if (this.fish.isEyeInFluid(FluidTags.WATER)) {
this.fish.setDeltaMovement(this.fish.getDeltaMovement().add(0.0D, 0.005D, 0.0D));
}
if (this.operation == MoveControl.Operation.MOVE_TO && !this.fish.getNavigation().isDone()) {
float f = (float)(this.speedModifier * this.fish.getAttributeValue(Attributes.MOVEMENT_SPEED));
this.fish.setSpeed(Mth.lerp(0.125F, this.fish.getSpeed(), f));
double d0 = this.wantedX - this.fish.getX();
double d1 = this.wantedY - this.fish.getY();
double d2 = this.wantedZ - this.fish.getZ();
if (d1 != 0.0D) {
double d3 = Math.sqrt(d0 * d0 + d1 * d1 + d2 * d2);
this.fish.setDeltaMovement(this.fish.getDeltaMovement().add(0.0D, (double)this.fish.getSpeed() * (d1 / d3) * 0.1D, 0.0D));
}
if (d0 != 0.0D || d2 != 0.0D) {
float f1 = (float)(Mth.atan2(d2, d0) * (double)(180F / (float)Math.PI)) - 90.0F;
this.fish.setYRot(this.rotlerp(this.fish.getYRot(), f1, 90.0F));
this.fish.yBodyRot = this.fish.getYRot();
}
} else {
this.fish.setSpeed(0.0F);
}
}
}
static class FishSwimGoal extends RandomSwimmingGoal {
private final AbstractFish fish;
public FishSwimGoal(AbstractFish p_27505_) {
super(p_27505_, 1.0D, 40);
this.fish = p_27505_;
}
public boolean canUse() {
return this.fish.canRandomSwim() && super.canUse();
}
}
}
|
/**
* Logback: the reliable, generic, fast and flexible logging framework.
* Copyright (C) 1999-2015, QOS.ch. All rights reserved.
*
* This program and the accompanying materials are dual-licensed under
* either the terms of the Eclipse Public License v1.0 as published by
* the Eclipse Foundation
*
* or (per the licensee's choosing)
*
* under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation.
*/
package ch.qos.logback.access.spi;
import java.util.Map;
/**
* An interface to access server-specific methods from
* the server-independent AccessEvent.
*
* @author Ceki Gülcü
* @author Sébastien Pennec
*/
public interface ServerAdapter {
long getRequestTimestamp();
long getContentLength();
int getStatusCode();
Map<String, String> buildResponseHeaderMap();
}
|
/*
* 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.jclouds.oauth.v2;
import static com.google.common.base.Charsets.UTF_8;
import static com.google.common.io.BaseEncoding.base64Url;
import static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static org.jclouds.Constants.PROPERTY_MAX_RETRIES;
import static org.jclouds.oauth.v2.config.CredentialType.P12_PRIVATE_KEY_CREDENTIALS;
import static org.jclouds.oauth.v2.config.CredentialType.CLIENT_CREDENTIALS_SECRET;
import static org.jclouds.oauth.v2.config.CredentialType.CLIENT_CREDENTIALS_P12_AND_CERTIFICATE;
import static org.jclouds.oauth.v2.config.OAuthProperties.CERTIFICATE;
import static org.jclouds.oauth.v2.config.OAuthProperties.AUDIENCE;
import static org.jclouds.oauth.v2.config.OAuthProperties.CREDENTIAL_TYPE;
import static org.jclouds.oauth.v2.config.OAuthProperties.JWS_ALG;
import static org.jclouds.oauth.v2.config.OAuthProperties.RESOURCE;
import static org.jclouds.util.Strings2.toStringAndClose;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import org.jclouds.ContextBuilder;
import org.jclouds.concurrent.config.ExecutorServiceModule;
import org.jclouds.oauth.v2.config.CredentialType;
import org.jclouds.oauth.v2.config.OAuthModule;
import org.jclouds.oauth.v2.config.OAuthScopes;
import org.jclouds.oauth.v2.config.OAuthScopes.SingleScope;
import org.jclouds.oauth.v2.domain.Claims;
import org.jclouds.oauth.v2.domain.ClientCredentialsClaims;
import org.jclouds.oauth.v2.domain.Token;
import org.jclouds.rest.AnonymousHttpApiMetadata;
import org.jclouds.rest.AuthorizationException;
import org.testng.annotations.Test;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.BaseEncoding;
import com.google.inject.Binder;
import com.google.inject.Module;
import com.squareup.okhttp.mockwebserver.MockResponse;
import com.squareup.okhttp.mockwebserver.MockWebServer;
import com.squareup.okhttp.mockwebserver.RecordedRequest;
@Test(groups = "unit", testName = "OAuthApiMockTest")
public class AuthorizationApiMockTest {
private static final String SCOPE = "https://www.googleapis.com/auth/prediction";
private static final String header = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}";
private static final String claims = "{\"iss\":\"761326798069-r5mljlln1rd4lrbhg75efgigp36m78j5@developer"
+ ".gserviceaccount.com\",\"scope\":\"" + SCOPE + "\",\"aud\":\"https://accounts.google"
+ ".com/o/oauth2/token\",\"exp\":1328573381,\"iat\":1328569781}";
private static final Token TOKEN = Token.create("1/8xbJqaOZXSUZbHLl5EOtu1pxz3fmmetKx9W8CV4t79M", "Bearer", 3600);
private static final Claims CLAIMS = Claims.create(
"761326798069-r5mljlln1rd4lrbhg75efgigp36m78j5@developer.gserviceaccount.com", // iss
SCOPE, // scope
"https://accounts.google.com/o/oauth2/token", // aud
1328573381, // exp
1328569781 // iat
);
private static final String clientCredentialsHeader = "{\"alg\":\"RS256\",\"typ\":\"JWT\",\"x5t\":\"RZk6mx4gGECvF6XWZWkK9qaGdHk=\"}";
private static final String clientCredentialsClaims = "{\"iss\":\"a242b44e-2c2a-3bdd-b094-6152da263c54\"," +
"\"sub\":\"a242b44e-2c2a-3bdd-b094-6152da263c54\",\"aud\":" +
"\"https://login.microsoftonline.com/a242ccee-1a1a-3bdd-b094-6152da263c54/oauth2/token\"" +
",\"exp\":1328573381,\"nbf\":1328569781,\"jti\":\"abcdefgh\"}";
private static final ClientCredentialsClaims CLIENT_CREDENTIALS_CLAIMS = ClientCredentialsClaims.create(
"a242b44e-2c2a-3bdd-b094-6152da263c54", // iss
"a242b44e-2c2a-3bdd-b094-6152da263c54", // sub
"https://login.microsoftonline.com/a242ccee-1a1a-3bdd-b094-6152da263c54/oauth2/token", //aud
1328573381, // exp
1328569781, // nbf
"abcdefgh" // jti
);
public void testGenerateJWTRequest() throws Exception {
MockWebServer server = new MockWebServer();
try {
server.enqueue(new MockResponse().setBody("{\n"
+ " \"access_token\" : \"1/8xbJqaOZXSUZbHLl5EOtu1pxz3fmmetKx9W8CV4t79M\",\n"
+ " \"token_type\" : \"Bearer\",\n" + " \"expires_in\" : 3600\n" + "}"));
server.play();
AuthorizationApi api = api(server.getUrl("/"), P12_PRIVATE_KEY_CREDENTIALS);
assertEquals(api.authorize(CLAIMS), TOKEN);
RecordedRequest request = server.takeRequest();
assertEquals(request.getMethod(), "POST");
assertEquals(request.getHeader("Accept"), APPLICATION_JSON);
assertEquals(request.getHeader("Content-Type"), "application/x-www-form-urlencoded");
assertEquals(
new String(request.getBody(), UTF_8), //
"grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&"
+
// Base64 Encoded Header
"assertion="
+ Joiner.on('.').join(encoding.encode(header.getBytes(UTF_8)),
encoding.encode(claims.getBytes(UTF_8)),
// Base64 encoded {header}.{claims} signature (using
// SHA256)
"W2Lesr_98AzVYiMbzxFqmwcOjpIWlwqkC6pNn1fXND9oSDNNnFhy-AAR6DKH-x9ZmxbY80"
+ "R5fH-OCeWumXlVgceKN8Z2SmgQsu8ElTpypQA54j_5j8vUImJ5hsOUYPeyF1U2BUzZ3L5g"
+ "03PXBA0YWwRU9E1ChH28dQBYuGiUmYw"));
} finally {
server.shutdown();
}
}
public void testAuthorizationExceptionIsPopulatedOn4xx() throws Exception {
MockWebServer server = new MockWebServer();
try {
server.enqueue(new MockResponse().setResponseCode(400));
server.play();
AuthorizationApi api = api(server.getUrl("/"), P12_PRIVATE_KEY_CREDENTIALS);
api.authorize(CLAIMS);
fail("An AuthorizationException should have been raised");
} catch (AuthorizationException ex) {
// Success
} finally {
server.shutdown();
}
}
public void testGenerateClientSecretRequest() throws Exception {
MockWebServer server = new MockWebServer();
String credential = "password";
String identity = "user";
String resource = "http://management.azure.com/";
String encoded_resource = "http%3A//management.azure.com/";
try {
server.enqueue(new MockResponse().setBody("{\n"
+ " \"access_token\" : \"1/8xbJqaOZXSUZbHLl5EOtu1pxz3fmmetKx9W8CV4t79M\",\n"
+ " \"token_type\" : \"Bearer\",\n" + " \"expires_in\" : 3600\n" + "}"));
server.play();
AuthorizationApi api = api(server.getUrl("/"), CLIENT_CREDENTIALS_SECRET);
assertEquals(api.authorizeClientSecret(identity, credential, resource, null), TOKEN);
RecordedRequest request = server.takeRequest();
assertEquals(request.getMethod(), "POST");
assertEquals(request.getHeader("Accept"), APPLICATION_JSON);
assertEquals(request.getHeader("Content-Type"), "application/x-www-form-urlencoded");
assertEquals(
new String(request.getBody(), UTF_8), //
"grant_type=client_credentials&client_id=" + identity
+ "&client_secret=" + credential
+ "&resource=" + encoded_resource);
} finally {
server.shutdown();
}
}
public void testGenerateClientCredentialsJWTRequest() throws Exception {
MockWebServer server = new MockWebServer();
String identity = "user";
String resource = "http://management.azure.com/";
String encoded_resource = "http%3A//management.azure.com/";
try {
server.enqueue(new MockResponse().setBody("{\n"
+ " \"access_token\" : \"1/8xbJqaOZXSUZbHLl5EOtu1pxz3fmmetKx9W8CV4t79M\",\n"
+ " \"token_type\" : \"Bearer\",\n" + " \"expires_in\" : 3600\n" + "}"));
server.play();
AuthorizationApi api = api(server.getUrl("/"), CLIENT_CREDENTIALS_P12_AND_CERTIFICATE);
assertEquals(api.authorize(identity, CLIENT_CREDENTIALS_CLAIMS, resource, null), TOKEN);
RecordedRequest request = server.takeRequest();
assertEquals(request.getMethod(), "POST");
assertEquals(request.getHeader("Accept"), APPLICATION_JSON);
assertEquals(request.getHeader("Content-Type"), "application/x-www-form-urlencoded");
assertEquals(
new String(request.getBody(), UTF_8),
"grant_type=client_credentials&" +
"client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer&" +
"client_id=" + identity + "&" +
"client_assertion=" +
Joiner.on(".").join(encoding.encode(clientCredentialsHeader.getBytes(UTF_8)),
encoding.encode(clientCredentialsClaims.getBytes(UTF_8)),
"ip3i0YLlunb4iq8sUMlpYDKnEuzmvlLpF4NQvn_aiysO5cuT5QHuGREq" +
"gyEa-UMhfZoW49ggUWjS7YBT00r64cFE3dovaNMiZYZuVWu_" +
"FpqO2QlwV7uXqhaRIE0cyabbKG44YJwA-NE4rtFZedFMo94F" +
"6aOz2FN3en8zS9UVqmM"
) + "&" +
"resource=" + encoded_resource);
} finally {
server.shutdown();
}
}
private final BaseEncoding encoding = base64Url().omitPadding();
private AuthorizationApi api(URL url, CredentialType credentialType) throws IOException {
Properties overrides = new Properties();
overrides.setProperty("oauth.endpoint", url.toString());
overrides.setProperty(JWS_ALG, "RS256");
overrides.setProperty(CREDENTIAL_TYPE, credentialType.toString());
overrides.setProperty(AUDIENCE, "https://accounts.google.com/o/oauth2/token");
overrides.setProperty(RESOURCE, "https://management.azure.com/");
overrides.setProperty(PROPERTY_MAX_RETRIES, "1");
overrides.setProperty(CERTIFICATE, toStringAndClose(OAuthTestUtils.class.getResourceAsStream("/testcert.pem")));
return ContextBuilder.newBuilder(AnonymousHttpApiMetadata.forApi(AuthorizationApi.class))
.credentials("foo", toStringAndClose(OAuthTestUtils.class.getResourceAsStream("/testpk.pem")))
.endpoint(url.toString())
.overrides(overrides)
.modules(ImmutableSet.of(new ExecutorServiceModule(newDirectExecutorService()), new OAuthModule(), new Module() {
@Override public void configure(Binder binder) {
binder.bind(OAuthScopes.class).toInstance(SingleScope.create(SCOPE));
}
}))
.buildApi(AuthorizationApi.class);
}
}
|
package cookbuddy.logic.commands;
import static java.util.Objects.requireNonNull;
import java.util.List;
import cookbuddy.commons.core.Messages;
import cookbuddy.commons.core.index.Index;
import cookbuddy.logic.commands.exceptions.CommandException;
import cookbuddy.model.Model;
import cookbuddy.model.recipe.Recipe;
import cookbuddy.ui.UiManager;
/**
* Lists all recipes in the recipe book to the user.
*/
public class ViewCommand extends Command {
public static final String COMMAND_WORD = "view";
public static final String MESSAGE_USAGE = COMMAND_WORD
+ ": Views the recipe identified by the index number shown in the displayed recipe list.\n"
+ "Parameters: INDEX (must be a positive integer)\n"
+ "Example: " + COMMAND_WORD + " 1";
public static final String MESSAGE_VIEW_RECIPE_SUCCESS = "Viewing Recipe: %1$s";
private final Index targetIndex;
public ViewCommand(Index targetIndex) {
this.targetIndex = targetIndex;
}
@Override
public CommandResult execute(Model model) throws CommandException {
requireNonNull(model);
List<Recipe> lastShownList = model.getFilteredRecipeList();
if (targetIndex.getZeroBased() >= lastShownList.size()) {
throw new CommandException(Messages.MESSAGE_INVALID_RECIPE_DISPLAYED_INDEX);
}
Recipe recipeToView = lastShownList.get(targetIndex.getZeroBased());
UiManager.changeRecipe(recipeToView);
return new CommandResult(String.format(MESSAGE_VIEW_RECIPE_SUCCESS, recipeToView.getName()));
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof ViewCommand // instanceof handles nulls
&& targetIndex.equals(((ViewCommand) other).targetIndex)); // state check
}
}
|
/*
* Copyright (c) 2015 Ha Duy Trung
*
* 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.github.hidroh.materialistic;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import javax.inject.Inject;
public class DrawerFragment extends BaseFragment {
@Inject AlertDialogBuilder mAlertDialogBuilder;
private TextView mDrawerAccount;
private View mDrawerLogout;
private View mDrawerUser;
private final SharedPreferences.OnSharedPreferenceChangeListener mLoginListener
= new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (getActivity() == null) {
return;
}
if (TextUtils.equals(key, getActivity().getString(R.string.pref_username))) {
setUsername();
}
}
};
@Override
public void onAttach(Context context) {
super.onAttach(context);
PreferenceManager.getDefaultSharedPreferences(getActivity())
.registerOnSharedPreferenceChangeListener(mLoginListener);
}
@Override
public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable final Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_drawer, container, false);
mDrawerAccount = (TextView) view.findViewById(R.id.drawer_account);
mDrawerAccount.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Account[] accounts = AccountManager.get(getActivity())
.getAccountsByType(BuildConfig.APPLICATION_ID);
if (accounts.length == 0) { // no accounts, ask to login or re-login
startActivity(new Intent(getActivity(), LoginActivity.class));
} else { // has accounts, show account chooser regardless of login status
AppUtils.showAccountChooser(getActivity(), mAlertDialogBuilder,
accounts);
}
}
});
mDrawerLogout = view.findViewById(R.id.drawer_logout);
mDrawerLogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAlertDialogBuilder
.init(getActivity())
.setMessage(R.string.logout_confirm)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Preferences.setUsername(getActivity(), null);
}
})
.show();
}
});
mDrawerUser = view.findViewById(R.id.drawer_user);
view.findViewById(R.id.drawer_list).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
navigate(ListActivity.class);
}
});
view.findViewById(R.id.drawer_popular).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
navigate(PopularActivity.class);
}
});
view.findViewById(R.id.drawer_new).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
navigate(NewActivity.class);
}
});
view.findViewById(R.id.drawer_show).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
navigate(ShowActivity.class);
}
});
view.findViewById(R.id.drawer_ask).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
navigate(AskActivity.class);
}
});
view.findViewById(R.id.drawer_job).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
navigate(JobsActivity.class);
}
});
view.findViewById(R.id.drawer_settings).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
navigate(SettingsActivity.class);
}
});
view.findViewById(R.id.drawer_about).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
navigate(AboutActivity.class);
}
});
view.findViewById(R.id.drawer_favorite).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
navigate(FavoriteActivity.class);
}
});
view.findViewById(R.id.drawer_submit).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
navigate(SubmitActivity.class);
}
});
view.findViewById(R.id.drawer_user).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bundle extras = new Bundle();
extras.putString(UserActivity.EXTRA_USERNAME, Preferences.getUsername(getActivity()));
navigate(UserActivity.class, extras);
}
});
view.findViewById(R.id.drawer_feedback).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
((DrawerActivity) getActivity()).showFeedback();
}
});
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setUsername();
}
@Override
public void onDestroy() {
super.onDestroy();
PreferenceManager.getDefaultSharedPreferences(getActivity())
.unregisterOnSharedPreferenceChangeListener(mLoginListener);
}
private void navigate(Class<? extends Activity> activityClass) {
navigate(activityClass, null);
}
private void navigate(Class<? extends Activity> activityClass, Bundle extras) {
((DrawerActivity) getActivity()).navigate(activityClass, extras);
}
private void setUsername() {
if (getView() == null) {
return;
}
String username = Preferences.getUsername(getActivity());
if (!TextUtils.isEmpty(username)) {
mDrawerAccount.setText(username);
mDrawerLogout.setVisibility(View.VISIBLE);
mDrawerUser.setVisibility(View.VISIBLE);
} else {
mDrawerAccount.setText(R.string.login);
mDrawerLogout.setVisibility(View.GONE);
mDrawerUser.setVisibility(View.GONE);
}
}
}
|
package io.github.mariazevedo88.travelsjavaapi.exception;
/**
* Class that implements TransactionInvalidUpdateException in the API.
*
* @author Mariana Azevedo
* @since 01/04/2020
*/
public class TravelInvalidUpdateException extends Exception{
private static final long serialVersionUID = -6443362632495638948L;
public TravelInvalidUpdateException(){
super();
}
public TravelInvalidUpdateException(String msg){
super(msg);
}
public TravelInvalidUpdateException(String msg, Throwable cause){
super(msg, cause);
}
}
|
package com.leyou.order.config;
import com.leyou.common.utils.IdWorker;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableConfigurationProperties(IdWorkerProperties.class)
public class IdWorkerConfig {
/**
* 注册IdWorker
* @param prop
* @return
*/
@Bean
public IdWorker idWorker(IdWorkerProperties prop) {
return new IdWorker(prop.getWorkerId(), prop.getDatacenterId());
}
}
|
/**
* Copyright 2009-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.ibatis.scripting;
import java.util.HashMap;
import java.util.Map;
/**
* @author Frank D. Martinez [mnesarco]
*/
public class LanguageDriverRegistry {
private final Map<Class<? extends LanguageDriver>, LanguageDriver> languageDriverMap = new HashMap<>();
private Class<? extends LanguageDriver> defaultDriverClass;
public void register(Class<? extends LanguageDriver> cls) {
if (cls == null) {
throw new IllegalArgumentException("null is not a valid Language Driver");
}
if (!languageDriverMap.containsKey(cls)) {
try {
languageDriverMap.put(cls, cls.newInstance());
} catch (Exception ex) {
throw new ScriptingException("Failed to load language driver for " + cls.getName(), ex);
}
}
}
public void register(LanguageDriver instance) {
if (instance == null) {
throw new IllegalArgumentException("null is not a valid Language Driver");
}
Class<? extends LanguageDriver> cls = instance.getClass();
if (!languageDriverMap.containsKey(cls)) {
languageDriverMap.put(cls, instance);
}
}
public LanguageDriver getDriver(Class<? extends LanguageDriver> cls) {
return languageDriverMap.get(cls);
}
public LanguageDriver getDefaultDriver() {
return getDriver(getDefaultDriverClass());
}
public Class<? extends LanguageDriver> getDefaultDriverClass() {
return defaultDriverClass;
}
public void setDefaultDriverClass(Class<? extends LanguageDriver> defaultDriverClass) {
register(defaultDriverClass);
this.defaultDriverClass = defaultDriverClass;
}
}
|
/*
* Copyright 2013 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.xd.dirt.integration.bus;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.junit.Before;
import org.junit.Test;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.converter.ContentTypeResolver;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;
import org.springframework.xd.dirt.integration.bus.MessageBusSupport.JavaClassMimeTypeConversion;
import org.springframework.xd.dirt.integration.bus.serializer.AbstractCodec;
import org.springframework.xd.dirt.integration.bus.serializer.CompositeCodec;
import org.springframework.xd.dirt.integration.bus.serializer.kryo.PojoCodec;
import org.springframework.xd.tuple.serializer.kryo.TupleCodec;
import org.springframework.xd.tuple.DefaultTuple;
import org.springframework.xd.tuple.Tuple;
import org.springframework.xd.tuple.TupleBuilder;
/**
* @author Gary Russell
* @author David Turanski
*/
public class MessageBusSupportTests {
private ContentTypeResolver contentTypeResolver = new StringConvertingContentTypeResolver();
private final TestMessageBus messageBus = new TestMessageBus();
@SuppressWarnings({"unchecked", "rawtypes"})
@Before
public void setUp() {
Map<Class<?>, AbstractCodec<?>> codecs = new HashMap<>();
codecs.put(Tuple.class, new TupleCodec());
messageBus.setCodec(new CompositeCodec(codecs, new PojoCodec()));
}
@Test
public void testBytesPassThru() {
byte[] payload = "foo".getBytes();
Message<byte[]> message = MessageBuilder.withPayload(payload).build();
MessageValues converted = messageBus.serializePayloadIfNecessary(message,
MimeTypeUtils.APPLICATION_OCTET_STREAM);
assertSame(payload, converted.getPayload());
Message<?> convertedMessage = converted.toMessage();
assertSame(payload, convertedMessage.getPayload());
assertEquals(MimeTypeUtils.APPLICATION_OCTET_STREAM,
contentTypeResolver.resolve(convertedMessage.getHeaders()));
MessageValues reconstructed = messageBus.deserializePayloadIfNecessary(convertedMessage);
payload = (byte[]) reconstructed.getPayload();
assertSame(converted.getPayload(), payload);
assertNull(reconstructed.get(XdHeaders.XD_ORIGINAL_CONTENT_TYPE));
}
@Test
public void testBytesPassThruContentType() {
byte[] payload = "foo".getBytes();
Message<byte[]> message = MessageBuilder.withPayload(payload)
.setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_OCTET_STREAM_VALUE)
.build();
MessageValues messageValues = messageBus.serializePayloadIfNecessary(message,
MimeTypeUtils.APPLICATION_OCTET_STREAM);
Message<?> converted = messageValues.toMessage();
assertSame(payload, converted.getPayload());
assertEquals(MimeTypeUtils.APPLICATION_OCTET_STREAM,
contentTypeResolver.resolve(converted.getHeaders()));
MessageValues reconstructed = messageBus.deserializePayloadIfNecessary(converted);
payload = (byte[]) reconstructed.getPayload();
assertSame(converted.getPayload(), payload);
assertEquals(MimeTypeUtils.APPLICATION_OCTET_STREAM_VALUE,
reconstructed.get(MessageHeaders.CONTENT_TYPE));
assertNull(reconstructed.get(XdHeaders.XD_ORIGINAL_CONTENT_TYPE));
}
@Test
public void testString() throws IOException {
MessageValues convertedValues = messageBus.serializePayloadIfNecessary(
new GenericMessage<String>("foo"), MimeTypeUtils.APPLICATION_OCTET_STREAM);
Message<?> converted = convertedValues.toMessage();
assertEquals(MimeTypeUtils.TEXT_PLAIN,
contentTypeResolver.resolve(converted.getHeaders()));
MessageValues reconstructed = messageBus.deserializePayloadIfNecessary(converted);
assertEquals("foo", reconstructed.getPayload());
assertNull(reconstructed.get(MessageHeaders.CONTENT_TYPE));
}
@Test
public void testContentTypePreserved() throws IOException {
Message<String> inbound = MessageBuilder.withPayload("{\"foo\":\"foo\"}")
.copyHeaders(Collections.singletonMap(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON))
.build();
MessageValues convertedValues = messageBus.serializePayloadIfNecessary(
inbound, MimeTypeUtils.APPLICATION_OCTET_STREAM);
Message<?> converted = convertedValues.toMessage();
assertEquals(MimeTypeUtils.TEXT_PLAIN,
contentTypeResolver.resolve(converted.getHeaders()));
assertEquals(MimeTypeUtils.APPLICATION_JSON,
converted.getHeaders().get(XdHeaders.XD_ORIGINAL_CONTENT_TYPE));
MessageValues reconstructed = messageBus.deserializePayloadIfNecessary(converted);
assertEquals("{\"foo\":\"foo\"}", reconstructed.getPayload());
assertEquals(MimeTypeUtils.APPLICATION_JSON, reconstructed.get(MessageHeaders.CONTENT_TYPE));
}
@Test
public void testPojoSerialization() {
MessageValues convertedValues = messageBus.serializePayloadIfNecessary(
new GenericMessage<Foo>(new Foo("bar")),
MimeTypeUtils.APPLICATION_OCTET_STREAM);
Message<?> converted = convertedValues.toMessage();
MimeType mimeType = contentTypeResolver.resolve(converted.getHeaders());
assertEquals("application", mimeType.getType());
assertEquals("x-java-object", mimeType.getSubtype());
assertEquals(Foo.class.getName(), mimeType.getParameter("type"));
MessageValues reconstructed = messageBus.deserializePayloadIfNecessary(converted);
assertEquals("bar", ((Foo) reconstructed.getPayload()).getBar());
assertNull(reconstructed.get(MessageHeaders.CONTENT_TYPE));
}
@Test
public void testPojoWithXJavaObjectMimeTypeNoType() {
MessageValues convertedValues = messageBus.serializePayloadIfNecessary(
new GenericMessage<Foo>(new Foo("bar")),
MimeTypeUtils.APPLICATION_OCTET_STREAM);
Message<?> converted = convertedValues.toMessage();
MimeType mimeType = contentTypeResolver.resolve(converted.getHeaders());
assertEquals("application", mimeType.getType());
assertEquals("x-java-object", mimeType.getSubtype());
assertEquals(Foo.class.getName(), mimeType.getParameter("type"));
MessageValues reconstructed = messageBus.deserializePayloadIfNecessary(converted);
assertEquals("bar", ((Foo) reconstructed.getPayload()).getBar());
assertNull(reconstructed.get(MessageHeaders.CONTENT_TYPE));
}
@Test
public void testPojoWithXJavaObjectMimeTypeExplicitType() {
MessageValues convertedValues = messageBus.serializePayloadIfNecessary(
new GenericMessage<Foo>(new Foo("bar")),
MimeTypeUtils.APPLICATION_OCTET_STREAM);
Message<?> converted = convertedValues.toMessage();
MimeType mimeType = contentTypeResolver.resolve(converted.getHeaders());
assertEquals("application", mimeType.getType());
assertEquals("x-java-object", mimeType.getSubtype());
assertEquals(Foo.class.getName(), mimeType.getParameter("type"));
MessageValues reconstructed = messageBus.deserializePayloadIfNecessary(converted);
assertEquals("bar", ((Foo) reconstructed.getPayload()).getBar());
assertNull(reconstructed.get(MessageHeaders.CONTENT_TYPE));
}
@Test
public void testTupleSerialization() {
Tuple payload = TupleBuilder.tuple().of("foo", "bar");
MessageValues convertedValues = messageBus.serializePayloadIfNecessary(new GenericMessage<Tuple>(payload),
MimeTypeUtils.APPLICATION_OCTET_STREAM);
Message<?> converted = convertedValues.toMessage();
MimeType mimeType = contentTypeResolver.resolve(converted.getHeaders());
assertEquals("application", mimeType.getType());
assertEquals("x-java-object", mimeType.getSubtype());
assertEquals(DefaultTuple.class.getName(), mimeType.getParameter("type"));
MessageValues reconstructed = messageBus.deserializePayloadIfNecessary(converted);
assertEquals("bar", ((Tuple) reconstructed.getPayload()).getString("foo"));
assertNull(reconstructed.get(MessageHeaders.CONTENT_TYPE));
}
@Test
public void mimeTypeIsSimpleObject() throws ClassNotFoundException {
MimeType mt = JavaClassMimeTypeConversion.mimeTypeFromObject(new Object());
String className = JavaClassMimeTypeConversion.classNameFromMimeType(mt);
assertEquals(Object.class, Class.forName(className));
}
@Test
public void mimeTypeIsObjectArray() throws ClassNotFoundException {
MimeType mt = JavaClassMimeTypeConversion.mimeTypeFromObject(new String[0]);
String className = JavaClassMimeTypeConversion.classNameFromMimeType(mt);
assertEquals(String[].class, Class.forName(className));
}
@Test
public void mimeTypeIsMultiDimensionalObjectArray() throws ClassNotFoundException {
MimeType mt = JavaClassMimeTypeConversion.mimeTypeFromObject(new String[0][0][0]);
String className = JavaClassMimeTypeConversion.classNameFromMimeType(mt);
assertEquals(String[][][].class, Class.forName(className));
}
@Test
public void mimeTypeIsPrimitiveArray() throws ClassNotFoundException {
MimeType mt = JavaClassMimeTypeConversion.mimeTypeFromObject(new int[0]);
String className = JavaClassMimeTypeConversion.classNameFromMimeType(mt);
assertEquals(int[].class, Class.forName(className));
}
@Test
public void mimeTypeIsMultiDimensionalPrimitiveArray() throws ClassNotFoundException {
MimeType mt = JavaClassMimeTypeConversion.mimeTypeFromObject(new int[0][0][0]);
String className = JavaClassMimeTypeConversion.classNameFromMimeType(mt);
assertEquals(int[][][].class, Class.forName(className));
}
public static class Foo {
private String bar;
public Foo() {
}
public Foo(String bar) {
this.bar = bar;
}
public String getBar() {
return bar;
}
public void setBar(String bar) {
this.bar = bar;
}
}
public static class Bar {
private String foo;
public Bar() {
}
public Bar(String foo) {
this.foo = foo;
}
public String getFoo() {
return foo;
}
public void setFoo(String foo) {
this.foo = foo;
}
}
public class TestMessageBus extends MessageBusSupport {
@Override
public void bindConsumer(String name, MessageChannel channel, Properties properties) {
}
@Override
public void bindPubSubConsumer(String name, MessageChannel moduleInputChannel,
Properties properties) {
}
@Override
public void bindPubSubProducer(String name, MessageChannel moduleOutputChannel,
Properties properties) {
}
@Override
public void bindProducer(String name, MessageChannel channel, Properties properties) {
}
@Override
public void bindRequestor(String name, MessageChannel requests, MessageChannel replies,
Properties properties) {
}
@Override
public void bindReplier(String name, MessageChannel requests, MessageChannel replies,
Properties properties) {
}
}
}
|
package mikenakis.tyraki.test;
import mikenakis.kit.functional.Procedure0;
import mikenakis.tyraki.MutableEnumerator;
import mikenakis.tyraki.legacy.LegacyCollections;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Test.
*
* @author michael.gr
*/
public class T02_Enumerator_On_Java_ArrayList extends EnumeratorTest
{
public T02_Enumerator_On_Java_ArrayList()
{
}
private static class ListFactory<T> implements Factory<T>
{
private final List<T> list;
ListFactory( List<T> list )
{
this.list = list;
}
@Override public MutableEnumerator<T> getResults()
{
return LegacyCollections.newEnumeratorOnJavaIterator( list.iterator(), Procedure0.noOp );
}
}
@SafeVarargs
@SuppressWarnings( "varargs" ) //for -Xlint
@Override protected final <T> Factory<T> onCreateFactory( T... elements )
{
return new ListFactory<>( new ArrayList<>( Arrays.asList( elements ) ) );
}
}
|
package org.cidrz.project.zeprs.valueobject.gen;
import org.cidrz.project.zeprs.valueobject.gen.*;
import org.cidrz.project.zeprs.valueobject.EncounterData;
import org.cidrz.webapp.dynasite.valueobject.Patient;
import java.sql.Date;
import java.util.Set;
import java.sql.Time;
import org.cidrz.webapp.dynasite.valueobject.AuditInfo;
import java.util.TreeSet;
/**
* JavaBean LatentFirstStageLabour generated from database;
* generated by DynasiteSourceGenerator, inspired by XslBeanGenerator by Klaus Berg.
*
* @author Chris Kelley
* Date: 2008-01-30
* Time: 15:19:41
* Form Name: Observations for Latent Phase of 1st Stage of Labour
* Form Id: 17
*/
/**
* @hibernate.joined-subclass table="latentfirststagelabour"
* @hibernate.joined-subclass-key column="id"
*/
public class LatentFirstStageLabour extends EncounterData {
private Time field1960; //time_exam
private Integer field230; //foetal_heart_rate_230
private Integer field171; //pulse_171
private Integer field224; //bp_systolic_224
private Integer field225; //bp_diastolic_225
private Float field266; //temperature_266
private Integer field240; //urinalysis_240
private Integer field242; //urinalysis_alb_242
private Integer field243; //urinalysis_glu_243
private Integer field244; //urinalysis_ace_244
private Integer field367; //contractions_367
private Integer field368; //contraction_freq_10_mins_368
private Integer field325; //cervix_dilatation325
private String field369; //remarks_369
private Integer field1761; //diagnosis
private Integer field1349; //priority_of_referral
private Integer field1620; //transport
/**
* @return
* @hibernate.property column="time_exam"
*/
public Time getField1960() {
return this.field1960;
}
public void setField1960(Time field1960) {
this.field1960 = field1960;
}
/**
* @return
* @hibernate.property column="foetal_heart_rate_230"
*/
public Integer getField230() {
return this.field230;
}
public void setField230(Integer field230) {
this.field230 = field230;
}
/**
* @return
* @hibernate.property column="pulse_171"
*/
public Integer getField171() {
return this.field171;
}
public void setField171(Integer field171) {
this.field171 = field171;
}
/**
* @return
* @hibernate.property column="bp_systolic_224"
*/
public Integer getField224() {
return this.field224;
}
public void setField224(Integer field224) {
this.field224 = field224;
}
/**
* @return
* @hibernate.property column="bp_diastolic_225"
*/
public Integer getField225() {
return this.field225;
}
public void setField225(Integer field225) {
this.field225 = field225;
}
/**
* @return
* @hibernate.property column="temperature_266"
*/
public Float getField266() {
return this.field266;
}
public void setField266(Float field266) {
this.field266 = field266;
}
/**
* @return
* @hibernate.property column="urinalysis_240"
*/
public Integer getField240() {
return this.field240;
}
public void setField240(Integer field240) {
this.field240 = field240;
}
/**
* @return
* @hibernate.property column="urinalysis_alb_242"
*/
public Integer getField242() {
return this.field242;
}
public void setField242(Integer field242) {
this.field242 = field242;
}
/**
* @return
* @hibernate.property column="urinalysis_glu_243"
*/
public Integer getField243() {
return this.field243;
}
public void setField243(Integer field243) {
this.field243 = field243;
}
/**
* @return
* @hibernate.property column="urinalysis_ace_244"
*/
public Integer getField244() {
return this.field244;
}
public void setField244(Integer field244) {
this.field244 = field244;
}
/**
* @return
* @hibernate.property column="contractions_367"
*/
public Integer getField367() {
return this.field367;
}
public void setField367(Integer field367) {
this.field367 = field367;
}
/**
* @return
* @hibernate.property column="contraction_freq_10_mins_368"
*/
public Integer getField368() {
return this.field368;
}
public void setField368(Integer field368) {
this.field368 = field368;
}
/**
* @return
* @hibernate.property column="cervix_dilatation325"
*/
public Integer getField325() {
return this.field325;
}
public void setField325(Integer field325) {
this.field325 = field325;
}
/**
* @return
* @hibernate.property column="remarks_369" type="text"
*/
public String getField369() {
return this.field369;
}
public void setField369(String field369) {
this.field369 = field369;
}
/**
* @return
* @hibernate.property column="diagnosis"
*/
public Integer getField1761() {
return this.field1761;
}
public void setField1761(Integer field1761) {
this.field1761 = field1761;
}
/**
* @return
* @hibernate.property column="priority_of_referral"
*/
public Integer getField1349() {
return this.field1349;
}
public void setField1349(Integer field1349) {
this.field1349 = field1349;
}
/**
* @return
* @hibernate.property column="transport"
*/
public Integer getField1620() {
return this.field1620;
}
public void setField1620(Integer field1620) {
this.field1620 = field1620;
}
}
|
package com.halink.scaffold.common.entity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.Date;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@ApiModel(value = "com-halink-scaffold-common-entity-RolePermissionRelation")
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class RolePermissionRelation implements Serializable {
@ApiModelProperty(value = "")
private Long roleId;
/**
* 权限id
*/
@ApiModelProperty(value = "权限id")
private Long permissionId;
/**
* 创建用户
*/
@ApiModelProperty(value = "创建用户")
private Long userCreate;
/**
* 修改用户
*/
@ApiModelProperty(value = "修改用户")
private Long userModified;
/**
* 创建时间
*/
@ApiModelProperty(value = "创建时间")
private Date gmtCreate;
/**
* 修改时间
*/
@ApiModelProperty(value = "修改时间")
private Date gmtModified;
private static final long serialVersionUID = 1L;
}
|
package uk.ac.manchester.cs.goblin.model;
/**
* @author Colin Puleston
*/
class ImpliedValueConstraint extends Constraint {
public ConstraintSemantics getSemantics() {
return ConstraintSemantics.IMPLIED_VALUE;
}
ImpliedValueConstraint(ConstraintType type, Concept sourceValue, Concept targetValue) {
super(type, sourceValue, targetValue);
}
EditAction createTargetValueRemovalEditAction(Concept target) {
return new RemoveAction(this);
}
boolean singleConstraintOfTypeAndSemanticsPerConcept() {
return getType().singleImpliedValues();
}
}
|
package com.project0.model;
public class Transaction {
private long id;
private long accountId;
private int type;
private double amount;
public Transaction() {
}
public Transaction(long accountId, int type, double amount) {
this.accountId = accountId;
this.type = type;
this.amount = amount;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getAccountId() {
return accountId;
}
public void setAccountId(long accountId) {
this.accountId = accountId;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
}
|
package org.json;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface JSONPropertyName {
String value();
}
|
/**
*
*/
package bgi.ipeak;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Set;
import java.util.Vector;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import com.compomics.util.pride.CvTerm;
import bgi.ipeak.io.WritePSM2Summary;
import bgi.ipeak.io.WriteProteins2Summary;
import bgi.ipeak.percolator.PlusPropertiesToMzid;
import bgi.ipeak.percolator.IPeakPercolator;
import bgi.ipeak.test.ThresholdPSM;
import bgi.ipeak.useMzIdentML.CallCombineSearchEngines;
import bgi.ipeak.useMzIdentML.CallExportAsMzid;
import bgi.ipeak.useMzIdentML.CallFalseDiscoveryRate;
import bgi.ipeak.useMzIdentML.CallFalseDiscoveryRateGlobal;
import bgi.ipeak.useMzIdentML.CallMzIdentMLToCSV;
import bgi.ipeak.useMzIdentML.CallInsertMetaDataFromFasta;
import bgi.ipeak.useMzIdentML.CallProteoGrouper;
import bgi.ipeak.useMzIdentML.CallThresholdMzid;
import bgi.ipeak.util.IPeakFileList;
import bgi.ipeak.util.Properties;
/**
* @author Administrator
*
*/
public class IPeak {
public static final String DESCRIPTION = "\nIPeak v1.0(2014-03-3)\nWritten by Guilin Li (liguilin@genomics.org.cn) "
+ "Chaoqin Du(duchaoqin@genomics.cn) Bo Wen(wenbo@genomics.cn) in the\n"
+ "Proteomics Research Group, Department of Science & Technology, BGI-Shenzhen.\n";
public static final String USAGE = "\nUSAGE:\n1. With single search file for each search engine:\n\tjava -cp mzidentml-lib.jar bgi.ipeak.IPeak "
+ "-msgf msgf.mzid "
+ "-omssa omssa.omx "
+ "-xtandem tandem.xml "
+ "-outdir outdir "
+ "-prefix output_file_prefix "
+ "-database database.fasta "
//+ "-mod omssa_mod_file "
+ " [options...]\n"
+ "2. With multiple search files for each search engine:\n\tjava -cp mzidentml-lib.jar bgi.ipeak.IPeak "
+ "-msgf ../msgf/ "
+ "-omssa ../omssa/ "
+ "-xtandem ../xtandem/ "
+ "-outdir outdir "
+ "-prefix output_file_prefix "
+ "-database database.fasta "
//+ "-mod omssa_mod_file "
//+ "-pp percolator_path [options...]\n";
+ " [options...]\n";
@Option(name = "-msgf", required = true, usage = "(required) MS-GF+ result file (*.mzid format): a single file or a directory containing multiple files")
private String msgf;
@Option(name = "-omssa", required = true, usage = "(required) OMSSA result file (*.omx format): a single file or a directory containing multiple files")
private String omssa;
@Option(name = "-xtandem", required = true, usage = "(required) X!Tandem result file (*.xml format): a single file or a directory containing multiple files")
private String xtandem;
@Option(name = "-database", required = true, usage = "(required) The database file (fasta format)")
private String database;
@Option(name = "-prefix", required = true, usage = "(required) The prefix of output file(s)")
private String output_file_prefix;
@Option(name = "-outdir", required = true, usage = "(required) Output directory")
private String out_file_dir;
@Option(name = "-u", required = false, usage = "(options)[true or false] Filter result in peptide-level FDR, default is true")
private String use_peptidefdr = "true";
//@Option(name = "-mod", required = true, usage = "(required) The OMSSA modification file")
//private String mod = "./mod.xml";
//@Option(name = "-pp", required = true, usage = "(required) The executable Percolator file path")
//private String percolator_path = "./percolator.exe";
@Option(name = "-decoyregrex", required = false, usage = "(optional) The prefix of decoy protein ID. Default is \"###REV###\"")
private String decoyregrex = "###REV###";
// @Option(name="-usermod",required=false,usage="(optional) The user modification file.")
private String umod = "";
// @Option(name="-databaseformat",required=false,usage="(optional) The database file format, default MS:1001348(FASTA).")
private String databaseformat = "MS:1001348";
// @Option(name="-spectrumformat",required=false,usage="(optional) The spectrum file format, default MS:1001062(MGF)")
private String spectrumformat = "MS:1001062";
// @Option(name="-bc",required=false,usage="The coordinates for spectra. Turn on for 0-based, mzML searched. Otherwise, off.")
private boolean bc = false;
@Option(name = "-accessionSplitRegex", required = false, usage = "(optional) Regular expression to split protein ID, surrounded by forward slashes e.g. \"/ /\"")
private String accessionSplitRegex = "/ /";
@Option(name = "-debug", required = false, usage = "(optional) Just for testing ")
private String debug = "false";
// @Option(name="-aST",required=false,usage="(optional,Test Parameter),analyse from step n[0:begin(default),1,1-3 steps,2,5-10 steps ,3,6-10 steps,4 7-10 steps,5 9-10steps,6 10step]\n"
// + "+single step:\n\t1: trans2mzid\n\t2: percolator\n\t3: add percolator score to mzid file\n\t4: combined mzid file"
// + "\n\t5: add protein infor\n\t6: combined three engine result and get fdr score\n\t7: trans mzid to summary file")
private Integer analyse_step = 0;
@Option(name = "-maxfdr", required = false, usage = "(optional) Max FDR for PSM filtering. Defalt 0.01")
private Double maxfdr = 0.01;
@Option(name = "-delete", required = false, usage = "(optional) Remove PSMs that don't pass the threshold")
private Boolean delete = false;
// @Option(name="-search_type",required=false,usage="(optional),combined spectrums search or split spectrums search :0: combined,1:split")
private Integer searchtype = 0;
// @Option(name="-group_type",required=false,usage="(optional),the protein group method :0:IPeak(default),1:FDRAnalyse")
private Integer group_type = 0;
/*
* function test optional
*/
// @Option(name="-th",required=false,usage="(function test optional),thresold 3 search engins result before combine (true or false(default))")
private String threshold_befor_combine = "false";
// @Option(name="-thacc",required=false,usage="(function test optional),the threshold score Acc,used only if the -th true,MS:1001491(default)")
private String thresholdScoreAcc = "MS:1001491";
// @Option(name="-thv",required=false,usage="(function test optional),the threshold score value,0.2(default)")
private Double thresholdScoreValue = 0.2;
private IPeakFileList files_list;
private File[] msgf_list;
private File[] xtandem_list;
private File[] omssa_list;
public static void main(String[] args) throws Exception {
IPeak ip = new IPeak();
CmdLineParser parser = new CmdLineParser(ip);
try {
parser.setUsageWidth(100);
parser.parseArgument(args);
System.out.println(IPeak.DESCRIPTION);
} catch (CmdLineException e) {
System.err.println(IPeak.DESCRIPTION + IPeak.USAGE);
parser.printUsage(System.err);
System.err.println("\nError:");
System.err.println(e.getMessage());
System.err.println("\n");
return;
}
ip.iPeak_CombinedResult();
}
//
//
public void iPeak_CombinedResult() throws Exception {
searchtype = set_filelist_and_get_analyse_method();
if (analyse_step != 0) {
single_step_run();
} else {
basic_analyse();
}
}
private int set_filelist_and_get_analyse_method() {
File msgf_file = new File(msgf);
File xtandem_file = new File(xtandem);
File omssa_file = new File(omssa);
int type = -1;
if (msgf_file.isFile() && xtandem_file.isFile() && omssa_file.isFile()) {
files_list = new IPeakFileList(msgf, omssa, xtandem, out_file_dir, output_file_prefix);
type = 0;
} else if (msgf_file.isDirectory() && xtandem_file.isDirectory() && omssa_file.isDirectory()) {
msgf_list = msgf_file.listFiles();
xtandem_list = xtandem_file.listFiles();
omssa_list = omssa_file.listFiles();
files_list = new IPeakFileList(msgf_file.getAbsolutePath() + "all.mzid", omssa_file.getAbsolutePath()
+ "all.omx", xtandem_file.getAbsolutePath() + "all.xml", out_file_dir, output_file_prefix);
type = 1;
} else {
type = 2;
}
return type;
}
private void basic_analyse() throws Exception {
basic_analyse_step_1();
add_percolatorScore2Mzid();
if (searchtype == 1) {
CombinedMzid();
}
basic_analyse_step_2();
}
private void basic_analyse_step_1() throws Exception {
trans_file2mzid();
percolator_analyse();
}
private void basic_analyse_step_2() throws Exception {
AddProtein2Mzid();
Combined_ThreeMethod();
Get_PeptideLevalFDR();
if (group_type == 1) {
Threshold_Result();
ProteinGroup();
Mzid2csv();
trans2summary_report();
} else {
Mzid2Summary();
}
}
private void single_step_run() throws Exception {
if (analyse_step == 1) {
basic_analyse_step_1();
System.exit(0);
}
if (group_type == 0) {
if (analyse_step == 2) {
basic_analyse_step_2();
} else if (analyse_step == 3) {
Combined_ThreeMethod();
Mzid2Summary();
} else if (analyse_step > 3) {
Mzid2Summary();
}
} else {
if (analyse_step == 2) {
basic_analyse_step_2();
System.exit(0);
} else if (analyse_step == 3) {
Combined_ThreeMethod();
Threshold_Result();
ProteinGroup();
Mzid2csv();
trans2summary_report();
System.exit(0);
} else if (analyse_step == 4) {
Threshold_Result();
ProteinGroup();
Mzid2csv();
trans2summary_report();
System.exit(0);
} else if (analyse_step == 5) {
Mzid2csv();
trans2summary_report();
System.exit(0);
} else if (analyse_step == 6) {
trans2summary_report();
System.exit(0);
}
}
}
private void trans_file2mzid() throws Exception {
if (searchtype == 0) {
String xtandem_mzidfile = files_list.getXtandem_mzid();
String omssa_mzidfile = files_list.getOmssa_mzid();
String msgf_mzidfile = files_list.getMsgf_mzid();
CallExportAsMzid omx2mzid = new CallExportAsMzid(omssa, omssa_mzidfile, umod, decoyregrex);
CallExportAsMzid xtd2mzid = new CallExportAsMzid(xtandem, xtandem_mzidfile, decoyregrex, databaseformat,
accessionSplitRegex, spectrumformat, bc);
SetDecoyInfo set_decoy = new SetDecoyInfo(msgf, msgf_mzidfile, decoyregrex);
set_decoy.SetAndPrint();
omx2mzid.convert();
xtd2mzid.convert();
} else {
for (File xtandem_file : xtandem_list) {
String out_dir = files_list.getXtandem_out_dir();
String name = xtandem_file.getName().substring(0, xtandem_file.getName().lastIndexOf("."));
CallExportAsMzid xtd2mzid = new CallExportAsMzid(xtandem_file.getAbsolutePath(),
out_dir + name + ".mzid", decoyregrex, databaseformat, accessionSplitRegex, spectrumformat, bc);
xtd2mzid.convert();
}
for (File omssa_file : omssa_list) {
String out_dir = files_list.getOmssa_out_dir();
String name = omssa_file.getName().substring(0, omssa_file.getName().lastIndexOf("."));
CallExportAsMzid omx2mzid = new CallExportAsMzid(omssa_file.getAbsolutePath(),
out_dir + name + ".mzid", umod, decoyregrex);
omx2mzid.convert();
}
for (File msgf_file : msgf_list) {
String out_dir = files_list.getMsgf_out_dir();
String name = msgf_file.getName().substring(0, msgf_file.getName().lastIndexOf("."));
SetDecoyInfo set_decoy = new SetDecoyInfo(msgf_file.getAbsolutePath(), out_dir + name + ".mzid", decoyregrex);
set_decoy.SetAndPrint();
}
}
System.out.println("convert prosperity\n\n");
}
private void percolator_analyse() throws Exception {
if (searchtype == 0) {
String xtandem_primaryfilename = files_list.getXtandem_primaryfilename();
String omssa_primaryfilename = files_list.getOmssa_primaryfilename();
String msgf_primaryfilename = files_list.getMsgf_primaryfilename();
System.out.println("\nxtandem get featrue...");
IPeakPercolator xp = new IPeakPercolator(3, xtandem, xtandem_primaryfilename, decoyregrex);
xp.get_Features();
if (analyse_step != 1) {
System.out.println("\nxtandem percolator...");
xp.runPercolator();
}
System.out.println("\nomssa get feature...");
IPeakPercolator op = new IPeakPercolator(2, omssa, omssa_primaryfilename, database, umod, decoyregrex);
op.get_Features();
if (analyse_step != 1) {
System.out.println("\nomssa percolator...");
op.runPercolator();
}
System.out.println("\nmsgf get feature...");
IPeakPercolator mp = new IPeakPercolator(1, msgf, msgf_primaryfilename, decoyregrex);
mp.get_Features();
System.out.println("Get Features prosperity\n\n");
if (analyse_step != 1) {
System.out.println("\nmsgf percolator...");
mp.runPercolator();
System.out.println("Percolator prosperity\n\n");
}
} else {
Vector<String> xtandem_feature_files = new Vector<String>();
Vector<String> omssa_feature_files = new Vector<String>();
Vector<String> msgf_feature_files = new Vector<String>();
xtandem_feature_files = get_featureFromSplitResult("xtandem", xtandem_list);
omssa_feature_files = get_featureFromSplitResult("omssa", omssa_list);
msgf_feature_files = get_featureFromSplitResult("msgf", msgf_list);
System.out.println("Feature get prosperity\n\n");
String xtandem_all_feature_file = files_list.getXtandem_feature_file();
String omssa_all_feature_file = files_list.getOmssa_feature_file();
String msgf_all_feature_file = files_list.getMsgf_feature_file();
combined_features(xtandem_feature_files, xtandem_all_feature_file);
combined_features(omssa_feature_files, omssa_all_feature_file);
combined_features(msgf_feature_files, msgf_all_feature_file);
System.out.println("Combined Feature files prosperity\n\n");
IPeakPercolator xtandem_percolator = new IPeakPercolator(xtandem_all_feature_file,
xtandem_all_feature_file.substring(0, xtandem_all_feature_file.lastIndexOf(".")));
xtandem_percolator.runPercolator();
IPeakPercolator omssa_percolator = new IPeakPercolator(omssa_all_feature_file,
omssa_all_feature_file.substring(0, omssa_all_feature_file.lastIndexOf(".")));
omssa_percolator.runPercolator();
IPeakPercolator msgf_percolator = new IPeakPercolator(msgf_all_feature_file,
msgf_all_feature_file.substring(0, msgf_all_feature_file.lastIndexOf(".")));
msgf_percolator.runPercolator();
String xtandem_per = xtandem_all_feature_file.substring(0, xtandem_all_feature_file.lastIndexOf(".")) + ".per.txt";
String omssa_per = omssa_all_feature_file.substring(0, omssa_all_feature_file.lastIndexOf(".")) + ".per.txt";
String msgf_per = msgf_all_feature_file.substring(0, msgf_all_feature_file.lastIndexOf(".")) + ".per.txt";
Set<String> xtandem_pertxt = split_percolatorResult(xtandem_per);
Set<String> omssa_pertxt = split_percolatorResult(omssa_per);
Set<String> msgf_pertxt = split_percolatorResult(msgf_per);
files_list.setMsgf_per_list(msgf_pertxt);
files_list.setOmssa_per_list(omssa_pertxt);
files_list.setXtandem_per_list(xtandem_pertxt);
}
}
private void add_percolatorScore2Mzid() throws InterruptedException, IOException {
if (searchtype == 0) {
String omssa_plused_file = files_list.getOmssa_mzidAddPer();
String msgf_plused_file = files_list.getMsgf_mzidAddPer();
String xtandem_plused_file = files_list.getXtandem_mzidAddPer();
PlusPropertiesToMzid pmp = new PlusPropertiesToMzid(files_list.getMsgf_mzid(), files_list.getMsgf_percolator_result_file(), msgf_plused_file);
PlusPropertiesToMzid pop = new PlusPropertiesToMzid(files_list.getOmssa_mzid(), files_list.getOmssa_percolator_result_file(), omssa_plused_file);
PlusPropertiesToMzid pxp = new PlusPropertiesToMzid(files_list.getXtandem_mzid(), files_list.getXtandem_percolator_result_file(), xtandem_plused_file);
pmp.export();
pop.export();
pxp.export();
System.out.println("Add percolator score prosperity\n\n");
} else {
Vector<String> msgf_addPmzid = addPercolator2mzid(files_list.getMsgf_per_list(),
files_list.getMsgf_out_dir(), files_list.getMsgf_out_dir());
Vector<String> omssa_addPmzid = addPercolator2mzid(files_list.getOmssa_per_list(),
files_list.getOmssa_out_dir(), files_list.getOmssa_out_dir());
Vector<String> xtandem_addPmzid = addPercolator2mzid(files_list.getXtandem_per_list(),
files_list.getXtandem_out_dir(), files_list.getXtandem_out_dir());
files_list.setMsgf_addP_list(msgf_addPmzid);
files_list.setOmssa_addP_list(omssa_addPmzid);
files_list.setXtandem_addP_list(xtandem_addPmzid);
}
}
private void CombinedMzid() {
Vector<String> list = files_list.getMsgf_addP_list();
Integer kInteger = 1;
HashMap<String, Integer> name_id = new HashMap<String, Integer>();
for (String j : list) {
File file = new File(j);
String name = file.getName();
name_id.put(name, kInteger);
kInteger++;
}
CombineMzidFiles combine_msgf = new CombineMzidFiles(files_list.getMsgf_addP_list(), files_list.getMsgf_mzidAddPer(), name_id);
combine_msgf.combined_mzid();
CombineMzidFiles combine_omssa = new CombineMzidFiles(files_list.getOmssa_addP_list(), files_list.getOmssa_mzidAddPer(), name_id);
combine_omssa.combined_mzid();
CombineMzidFiles combine_xtandem = new CombineMzidFiles(files_list.getXtandem_addP_list(), files_list.getXtandem_mzidAddPer(), name_id);
combine_xtandem.combined_mzid();
}
private void AddProtein2Mzid() throws InterruptedException, IOException {
CallInsertMetaDataFromFasta plus_pro_msgf = new CallInsertMetaDataFromFasta(files_list.getMsgf_mzidAddPer(), files_list.getMsgf_mzidAddProPer(), database, accessionSplitRegex);
plus_pro_msgf.AddFasta_UseMzidlib();
CallInsertMetaDataFromFasta plus_pro_omssa = new CallInsertMetaDataFromFasta(files_list.getOmssa_mzidAddPer(), files_list.getOmssa_mzidAddProPer(), database, accessionSplitRegex);
plus_pro_omssa.AddFasta_UseMzidlib();
CallInsertMetaDataFromFasta plus_pro_xtandem = new CallInsertMetaDataFromFasta(files_list.getXtandem_mzidAddPer(), files_list.getXtandem_mzidAddProPer(), database, accessionSplitRegex);
plus_pro_xtandem.AddFasta_UseMzidlib();
System.out.println("Add Proteins prosperity\n\n");
}
/**
* combined three search engine result,the score of each engine use
* percolator score; the out put mzid has the combined fdr score if debug
* modle,combined with e-value,and each single engine reported the
* result,evalue and the percolator score result are both reported;
*
* @throws IOException
* @throws InterruptedException
*/
private void Combined_ThreeMethod() throws IOException, InterruptedException {
String omssa_plused_file = files_list.getOmssa_mzidAddProPer();
String msgf_plused_file = files_list.getMsgf_mzidAddProPer();
String xtandem_plused_file = files_list.getXtandem_mzidAddProPer();
if (Boolean.valueOf(threshold_befor_combine)) {
ThresholdPSM thresholdOmssa = new ThresholdPSM(omssa_plused_file, omssa_plused_file + "T", thresholdScoreValue, thresholdScoreAcc);
thresholdOmssa.ThresholdAndPrint();
ThresholdPSM thresholdMsgf = new ThresholdPSM(msgf_plused_file, msgf_plused_file + "T", thresholdScoreValue, thresholdScoreAcc);
thresholdMsgf.ThresholdAndPrint();
ThresholdPSM thresholdXtandem = new ThresholdPSM(xtandem_plused_file, xtandem_plused_file + "T", thresholdScoreValue, thresholdScoreAcc);
thresholdXtandem.ThresholdAndPrint();
omssa_plused_file = files_list.getOmssa_mzidAddProPer() + "T";
msgf_plused_file = files_list.getMsgf_mzidAddProPer() + "T";
xtandem_plused_file = files_list.getXtandem_mzidAddProPer() + "T";
}
String mxo_combined_fiel = files_list.getCombined_resultUsePerScore_primaryfilename();
String debug_file = files_list.getCombined_result_debugfile();
CallCombineSearchEngines combine = new CallCombineSearchEngines(msgf_plused_file, omssa_plused_file, xtandem_plused_file,
mxo_combined_fiel, decoyregrex, debug_file, 0);
combine.Comined_Search();
System.out.println("Combine result prosperity\n\n");
if (Boolean.valueOf(debug)) {
String Emxo_combined_fiel = files_list.getEcombined_resultUseEvalue_primaryfilename();
String Edebug_file = files_list.getEcombined_result_debugfile();
CallCombineSearchEngines Ecombine = new CallCombineSearchEngines(msgf_plused_file, omssa_plused_file, xtandem_plused_file,
Emxo_combined_fiel, decoyregrex, Edebug_file, 1);
Ecombine.Comined_Search();
System.out.println("Combine result prosperity\n\n");
String mzid2fdr_m = files_list.getMsgf_mzidAddProPer();
String mzid2fdr_x = files_list.getXtandem_mzidAddProPer();
String mzid2fdr_o = files_list.getOmssa_mzidAddProPer();
String mzid2threshold_me = files_list.getMsgfPP_efdr();
String mzid2threshold_xe = files_list.getXtandemPP_efdr();
String mzid2threshold_oe = files_list.getOmssaPP_efdr();
String mzid2threshold_mp = files_list.getMsgfPP_pfdr();
String mzid2threshold_xp = files_list.getXtandemPP_pfdr();
String mzid2threshold_op = files_list.getOmssaPP_pfdr();
CallFalseDiscoveryRate get_fdr_me = new CallFalseDiscoveryRate(mzid2fdr_m, mzid2threshold_me, decoyregrex, 1, "MS:1002053", true);
CallFalseDiscoveryRate get_fdr_xe = new CallFalseDiscoveryRate(mzid2fdr_x, mzid2threshold_xe, decoyregrex, 1, "MS:1001330", true);
CallFalseDiscoveryRate get_fdr_oe = new CallFalseDiscoveryRate(mzid2fdr_o, mzid2threshold_oe, decoyregrex, 1, "MS:1001328", true);
CallFalseDiscoveryRate get_fdr_mp = new CallFalseDiscoveryRate(mzid2fdr_m, mzid2threshold_mp, decoyregrex, 1, "MS:1001492", false);
CallFalseDiscoveryRate get_fdr_xp = new CallFalseDiscoveryRate(mzid2fdr_x, mzid2threshold_xp, decoyregrex, 1, "MS:1001492", false);
CallFalseDiscoveryRate get_fdr_op = new CallFalseDiscoveryRate(mzid2fdr_o, mzid2threshold_op, decoyregrex, 1, "MS:1001492", false);
get_fdr_me.UseMzid2GetFalseDiscoverRate();
get_fdr_xe.UseMzid2GetFalseDiscoverRate();
get_fdr_oe.UseMzid2GetFalseDiscoverRate();
get_fdr_mp.UseMzid2GetFalseDiscoverRate();
get_fdr_xp.UseMzid2GetFalseDiscoverRate();
get_fdr_op.UseMzid2GetFalseDiscoverRate();
}
}
/**
*
*/
private void Get_PeptideLevalFDR() {
/*
* peptide leval fdr options;
*/
String decoy_rate = "1";
String FDRScoreCV = "MS:1002355";
String CombinedFDRScore = "MS:1002356";
Boolean better_score_are_lower = true;
String fdr_leval = "Peptide";
String protein_leval = "PAG";
String mxo_percolator = files_list.getCombined_resultUsePerScore();
String outpep_mxo_percolator = files_list.getPepFDR_combined_resultUsePerScore();
System.out.println("Combine result prosperity\n\n");
CallFalseDiscoveryRateGlobal mxo_pep = new CallFalseDiscoveryRateGlobal(mxo_percolator, outpep_mxo_percolator,
decoy_rate, decoyregrex, CombinedFDRScore, better_score_are_lower, fdr_leval, protein_leval);
mxo_pep.run_FdrAnalyse();
if (Boolean.valueOf(debug)) {
String mxo_evalue = files_list.getEcombined_resultUseEvalue();
String outpep_mxo_evalue = files_list.getPepFDR_Ecombined_resultUseEvalue();
CallFalseDiscoveryRateGlobal mxo_evalue_pep = new CallFalseDiscoveryRateGlobal(mxo_evalue, outpep_mxo_evalue,
decoy_rate, decoyregrex, CombinedFDRScore, better_score_are_lower, fdr_leval, protein_leval);
mxo_evalue_pep.run_FdrAnalyse();
System.out.println("Combine result prosperity\n\n");
String mzid2pepFDR_me = files_list.getMsgfPP_efdr();
String mzid2pepFDR_xe = files_list.getXtandemPP_efdr();
String mzid2pepFDR_oe = files_list.getOmssaPP_efdr();
String mzid2pepFDR_mp = files_list.getMsgfPP_pfdr();
String mzid2pepFDR_xp = files_list.getXtandemPP_pfdr();
String mzid2pepFDR_op = files_list.getOmssaPP_pfdr();
String outpep_mzid2pepFDR_me = files_list.getPepFDR_msgfPP_efdr();
String outpep_mzid2pepFDR_xe = files_list.getPepFDR_xtandemPP_efdr();
String outpep_mzid2pepFDR_oe = files_list.getPepFDR_omssaPP_efdr();
String outpep_mzid2pepFDR_mp = files_list.getPepFDR_msgfPP_pfdr();
String outpep_mzid2pepFDR_xp = files_list.getPepFDR_xtandemPP_pfdr();
String outpep_mzid2pepFDR_op = files_list.getPepFDR_omssaPP_pfdr();
CallFalseDiscoveryRateGlobal getpep_mzid2pepFDR_me = new CallFalseDiscoveryRateGlobal(mzid2pepFDR_me, outpep_mzid2pepFDR_me,
decoy_rate, decoyregrex, FDRScoreCV, better_score_are_lower, fdr_leval, protein_leval);
getpep_mzid2pepFDR_me.run_FdrAnalyse();
CallFalseDiscoveryRateGlobal getpep_mzid2pepFDR_xe = new CallFalseDiscoveryRateGlobal(mzid2pepFDR_xe, outpep_mzid2pepFDR_xe,
decoy_rate, decoyregrex, FDRScoreCV, better_score_are_lower, fdr_leval, protein_leval);
getpep_mzid2pepFDR_xe.run_FdrAnalyse();
CallFalseDiscoveryRateGlobal getpep_mzid2pepFDR_oe = new CallFalseDiscoveryRateGlobal(mzid2pepFDR_oe, outpep_mzid2pepFDR_oe,
decoy_rate, decoyregrex, FDRScoreCV, better_score_are_lower, fdr_leval, protein_leval);
getpep_mzid2pepFDR_oe.run_FdrAnalyse();
CallFalseDiscoveryRateGlobal getpep_mzid2pepFDR_mp = new CallFalseDiscoveryRateGlobal(mzid2pepFDR_mp, outpep_mzid2pepFDR_mp,
decoy_rate, decoyregrex, FDRScoreCV, better_score_are_lower, fdr_leval, protein_leval);
getpep_mzid2pepFDR_mp.run_FdrAnalyse();
CallFalseDiscoveryRateGlobal getpep_mzid2pepFDR_xp = new CallFalseDiscoveryRateGlobal(mzid2pepFDR_xp, outpep_mzid2pepFDR_xp,
decoy_rate, decoyregrex, FDRScoreCV, better_score_are_lower, fdr_leval, protein_leval);
getpep_mzid2pepFDR_xp.run_FdrAnalyse();
CallFalseDiscoveryRateGlobal getpep_mzid2pepFDR_op = new CallFalseDiscoveryRateGlobal(mzid2pepFDR_op, outpep_mzid2pepFDR_op,
decoy_rate, decoyregrex, FDRScoreCV, better_score_are_lower, fdr_leval, protein_leval);
getpep_mzid2pepFDR_op.run_FdrAnalyse();
}
}
/**
*
* @throws IOException
* @throws InterruptedException
*/
private void Mzid2Summary() throws IOException, InterruptedException {
String Combined_FDRScoreCV = "MS:1002356";
String FDRScoreCV = "MS:1002355";
if (Boolean.valueOf(use_peptidefdr)) {
Combined_FDRScoreCV = "MS:1002360";
FDRScoreCV = "MS:1002360";
}
String mzid2threshold = files_list.getPepFDR_combined_resultUsePerScore();
String output_summary = files_list.getCombined_resultUsePerScore_primaryfilename();
Mzid2Summary mxo_mzid2Summary = new Mzid2Summary(mzid2threshold, output_summary, database,
maxfdr, true, Combined_FDRScoreCV, decoyregrex, true);
mxo_mzid2Summary.trans_mzid2txt();
Integer mxo_protein_number = mxo_mzid2Summary.getProtein_number();
Integer mxo_peptide_number = mxo_mzid2Summary.getPeptide_number();
Integer mxo_psm_number = mxo_mzid2Summary.getPSM_number();
System.out.println("trans combined percolator result file to summary result prosperity\n\n");
FileWriter writeFile = new FileWriter(files_list.getStatistic_analysis_file());
writeFile.write("the number of psm,peptide,protein\n");
writeFile.write("\tPSM\tPeptide\tProtein\n");
writeFile.write("IPeak\t" + mxo_psm_number + "\t" + mxo_peptide_number + "\t" + mxo_protein_number + "\n");
if (Boolean.valueOf(debug)) {
String Emzid2threshold = files_list.getPepFDR_Ecombined_resultUseEvalue();
String Eoutput_summary = files_list.getEcombined_resultUseEvalue_primaryfilename();
Mzid2Summary Emxo_mzid2Summary = new Mzid2Summary(Emzid2threshold, Eoutput_summary, database,
maxfdr, true, Combined_FDRScoreCV, decoyregrex, true);
Emxo_mzid2Summary.trans_mzid2txt();
Integer Emxo_protein_number = Emxo_mzid2Summary.getProtein_number();
Integer Emxo_peptide_number = Emxo_mzid2Summary.getPeptide_number();
Integer Emxo_psm_number = Emxo_mzid2Summary.getPSM_number();
System.out.println("trans combined evalue result file to summary result prosperity\n\n");
String mzid2summary_me = files_list.getPepFDR_msgfPP_efdr();
String mzid2summary_xe = files_list.getPepFDR_xtandemPP_efdr();
String mzid2summary_oe = files_list.getPepFDR_omssaPP_efdr();
String mzid2summary_mp = files_list.getPepFDR_msgfPP_pfdr();
String mzid2summary_xp = files_list.getPepFDR_xtandemPP_pfdr();
String mzid2summary_op = files_list.getPepFDR_omssaPP_pfdr();
String summary_me = files_list.getMsgf_primaryfilename() + "efdr_";
String summary_xe = files_list.getXtandem_primaryfilename() + "efdr";
String summary_oe = files_list.getOmssa_primaryfilename() + "efdr";
String summary_mp = files_list.getMsgf_primaryfilename() + "pfdr";
String summary_xp = files_list.getXtandem_primaryfilename() + "pfdr";
String summary_op = files_list.getOmssa_primaryfilename() + "pfdr";
Mzid2Summary me_Mzid2Summary = new Mzid2Summary(mzid2summary_me, summary_me, database, maxfdr, true, FDRScoreCV, decoyregrex, true);
Mzid2Summary xe_Mzid2Summary = new Mzid2Summary(mzid2summary_xe, summary_xe, database, maxfdr, true, FDRScoreCV, decoyregrex, true);
Mzid2Summary oe_Mzid2Summary = new Mzid2Summary(mzid2summary_oe, summary_oe, database, maxfdr, true, FDRScoreCV, decoyregrex, true);
Mzid2Summary mp_Mzid2Summary = new Mzid2Summary(mzid2summary_mp, summary_mp, database, maxfdr, true, FDRScoreCV, decoyregrex, true);
Mzid2Summary xp_Mzid2Summary = new Mzid2Summary(mzid2summary_xp, summary_xp, database, maxfdr, true, FDRScoreCV, decoyregrex, true);
Mzid2Summary op_Mzid2Summary = new Mzid2Summary(mzid2summary_op, summary_op, database, maxfdr, true, FDRScoreCV, decoyregrex, true);
me_Mzid2Summary.trans_mzid2txt();
Integer me_protein_number = me_Mzid2Summary.getProtein_number();
Integer me_peptide_number = me_Mzid2Summary.getPeptide_number();
Integer me_psm_number = me_Mzid2Summary.getPSM_number();
System.out.println("trans msgf evalue result file to summary result prosperity\n\n");
mp_Mzid2Summary.trans_mzid2txt();
Integer mp_protein_number = mp_Mzid2Summary.getProtein_number();
Integer mp_peptide_number = mp_Mzid2Summary.getPeptide_number();
Integer mp_psm_number = mp_Mzid2Summary.getPSM_number();
System.out.println("trans msgf percolator result file to summary result prosperity\n\n");
xe_Mzid2Summary.trans_mzid2txt();
Integer xe_protein_number = xe_Mzid2Summary.getProtein_number();
Integer xe_peptide_number = xe_Mzid2Summary.getPeptide_number();
Integer xe_psm_number = xe_Mzid2Summary.getPSM_number();
System.out.println("trans xtandem evalue result file to summary result prosperity\n\n");
xp_Mzid2Summary.trans_mzid2txt();
Integer xp_protein_number = xp_Mzid2Summary.getProtein_number();
Integer xp_peptide_number = xp_Mzid2Summary.getPeptide_number();
Integer xp_psm_number = xp_Mzid2Summary.getPSM_number();
System.out.println("trans xtandem percolator result file to summary result prosperity\n\n");
oe_Mzid2Summary.trans_mzid2txt();
Integer oe_protein_number = oe_Mzid2Summary.getProtein_number();
Integer oe_peptide_number = oe_Mzid2Summary.getPeptide_number();
Integer oe_psm_number = oe_Mzid2Summary.getPSM_number();
System.out.println("trans omssa evalue result file to summary result prosperity\n\n");
op_Mzid2Summary.trans_mzid2txt();
Integer op_protein_number = op_Mzid2Summary.getProtein_number();
Integer op_peptide_number = op_Mzid2Summary.getPeptide_number();
Integer op_psm_number = op_Mzid2Summary.getPSM_number();
System.out.println("trans omssa percolaotor result file to summary result prosperity\n\n");
writeFile.write("FDRAnalyse\t" + Emxo_psm_number + "\t" + Emxo_peptide_number + "\t" + Emxo_protein_number + "\n");
writeFile.write("MP\t" + mp_psm_number + "\t" + mp_peptide_number + "\t" + mp_protein_number + "\n");
writeFile.write("MS-GF+\t" + me_psm_number + "\t" + me_peptide_number + "\t" + me_protein_number + "\n");
writeFile.write("OP\t" + op_psm_number + "\t" + op_peptide_number + "\t" + op_protein_number + "\n");
writeFile.write("Omssa\t" + oe_psm_number + "\t" + oe_peptide_number + "\t" + oe_protein_number + "\n");
writeFile.write("XP\t" + xp_psm_number + "\t" + xp_peptide_number + "\t" + xp_protein_number + "\n");
writeFile.write("X!Tandem\t" + xe_psm_number + "\t" + xe_peptide_number + "\t" + xe_protein_number + "\n");
}
writeFile.close();
}
/**
* the four function working when the option -group_type=1; used the
* mzidentml-lib's threshold,protein group method,report method;
*
* @throws IOException
* @throws InterruptedException
*/
private void Threshold_Result() throws IOException, InterruptedException {
String mzid2threshold = files_list.getCombined_resultUsePerScore();
String output_mzid_t = files_list.getCombined_threshold_file();
CallThresholdMzid mxo_threshold = new CallThresholdMzid(mzid2threshold, output_mzid_t, "MS:1002356", maxfdr, true, true, delete);
mxo_threshold.Use_mzidlib2threshold();
System.out.println("threshold the combined result prosperity\n\n");
if (Boolean.valueOf(debug)) {
String Emzid2threshold = files_list.getEcombined_resultUseEvalue();
String Eoutput_mzid_t = files_list.getEcombined_threshold_file();
CallThresholdMzid Emxo_threshold = new CallThresholdMzid(Emzid2threshold, Eoutput_mzid_t, "MS:1002356", maxfdr, true, true, delete);
Emxo_threshold.Use_mzidlib2threshold();
System.out.println("threshold the combined result prosperity\n\n");
String mzid2threshold_me = files_list.getMsgfPP_efdr();
String mzid2threshold_xe = files_list.getXtandemPP_efdr();
String mzid2threshold_oe = files_list.getOmssaPP_efdr();
String mzid2threshold_mp = files_list.getMsgfPP_pfdr();
String mzid2threshold_xp = files_list.getXtandemPP_pfdr();
String mzid2threshold_op = files_list.getOmssaPP_pfdr();
String mzid2group_me = files_list.getMsgfPP_efdr_threshold();
String mzid2group_xe = files_list.getXtandemPP_efdr_threshold();
String mzid2group_oe = files_list.getOmssaPP_efdr_threshold();
String mzid2group_mp = files_list.getMsgfPP_pfdr_threshold();
String mzid2group_xp = files_list.getXtandemPP_pfdr_threshold();
String mzid2group_op = files_list.getOmssaPP_pfdr_threshold();
CallThresholdMzid me_threshold = new CallThresholdMzid(mzid2threshold_me, mzid2group_me, "MS:1001874", maxfdr, true, true, delete);
CallThresholdMzid xe_threshold = new CallThresholdMzid(mzid2threshold_xe, mzid2group_xe, "MS:1001874", maxfdr, true, true, delete);
CallThresholdMzid oe_threshold = new CallThresholdMzid(mzid2threshold_oe, mzid2group_oe, "MS:1001874", maxfdr, true, true, delete);
CallThresholdMzid mp_threshold = new CallThresholdMzid(mzid2threshold_mp, mzid2group_mp, "MS:1001874", maxfdr, true, true, delete);
CallThresholdMzid xp_threshold = new CallThresholdMzid(mzid2threshold_xp, mzid2group_xp, "MS:1001874", maxfdr, true, true, delete);
CallThresholdMzid op_threshold = new CallThresholdMzid(mzid2threshold_op, mzid2group_op, "MS:1001874", maxfdr, true, true, delete);
mp_threshold.Use_mzidlib2threshold();
xp_threshold.Use_mzidlib2threshold();
op_threshold.Use_mzidlib2threshold();
me_threshold.Use_mzidlib2threshold();
xe_threshold.Use_mzidlib2threshold();
oe_threshold.Use_mzidlib2threshold();
}
}
/**
* the four function working when the option -group_type=1; used the
* mzidentml-lib's threshold,protein group method,report method;
*
* @throws IOException
* @throws InterruptedException
*/
private void ProteinGroup() throws IOException, InterruptedException {
String mzid2group = files_list.getCombined_threshold_file();
String output_mzid_g = files_list.getGroup_combined_threshold_file();
CallProteoGrouper mxo_pro_group = new CallProteoGrouper(mzid2group, output_mzid_g, true, false, "MS:1002356", true);
mxo_pro_group.Use_mzidlib2ProteinGroup();
System.out.println("group proteins prosperity\n\n");
if (Boolean.valueOf(debug)) {
String Emzid2group = files_list.getEcombined_threshold_file();
String Eoutput_mzid_g = files_list.getEgroup_combined_threshold_file();
CallProteoGrouper Emxo_pro_group = new CallProteoGrouper(Emzid2group, Eoutput_mzid_g, true, false, "MS:1002356", true);
Emxo_pro_group.Use_mzidlib2ProteinGroup();
System.out.println("group proteins prosperity\n\n");
String mzid2group_me = files_list.getMsgfPP_efdr_threshold();
String mzid2group_xe = files_list.getXtandemPP_efdr_threshold();
String mzid2group_oe = files_list.getOmssaPP_efdr_threshold();
String mzid2group_mp = files_list.getMsgfPP_pfdr_threshold();
String mzid2group_xp = files_list.getXtandemPP_pfdr_threshold();
String mzid2group_op = files_list.getOmssaPP_pfdr_threshold();
String grouped_mzid_me = files_list.getMsgfPP_efdr_threshold_group();
String grouped_mzid_xe = files_list.getXtandemPP_efdr_threshold_group();
String grouped_mzid_oe = files_list.getOmssaPP_efdr_threshold_group();
String grouped_mzid_mp = files_list.getMsgfPP_pfdr_threshold_group();
String grouped_mzid_xp = files_list.getXtandemPP_pfdr_threshold_group();
String grouped_mzid_op = files_list.getOmssaPP_pfdr_threshold_group();
CallProteoGrouper me_pro_group = new CallProteoGrouper(mzid2group_me, grouped_mzid_me, true, false, "MS:1001874", true);
CallProteoGrouper xe_pro_group = new CallProteoGrouper(mzid2group_xe, grouped_mzid_xe, true, false, "MS:1001874", true);
CallProteoGrouper oe_pro_group = new CallProteoGrouper(mzid2group_oe, grouped_mzid_oe, true, false, "MS:1001874", true);
CallProteoGrouper mp_pro_group = new CallProteoGrouper(mzid2group_mp, grouped_mzid_mp, true, false, "MS:1001874", true);
CallProteoGrouper xp_pro_group = new CallProteoGrouper(mzid2group_xp, grouped_mzid_xp, true, false, "MS:1001874", true);
CallProteoGrouper op_pro_group = new CallProteoGrouper(mzid2group_op, grouped_mzid_op, true, false, "MS:1001874", true);
me_pro_group.Use_mzidlib2ProteinGroup();
xe_pro_group.Use_mzidlib2ProteinGroup();
oe_pro_group.Use_mzidlib2ProteinGroup();
mp_pro_group.Use_mzidlib2ProteinGroup();
xp_pro_group.Use_mzidlib2ProteinGroup();
op_pro_group.Use_mzidlib2ProteinGroup();
System.out.println("group proteins prosperity\n\n");
}
}
/**
* the four function working when the option -group_type=1; used the
* mzidentml-lib's threshold,protein group method,report method;
*
* @throws IOException
* @throws InterruptedException
*/
private void Mzid2csv() throws IOException, InterruptedException {
String mzid2trans = files_list.getGroup_combined_threshold_file();
String out_put_csv_psm = files_list.getPsm_combined_threshold_csvfile();
String out_put_csv_pro = files_list.getProtein_combined_threshold_csvfile();
CallMzIdentMLToCSV mxo_trans_psm = new CallMzIdentMLToCSV(mzid2trans, out_put_csv_psm, "true", "exportPSMs");
CallMzIdentMLToCSV mxo_trans_pro = new CallMzIdentMLToCSV(mzid2trans, out_put_csv_pro, "true", "exportProteinGroups");
mxo_trans_psm.Use_mzidlib2trans();
mxo_trans_pro.Use_mzidlib2trans();
System.out.println("trans to csv prosperity\n\n");
System.out.println("iPeak result file :\ncombined mzid file: " + mzid2trans + "\npsm csv file: " + out_put_csv_psm + "\n"
+ "protein group file: " + out_put_csv_pro + "\n");
if (Boolean.valueOf(debug)) {
String e_mzid2trans = files_list.getEgroup_combined_threshold_file();
String e_out_put_csv_psm = files_list.getEpsm_combined_threshold_csvfile();
String e_out_put_csv_pro = files_list.getEprotein_combined_threshold_csvfile();
CallMzIdentMLToCSV e_mxo_trans_psm = new CallMzIdentMLToCSV(e_mzid2trans, e_out_put_csv_psm, "true", "exportPSMs");
CallMzIdentMLToCSV e_mxo_trans_pro = new CallMzIdentMLToCSV(e_mzid2trans, e_out_put_csv_pro, "true", "exportProteinGroups");
e_mxo_trans_psm.Use_mzidlib2trans();
e_mxo_trans_pro.Use_mzidlib2trans();
System.out.println("trans to csv prosperity\n\n");
System.out.println("iPeak result file :\ncombined mzid file: " + mzid2trans + "\npsm csv file: " + out_put_csv_psm + "\n"
+ "protein group file: " + out_put_csv_pro + "\n");
String grouped_mzid_me = files_list.getMsgfPP_efdr_threshold_group();
String grouped_mzid_xe = files_list.getXtandemPP_efdr_threshold_group();
String grouped_mzid_oe = files_list.getOmssaPP_efdr_threshold_group();
String grouped_mzid_mp = files_list.getMsgfPP_pfdr_threshold_group();
String grouped_mzid_xp = files_list.getXtandemPP_pfdr_threshold_group();
String grouped_mzid_op = files_list.getOmssaPP_pfdr_threshold_group();
String csv_psm_me = files_list.getMsgfPP_efdr_threshold_group_psmcsv();
String csv_psm_xe = files_list.getXtandemPP_efdr_threshold_group_psmcsv();
String csv_psm_oe = files_list.getOmssaPP_efdr_threshold_group_psmcsv();
String csv_psm_mp = files_list.getMsgfPP_pfdr_threshold_group_psmcsv();
String csv_psm_xp = files_list.getXtandemPP_pfdr_threshold_group_psmcsv();
String csv_psm_op = files_list.getOmssaPP_pfdr_threshold_group_psmcsv();
String csv_pro_me = files_list.getMsgfPP_efdr_threshold_group_procsv();
String csv_pro_xe = files_list.getXtandemPP_efdr_threshold_group_procsv();
String csv_pro_oe = files_list.getOmssaPP_efdr_threshold_group_procsv();
String csv_pro_mp = files_list.getMsgfPP_pfdr_threshold_group_procsv();
String csv_pro_xp = files_list.getXtandemPP_pfdr_threshold_group_procsv();
String csv_pro_op = files_list.getOmssaPP_pfdr_threshold_group_procsv();
CallMzIdentMLToCSV me_trans_psm = new CallMzIdentMLToCSV(grouped_mzid_me, csv_psm_me, "true", "exportPSMs");
CallMzIdentMLToCSV xe_trans_psm = new CallMzIdentMLToCSV(grouped_mzid_xe, csv_psm_xe, "true", "exportPSMs");
CallMzIdentMLToCSV oe_trans_psm = new CallMzIdentMLToCSV(grouped_mzid_oe, csv_psm_oe, "true", "exportPSMs");
CallMzIdentMLToCSV mp_trans_psm = new CallMzIdentMLToCSV(grouped_mzid_mp, csv_psm_mp, "true", "exportPSMs");
CallMzIdentMLToCSV xp_trans_psm = new CallMzIdentMLToCSV(grouped_mzid_xp, csv_psm_xp, "true", "exportPSMs");
CallMzIdentMLToCSV op_trans_psm = new CallMzIdentMLToCSV(grouped_mzid_op, csv_psm_op, "true", "exportPSMs");
CallMzIdentMLToCSV me_trans_pro = new CallMzIdentMLToCSV(grouped_mzid_me, csv_pro_me, "true", "exportProteinGroups");
CallMzIdentMLToCSV xe_trans_pro = new CallMzIdentMLToCSV(grouped_mzid_xe, csv_pro_xe, "true", "exportProteinGroups");
CallMzIdentMLToCSV oe_trans_pro = new CallMzIdentMLToCSV(grouped_mzid_oe, csv_pro_oe, "true", "exportProteinGroups");
CallMzIdentMLToCSV mp_trans_pro = new CallMzIdentMLToCSV(grouped_mzid_mp, csv_pro_mp, "true", "exportProteinGroups");
CallMzIdentMLToCSV xp_trans_pro = new CallMzIdentMLToCSV(grouped_mzid_xp, csv_pro_xp, "true", "exportProteinGroups");
CallMzIdentMLToCSV op_trans_pro = new CallMzIdentMLToCSV(grouped_mzid_op, csv_pro_op, "true", "exportProteinGroups");
me_trans_psm.Use_mzidlib2trans();
xe_trans_psm.Use_mzidlib2trans();
oe_trans_psm.Use_mzidlib2trans();
mp_trans_psm.Use_mzidlib2trans();
op_trans_psm.Use_mzidlib2trans();
xp_trans_psm.Use_mzidlib2trans();
me_trans_pro.Use_mzidlib2trans();
xe_trans_pro.Use_mzidlib2trans();
oe_trans_pro.Use_mzidlib2trans();
mp_trans_pro.Use_mzidlib2trans();
xp_trans_pro.Use_mzidlib2trans();
op_trans_pro.Use_mzidlib2trans();
}
}
/**
* the four function working when the option -group_type=1; used the
* mzidentml-lib's threshold,protein group method,report method;
*
* @throws IOException
*/
private void trans2summary_report() throws IOException {
WriteProteins2Summary mxo_percolator_pro = new WriteProteins2Summary(files_list.getProtein_combined_threshold_csvfile(), files_list.getProtein_combined_threshold_summaryfile());
mxo_percolator_pro.transcsv2summary();
Integer mxo_Percolator_protein_number = mxo_percolator_pro.getProtein_number();
WritePSM2Summary mxo_percolator_psm = new WritePSM2Summary(files_list.getPsm_combined_threshold_csvfile(), files_list.getPsm_combined_threshold_summaryfile());
mxo_percolator_psm.transcsv2summary();
Integer mxo_percolator_pep_number = mxo_percolator_psm.getPeptide_number();
Integer mxo_percolator_psm_number = mxo_percolator_psm.getPSM_number();
FileWriter writeFile = new FileWriter(files_list.getStatistic_analysis_file());
writeFile.write("the number of psm,peptide,protein\n");
writeFile.write("\tPSM\tPeptide\tProtein\n");
writeFile.write("iPeak\t" + mxo_percolator_psm_number + "\t" + mxo_percolator_pep_number + "\t" + mxo_Percolator_protein_number + "\n");
if (Boolean.valueOf(debug)) {
WriteProteins2Summary mxo_evalue_pro = new WriteProteins2Summary(files_list.getEprotein_combined_threshold_csvfile(), files_list.getEprotein_combined_threshold_summaryfile());
mxo_evalue_pro.transcsv2summary();
Integer mxo_Evalue_protein_number = mxo_evalue_pro.getProtein_number();
WritePSM2Summary mxo_evalue_psm = new WritePSM2Summary(files_list.getEpsm_combined_threshold_csvfile(), files_list.getEpsm_combined_threshold_summaryfile());
mxo_evalue_psm.transcsv2summary();
Integer mxo_evalue_pep_number = mxo_evalue_psm.getPeptide_number();
Integer mxo_evalue_psm_number = mxo_evalue_psm.getPSM_number();
WriteProteins2Summary xtandem_percolator_pro = new WriteProteins2Summary(files_list.getXtandemPP_pfdr_threshold_group_procsv(), files_list.getXtandemPP_pfdr_threshold_group_prosummary());
xtandem_percolator_pro.transcsv2summary();
Integer xtandem_Percolator_protein_number = xtandem_percolator_pro.getProtein_number();
WriteProteins2Summary xtandem_evalue_pro = new WriteProteins2Summary(files_list.getXtandemPP_efdr_threshold_group_procsv(), files_list.getXtandemPP_efdr_threshold_group_prosummary());
xtandem_evalue_pro.transcsv2summary();
Integer xtandem_Evalue_protein_number = xtandem_evalue_pro.getProtein_number();
WriteProteins2Summary omssa_percolator_pro = new WriteProteins2Summary(files_list.getOmssaPP_pfdr_threshold_group_procsv(), files_list.getOmssaPP_pfdr_threshold_group_prosummary());
omssa_percolator_pro.transcsv2summary();
Integer omssa_Percolator_protein_number = omssa_percolator_pro.getProtein_number();
WriteProteins2Summary omssa_evalue_pro = new WriteProteins2Summary(files_list.getOmssaPP_efdr_threshold_group_procsv(), files_list.getOmssaPP_efdr_threshold_group_prosummary());
omssa_evalue_pro.transcsv2summary();
Integer omssa_Evalue_protein_number = omssa_evalue_pro.getProtein_number();
WriteProteins2Summary msgf_percolator_pro = new WriteProteins2Summary(files_list.getMsgfPP_pfdr_threshold_group_procsv(), files_list.getMsgfPP_pfdr_threshold_group_prosummary());
msgf_percolator_pro.transcsv2summary();
Integer msgf_Percolator_protein_number = msgf_percolator_pro.getProtein_number();
WriteProteins2Summary msgf_evalue_pro = new WriteProteins2Summary(files_list.getMsgfPP_efdr_threshold_group_procsv(), files_list.getMsgfPP_efdr_threshold_group_prosummary());
msgf_evalue_pro.transcsv2summary();
Integer msgf_Evalue_protein_number = msgf_evalue_pro.getProtein_number();
WritePSM2Summary xtandem_percolator_psm = new WritePSM2Summary(files_list.getXtandemPP_pfdr_threshold_group_psmcsv(), files_list.getXtandemPP_pfdr_threshold_group_psmsummary());
xtandem_percolator_psm.transcsv2summary();
Integer xtandem_percolator_pep_number = xtandem_percolator_psm.getPeptide_number();
Integer xtandem_percolator_psm_number = xtandem_percolator_psm.getPSM_number();
WritePSM2Summary xtandem_evalue_psm = new WritePSM2Summary(files_list.getXtandemPP_efdr_threshold_group_psmcsv(), files_list.getXtandemPP_efdr_threshold_group_psmsummary());
xtandem_evalue_psm.transcsv2summary();
Integer xtandem_evalue_pep_number = xtandem_evalue_psm.getPeptide_number();
Integer xtandem_evalue_psm_number = xtandem_evalue_psm.getPSM_number();
WritePSM2Summary omssa_percolator_psm = new WritePSM2Summary(files_list.getOmssaPP_pfdr_threshold_group_psmcsv(), files_list.getOmssaPP_pfdr_threshold_group_psmsummary());
omssa_percolator_psm.transcsv2summary();
Integer omssa_percolator_pep_number = omssa_percolator_psm.getPeptide_number();
Integer omssa_percolator_psm_number = omssa_percolator_psm.getPSM_number();
WritePSM2Summary omssa_evalue_psm = new WritePSM2Summary(files_list.getOmssaPP_efdr_threshold_group_psmcsv(), files_list.getOmssaPP_efdr_threshold_group_psmsummary());
omssa_evalue_psm.transcsv2summary();
Integer omssa_evalue_pep_number = omssa_evalue_psm.getPeptide_number();
Integer omssa_evalue_psm_number = omssa_evalue_psm.getPSM_number();
WritePSM2Summary msgf_percolator_psm = new WritePSM2Summary(files_list.getMsgfPP_pfdr_threshold_group_psmcsv(), files_list.getMsgfPP_pfdr_threshold_group_psmsummary());
msgf_percolator_psm.transcsv2summary();
Integer msgf_percolator_pep_number = msgf_percolator_psm.getPeptide_number();
Integer msgf_percolator_psm_number = msgf_percolator_psm.getPSM_number();
WritePSM2Summary msgf_evalue_psm = new WritePSM2Summary(files_list.getMsgfPP_efdr_threshold_group_psmcsv(), files_list.getMsgfPP_efdr_threshold_group_psmsummary());
msgf_evalue_psm.transcsv2summary();
Integer msgf_evalue_pep_number = msgf_evalue_psm.getPeptide_number();
Integer msgf_evalue_psm_number = msgf_evalue_psm.getPSM_number();
writeFile.write("FDRAnalyse\t" + mxo_evalue_psm_number + "\t" + mxo_evalue_pep_number + "\t" + mxo_Evalue_protein_number + "\n");
writeFile.write("msgf\t" + msgf_evalue_psm_number + "\t" + msgf_evalue_pep_number + "\t" + msgf_Evalue_protein_number + "\n");
writeFile.write("MP\t" + msgf_percolator_psm_number + "\t" + msgf_percolator_pep_number + "\t" + msgf_Percolator_protein_number + "\n");
writeFile.write("omssa\t" + omssa_evalue_psm_number + "\t" + omssa_evalue_pep_number + "\t" + omssa_Evalue_protein_number + "\n");
writeFile.write("OP\t" + omssa_percolator_psm_number + "\t" + omssa_percolator_pep_number + "\t" + omssa_Percolator_protein_number + "\n");
writeFile.write("xtandem\t" + xtandem_evalue_psm_number + "\t" + xtandem_evalue_pep_number + "\t" + xtandem_Evalue_protein_number + "\n");
writeFile.write("XP\t" + xtandem_percolator_psm_number + "\t" + xtandem_percolator_pep_number + "\t" + xtandem_Percolator_protein_number + "\n");
}
writeFile.close();
}
private Vector<String> get_featureFromSplitResult(String engine_name, File[] search_result_list) throws Exception {
HashMap<String, Integer> enginename2engineID = new HashMap<String, Integer>();
enginename2engineID.put("xtandem", 3);
enginename2engineID.put("omssa", 2);
enginename2engineID.put("msgf", 1);
int engineID = enginename2engineID.get(engine_name);
System.out.println("\n" + engine_name + "percolator...");
String out_dir = "";
if (engineID == 3) {
out_dir = files_list.getXtandem_out_dir();
} else if (engineID == 2) {
out_dir = files_list.getOmssa_out_dir();
} else if (engineID == 1) {
out_dir = files_list.getMsgf_out_dir();
} else {
System.err.println("error: can not get features for can not found the ok out dir ");
}
Vector<String> features_files_list = new Vector<String>();
for (File result_file : search_result_list) {
String primaryfilename = result_file.getName();
primaryfilename = primaryfilename.substring(0, primaryfilename.lastIndexOf("."));
primaryfilename = out_dir + primaryfilename;
String result_file_path = result_file.getAbsolutePath();
IPeakPercolator resul2feature;
if (engineID == 2) {
resul2feature = new IPeakPercolator(engineID, result_file_path, primaryfilename, database, umod, decoyregrex);
} else {
resul2feature = new IPeakPercolator(engineID, result_file_path, primaryfilename, decoyregrex);
}
resul2feature.get_Features();
features_files_list.add(resul2feature.getFeature_file());
}
return features_files_list;
}
private void combined_features(Vector<String> feature_file_list, String all_feature_file) throws IOException {
File test_file = new File(all_feature_file);
if (test_file.exists()) {
test_file.delete();
}
BufferedReader readtitle = new BufferedReader(new FileReader(feature_file_list.get(0)));
String title = readtitle.readLine();
readtitle.close();
Vector<String> featureinfors = new Vector<String>();
for (String feature_file : feature_file_list) {
System.out.println(feature_file);
BufferedReader read = new BufferedReader(new FileReader(feature_file));
String line = read.readLine();
while ((line = read.readLine()) != null) {
featureinfors.add(line);
}
read.close();
}
BufferedWriter writeFile = new BufferedWriter(new FileWriter(all_feature_file));
writeFile.write(title);
for (String infor : featureinfors) {
writeFile.append(infor);
writeFile.newLine();
}
writeFile.close();
}
private Set<String> split_percolatorResult(String pertxtfile) throws IOException {
File per_file = new File(pertxtfile);
String out_dir = per_file.getParent() + "/";
BufferedReader read = new BufferedReader(new FileReader(pertxtfile));
String line = read.readLine();
String title = line;
HashMap<String, Vector<String>> per_file_list = new HashMap<String, Vector<String>>();
while ((line = read.readLine()) != null) {
String[] items = line.split(":");
String id = out_dir + items[0] + ".per.txt";
if (per_file_list.containsKey(id)) {
Vector<String> infor = per_file_list.get(id);
infor.add(line);
per_file_list.put(id, infor);
} else {
Vector<String> infor = new Vector<String>();
infor.add(line);
per_file_list.put(id, infor);
}
}
read.close();
Set<String> out_names = per_file_list.keySet();
for (String out : out_names) {
BufferedWriter writer = new BufferedWriter(new FileWriter(out));
writer.append(title);
writer.newLine();
for (String line_infor : per_file_list.get(out)) {
writer.append(line_infor);
writer.newLine();
}
writer.close();
}
return out_names;
}
private Vector<String> addPercolator2mzid(Set<String> per_name, String mziddir, String out_dir) throws IOException {
if (mziddir.lastIndexOf("/") != mziddir.length() - 1) {
mziddir = mziddir + "/";
}
if (out_dir.lastIndexOf("/") != out_dir.length() - 1) {
out_dir = out_dir + "/";
}
String tag = ".mzid";
String tag_out = "AddP.mzid";
Vector<String> addp_mzdi_list = new Vector<String>();
for (String file_name : per_name) {
File per_file = new File(file_name);
String name = per_file.getName().substring(0, per_file.getName().lastIndexOf(".per.txt"));
String mzid_path = mziddir + name + tag;
String mzidP_path = out_dir + name + tag_out;
File mz_file = new File(mzid_path);
if (mz_file.exists()) {
PlusPropertiesToMzid pmp = new PlusPropertiesToMzid(mzid_path, file_name, mzidP_path);
pmp.export();
}
addp_mzdi_list.add(mzidP_path);
}
return addp_mzdi_list;
}
}
|
package com.example.notispanner;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
}
|
/*
* Copyright 2017 The Bazel Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.idea.blaze.python.run.producers;
import static com.google.common.truth.Truth.assertThat;
import com.google.idea.blaze.base.command.BlazeCommandName;
import com.google.idea.blaze.base.ideinfo.TargetIdeInfo;
import com.google.idea.blaze.base.ideinfo.TargetMapBuilder;
import com.google.idea.blaze.base.model.MockBlazeProjectDataBuilder;
import com.google.idea.blaze.base.model.MockBlazeProjectDataManager;
import com.google.idea.blaze.base.model.primitives.TargetExpression;
import com.google.idea.blaze.base.model.primitives.WorkspacePath;
import com.google.idea.blaze.base.run.BlazeCommandRunConfiguration;
import com.google.idea.blaze.base.run.producer.BlazeRunConfigurationProducerTestCase;
import com.google.idea.blaze.base.run.producers.BinaryContextRunConfigurationProducer;
import com.google.idea.blaze.base.sync.data.BlazeProjectDataManager;
import com.intellij.execution.actions.ConfigurationContext;
import com.intellij.execution.actions.ConfigurationFromContext;
import com.intellij.psi.PsiFile;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Integration tests for {@link PyBinaryContextProvider}. */
@RunWith(JUnit4.class)
public class PyBinaryContextProviderTest extends BlazeRunConfigurationProducerTestCase {
@Test
public void testProducedFromPyFile() throws Throwable {
PsiFile pyFile =
createAndIndexFile(
new WorkspacePath("py/bin/main.py"),
"def main():",
" return",
"if __name__ == '__main__':",
" main()");
workspace.createFile(new WorkspacePath("py/bin/BUILD"), "py_binary(name = 'main')");
MockBlazeProjectDataBuilder builder = MockBlazeProjectDataBuilder.builder(workspaceRoot);
builder.setTargetMap(
TargetMapBuilder.builder()
.addTarget(
TargetIdeInfo.builder()
.setKind("py_binary")
.setLabel("//py/bin:main")
.addSource(sourceRoot("py/bin/main.py"))
.build())
.build());
registerProjectService(
BlazeProjectDataManager.class, new MockBlazeProjectDataManager(builder.build()));
ConfigurationContext context = createContextFromPsi(pyFile);
List<ConfigurationFromContext> configurations = context.getConfigurationsFromContext();
assertThat(configurations).hasSize(1);
ConfigurationFromContext fromContext = configurations.get(0);
assertThat(fromContext.isProducedBy(BinaryContextRunConfigurationProducer.class)).isTrue();
assertThat(fromContext.getConfiguration()).isInstanceOf(BlazeCommandRunConfiguration.class);
BlazeCommandRunConfiguration config =
(BlazeCommandRunConfiguration) fromContext.getConfiguration();
assertThat(config.getTargets())
.containsExactly(TargetExpression.fromStringSafe("//py/bin:main"));
assertThat(getCommandType(config)).isEqualTo(BlazeCommandName.RUN);
}
}
|
/*
* Copyright 2021 Red Hat
*
* 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.apicurio.registry.rest.client;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import io.apicurio.registry.rest.v2.beans.ArtifactMetaData;
import io.apicurio.registry.rest.v2.beans.ArtifactSearchResults;
import io.apicurio.registry.rest.v2.beans.EditableMetaData;
import io.apicurio.registry.rest.v2.beans.IfExists;
import io.apicurio.registry.rest.v2.beans.LogConfiguration;
import io.apicurio.registry.rest.v2.beans.NamedLogConfiguration;
import io.apicurio.registry.rest.v2.beans.RoleMapping;
import io.apicurio.registry.rest.v2.beans.Rule;
import io.apicurio.registry.rest.v2.beans.SortBy;
import io.apicurio.registry.rest.v2.beans.SortOrder;
import io.apicurio.registry.rest.v2.beans.UpdateState;
import io.apicurio.registry.rest.v2.beans.UserInfo;
import io.apicurio.registry.rest.v2.beans.VersionMetaData;
import io.apicurio.registry.rest.v2.beans.VersionSearchResults;
import io.apicurio.registry.types.ArtifactType;
import io.apicurio.registry.types.RoleType;
import io.apicurio.registry.types.RuleType;
/**
* @author Carles Arnal 'carnalca@redhat.com'
* <p>
* Rest client compatible with the Registry API V2
*/
public interface RegistryClient {
InputStream getLatestArtifact(String groupId, String artifactId);
ArtifactMetaData updateArtifact(String groupId, String artifactId, String version, String artifactName, String artifactDescription, InputStream data);
default ArtifactMetaData updateArtifact(String groupId, String artifactId, String version, InputStream data) {
return updateArtifact(groupId, artifactId, version, null, null, data);
}
default ArtifactMetaData updateArtifact(String groupId, String artifactId, InputStream data) {
return updateArtifact(groupId, artifactId, null, null, null, data);
}
void deleteArtifact(String groupId, String artifactId);
ArtifactMetaData getArtifactMetaData(String groupId, String artifactId);
void updateArtifactMetaData(String groupId, String artifactId, EditableMetaData data);
VersionMetaData getArtifactVersionMetaDataByContent(String groupId, String artifactId, Boolean canonical, InputStream data);
default VersionMetaData getArtifactVersionMetaDataByContent(String groupId, String artifactId, InputStream data) {
return getArtifactVersionMetaDataByContent(groupId, artifactId, null, data);
}
List<RuleType> listArtifactRules(String groupId, String artifactId);
void createArtifactRule(String groupId, String artifactId, Rule data);
void deleteArtifactRules(String groupId, String artifactId);
Rule getArtifactRuleConfig(String groupId, String artifactId, RuleType rule);
Rule updateArtifactRuleConfig(String groupId, String artifactId, RuleType rule, Rule data);
void deleteArtifactRule(String groupId, String artifactId, RuleType rule);
void updateArtifactState(String groupId, String artifactId, UpdateState data);
void testUpdateArtifact(String groupId, String artifactId, InputStream data);
InputStream getArtifactVersion(String groupId, String artifactId, String version);
VersionMetaData getArtifactVersionMetaData(String groupId, String artifactId, String version);
void updateArtifactVersionMetaData(String groupId, String artifactId, String version,
EditableMetaData data);
void deleteArtifactVersionMetaData(String groupId, String artifactId, String version);
void updateArtifactVersionState(String groupId, String artifactId, String version, UpdateState data);
VersionSearchResults listArtifactVersions(String groupId, String artifactId, Integer offset,
Integer limit);
VersionMetaData createArtifactVersion(String groupId, String artifactId, String version, String artifactName, String artifactDescription, InputStream data);
default VersionMetaData createArtifactVersion(String groupId, String artifactId, String version, InputStream data) {
return createArtifactVersion(groupId, artifactId, version, null, null, data);
}
ArtifactSearchResults listArtifactsInGroup(String groupId, SortBy orderBy, SortOrder order, Integer offset, Integer limit);
default ArtifactSearchResults listArtifactsInGroup(String groupId) {
return listArtifactsInGroup(groupId, null, null, null, null);
}
ArtifactMetaData createArtifact(String groupId, String artifactId, String version, ArtifactType artifactType, IfExists ifExists, Boolean canonical, String artifactName, String artifactDescription, InputStream data);;
default ArtifactMetaData createArtifact(String groupId, String artifactId, String version, ArtifactType artifactType, IfExists ifExists, Boolean canonical, InputStream data) {
return createArtifact(groupId, artifactId, version, artifactType, ifExists, canonical, null, null, data);
}
default ArtifactMetaData createArtifact(String groupId, String artifactId, InputStream data) {
return createArtifact(groupId, artifactId, null, null, null, null, null, null, data);
}
default ArtifactMetaData createArtifact(String groupId, String artifactId, String version, InputStream data) {
return createArtifact(groupId, artifactId, version, null, null, null, null, null, data);
}
default ArtifactMetaData createArtifact(String groupId, String artifactId, ArtifactType artifactType, InputStream data) {
return createArtifact(groupId, artifactId, null, artifactType, null, null, null, null, data);
}
default ArtifactMetaData createArtifact(String groupId, String artifactId, ArtifactType artifactType, IfExists ifExists, InputStream data) {
return createArtifact(groupId, artifactId, null, artifactType, ifExists, null, null, null, data);
}
void deleteArtifactsInGroup(String groupId);
InputStream getContentById(long contentId);
InputStream getContentByGlobalId(long globalId);
InputStream getContentByHash(String contentHash, Boolean canonical);
default InputStream getContentByHash(String contentHash) {
return getContentByHash(contentHash, null);
};
ArtifactSearchResults searchArtifacts(String group, String name, String description, List<String> labels,
List<String> properties, SortBy orderBy, SortOrder order, Integer offset, Integer limit);
ArtifactSearchResults searchArtifactsByContent(InputStream data, SortBy orderBy, SortOrder order, Integer offset, Integer limit);
List<RuleType> listGlobalRules();
void createGlobalRule(Rule data);
void deleteAllGlobalRules();
Rule getGlobalRuleConfig(RuleType rule);
Rule updateGlobalRuleConfig(RuleType rule, Rule data);
void deleteGlobalRule(RuleType rule);
List<NamedLogConfiguration> listLogConfigurations();
NamedLogConfiguration getLogConfiguration(String logger);
NamedLogConfiguration setLogConfiguration(String logger, LogConfiguration data);
NamedLogConfiguration removeLogConfiguration(String logger);
InputStream exportData();
void importData(InputStream data);
List<RoleMapping> listRoleMappings();
void createRoleMapping(RoleMapping data);
RoleMapping getRoleMapping(String principalId);
void updateRoleMapping(String principalId, RoleType role);
void deleteRoleMapping(String principalId);
UserInfo getCurrentUserInfo();
void setNextRequestHeaders(Map<String, String> requestHeaders);
Map<String, String> getHeaders();
}
|
package com.wealth.wealthusers.controller;
import com.wealth.wealthusers.common.ControllerUtil;
import com.wealth.wealthusers.common.LoadUtil;
import com.wealth.wealthusers.entity.WcWealthManager;
import com.wealth.wealthusers.service.WcWealthManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@CrossOrigin
@RestController
@RequestMapping("/api/wealthmanager")
public class WcWealthManagerController {
@Autowired
WcWealthManagerService service;
@CrossOrigin
@GetMapping
private List<WcWealthManager> findAll() {
LoadUtil.processLoad();
return service.findAll();
}
@CrossOrigin
@GetMapping("/{id}")
@ResponseBody
private WcWealthManager findOne (@PathVariable("id") int id) {
LoadUtil.processLoad();
return service.find(id);
}
@CrossOrigin
@PostMapping
private ResponseEntity<?> create(@RequestBody WcWealthManager entity) {
LoadUtil.processLoad();
Object result = service.create(entity);
return ControllerUtil.getResponseEntityForCreate(result);
}
@CrossOrigin
@PutMapping
private WcWealthManager update(@RequestBody WcWealthManager entity) {
LoadUtil.processLoad();
return service.update(entity);
}
@CrossOrigin
@DeleteMapping("/{id}")
private WcWealthManager delete (@PathVariable("id") int id) {
LoadUtil.processLoad();
return service.delete(id);
}
}
|
package openanonymizer.model.wrapper;
import openanonymizer.model.describer.EntityDescriber;
import java.util.Map;
/**
* Container for {@link openanonymizer.model.dataset.DataSet} values.
*
* @version 0.1
* @since Open Anonymizer 1.0.0
*/
public interface EntityWrapper {
/**
* @return id of entity
*/
Object getId();
/**
* @param field name
* @return field value by field key
*/
Object getValue(final String field);
/**
* Inserts new field with its value into container
*
* @param field name
* @param value inserted value
* @return entity container
* */
EntityWrapper insert(final String field, final Object value);
/**
* Updates existing field value
*
* @param field name
* @param value updated value
* @return entity container
* */
EntityWrapper update(final String field, final Object value);
/**
* Removes field from container
*
* @param field name
* @return entity container
* */
EntityWrapper delete(final String field);
/**
* @return wrapped entity structure
* */
EntityDescriber describeEntity();
/**
* @return entity as {@link Map}
* */
Map<String, Object> getEntityAsMap();
}
|
/**
* Copyright 2010-2014 Axel Fontaine
*
* 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.flywaydb.core.internal.dbsupport.hsql;
import org.flywaydb.core.api.FlywayException;
import org.flywaydb.core.internal.dbsupport.DbSupport;
import org.flywaydb.core.internal.dbsupport.JdbcTemplate;
import org.flywaydb.core.internal.dbsupport.Schema;
import org.flywaydb.core.internal.dbsupport.Table;
import org.flywaydb.core.internal.util.logging.Log;
import org.flywaydb.core.internal.util.logging.LogFactory;
import java.sql.SQLException;
/**
* Hsql-specific table.
*/
public class HsqlTable extends Table {
private static final Log LOG = LogFactory.getLog(HsqlDbSupport.class);
/**
* Flag indicating whether we are running against the old Hsql 1.8 instead of the newer 2.x.
*/
private boolean version18;
/**
* Creates a new Hsql table.
*
* @param jdbcTemplate The Jdbc Template for communicating with the DB.
* @param dbSupport The database-specific support.
* @param schema The schema this table lives in.
* @param name The name of the table.
*/
public HsqlTable(JdbcTemplate jdbcTemplate, DbSupport dbSupport, Schema schema, String name) {
super(jdbcTemplate, dbSupport, schema, name);
try {
int majorVersion = jdbcTemplate.getMetaData().getDatabaseMajorVersion();
version18 = majorVersion < 2;
} catch (SQLException e) {
throw new FlywayException("Unable to determine the Hsql version", e);
}
}
@Override
protected void doDrop() throws SQLException {
jdbcTemplate.execute("DROP TABLE " + dbSupport.quote(schema.getName(), name) + " CASCADE");
}
@Override
protected boolean doExists() throws SQLException {
return exists(null, schema, name);
}
@Override
protected void doLock() throws SQLException {
if (version18) {
LOG.debug("Unable to lock " + this + " as Hsql 1.8 does not support locking. No concurrent migration supported.");
} else {
jdbcTemplate.execute("LOCK TABLE " + this + " WRITE");
}
}
}
|
/*
* Copyright 2006-2010 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.security.oauth2.provider;
import org.junit.Test;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.core.io.FileSystemResource;
/**
* @author Dave Syer
*
*/
public class TestBootstrap {
@Test
public void testRootContext() throws Exception {
GenericXmlApplicationContext context = new GenericXmlApplicationContext(new FileSystemResource("src/main/webapp/WEB-INF/spring-servlet.xml"));
context.close();
}
}
|
package io.atlasmap.core;
import java.util.ArrayList;
import java.util.List;
import io.atlasmap.v2.AtlasMapping;
import io.atlasmap.v2.BaseMapping;
import io.atlasmap.v2.Collection;
import io.atlasmap.v2.Field;
import io.atlasmap.v2.Mapping;
public class AtlasModuleSupport {
public static List<String> listTargetPaths(AtlasMapping atlasMapping) {
if (atlasMapping == null || atlasMapping.getMappings() == null
|| atlasMapping.getMappings().getMapping() == null
|| atlasMapping.getMappings().getMapping().size() == 0) {
return new ArrayList<String>();
}
return listTargetPaths(atlasMapping.getMappings().getMapping());
}
public static List<String> listTargetPaths(List<BaseMapping> mappings) {
List<String> targetPaths = new ArrayList<String>();
if (mappings == null || mappings.size() == 0) {
return targetPaths;
}
for (BaseMapping fm : mappings) {
if (fm instanceof Mapping) {
for (Field f : ((Mapping) fm).getOutputField()) {
targetPaths.add(f.getPath());
}
} else if (fm instanceof Collection) {
if (((Collection) fm).getMappings() != null) {
targetPaths.addAll(listTargetPaths(((Collection) fm).getMappings().getMapping()));
}
}
}
return targetPaths;
}
}
|
/*
* Copyright 2021-2022 Aklivity Inc.
*
* Aklivity licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.aklivity.zilla.runtime.engine.internal.context;
import java.util.function.Function;
import java.util.function.LongConsumer;
import java.util.function.ToIntFunction;
import org.agrona.collections.Int2ObjectHashMap;
import io.aklivity.zilla.runtime.engine.cog.Axle;
import io.aklivity.zilla.runtime.engine.config.Namespace;
import io.aklivity.zilla.runtime.engine.internal.stream.NamespacedId;
public class ConfigurationContext
{
private final Function<String, Axle> axlesByName;
private final ToIntFunction<String> supplyLabelId;
private final LongConsumer supplyLoadEntry;
private final Int2ObjectHashMap<NamespaceContext> namespacesById;
public ConfigurationContext(
Function<String, Axle> axlesByName,
ToIntFunction<String> supplyLabelId,
LongConsumer supplyLoadEntry)
{
this.axlesByName = axlesByName;
this.supplyLabelId = supplyLabelId;
this.supplyLoadEntry = supplyLoadEntry;
this.namespacesById = new Int2ObjectHashMap<>();
}
public NamespaceTask attach(
Namespace namespace)
{
return new NamespaceTask(namespace, this::attachNamespace);
}
public NamespaceTask detach(
Namespace namespace)
{
return new NamespaceTask(namespace, this::detachNamespace);
}
public BindingContext resolveBinding(
long bindingId)
{
int namespaceId = NamespacedId.namespaceId(bindingId);
int localId = NamespacedId.localId(bindingId);
NamespaceContext namespace = findNamespace(namespaceId);
return namespace != null ? namespace.findBinding(localId) : null;
}
public VaultContext resolveVault(
long vaultId)
{
int namespaceId = NamespacedId.namespaceId(vaultId);
int localId = NamespacedId.localId(vaultId);
NamespaceContext namespace = findNamespace(namespaceId);
return namespace != null ? namespace.findVault(localId) : null;
}
public void detachAll()
{
namespacesById.values().forEach(n -> n.detach());
namespacesById.clear();
}
private NamespaceContext findNamespace(
int namespaceId)
{
return namespacesById.get(namespaceId);
}
private void attachNamespace(
Namespace namespace)
{
NamespaceContext context = new NamespaceContext(namespace, axlesByName, supplyLabelId, supplyLoadEntry);
namespacesById.put(context.namespaceId(), context);
context.attach();
}
protected void detachNamespace(
Namespace namespace)
{
int namespaceId = supplyLabelId.applyAsInt(namespace.name);
NamespaceContext context = namespacesById.remove(namespaceId);
context.detach();
}
}
|
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests.extensions;
import com.microsoft.graph.requests.extensions.IWorkbookFunctionsIsNumberRequest;
import com.microsoft.graph.http.IRequestBuilder;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The interface for the Workbook Functions Is Number Request Builder.
*/
public interface IWorkbookFunctionsIsNumberRequestBuilder extends IRequestBuilder {
/**
* Creates the IWorkbookFunctionsIsNumberRequest
*
* @return the IWorkbookFunctionsIsNumberRequest instance
*/
IWorkbookFunctionsIsNumberRequest buildRequest();
/**
* Creates the IWorkbookFunctionsIsNumberRequest with specific options instead of the existing options
*
* @param requestOptions the options for the request
* @return the IWorkbookFunctionsIsNumberRequest instance
*/
IWorkbookFunctionsIsNumberRequest buildRequest(final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions);
}
|
/*
* CommonPackage
*
* Copyright (c) 2021-2022
*
* @author: Viet-Man Le (vietman.le@ist.tugraz.at)
*/
package at.tugraz.ist.ase.common;
import lombok.Getter;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import java.util.Random;
/**
* Random stuff for projects
*
* This random uses a seed to generate the same sequence of random numbers.
* This lets us make all randomness in the project predictable,
* if desired, for when we run unit tests, which should be repeatable.
*/
@Slf4j
@UtilityClass
public class RandomUtils {
@Getter
private long SEED = 141982;
private final Random random;
static {
random = new Random(SEED);
log.trace("{}Created a Random object [seed={}]", LoggerUtils.tab, SEED);
}
public void setSeed(long seed) {
SEED = seed;
random.setSeed(SEED);
log.debug("{}Reset the Random object with new seed [seed={}]", LoggerUtils.tab, SEED);
}
public int getRandomInt(int bound) {
return random.nextInt(bound);
}
public int getRandomInt(int bound, int offset) {
return random.nextInt(bound) + offset;
}
public double getRandomDouble(double bound) {
return random.nextDouble() * bound;
}
public double getRandomDouble(double bound, double offset) {
return random.nextDouble() * bound + offset;
}
public boolean getRandomBoolean() {
return random.nextBoolean();
}
}
|
package org.rcsb.cif.api.generated;
import org.rcsb.cif.model.*;
import javax.annotation.Generated;
import java.util.Map;
/**
* Data items in the category record overall map properties such
* as correlation, real space Rfactors and the Zscore calculated
* from refmac and mapman.
*/
@Generated("org.rcsb.cif.generator.SchemaGenerator")
public class PdbxDccRsccMapmanOverall extends BaseCategory {
public PdbxDccRsccMapmanOverall(String name, Map<String, Column> columns) {
super(name, columns);
}
public PdbxDccRsccMapmanOverall(String name, int rowCount, Object[] encodedColumns) {
super(name, rowCount, encodedColumns);
}
public PdbxDccRsccMapmanOverall(String name) {
super(name);
}
/**
* The PDB id code.
* @return StrColumn
*/
public StrColumn getPdbid() {
return (StrColumn) (isText ? textFields.computeIfAbsent("pdbid", StrColumn::new) :
getBinaryColumn("pdbid"));
}
/**
* The overall real space electron density correlation coefficient
* (RSCC) for the structure.
* @return FloatColumn
*/
public FloatColumn getCorrelation() {
return (FloatColumn) (isText ? textFields.computeIfAbsent("correlation", FloatColumn::new) :
getBinaryColumn("correlation"));
}
/**
* The overall standard deviation of the real space electron density
* correlation coefficient (RSCC) for the structure.
* @return FloatColumn
*/
public FloatColumn getCorrelationSigma() {
return (FloatColumn) (isText ? textFields.computeIfAbsent("correlation_sigma", FloatColumn::new) :
getBinaryColumn("correlation_sigma"));
}
/**
* The overall Real Space Rfactor (RSR) for the structure.
* @return FloatColumn
*/
public FloatColumn getRealSpaceR() {
return (FloatColumn) (isText ? textFields.computeIfAbsent("real_space_R", FloatColumn::new) :
getBinaryColumn("real_space_R"));
}
/**
* The overall standard deviation of the Real Space Rfactor (RSR)
* for the structure.
* @return FloatColumn
*/
public FloatColumn getRealSpaceRSigma() {
return (FloatColumn) (isText ? textFields.computeIfAbsent("real_space_R_sigma", FloatColumn::new) :
getBinaryColumn("real_space_R_sigma"));
}
}
|
/*
* Copyright 2000-2017 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.debugger.streams.trace;
import com.intellij.debugger.streams.resolve.ResolvedStreamChain;
import com.intellij.debugger.streams.wrapper.StreamChain;
import org.jetbrains.annotations.NotNull;
/**
* @author Vitaliy.Bibaev
*/
public interface ResolvedTracingResult {
@NotNull
ResolvedStreamChain getResolvedChain();
@NotNull
StreamChain getSourceChain();
boolean exceptionThrown();
@NotNull
TraceElement getResult();
}
|
package jsky.image.gui;
import edu.gemini.shared.util.immutable.Pair;
import jsky.image.ImageChangeEvent;
import jsky.util.I18N;
import javax.swing.*;
import java.util.HashMap;
public final class ImageScaleMenu extends JMenu {
private static final I18N _I18N = I18N.getInstance(ImageDisplayMenuBar.class);
private static final int MAX_SCALE = ImageDisplayMenuBar.MAX_SCALE;
private final HashMap<Pair<Integer, Integer>, JRadioButtonMenuItem> scaleToButton;
public ImageScaleMenu(final DivaMainImageDisplay imageDisplay) {
super(_I18N.getString("scale"));
// A lookup to be able to mark the appropriate radio button as selected when the image scale changes externally.
scaleToButton = new HashMap<>();
/** Create the zoom in and zoom out menu items **/
final ButtonGroup group = new ButtonGroup();
for (ScaleMenuOptions o : ScaleMenuOptions.values()) {
final JMenu menu = new JMenu(o.i18nName);
for (int i=o.lowerBound; i <= o.upperBound; ++i) {
final float scale = o.createScaleForIndex(i);
final Pair<Integer, Integer> rational = o.createRationalScaleForIndex(i);
final JRadioButtonMenuItem b = new JRadioButtonMenuItem(o.createLabelForIndex(i));
b.addActionListener(e -> {
imageDisplay.setScale(scale);
imageDisplay.updateImage();
});
group.add(b);
menu.add(b);
scaleToButton.put(rational, b);
}
add(menu);
}
/** Create the fit to window menu item **/
final JMenuItem menuItem = new JMenuItem(_I18N.getString("fitImageInWindow"));
menuItem.addActionListener(ae -> {
imageDisplay.scaleToFit();
imageDisplay.updateImage();
});
add(menuItem);
/** Register a change listener to set the button if the scaling is changed externally. **/
imageDisplay.addChangeListener(ce -> {
final ImageChangeEvent e = (ImageChangeEvent) ce;
if (e.isNewScale())
enableButtonForScale(imageDisplay.getScale());
});
// Set the default button to selected.
enableButtonForScale(imageDisplay.getScale());
}
private void enableButtonForScale(float scale) {
final Pair<Integer, Integer> rational = convertScaleToRational(scale);
final JRadioButtonMenuItem b = scaleToButton.get(rational);
if (b != null)
b.setSelected(true);
}
private static Pair<Integer, Integer> convertScaleToRational(float scale) {
if (scale > 0 && scale < 1)
return new Pair<>(1, Math.round(1.0f/scale));
return new Pair<>(Math.round(scale),1);
}
private enum ScaleMenuOptions {
ZoomOut("zoomOut", 2, MAX_SCALE) {
@Override
String createLabelForIndex(int idx) {
return "1/" + idx + "x";
}
@Override
Pair<Integer, Integer> createRationalScaleForIndex(int idx) {
return new Pair<>(1, idx);
}
},
ZoomIn("zoomIn", 1, MAX_SCALE) {
@Override
String createLabelForIndex(int idx) {
return idx + "x";
}
@Override
Pair<Integer, Integer> createRationalScaleForIndex(int idx) {
return new Pair<>(idx, 1);
}
},;
// Name of this item.
final String i18nName;
final int lowerBound;
final int upperBound;
ScaleMenuOptions(final String name, final int lowerBound, final int upperBound) {
i18nName = _I18N.getString(name);
this.lowerBound = lowerBound;
this.upperBound = upperBound;
}
abstract String createLabelForIndex(int idx);
abstract Pair<Integer, Integer> createRationalScaleForIndex(int idx);
float createScaleForIndex(int idx) {
final Pair<Integer, Integer> rational = createRationalScaleForIndex(idx);
// This should never happen.
if (rational._2() == 0)
return 0;
return ((float) rational._1()) / rational._2();
}
}
}
|
package com.xero.api;
import com.google.api.client.auth.oauth.OAuthAuthorizeTemporaryTokenUrl;
public class OAuthAuthorizeToken {
private String authUrl = null;
public OAuthAuthorizeToken(Config c, String tempToken)
{
OAuthAuthorizeTemporaryTokenUrl accessTempToken = new OAuthAuthorizeTemporaryTokenUrl(c.getAuthorizeUrl());
accessTempToken.temporaryToken = tempToken;
accessTempToken.set("oauth_callback",c.getRedirectUri());
authUrl = accessTempToken.build();
}
public String getAuthUrl()
{
return authUrl;
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.rocketmq.streams.filter.operator;
public class FilterOperator extends Rule {
public FilterOperator(String namespace, String name, String expression) {
super(namespace, name, expression);
}
public FilterOperator() {}
public FilterOperator(String expression) {
super(expression);
}
}
|
package info.hebbeker.david.memorex;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.preference.PreferenceManager;
import android.util.AttributeSet;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import static java.lang.Math.max;
/**
* Extends AppCompatButton with capabilities to signal a symbol.
* <p>
* Symbols can be one of the following: 0, 1, 2, 3
*/
final class SymbolButton extends android.support.v7.widget.AppCompatButton implements Symbol
{
final static private SoundPool soundPool = new SoundPool(1, AudioManager.STREAM_SYSTEM, 0);
private static long signallingDuration = 0;
private static int maxSoundDuration = 0;
private static long animationDuration;
private static boolean isSilent;
final private int symbol;
final private Animation animation;
private int soundId = -1;
public SymbolButton(final Context context, final AttributeSet attrs)
{
super(context, attrs);
{
final TypedArray styledAttributes = context.obtainStyledAttributes(attrs, R.styleable.SymbolButton);
symbol = styledAttributes.getInteger(R.styleable.SymbolButton_symbol, 0);
styledAttributes.recycle();
}
animation = AnimationUtils.loadAnimation(context, R.anim.shake);
try
{
final int rawSoundResourceId = getRawSoundResourceId();
soundId = soundPool.load(context, rawSoundResourceId, 1);
try
{
maxSoundDuration = max(maxSoundDuration, getSoundDuration(context, rawSoundResourceId));
} catch (Exception exceptionGettingSoundDuration)
{
// can not do much in case getting sound duration fails. Fall back to default value.
exceptionGettingSoundDuration.printStackTrace();
}
} catch (Exception exceptionLoadingSoundResource)
{
// can not do much in case getting sound duration fails. Fall back to default value.
// An invalid soundId will not be played but does not lead to an exception.
exceptionLoadingSoundResource.printStackTrace();
}
// Load preferences
final String preferenceKeySilent = context.getString(R.string.preference_switch_sound);
final String preferenceKeySpeed = context.getString(R.string.preference_speed_list);
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
updateSignallingDurationSettings(Long.parseLong(sharedPreferences.getString(preferenceKeySpeed, "250")));
setIsSilent(sharedPreferences.getBoolean(preferenceKeySilent, false));
}
static long getSignallingDuration()
{
return signallingDuration;
}
/**
* Updates the signalling duration times according to the preferences.
*/
static void updateSignallingDurationSettings(final long newAnimationDuration)
{
animationDuration = newAnimationDuration;
signallingDuration = max(animationDuration, maxSoundDuration);
}
static void setIsSilent(final boolean isSilent)
{
SymbolButton.isSilent = isSilent;
}
/**
* @param rawId the raw resource id ({@code R.raw.<something>}) for the resource to use as sound source
* @return the duration in milliseconds, if no duration is available exception is thrown
*/
private int getSoundDuration(final Context context, final int rawId) throws Exception
{
final MediaPlayer mediaPlayer = MediaPlayer.create(context, rawId);
final int duration = mediaPlayer.getDuration();
mediaPlayer.release();
if (duration < 0)
throw new Exception("fetching duration of sound failed (raw resource id:" + rawId + ", duration:" + duration + ")");
return duration;
}
/**
* @return the raw resource id ({@code R.raw.<something>}) for the resource to use as sound source
*/
private int getRawSoundResourceId() throws Exception
{
switch (symbol)
{
case 0:
return R.raw.keyok1;
case 1:
return R.raw.keyok2;
case 2:
return R.raw.keyok3;
case 3:
return R.raw.keyok5;
default:
throw new Exception("No sound resource found for symbol '" + symbol + "'!");
}
}
void signalSymbol()
{
animation.setDuration(animationDuration);
startAnimation(animation);
if (!isSilent)
{
soundPool.play(soundId, 1f, 1f, 1, 0, 1f);
}
}
}
|
package com.brucetoo.videoplayer.videomanage.messages;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import com.brucetoo.videoplayer.videomanage.interfaces.VideoPlayerManagerCallback;
import com.brucetoo.videoplayer.videomanage.meta.MetaData;
import com.brucetoo.videoplayer.videomanage.player.VideoPlayerView;
/**
* This PlayerMessage calls {@link MediaPlayer#setDataSource(Context, Uri)} on the instance that is used inside {@link VideoPlayerView}
*/
public class SetUrlDataSourceMessage extends SetDataSourceMessage{
private final MetaData mMetaData;
public SetUrlDataSourceMessage(VideoPlayerView videoPlayerView, MetaData metaData, VideoPlayerManagerCallback callback) {
super(videoPlayerView, callback);
mMetaData = metaData;
}
@Override
protected void performAction(VideoPlayerView currentPlayer) {
//Get video url
currentPlayer.setDataSource(mMetaData.getVideoUrl());
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.applicationinsights.models;
import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;
/** An XML configuration specification for a WebTest. */
@Fluent
public final class WebTestPropertiesConfiguration {
/*
* The XML specification of a WebTest to run against an application.
*/
@JsonProperty(value = "WebTest")
private String webTest;
/**
* Get the webTest property: The XML specification of a WebTest to run against an application.
*
* @return the webTest value.
*/
public String webTest() {
return this.webTest;
}
/**
* Set the webTest property: The XML specification of a WebTest to run against an application.
*
* @param webTest the webTest value to set.
* @return the WebTestPropertiesConfiguration object itself.
*/
public WebTestPropertiesConfiguration withWebTest(String webTest) {
this.webTest = webTest;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
}
}
|
package Chapter20;
import java.util.*;
public class TestArrayAndLinkedLiest {
public static void main(String[] args) {
List<Integer> arrayList = new ArrayList<>();
arrayList.add(1);
arrayList.add(2);
arrayList.add(3);
arrayList.add(1);
arrayList.add(1);
arrayList.add(5);
System.out.println(arrayList + "");
arrayList.add(0, 10);
arrayList.add(3, 30);
arrayList.add(5, 80);
System.out.println("A list of integers in the array list");
System.out.println(arrayList);
LinkedList<Object> linkedList = new LinkedList<>(arrayList);
linkedList.add(1, "red");
linkedList.removeLast();
linkedList.addFirst("green");
System.out.println("Display the linked list forward");
ListIterator<Object> listIterator = linkedList.listIterator();
while (listIterator.hasNext()) {
System.out.print(listIterator.next() + " ");
}
System.out.println();
System.out.println("Display the linked list backward: ");
listIterator = linkedList.listIterator(linkedList.size());
while (listIterator.hasPrevious()) {
System.out.print(listIterator.previous() + "");
}
}
}
|
package org.cjzheng01.inventory.pojo.response;
import java.util.List;
public class ListResponse <T> extends CommonResponse {
private static final long serialVersionUID = 1610792978872732678L;
private List<T> data;
public List<T> getData() {
return data;
}
public ListResponse<T> setData(List<T> data) {
this.data = data;
return this;
}
}
|
package net.zhongli.tech.luwu.admin.module.system.contorller;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.swagger.models.Model;
import net.zhongli.tech.luwu.admin.common.annotation.OperateLog;
import net.zhongli.tech.luwu.admin.common.base.BaseController;
import net.zhongli.tech.luwu.admin.common.dto.Pager;
import net.zhongli.tech.luwu.admin.common.enums.OperateLogTypes;
import net.zhongli.tech.luwu.admin.common.utils.Result;
import net.zhongli.tech.luwu.admin.common.utils.ResultUtil;
import net.zhongli.tech.luwu.admin.module.system.entity.UserEntity;
import net.zhongli.tech.luwu.admin.module.system.service.UserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
/**
* 用户控制器
* @author lk
* @create 2020/12/22 2:32 下午
**/
@Controller
@RequestMapping("/system/users")
public class UserController extends BaseController {
@Resource
private UserService userService;
/**
* 用户页面
* @param model
* @return
*/
@PreAuthorize("hasAuthority('system:users:index')")
@GetMapping("/index.html")
public String index(Model model) {
return "user/index";
}
/**
* 列表页面
* @return
*/
@PreAuthorize("hasAuthority('system:users:list')")
@GetMapping("/list.html")
public String list(){
return "user/list";
}
/**
* 表单页面
* @return
*/
@PreAuthorize("hasAuthority('system:users:form')")
@GetMapping("/form.html")
public String form() {
return "user/form";
}
/**
* 获取用户分页列表
* @param pager
* @return
*/
@PreAuthorize("hasAuthority('system:users:list:post')")
@PostMapping("/list")
@ResponseBody
public Pager userList(@RequestBody Pager pager) {
Page<Object> page = PageHelper.startPage(pager.getPageNum(), pager.getPageSize());
List<UserEntity> userEntityList = this.userService.queryList(pager.getParameters());
return ResultUtil.page(page, userEntityList);
}
/**
* 获取用户列表
* @param parameters
* @return
*/
@PreAuthorize("hasAuthority('system:users:get')")
@GetMapping
@ResponseBody
public Result<List<UserEntity>> userList(@RequestParam Map<String, Object> parameters) {
List<UserEntity> userEntityList = this.userService.findBy(parameters);
return ResultUtil.success(userEntityList);
}
/**
* 通过用户 id 查找用户信息
* @param userId
* @return
*/
@PreAuthorize("hasAuthority('system:users:user')")
@GetMapping("/{userId}")
@ResponseBody
public Result<UserEntity> findById(@PathVariable("userId") Long userId) {
UserEntity userEntity = this.userService.findById(userId);
return ResultUtil.success(userEntity);
}
/**
* 添加用户方法
* @param userEntity
* @return
*/
@PreAuthorize("hasAuthority('system:users:post')")
@PostMapping
@ResponseBody
@OperateLog(description = "添加用户信息", operateType = OperateLogTypes.SAVE)
public Result<UserEntity> save(@RequestBody @Validated UserEntity userEntity) {
this.userService.save(userEntity);
return ResultUtil.success(userEntity);
}
/**
* 修改用户方法
* @param userEntity
* @return
*/
@PreAuthorize("hasAuthority('system:users:put')")
@PutMapping
@ResponseBody
@OperateLog(description = "修改用户信息", operateType = OperateLogTypes.UPDATE)
public Result<UserEntity> update(@RequestBody @Validated UserEntity userEntity) {
this.userService.update(userEntity);
return ResultUtil.success();
}
/**
* 通过用户 id 删除用户
* @param userId
* @return
*/
@PreAuthorize("hasAuthority('system:users:delete')")
@DeleteMapping("/{userId}")
@ResponseBody
@OperateLog(description = "修改用户信息", operateType = OperateLogTypes.DELETE)
public Result<String> deleteById(@PathVariable("userId") Long userId) {
this.userService.deleteById(userId);
return ResultUtil.success();
}
}
|
/*
* Copyright 2018 JDCLOUD.COM
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http:#www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Zone Settings
* A Zone setting changes how the Zone works in relation to caching, security, or other features of JDC StarShield
*
* OpenAPI spec version: v1
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
package com.jdcloud.sdk.service.starshield.model;
import com.jdcloud.sdk.annotation.Required;
import com.jdcloud.sdk.service.JdcloudRequest;
/**
* 获取HTTP3设置的状态
*/
public class GetHTTP3SettingRequest extends JdcloudRequest implements java.io.Serializable {
private static final long serialVersionUID = 1L;
/**
* zone_identifier
* Required:true
*/
@Required
private String zone_identifier;
/**
* get zone_identifier
*
* @return
*/
public String getZone_identifier() {
return zone_identifier;
}
/**
* set zone_identifier
*
* @param zone_identifier
*/
public void setZone_identifier(String zone_identifier) {
this.zone_identifier = zone_identifier;
}
/**
* set zone_identifier
*
* @param zone_identifier
*/
public GetHTTP3SettingRequest zone_identifier(String zone_identifier) {
this.zone_identifier = zone_identifier;
return this;
}
}
|
package ru.sbtqa.tag.pagefactory.tasks;
import java.io.IOException;
import org.apache.commons.lang3.SystemUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.sbtqa.tag.pagefactory.properties.Configuration;
import ru.sbtqa.tag.pagefactory.junit.CoreSetupSteps;
public class KillProcessesTask implements Task {
private static final Logger LOG = LoggerFactory.getLogger(CoreSetupSteps.class);
private static final Configuration PROPERTIES = Configuration.create();
@Override
public void handle() {
stopTasksToKill();
}
private void stopTasksToKill() {
String tasks = PROPERTIES.getTasksToKill();
if (!tasks.isEmpty()) {
for (String task : tasks.split(",")) {
stopTask(task);
}
}
}
private void stopTask(String task) {
try {
if (SystemUtils.IS_OS_WINDOWS) {
Runtime.getRuntime().exec("taskkill /IM " + task.trim() + " /F");
} else {
Runtime.getRuntime().exec("killall " + task.trim());
}
} catch (IOException e) {
LOG.debug("Failed to kill " + task, e);
}
}
}
|
package com.github.siyamed.shapeimageview.shader;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import com.github.siyamed.shapeimageview.R;
@SuppressWarnings("WeakerAccess")
public abstract class ShaderHelper {
private final static int ALPHA_MAX = 255;
protected int viewWidth;
protected int viewHeight;
protected int borderColor = Color.BLACK;
protected int borderWidth = 0;
protected float borderAlpha = 1f;
protected boolean square = false;
protected final Paint borderPaint;
protected final Paint imagePaint;
protected BitmapShader shader;
protected Drawable drawable;
protected final Matrix matrix = new Matrix();
public ShaderHelper() {
borderPaint = new Paint();
borderPaint.setStyle(Paint.Style.STROKE);
borderPaint.setAntiAlias(true);
imagePaint = new Paint();
imagePaint.setAntiAlias(true);
}
public abstract void draw(Canvas canvas, Paint imagePaint, Paint borderPaint);
public abstract void reset();
@SuppressWarnings("UnusedParameters")
public abstract void calculate(int bitmapWidth, int bitmapHeight, float width, float height, float scale, float translateX, float translateY);
@SuppressWarnings("SameParameterValue")
protected final int dpToPx(DisplayMetrics displayMetrics, int dp) {
return Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
}
public boolean isSquare() {
return square;
}
public void init(Context context, AttributeSet attrs, int defStyle) {
if(attrs != null){
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ShaderImageView, defStyle, 0);
borderColor = typedArray.getColor(R.styleable.ShaderImageView_siBorderColor, borderColor);
borderWidth = typedArray.getDimensionPixelSize(R.styleable.ShaderImageView_siBorderWidth, borderWidth);
borderAlpha = typedArray.getFloat(R.styleable.ShaderImageView_siBorderAlpha, borderAlpha);
square = typedArray.getBoolean(R.styleable.ShaderImageView_siSquare, square);
typedArray.recycle();
}
borderPaint.setColor(borderColor);
borderPaint.setAlpha(Float.valueOf(borderAlpha * ALPHA_MAX).intValue());
borderPaint.setStrokeWidth(borderWidth);
}
public boolean onDraw(Canvas canvas) {
if (shader == null) {
createShader();
}
if (shader != null && viewWidth > 0 && viewHeight > 0) {
draw(canvas, imagePaint, borderPaint);
return true;
}
return false;
}
public void onSizeChanged(int width, int height) {
viewWidth = width;
viewHeight = height;
if(isSquare()) {
viewWidth = viewHeight = Math.min(width, height);
}
if(shader != null) {
calculateDrawableSizes();
}
}
public Bitmap calculateDrawableSizes() {
Bitmap bitmap = getBitmap();
if(bitmap != null) {
int bitmapWidth = bitmap.getWidth();
int bitmapHeight = bitmap.getHeight();
if(bitmapWidth > 0 && bitmapHeight > 0) {
float width = Math.round(viewWidth - 2f * borderWidth);
float height = Math.round(viewHeight - 2f * borderWidth);
float scale;
float translateX = 0;
float translateY = 0;
if (bitmapWidth * height > width * bitmapHeight) {
scale = height / bitmapHeight;
translateX = Math.round((width/scale - bitmapWidth) / 2f);
} else {
scale = width / (float) bitmapWidth;
translateY = Math.round((height/scale - bitmapHeight) / 2f);
}
matrix.setScale(scale, scale);
matrix.preTranslate(translateX, translateY);
matrix.postTranslate(borderWidth, borderWidth);
calculate(bitmapWidth, bitmapHeight, width, height, scale, translateX, translateY);
return bitmap;
}
}
reset();
return null;
}
public final void onImageDrawableReset(Drawable drawable) {
this.drawable = drawable;
shader = null;
imagePaint.setShader(null);
}
protected void createShader() {
Bitmap bitmap = calculateDrawableSizes();
if(bitmap != null && bitmap.getWidth() > 0 && bitmap.getHeight() > 0) {
shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
imagePaint.setShader(shader);
}
}
protected Bitmap getBitmap() {
Bitmap bitmap = null;
if(drawable != null) {
if(drawable instanceof BitmapDrawable) {
bitmap = ((BitmapDrawable) drawable).getBitmap();
}
}
return bitmap;
}
}
|
package fr.aumgn.bukkitutils.gson;
import com.google.common.base.Charsets;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import org.bukkit.plugin.Plugin;
import java.io.*;
import java.lang.reflect.Type;
/**
* Class which handle loading of .json resources
* for a given plugin using {@link Gson}.
*/
public class GsonLoader {
private final Gson gson;
private final Plugin plugin;
public GsonLoader(Gson gson, Plugin plugin) {
this.gson = gson;
this.plugin = plugin;
}
private File getFile(String filename)
throws GsonLoadException {
File file = new File(plugin.getDataFolder(), filename);
File folder = file.getParentFile();
if (!file.exists() && !folder.exists() && !folder.mkdirs()) {
throw new GsonLoadException("Unable to create directory : "
+ plugin.getDataFolder().getPath());
}
return file;
}
/**
* Loads if exists or creates the given resource.
*/
public <T> T loadOrCreate(String filename, Class<T> klass)
throws GsonLoadException {
return loadOrCreate(filename, klass, klass);
}
/**
* Loads if exists or creates the given resource.
*/
@SuppressWarnings("unchecked")
public <T> T loadOrCreate(String filename, TypeToken<T> typeToken)
throws GsonLoadException {
return (T) loadOrCreate(filename, typeToken.getType(),
typeToken.getRawType());
}
private <T> T loadOrCreate(String filename, Type type, Class<T> klass)
throws GsonLoadException {
try {
File file = getFile(filename);
T instance;
if (file.createNewFile()) {
instance = klass.newInstance();
}
else {
instance = unsafeLoad(file, type);
}
// This ensures user file is updated with newer fields.
write(file, instance);
return instance;
}
catch (IOException exc) {
throw new GsonLoadException(exc);
}
catch (InstantiationException exc) {
throw new GsonLoadException(exc);
}
catch (IllegalAccessException exc) {
throw new GsonLoadException(exc);
}
}
/**
* Loads the given resource.
*/
public <T> T load(File file, Type klass) throws GsonLoadException {
try {
return unsafeLoad(file, klass);
}
catch (IOException exc) {
throw new GsonLoadException(exc);
}
}
/**
* Loads the given resource.
*/
public <T> T load(File file, TypeToken<T> typeToken)
throws GsonLoadException {
try {
return unsafeLoad(file, typeToken.getRawType());
}
catch (IOException exc) {
throw new GsonLoadException(exc);
}
}
private <T> T unsafeLoad(File file, Type klass) throws IOException {
InputStreamReader isr = new InputStreamReader(
new FileInputStream(file), Charsets.UTF_8);
JsonReader reader = new JsonReader(isr);
try {
return gson.fromJson(reader, klass);
}
finally {
reader.close();
}
}
/**
* Writes the given resource.
*/
public void write(String filename, Object instance)
throws GsonLoadException {
try {
write(getFile(filename), instance);
}
catch (IOException exc) {
throw new GsonLoadException(exc);
}
}
private void write(File file, Object instance) throws IOException {
OutputStreamWriter osw = new OutputStreamWriter(
new FileOutputStream(file), Charsets.UTF_8);
BufferedWriter writer = new BufferedWriter(osw);
try {
writer.write(gson.toJson(instance));
}
finally {
writer.close();
}
}
}
|
package org.zstack.sdk;
import java.util.HashMap;
import java.util.Map;
import org.zstack.sdk.*;
public class GetL3NetworkMtuAction extends AbstractAction {
private static final HashMap<String, Parameter> parameterMap = new HashMap<>();
private static final HashMap<String, Parameter> nonAPIParameterMap = new HashMap<>();
public static class Result {
public ErrorCode error;
public org.zstack.sdk.GetL3NetworkMtuResult value;
public Result throwExceptionIfError() {
if (error != null) {
throw new ApiException(
String.format("error[code: %s, description: %s, details: %s]", error.code, error.description, error.details)
);
}
return this;
}
}
@Param(required = true, nonempty = false, nullElements = false, emptyString = true, noTrim = false)
public java.lang.String l3NetworkUuid;
@Param(required = false)
public java.util.List systemTags;
@Param(required = false)
public java.util.List userTags;
@Param(required = false)
public String sessionId;
@Param(required = false)
public String accessKeyId;
@Param(required = false)
public String accessKeySecret;
@Param(required = false)
public String requestIp;
private Result makeResult(ApiResult res) {
Result ret = new Result();
if (res.error != null) {
ret.error = res.error;
return ret;
}
org.zstack.sdk.GetL3NetworkMtuResult value = res.getResult(org.zstack.sdk.GetL3NetworkMtuResult.class);
ret.value = value == null ? new org.zstack.sdk.GetL3NetworkMtuResult() : value;
return ret;
}
public Result call() {
ApiResult res = ZSClient.call(this);
return makeResult(res);
}
public void call(final Completion<Result> completion) {
ZSClient.call(this, new InternalCompletion() {
@Override
public void complete(ApiResult res) {
completion.complete(makeResult(res));
}
});
}
protected Map<String, Parameter> getParameterMap() {
return parameterMap;
}
protected Map<String, Parameter> getNonAPIParameterMap() {
return nonAPIParameterMap;
}
protected RestInfo getRestInfo() {
RestInfo info = new RestInfo();
info.httpMethod = "GET";
info.path = "/l3-networks/{l3NetworkUuid}/mtu";
info.needSession = true;
info.needPoll = false;
info.parameterName = "";
return info;
}
}
|
package aleGrammar;
import java.io.*;
import java.util.ArrayList;
import org.antlr.runtime.ANTLRFileStream;
import org.antlr.runtime.ANTLRStringStream;
import org.antlr.runtime.CharStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.ParserRuleReturnScope;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.tree.*;
import org.antlr.stringtemplate.StringTemplate;
import aleGrammar.FTLSyntaxParser.root_return;
import AGEval.InvalidGrammarException;
//one instance per document
public class FrontendBeta {
public Tree reparse (String s) throws IOException, RecognitionException {
FTLSyntaxLexer lex = new FTLSyntaxLexer(new ANTLRStringStream(s));
CommonTokenStream tokens = new CommonTokenStream(lex);
FTLSyntaxParser parser = new FTLSyntaxParser (tokens);
FTLSyntaxParser.root_return r = parser.root();
return (Tree) r.tree;
}
public String reparseAll (Tree t) throws IOException, RecognitionException {
return reparse(t.toStringTree()).toStringTree();
}
public static String prettify (String tree) {
return tree
.replaceAll(" class ", "\nclass ")
.replaceAll("interface ([a-zA-Z0-9]+) \\{", "\ninterface $1 {\n")
.replaceAll(" schedule ", "\nschedule ")
.replaceAll("actions \\{", "\n actions {\n")
.replaceAll("children \\{", "\n children {\n")
// .replaceAll("^ ([a-zA-Z0-9]+) : ", " $1 : ")
.replaceAll("phantom \\{", "\n phantom {\n")
.replaceAll("attributes", "\n attributes")
.replaceAll(";", ";\n")
// .replaceAll("[ ]*([a-z0-9A-Z]* :=)", " $1")
;
}
public static void prettyPrint (String tree) {
System.out.println(prettify(tree));
}
public static CommonTree reorder (Tree raw) throws RecognitionException {
FTLReorderToplevelsLexer lex2 = new FTLReorderToplevelsLexer(new ANTLRStringStream(raw.toStringTree()));
CommonTokenStream tokens2 = new CommonTokenStream(lex2);
FTLReorderToplevelsParser parser2 = new FTLReorderToplevelsParser (tokens2);
FTLReorderToplevelsParser.root_return r2 = parser2.root();
return r2.tree;
}
public static CommonTree checkIdentifiers (Tree raw) throws RecognitionException {
FTLCheckIdentifiersLexer lex2 = new FTLCheckIdentifiersLexer(new ANTLRStringStream(raw.toStringTree()));
CommonTokenStream tokens2 = new CommonTokenStream(lex2);
FTLCheckIdentifiersParser parser2 = new FTLCheckIdentifiersParser (tokens2);
FTLCheckIdentifiersParser.root_return r2 = parser2.root();
if (parser2.errors.size() > 0) {
System.err.println(" checkIdentifiers: Tree " + (r2.tree == null) + ", error count: " + parser2.errors.size());
throw new RecognitionException();
}
return r2.tree;
}
public static void checkGrammar (String grammarFilePath) throws IOException, RecognitionException {
System.err.println("Checking grammar..");
//====== Syntax check
// System.err.println("===============");
// System.err.println("Syntax");
FTLSyntaxLexer lex = new FTLSyntaxLexer(new ANTLRFileStream(grammarFilePath));
CommonTokenStream tokens = new CommonTokenStream(lex);
FTLSyntaxParser parser = new FTLSyntaxParser (tokens);
FTLSyntaxParser.root_return r = parser.root();
//====== Sort top levels
// System.err.println("===============");
// System.err.println("Sort");
if (r.tree == null) {
System.err.println("Null tree: "+ grammarFilePath);
return;
}
CommonTree r2 = reorder((Tree) r.tree);
//====== Desugar traits
// System.err.println("===============");
// System.err.println("Expand traits");
FTLExpandTraitsLexer lex4 = new FTLExpandTraitsLexer(new ANTLRStringStream(r2.toStringTree()));
CommonTokenStream tokens4 = new CommonTokenStream(lex4);
FTLExpandTraitsParser parser4 = new FTLExpandTraitsParser (tokens4);
FTLExpandTraitsParser.root_return r4 = parser4.root();
CommonTree r5 = reorder((Tree)r4.tree);
CommonTree r7 = checkIdentifiers(r5);
// System.out.println("====Valid grammar!===");
// prettyPrint(r7.toStringTree());
// System.out.println("====Valid grammar!===");
System.err.println("Checks complete.");
}
public FrontendBeta (String grammarFilePath) throws IOException, RecognitionException, InvalidGrammarException {
//====== Syntax check
System.err.println("===============");
System.err.println("Syntax");
FTLSyntaxLexer lex = new FTLSyntaxLexer(new ANTLRFileStream(grammarFilePath));
CommonTokenStream tokens = new CommonTokenStream(lex);
FTLSyntaxParser parser = new FTLSyntaxParser (tokens);
FTLSyntaxParser.root_return r = parser.root();
//====== Sort top levels
System.err.println("===============");
System.err.println("Sort");
System.err.println(((Tree)r.tree).toStringTree());
CommonTree r2 = reorder((Tree) r.tree);
//====== Desugar traits
System.err.println("===============");
System.err.println("Expand traits");
FTLExpandTraitsLexer lex4 = new FTLExpandTraitsLexer(new ANTLRStringStream(r2.toStringTree()));
CommonTokenStream tokens4 = new CommonTokenStream(lex4);
FTLExpandTraitsParser parser4 = new FTLExpandTraitsParser (tokens4);
FTLExpandTraitsParser.root_return r4 = parser4.root();
CommonTree r5 = reorder((Tree)r4.tree);
//====== Expand conditionals
System.err.println("===============");
System.err.println("Expand conditionals");
System.err.println(prettify(r5.toStringTree()));
/*
FTLExpandConditionalsLexer lex5 = new FTLExpandConditionalsLexer(new ANTLRStringStream(prettify(r5.toStringTree())));
//FTLExpandConditionalsLexer lex5 = new FTLExpandConditionalsLexer(new ANTLRStringStream(r5.toStringTree()));
CommonTokenStream tokens5 = new CommonTokenStream(lex5);
FTLExpandConditionalsParser parser5 = new FTLExpandConditionalsParser (tokens5);
FTLExpandConditionalsParser.root_return r6r = parser5.root();
*/
/*
System.err.println(prettify(r5.toStringTree()));
FTLExpandConditionals parser5 = new FTLExpandConditionals(new CommonTreeNodeStream(r5));
FTLExpandConditionals.root_return r6r = parser5.root();
System.err.println(prettify(r6r.toString()));
CommonTree r6 = r6r.tree;
System.err.println("Expanded conditionals:");
System.err.println(prettify(r6.toStringTree()));
*/
//====== Expand conditionals
System.err.println("===============");
System.err.println("Check identifiers");
CommonTree r7 = checkIdentifiers(r5);
System.out.println("====Valid grammar!===");
prettyPrint(r7.toStringTree());
System.out.println("====Valid grammar!===");
//======
//Tree clean = reparse(((Tree)r2.tree).toStringTree());
//System.out.println(new DOTTreeGenerator().toDOT((CommonTree) clean));
}
//1: input grammar file url
public static void main(String[] args) throws Exception {
int numArgs = 1;
if (args.length != numArgs) {
System.err.println("Arg 1: ALE grammar file");
throw new Exception ("Not enough args to frontend");
}
FrontendBeta grammar = new FrontendBeta(args[0]);
}
}
|
package com.nicolas.coding.third.salvage;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
/**
* A {@link PagerAdapter} which behaves like an {@link android.widget.Adapter} with view types and
* view recycling.
*/
public abstract class RecyclingPagerAdapter extends PagerAdapter {
static final int IGNORE_ITEM_VIEW_TYPE = AdapterView.ITEM_VIEW_TYPE_IGNORE;
private final RecycleBin recycleBin;
public RecyclingPagerAdapter() {
this(new RecycleBin());
}
RecyclingPagerAdapter(RecycleBin recycleBin) {
this.recycleBin = recycleBin;
recycleBin.setViewTypeCount(getViewTypeCount());
}
@Override
public void notifyDataSetChanged() {
recycleBin.scrapActiveViews();
super.notifyDataSetChanged();
}
@Override
public final Object instantiateItem(ViewGroup container, int position) {
int viewType = getItemViewType(position);
View view = null;
if (viewType != IGNORE_ITEM_VIEW_TYPE) {
view = recycleBin.getScrapView(position, viewType);
}
view = getView(position, view, container);
container.addView(view);
return view;
}
@Override
public final void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
int viewType = getItemViewType(position);
if (viewType != IGNORE_ITEM_VIEW_TYPE) {
recycleBin.addScrapView(view, position, viewType);
}
}
@Override
public final boolean isViewFromObject(View view, Object object) {
return view == object;
}
/**
* <p>
* Returns the number of types of Views that will be created by
* {@link #getView}. Each type represents a set of views that can be
* converted in {@link #getView}. If the adapter always returns the same
* type of View for all items, this method should return 1.
* </p>
* <p>
* This method will only be called when when the adapter is set on the
* the {@link AdapterView}.
* </p>
*
* @return The number of types of Views that will be created by this adapter
*/
public int getViewTypeCount() {
return 1;
}
/**
* Get the type of View that will be created by {@link #getView} for the specified item.
*
* @param position The position of the item within the adapter's data set whose view type we
* want.
* @return An integer representing the type of View. Two views should share the same type if one
* can be converted to the other in {@link #getView}. Note: Integers must be in the
* range 0 to {@link #getViewTypeCount} - 1. {@link #IGNORE_ITEM_VIEW_TYPE} can
* also be returned.
* @see #IGNORE_ITEM_VIEW_TYPE
*/
@SuppressWarnings("UnusedParameters") // Argument potentially used by subclasses.
public int getItemViewType(int position) {
return 0;
}
/**
* Get a View that displays the data at the specified position in the data set. You can either
* create a View manually or inflate it from an XML layout file. When the View is inflated, the
* parent View (GridView, ListView...) will apply default layout parameters unless you use
* {@link android.view.LayoutInflater#inflate(int, ViewGroup, boolean)}
* to specify a root view and to prevent attachment to the root.
*
* @param position The position of the item within the adapter's data set of the item whose view
* we want.
* @param convertView The old view to reuse, if possible. Note: You should check that this view
* is non-null and of an appropriate type before using. If it is not possible to convert
* this view to display the correct data, this method can create a new view.
* Heterogeneous lists can specify their number of view types, so that this View is
* always of the right type (see {@link #getViewTypeCount()} and
* {@link #getItemViewType(int)}).
* @param container The parent that this view will eventually be attached to
* @return A View corresponding to the data at the specified position.
*/
public abstract View getView(int position, View convertView, ViewGroup container);
}
|
package org.hl7.fhir.r5.model;
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, \
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this \
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, \
this list of conditions and the following disclaimer in the documentation \
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND \
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED \
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. \
IN NO EVENT SHALL THE COPYRIGHT HOLDER 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.
*/
// Generated on Thu, Aug 20, 2020 19:42+1000 for FHIR vcurrent
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.hl7.fhir.utilities.Utilities;
import org.hl7.fhir.r5.model.Enumerations.*;
import org.hl7.fhir.instance.model.api.IBaseBackboneElement;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.instance.model.api.ICompositeType;
import ca.uhn.fhir.model.api.annotation.ResourceDef;
import ca.uhn.fhir.model.api.annotation.SearchParamDefinition;
import org.hl7.fhir.instance.model.api.IBaseBackboneElement;
import ca.uhn.fhir.model.api.annotation.Child;
import ca.uhn.fhir.model.api.annotation.ChildOrder;
import ca.uhn.fhir.model.api.annotation.Description;
import ca.uhn.fhir.model.api.annotation.Block;
/**
* This resource is primarily used for the identification and definition of a medication, including ingredients, for the purposes of prescribing, dispensing, and administering a medication as well as for making statements about medication use.
*/
@ResourceDef(name="Medication", profile="http://hl7.org/fhir/StructureDefinition/Medication")
public class Medication extends DomainResource {
public enum MedicationStatusCodes {
/**
* The medication is available for use.
*/
ACTIVE,
/**
* The medication is not available for use.
*/
INACTIVE,
/**
* The medication was entered in error.
*/
ENTEREDINERROR,
/**
* added to help the parsers with the generic types
*/
NULL;
public static MedicationStatusCodes fromCode(String codeString) throws FHIRException {
if (codeString == null || "".equals(codeString))
return null;
if ("active".equals(codeString))
return ACTIVE;
if ("inactive".equals(codeString))
return INACTIVE;
if ("entered-in-error".equals(codeString))
return ENTEREDINERROR;
if (Configuration.isAcceptInvalidEnums())
return null;
else
throw new FHIRException("Unknown MedicationStatusCodes code '"+codeString+"'");
}
public String toCode() {
switch (this) {
case ACTIVE: return "active";
case INACTIVE: return "inactive";
case ENTEREDINERROR: return "entered-in-error";
case NULL: return null;
default: return "?";
}
}
public String getSystem() {
switch (this) {
case ACTIVE: return "http://hl7.org/fhir/CodeSystem/medication-status";
case INACTIVE: return "http://hl7.org/fhir/CodeSystem/medication-status";
case ENTEREDINERROR: return "http://hl7.org/fhir/CodeSystem/medication-status";
case NULL: return null;
default: return "?";
}
}
public String getDefinition() {
switch (this) {
case ACTIVE: return "The medication is available for use.";
case INACTIVE: return "The medication is not available for use.";
case ENTEREDINERROR: return "The medication was entered in error.";
case NULL: return null;
default: return "?";
}
}
public String getDisplay() {
switch (this) {
case ACTIVE: return "Active";
case INACTIVE: return "Inactive";
case ENTEREDINERROR: return "Entered in Error";
case NULL: return null;
default: return "?";
}
}
}
public static class MedicationStatusCodesEnumFactory implements EnumFactory<MedicationStatusCodes> {
public MedicationStatusCodes fromCode(String codeString) throws IllegalArgumentException {
if (codeString == null || "".equals(codeString))
if (codeString == null || "".equals(codeString))
return null;
if ("active".equals(codeString))
return MedicationStatusCodes.ACTIVE;
if ("inactive".equals(codeString))
return MedicationStatusCodes.INACTIVE;
if ("entered-in-error".equals(codeString))
return MedicationStatusCodes.ENTEREDINERROR;
throw new IllegalArgumentException("Unknown MedicationStatusCodes code '"+codeString+"'");
}
public Enumeration<MedicationStatusCodes> fromType(Base code) throws FHIRException {
if (code == null)
return null;
if (code.isEmpty())
return new Enumeration<MedicationStatusCodes>(this);
String codeString = ((PrimitiveType) code).asStringValue();
if (codeString == null || "".equals(codeString))
return null;
if ("active".equals(codeString))
return new Enumeration<MedicationStatusCodes>(this, MedicationStatusCodes.ACTIVE);
if ("inactive".equals(codeString))
return new Enumeration<MedicationStatusCodes>(this, MedicationStatusCodes.INACTIVE);
if ("entered-in-error".equals(codeString))
return new Enumeration<MedicationStatusCodes>(this, MedicationStatusCodes.ENTEREDINERROR);
throw new FHIRException("Unknown MedicationStatusCodes code '"+codeString+"'");
}
public String toCode(MedicationStatusCodes code) {
if (code == MedicationStatusCodes.ACTIVE)
return "active";
if (code == MedicationStatusCodes.INACTIVE)
return "inactive";
if (code == MedicationStatusCodes.ENTEREDINERROR)
return "entered-in-error";
return "?";
}
public String toSystem(MedicationStatusCodes code) {
return code.getSystem();
}
}
@Block()
public static class MedicationIngredientComponent extends BackboneElement implements IBaseBackboneElement {
/**
* The ingredient (substance or medication) that the ingredient.strength relates to. This is represented as a concept from a code system or described in another resource (Substance or Medication).
*/
@Child(name = "item", type = {CodeableReference.class}, order=1, min=1, max=1, modifier=false, summary=false)
@Description(shortDefinition="The ingredient (substance or medication) that the ingredient.strength relates to", formalDefinition="The ingredient (substance or medication) that the ingredient.strength relates to. This is represented as a concept from a code system or described in another resource (Substance or Medication)." )
protected CodeableReference item;
/**
* Indication of whether this ingredient affects the therapeutic action of the drug.
*/
@Child(name = "isActive", type = {BooleanType.class}, order=2, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="Active ingredient indicator", formalDefinition="Indication of whether this ingredient affects the therapeutic action of the drug." )
protected BooleanType isActive;
/**
* Specifies how many (or how much) of the items there are in this Medication. For example, 250 mg per tablet. This is expressed as a ratio where the numerator is 250mg and the denominator is 1 tablet but can also be expressed a quantity when the denominator is assumed to be 1 tablet.
*/
@Child(name = "strength", type = {Ratio.class, CodeableConcept.class, Quantity.class}, order=3, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="Quantity of ingredient present", formalDefinition="Specifies how many (or how much) of the items there are in this Medication. For example, 250 mg per tablet. This is expressed as a ratio where the numerator is 250mg and the denominator is 1 tablet but can also be expressed a quantity when the denominator is assumed to be 1 tablet." )
@ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/medication-ingredientstrength")
protected DataType strength;
private static final long serialVersionUID = -979760018L;
/**
* Constructor
*/
public MedicationIngredientComponent() {
super();
}
/**
* Constructor
*/
public MedicationIngredientComponent(CodeableReference item) {
super();
this.setItem(item);
}
/**
* @return {@link #item} (The ingredient (substance or medication) that the ingredient.strength relates to. This is represented as a concept from a code system or described in another resource (Substance or Medication).)
*/
public CodeableReference getItem() {
if (this.item == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create MedicationIngredientComponent.item");
else if (Configuration.doAutoCreate())
this.item = new CodeableReference(); // cc
return this.item;
}
public boolean hasItem() {
return this.item != null && !this.item.isEmpty();
}
/**
* @param value {@link #item} (The ingredient (substance or medication) that the ingredient.strength relates to. This is represented as a concept from a code system or described in another resource (Substance or Medication).)
*/
public MedicationIngredientComponent setItem(CodeableReference value) {
this.item = value;
return this;
}
/**
* @return {@link #isActive} (Indication of whether this ingredient affects the therapeutic action of the drug.). This is the underlying object with id, value and extensions. The accessor "getIsActive" gives direct access to the value
*/
public BooleanType getIsActiveElement() {
if (this.isActive == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create MedicationIngredientComponent.isActive");
else if (Configuration.doAutoCreate())
this.isActive = new BooleanType(); // bb
return this.isActive;
}
public boolean hasIsActiveElement() {
return this.isActive != null && !this.isActive.isEmpty();
}
public boolean hasIsActive() {
return this.isActive != null && !this.isActive.isEmpty();
}
/**
* @param value {@link #isActive} (Indication of whether this ingredient affects the therapeutic action of the drug.). This is the underlying object with id, value and extensions. The accessor "getIsActive" gives direct access to the value
*/
public MedicationIngredientComponent setIsActiveElement(BooleanType value) {
this.isActive = value;
return this;
}
/**
* @return Indication of whether this ingredient affects the therapeutic action of the drug.
*/
public boolean getIsActive() {
return this.isActive == null || this.isActive.isEmpty() ? false : this.isActive.getValue();
}
/**
* @param value Indication of whether this ingredient affects the therapeutic action of the drug.
*/
public MedicationIngredientComponent setIsActive(boolean value) {
if (this.isActive == null)
this.isActive = new BooleanType();
this.isActive.setValue(value);
return this;
}
/**
* @return {@link #strength} (Specifies how many (or how much) of the items there are in this Medication. For example, 250 mg per tablet. This is expressed as a ratio where the numerator is 250mg and the denominator is 1 tablet but can also be expressed a quantity when the denominator is assumed to be 1 tablet.)
*/
public DataType getStrength() {
return this.strength;
}
/**
* @return {@link #strength} (Specifies how many (or how much) of the items there are in this Medication. For example, 250 mg per tablet. This is expressed as a ratio where the numerator is 250mg and the denominator is 1 tablet but can also be expressed a quantity when the denominator is assumed to be 1 tablet.)
*/
public Ratio getStrengthRatio() throws FHIRException {
if (this.strength == null)
this.strength = new Ratio();
if (!(this.strength instanceof Ratio))
throw new FHIRException("Type mismatch: the type Ratio was expected, but "+this.strength.getClass().getName()+" was encountered");
return (Ratio) this.strength;
}
public boolean hasStrengthRatio() {
return this != null && this.strength instanceof Ratio;
}
/**
* @return {@link #strength} (Specifies how many (or how much) of the items there are in this Medication. For example, 250 mg per tablet. This is expressed as a ratio where the numerator is 250mg and the denominator is 1 tablet but can also be expressed a quantity when the denominator is assumed to be 1 tablet.)
*/
public CodeableConcept getStrengthCodeableConcept() throws FHIRException {
if (this.strength == null)
this.strength = new CodeableConcept();
if (!(this.strength instanceof CodeableConcept))
throw new FHIRException("Type mismatch: the type CodeableConcept was expected, but "+this.strength.getClass().getName()+" was encountered");
return (CodeableConcept) this.strength;
}
public boolean hasStrengthCodeableConcept() {
return this != null && this.strength instanceof CodeableConcept;
}
/**
* @return {@link #strength} (Specifies how many (or how much) of the items there are in this Medication. For example, 250 mg per tablet. This is expressed as a ratio where the numerator is 250mg and the denominator is 1 tablet but can also be expressed a quantity when the denominator is assumed to be 1 tablet.)
*/
public Quantity getStrengthQuantity() throws FHIRException {
if (this.strength == null)
this.strength = new Quantity();
if (!(this.strength instanceof Quantity))
throw new FHIRException("Type mismatch: the type Quantity was expected, but "+this.strength.getClass().getName()+" was encountered");
return (Quantity) this.strength;
}
public boolean hasStrengthQuantity() {
return this != null && this.strength instanceof Quantity;
}
public boolean hasStrength() {
return this.strength != null && !this.strength.isEmpty();
}
/**
* @param value {@link #strength} (Specifies how many (or how much) of the items there are in this Medication. For example, 250 mg per tablet. This is expressed as a ratio where the numerator is 250mg and the denominator is 1 tablet but can also be expressed a quantity when the denominator is assumed to be 1 tablet.)
*/
public MedicationIngredientComponent setStrength(DataType value) {
if (value != null && !(value instanceof Ratio || value instanceof CodeableConcept || value instanceof Quantity))
throw new Error("Not the right type for Medication.ingredient.strength[x]: "+value.fhirType());
this.strength = value;
return this;
}
protected void listChildren(List<Property> children) {
super.listChildren(children);
children.add(new Property("item", "CodeableReference(Substance|Medication)", "The ingredient (substance or medication) that the ingredient.strength relates to. This is represented as a concept from a code system or described in another resource (Substance or Medication).", 0, 1, item));
children.add(new Property("isActive", "boolean", "Indication of whether this ingredient affects the therapeutic action of the drug.", 0, 1, isActive));
children.add(new Property("strength[x]", "Ratio|CodeableConcept|Quantity", "Specifies how many (or how much) of the items there are in this Medication. For example, 250 mg per tablet. This is expressed as a ratio where the numerator is 250mg and the denominator is 1 tablet but can also be expressed a quantity when the denominator is assumed to be 1 tablet.", 0, 1, strength));
}
@Override
public Property getNamedProperty(int _hash, String _name, boolean _checkValid) throws FHIRException {
switch (_hash) {
case 3242771: /*item*/ return new Property("item", "CodeableReference(Substance|Medication)", "The ingredient (substance or medication) that the ingredient.strength relates to. This is represented as a concept from a code system or described in another resource (Substance or Medication).", 0, 1, item);
case -748916528: /*isActive*/ return new Property("isActive", "boolean", "Indication of whether this ingredient affects the therapeutic action of the drug.", 0, 1, isActive);
case 127377567: /*strength[x]*/ return new Property("strength[x]", "Ratio|CodeableConcept|Quantity", "Specifies how many (or how much) of the items there are in this Medication. For example, 250 mg per tablet. This is expressed as a ratio where the numerator is 250mg and the denominator is 1 tablet but can also be expressed a quantity when the denominator is assumed to be 1 tablet.", 0, 1, strength);
case 1791316033: /*strength*/ return new Property("strength[x]", "Ratio|CodeableConcept|Quantity", "Specifies how many (or how much) of the items there are in this Medication. For example, 250 mg per tablet. This is expressed as a ratio where the numerator is 250mg and the denominator is 1 tablet but can also be expressed a quantity when the denominator is assumed to be 1 tablet.", 0, 1, strength);
case 2141786186: /*strengthRatio*/ return new Property("strength[x]", "Ratio", "Specifies how many (or how much) of the items there are in this Medication. For example, 250 mg per tablet. This is expressed as a ratio where the numerator is 250mg and the denominator is 1 tablet but can also be expressed a quantity when the denominator is assumed to be 1 tablet.", 0, 1, strength);
case -1455903456: /*strengthCodeableConcept*/ return new Property("strength[x]", "CodeableConcept", "Specifies how many (or how much) of the items there are in this Medication. For example, 250 mg per tablet. This is expressed as a ratio where the numerator is 250mg and the denominator is 1 tablet but can also be expressed a quantity when the denominator is assumed to be 1 tablet.", 0, 1, strength);
case -1793570836: /*strengthQuantity*/ return new Property("strength[x]", "Quantity", "Specifies how many (or how much) of the items there are in this Medication. For example, 250 mg per tablet. This is expressed as a ratio where the numerator is 250mg and the denominator is 1 tablet but can also be expressed a quantity when the denominator is assumed to be 1 tablet.", 0, 1, strength);
default: return super.getNamedProperty(_hash, _name, _checkValid);
}
}
@Override
public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException {
switch (hash) {
case 3242771: /*item*/ return this.item == null ? new Base[0] : new Base[] {this.item}; // CodeableReference
case -748916528: /*isActive*/ return this.isActive == null ? new Base[0] : new Base[] {this.isActive}; // BooleanType
case 1791316033: /*strength*/ return this.strength == null ? new Base[0] : new Base[] {this.strength}; // DataType
default: return super.getProperty(hash, name, checkValid);
}
}
@Override
public Base setProperty(int hash, String name, Base value) throws FHIRException {
switch (hash) {
case 3242771: // item
this.item = TypeConvertor.castToCodeableReference(value); // CodeableReference
return value;
case -748916528: // isActive
this.isActive = TypeConvertor.castToBoolean(value); // BooleanType
return value;
case 1791316033: // strength
this.strength = TypeConvertor.castToType(value); // DataType
return value;
default: return super.setProperty(hash, name, value);
}
}
@Override
public Base setProperty(String name, Base value) throws FHIRException {
if (name.equals("item")) {
this.item = TypeConvertor.castToCodeableReference(value); // CodeableReference
} else if (name.equals("isActive")) {
this.isActive = TypeConvertor.castToBoolean(value); // BooleanType
} else if (name.equals("strength[x]")) {
this.strength = TypeConvertor.castToType(value); // DataType
} else
return super.setProperty(name, value);
return value;
}
@Override
public Base makeProperty(int hash, String name) throws FHIRException {
switch (hash) {
case 3242771: return getItem();
case -748916528: return getIsActiveElement();
case 127377567: return getStrength();
case 1791316033: return getStrength();
default: return super.makeProperty(hash, name);
}
}
@Override
public String[] getTypesForProperty(int hash, String name) throws FHIRException {
switch (hash) {
case 3242771: /*item*/ return new String[] {"CodeableReference"};
case -748916528: /*isActive*/ return new String[] {"boolean"};
case 1791316033: /*strength*/ return new String[] {"Ratio", "CodeableConcept", "Quantity"};
default: return super.getTypesForProperty(hash, name);
}
}
@Override
public Base addChild(String name) throws FHIRException {
if (name.equals("item")) {
this.item = new CodeableReference();
return this.item;
}
else if (name.equals("isActive")) {
throw new FHIRException("Cannot call addChild on a primitive type Medication.ingredient.isActive");
}
else if (name.equals("strengthRatio")) {
this.strength = new Ratio();
return this.strength;
}
else if (name.equals("strengthCodeableConcept")) {
this.strength = new CodeableConcept();
return this.strength;
}
else if (name.equals("strengthQuantity")) {
this.strength = new Quantity();
return this.strength;
}
else
return super.addChild(name);
}
public MedicationIngredientComponent copy() {
MedicationIngredientComponent dst = new MedicationIngredientComponent();
copyValues(dst);
return dst;
}
public void copyValues(MedicationIngredientComponent dst) {
super.copyValues(dst);
dst.item = item == null ? null : item.copy();
dst.isActive = isActive == null ? null : isActive.copy();
dst.strength = strength == null ? null : strength.copy();
}
@Override
public boolean equalsDeep(Base other_) {
if (!super.equalsDeep(other_))
return false;
if (!(other_ instanceof MedicationIngredientComponent))
return false;
MedicationIngredientComponent o = (MedicationIngredientComponent) other_;
return compareDeep(item, o.item, true) && compareDeep(isActive, o.isActive, true) && compareDeep(strength, o.strength, true)
;
}
@Override
public boolean equalsShallow(Base other_) {
if (!super.equalsShallow(other_))
return false;
if (!(other_ instanceof MedicationIngredientComponent))
return false;
MedicationIngredientComponent o = (MedicationIngredientComponent) other_;
return compareValues(isActive, o.isActive, true);
}
public boolean isEmpty() {
return super.isEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty(item, isActive, strength
);
}
public String fhirType() {
return "Medication.ingredient";
}
}
@Block()
public static class MedicationBatchComponent extends BackboneElement implements IBaseBackboneElement {
/**
* The assigned lot number of a batch of the specified product.
*/
@Child(name = "lotNumber", type = {StringType.class}, order=1, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="Identifier assigned to batch", formalDefinition="The assigned lot number of a batch of the specified product." )
protected StringType lotNumber;
/**
* When this specific batch of product will expire.
*/
@Child(name = "expirationDate", type = {DateTimeType.class}, order=2, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="When batch will expire", formalDefinition="When this specific batch of product will expire." )
protected DateTimeType expirationDate;
private static final long serialVersionUID = 1982738755L;
/**
* Constructor
*/
public MedicationBatchComponent() {
super();
}
/**
* @return {@link #lotNumber} (The assigned lot number of a batch of the specified product.). This is the underlying object with id, value and extensions. The accessor "getLotNumber" gives direct access to the value
*/
public StringType getLotNumberElement() {
if (this.lotNumber == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create MedicationBatchComponent.lotNumber");
else if (Configuration.doAutoCreate())
this.lotNumber = new StringType(); // bb
return this.lotNumber;
}
public boolean hasLotNumberElement() {
return this.lotNumber != null && !this.lotNumber.isEmpty();
}
public boolean hasLotNumber() {
return this.lotNumber != null && !this.lotNumber.isEmpty();
}
/**
* @param value {@link #lotNumber} (The assigned lot number of a batch of the specified product.). This is the underlying object with id, value and extensions. The accessor "getLotNumber" gives direct access to the value
*/
public MedicationBatchComponent setLotNumberElement(StringType value) {
this.lotNumber = value;
return this;
}
/**
* @return The assigned lot number of a batch of the specified product.
*/
public String getLotNumber() {
return this.lotNumber == null ? null : this.lotNumber.getValue();
}
/**
* @param value The assigned lot number of a batch of the specified product.
*/
public MedicationBatchComponent setLotNumber(String value) {
if (Utilities.noString(value))
this.lotNumber = null;
else {
if (this.lotNumber == null)
this.lotNumber = new StringType();
this.lotNumber.setValue(value);
}
return this;
}
/**
* @return {@link #expirationDate} (When this specific batch of product will expire.). This is the underlying object with id, value and extensions. The accessor "getExpirationDate" gives direct access to the value
*/
public DateTimeType getExpirationDateElement() {
if (this.expirationDate == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create MedicationBatchComponent.expirationDate");
else if (Configuration.doAutoCreate())
this.expirationDate = new DateTimeType(); // bb
return this.expirationDate;
}
public boolean hasExpirationDateElement() {
return this.expirationDate != null && !this.expirationDate.isEmpty();
}
public boolean hasExpirationDate() {
return this.expirationDate != null && !this.expirationDate.isEmpty();
}
/**
* @param value {@link #expirationDate} (When this specific batch of product will expire.). This is the underlying object with id, value and extensions. The accessor "getExpirationDate" gives direct access to the value
*/
public MedicationBatchComponent setExpirationDateElement(DateTimeType value) {
this.expirationDate = value;
return this;
}
/**
* @return When this specific batch of product will expire.
*/
public Date getExpirationDate() {
return this.expirationDate == null ? null : this.expirationDate.getValue();
}
/**
* @param value When this specific batch of product will expire.
*/
public MedicationBatchComponent setExpirationDate(Date value) {
if (value == null)
this.expirationDate = null;
else {
if (this.expirationDate == null)
this.expirationDate = new DateTimeType();
this.expirationDate.setValue(value);
}
return this;
}
protected void listChildren(List<Property> children) {
super.listChildren(children);
children.add(new Property("lotNumber", "string", "The assigned lot number of a batch of the specified product.", 0, 1, lotNumber));
children.add(new Property("expirationDate", "dateTime", "When this specific batch of product will expire.", 0, 1, expirationDate));
}
@Override
public Property getNamedProperty(int _hash, String _name, boolean _checkValid) throws FHIRException {
switch (_hash) {
case 462547450: /*lotNumber*/ return new Property("lotNumber", "string", "The assigned lot number of a batch of the specified product.", 0, 1, lotNumber);
case -668811523: /*expirationDate*/ return new Property("expirationDate", "dateTime", "When this specific batch of product will expire.", 0, 1, expirationDate);
default: return super.getNamedProperty(_hash, _name, _checkValid);
}
}
@Override
public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException {
switch (hash) {
case 462547450: /*lotNumber*/ return this.lotNumber == null ? new Base[0] : new Base[] {this.lotNumber}; // StringType
case -668811523: /*expirationDate*/ return this.expirationDate == null ? new Base[0] : new Base[] {this.expirationDate}; // DateTimeType
default: return super.getProperty(hash, name, checkValid);
}
}
@Override
public Base setProperty(int hash, String name, Base value) throws FHIRException {
switch (hash) {
case 462547450: // lotNumber
this.lotNumber = TypeConvertor.castToString(value); // StringType
return value;
case -668811523: // expirationDate
this.expirationDate = TypeConvertor.castToDateTime(value); // DateTimeType
return value;
default: return super.setProperty(hash, name, value);
}
}
@Override
public Base setProperty(String name, Base value) throws FHIRException {
if (name.equals("lotNumber")) {
this.lotNumber = TypeConvertor.castToString(value); // StringType
} else if (name.equals("expirationDate")) {
this.expirationDate = TypeConvertor.castToDateTime(value); // DateTimeType
} else
return super.setProperty(name, value);
return value;
}
@Override
public Base makeProperty(int hash, String name) throws FHIRException {
switch (hash) {
case 462547450: return getLotNumberElement();
case -668811523: return getExpirationDateElement();
default: return super.makeProperty(hash, name);
}
}
@Override
public String[] getTypesForProperty(int hash, String name) throws FHIRException {
switch (hash) {
case 462547450: /*lotNumber*/ return new String[] {"string"};
case -668811523: /*expirationDate*/ return new String[] {"dateTime"};
default: return super.getTypesForProperty(hash, name);
}
}
@Override
public Base addChild(String name) throws FHIRException {
if (name.equals("lotNumber")) {
throw new FHIRException("Cannot call addChild on a primitive type Medication.batch.lotNumber");
}
else if (name.equals("expirationDate")) {
throw new FHIRException("Cannot call addChild on a primitive type Medication.batch.expirationDate");
}
else
return super.addChild(name);
}
public MedicationBatchComponent copy() {
MedicationBatchComponent dst = new MedicationBatchComponent();
copyValues(dst);
return dst;
}
public void copyValues(MedicationBatchComponent dst) {
super.copyValues(dst);
dst.lotNumber = lotNumber == null ? null : lotNumber.copy();
dst.expirationDate = expirationDate == null ? null : expirationDate.copy();
}
@Override
public boolean equalsDeep(Base other_) {
if (!super.equalsDeep(other_))
return false;
if (!(other_ instanceof MedicationBatchComponent))
return false;
MedicationBatchComponent o = (MedicationBatchComponent) other_;
return compareDeep(lotNumber, o.lotNumber, true) && compareDeep(expirationDate, o.expirationDate, true)
;
}
@Override
public boolean equalsShallow(Base other_) {
if (!super.equalsShallow(other_))
return false;
if (!(other_ instanceof MedicationBatchComponent))
return false;
MedicationBatchComponent o = (MedicationBatchComponent) other_;
return compareValues(lotNumber, o.lotNumber, true) && compareValues(expirationDate, o.expirationDate, true)
;
}
public boolean isEmpty() {
return super.isEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty(lotNumber, expirationDate
);
}
public String fhirType() {
return "Medication.batch";
}
}
/**
* Business identifier for this medication.
*/
@Child(name = "identifier", type = {Identifier.class}, order=0, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true)
@Description(shortDefinition="Business identifier for this medication", formalDefinition="Business identifier for this medication." )
protected List<Identifier> identifier;
/**
* A code (or set of codes) that specify this medication, or a textual description if no code is available. Usage note: This could be a standard medication code such as a code from RxNorm, SNOMED CT, IDMP etc. It could also be a national or local formulary code, optionally with translations to other code systems.
*/
@Child(name = "code", type = {CodeableConcept.class}, order=1, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Codes that identify this medication", formalDefinition="A code (or set of codes) that specify this medication, or a textual description if no code is available. Usage note: This could be a standard medication code such as a code from RxNorm, SNOMED CT, IDMP etc. It could also be a national or local formulary code, optionally with translations to other code systems." )
@ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/medication-codes")
protected CodeableConcept code;
/**
* A code to indicate if the medication is in active use.
*/
@Child(name = "status", type = {CodeType.class}, order=2, min=0, max=1, modifier=true, summary=true)
@Description(shortDefinition="active | inactive | entered-in-error", formalDefinition="A code to indicate if the medication is in active use." )
@ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/medication-status")
protected Enumeration<MedicationStatusCodes> status;
/**
* Describes the details of the manufacturer of the medication product. This is not intended to represent the distributor of a medication product.
*/
@Child(name = "manufacturer", type = {Organization.class}, order=3, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Manufacturer of the item", formalDefinition="Describes the details of the manufacturer of the medication product. This is not intended to represent the distributor of a medication product." )
protected Reference manufacturer;
/**
* Describes the form of the item. Powder; tablets; capsule.
*/
@Child(name = "doseForm", type = {CodeableConcept.class}, order=4, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="powder | tablets | capsule +", formalDefinition="Describes the form of the item. Powder; tablets; capsule." )
@ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/medication-form-codes")
protected CodeableConcept doseForm;
/**
* Specific amount of the drug in the packaged product. For example, when specifying a product that has the same strength (For example, Insulin glargine 100 unit per mL solution for injection), this attribute provides additional clarification of the package amount (For example, 3 mL, 10mL, etc.).
*/
@Child(name = "amount", type = {Ratio.class}, order=5, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Amount of drug in package", formalDefinition="Specific amount of the drug in the packaged product. For example, when specifying a product that has the same strength (For example, Insulin glargine 100 unit per mL solution for injection), this attribute provides additional clarification of the package amount (For example, 3 mL, 10mL, etc.)." )
protected Ratio amount;
/**
* Identifies a particular constituent of interest in the product.
*/
@Child(name = "ingredient", type = {}, order=6, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false)
@Description(shortDefinition="Active or inactive ingredient", formalDefinition="Identifies a particular constituent of interest in the product." )
protected List<MedicationIngredientComponent> ingredient;
/**
* Information that only applies to packages (not products).
*/
@Child(name = "batch", type = {}, order=7, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="Details about packaged medications", formalDefinition="Information that only applies to packages (not products)." )
protected MedicationBatchComponent batch;
private static final long serialVersionUID = 1712967281L;
/**
* Constructor
*/
public Medication() {
super();
}
/**
* @return {@link #identifier} (Business identifier for this medication.)
*/
public List<Identifier> getIdentifier() {
if (this.identifier == null)
this.identifier = new ArrayList<Identifier>();
return this.identifier;
}
/**
* @return Returns a reference to <code>this</code> for easy method chaining
*/
public Medication setIdentifier(List<Identifier> theIdentifier) {
this.identifier = theIdentifier;
return this;
}
public boolean hasIdentifier() {
if (this.identifier == null)
return false;
for (Identifier item : this.identifier)
if (!item.isEmpty())
return true;
return false;
}
public Identifier addIdentifier() { //3
Identifier t = new Identifier();
if (this.identifier == null)
this.identifier = new ArrayList<Identifier>();
this.identifier.add(t);
return t;
}
public Medication addIdentifier(Identifier t) { //3
if (t == null)
return this;
if (this.identifier == null)
this.identifier = new ArrayList<Identifier>();
this.identifier.add(t);
return this;
}
/**
* @return The first repetition of repeating field {@link #identifier}, creating it if it does not already exist {3}
*/
public Identifier getIdentifierFirstRep() {
if (getIdentifier().isEmpty()) {
addIdentifier();
}
return getIdentifier().get(0);
}
/**
* @return {@link #code} (A code (or set of codes) that specify this medication, or a textual description if no code is available. Usage note: This could be a standard medication code such as a code from RxNorm, SNOMED CT, IDMP etc. It could also be a national or local formulary code, optionally with translations to other code systems.)
*/
public CodeableConcept getCode() {
if (this.code == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Medication.code");
else if (Configuration.doAutoCreate())
this.code = new CodeableConcept(); // cc
return this.code;
}
public boolean hasCode() {
return this.code != null && !this.code.isEmpty();
}
/**
* @param value {@link #code} (A code (or set of codes) that specify this medication, or a textual description if no code is available. Usage note: This could be a standard medication code such as a code from RxNorm, SNOMED CT, IDMP etc. It could also be a national or local formulary code, optionally with translations to other code systems.)
*/
public Medication setCode(CodeableConcept value) {
this.code = value;
return this;
}
/**
* @return {@link #status} (A code to indicate if the medication is in active use.). This is the underlying object with id, value and extensions. The accessor "getStatus" gives direct access to the value
*/
public Enumeration<MedicationStatusCodes> getStatusElement() {
if (this.status == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Medication.status");
else if (Configuration.doAutoCreate())
this.status = new Enumeration<MedicationStatusCodes>(new MedicationStatusCodesEnumFactory()); // bb
return this.status;
}
public boolean hasStatusElement() {
return this.status != null && !this.status.isEmpty();
}
public boolean hasStatus() {
return this.status != null && !this.status.isEmpty();
}
/**
* @param value {@link #status} (A code to indicate if the medication is in active use.). This is the underlying object with id, value and extensions. The accessor "getStatus" gives direct access to the value
*/
public Medication setStatusElement(Enumeration<MedicationStatusCodes> value) {
this.status = value;
return this;
}
/**
* @return A code to indicate if the medication is in active use.
*/
public MedicationStatusCodes getStatus() {
return this.status == null ? null : this.status.getValue();
}
/**
* @param value A code to indicate if the medication is in active use.
*/
public Medication setStatus(MedicationStatusCodes value) {
if (value == null)
this.status = null;
else {
if (this.status == null)
this.status = new Enumeration<MedicationStatusCodes>(new MedicationStatusCodesEnumFactory());
this.status.setValue(value);
}
return this;
}
/**
* @return {@link #manufacturer} (Describes the details of the manufacturer of the medication product. This is not intended to represent the distributor of a medication product.)
*/
public Reference getManufacturer() {
if (this.manufacturer == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Medication.manufacturer");
else if (Configuration.doAutoCreate())
this.manufacturer = new Reference(); // cc
return this.manufacturer;
}
public boolean hasManufacturer() {
return this.manufacturer != null && !this.manufacturer.isEmpty();
}
/**
* @param value {@link #manufacturer} (Describes the details of the manufacturer of the medication product. This is not intended to represent the distributor of a medication product.)
*/
public Medication setManufacturer(Reference value) {
this.manufacturer = value;
return this;
}
/**
* @return {@link #doseForm} (Describes the form of the item. Powder; tablets; capsule.)
*/
public CodeableConcept getDoseForm() {
if (this.doseForm == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Medication.doseForm");
else if (Configuration.doAutoCreate())
this.doseForm = new CodeableConcept(); // cc
return this.doseForm;
}
public boolean hasDoseForm() {
return this.doseForm != null && !this.doseForm.isEmpty();
}
/**
* @param value {@link #doseForm} (Describes the form of the item. Powder; tablets; capsule.)
*/
public Medication setDoseForm(CodeableConcept value) {
this.doseForm = value;
return this;
}
/**
* @return {@link #amount} (Specific amount of the drug in the packaged product. For example, when specifying a product that has the same strength (For example, Insulin glargine 100 unit per mL solution for injection), this attribute provides additional clarification of the package amount (For example, 3 mL, 10mL, etc.).)
*/
public Ratio getAmount() {
if (this.amount == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Medication.amount");
else if (Configuration.doAutoCreate())
this.amount = new Ratio(); // cc
return this.amount;
}
public boolean hasAmount() {
return this.amount != null && !this.amount.isEmpty();
}
/**
* @param value {@link #amount} (Specific amount of the drug in the packaged product. For example, when specifying a product that has the same strength (For example, Insulin glargine 100 unit per mL solution for injection), this attribute provides additional clarification of the package amount (For example, 3 mL, 10mL, etc.).)
*/
public Medication setAmount(Ratio value) {
this.amount = value;
return this;
}
/**
* @return {@link #ingredient} (Identifies a particular constituent of interest in the product.)
*/
public List<MedicationIngredientComponent> getIngredient() {
if (this.ingredient == null)
this.ingredient = new ArrayList<MedicationIngredientComponent>();
return this.ingredient;
}
/**
* @return Returns a reference to <code>this</code> for easy method chaining
*/
public Medication setIngredient(List<MedicationIngredientComponent> theIngredient) {
this.ingredient = theIngredient;
return this;
}
public boolean hasIngredient() {
if (this.ingredient == null)
return false;
for (MedicationIngredientComponent item : this.ingredient)
if (!item.isEmpty())
return true;
return false;
}
public MedicationIngredientComponent addIngredient() { //3
MedicationIngredientComponent t = new MedicationIngredientComponent();
if (this.ingredient == null)
this.ingredient = new ArrayList<MedicationIngredientComponent>();
this.ingredient.add(t);
return t;
}
public Medication addIngredient(MedicationIngredientComponent t) { //3
if (t == null)
return this;
if (this.ingredient == null)
this.ingredient = new ArrayList<MedicationIngredientComponent>();
this.ingredient.add(t);
return this;
}
/**
* @return The first repetition of repeating field {@link #ingredient}, creating it if it does not already exist {3}
*/
public MedicationIngredientComponent getIngredientFirstRep() {
if (getIngredient().isEmpty()) {
addIngredient();
}
return getIngredient().get(0);
}
/**
* @return {@link #batch} (Information that only applies to packages (not products).)
*/
public MedicationBatchComponent getBatch() {
if (this.batch == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Medication.batch");
else if (Configuration.doAutoCreate())
this.batch = new MedicationBatchComponent(); // cc
return this.batch;
}
public boolean hasBatch() {
return this.batch != null && !this.batch.isEmpty();
}
/**
* @param value {@link #batch} (Information that only applies to packages (not products).)
*/
public Medication setBatch(MedicationBatchComponent value) {
this.batch = value;
return this;
}
protected void listChildren(List<Property> children) {
super.listChildren(children);
children.add(new Property("identifier", "Identifier", "Business identifier for this medication.", 0, java.lang.Integer.MAX_VALUE, identifier));
children.add(new Property("code", "CodeableConcept", "A code (or set of codes) that specify this medication, or a textual description if no code is available. Usage note: This could be a standard medication code such as a code from RxNorm, SNOMED CT, IDMP etc. It could also be a national or local formulary code, optionally with translations to other code systems.", 0, 1, code));
children.add(new Property("status", "code", "A code to indicate if the medication is in active use.", 0, 1, status));
children.add(new Property("manufacturer", "Reference(Organization)", "Describes the details of the manufacturer of the medication product. This is not intended to represent the distributor of a medication product.", 0, 1, manufacturer));
children.add(new Property("doseForm", "CodeableConcept", "Describes the form of the item. Powder; tablets; capsule.", 0, 1, doseForm));
children.add(new Property("amount", "Ratio", "Specific amount of the drug in the packaged product. For example, when specifying a product that has the same strength (For example, Insulin glargine 100 unit per mL solution for injection), this attribute provides additional clarification of the package amount (For example, 3 mL, 10mL, etc.).", 0, 1, amount));
children.add(new Property("ingredient", "", "Identifies a particular constituent of interest in the product.", 0, java.lang.Integer.MAX_VALUE, ingredient));
children.add(new Property("batch", "", "Information that only applies to packages (not products).", 0, 1, batch));
}
@Override
public Property getNamedProperty(int _hash, String _name, boolean _checkValid) throws FHIRException {
switch (_hash) {
case -1618432855: /*identifier*/ return new Property("identifier", "Identifier", "Business identifier for this medication.", 0, java.lang.Integer.MAX_VALUE, identifier);
case 3059181: /*code*/ return new Property("code", "CodeableConcept", "A code (or set of codes) that specify this medication, or a textual description if no code is available. Usage note: This could be a standard medication code such as a code from RxNorm, SNOMED CT, IDMP etc. It could also be a national or local formulary code, optionally with translations to other code systems.", 0, 1, code);
case -892481550: /*status*/ return new Property("status", "code", "A code to indicate if the medication is in active use.", 0, 1, status);
case -1969347631: /*manufacturer*/ return new Property("manufacturer", "Reference(Organization)", "Describes the details of the manufacturer of the medication product. This is not intended to represent the distributor of a medication product.", 0, 1, manufacturer);
case 1303858817: /*doseForm*/ return new Property("doseForm", "CodeableConcept", "Describes the form of the item. Powder; tablets; capsule.", 0, 1, doseForm);
case -1413853096: /*amount*/ return new Property("amount", "Ratio", "Specific amount of the drug in the packaged product. For example, when specifying a product that has the same strength (For example, Insulin glargine 100 unit per mL solution for injection), this attribute provides additional clarification of the package amount (For example, 3 mL, 10mL, etc.).", 0, 1, amount);
case -206409263: /*ingredient*/ return new Property("ingredient", "", "Identifies a particular constituent of interest in the product.", 0, java.lang.Integer.MAX_VALUE, ingredient);
case 93509434: /*batch*/ return new Property("batch", "", "Information that only applies to packages (not products).", 0, 1, batch);
default: return super.getNamedProperty(_hash, _name, _checkValid);
}
}
@Override
public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException {
switch (hash) {
case -1618432855: /*identifier*/ return this.identifier == null ? new Base[0] : this.identifier.toArray(new Base[this.identifier.size()]); // Identifier
case 3059181: /*code*/ return this.code == null ? new Base[0] : new Base[] {this.code}; // CodeableConcept
case -892481550: /*status*/ return this.status == null ? new Base[0] : new Base[] {this.status}; // Enumeration<MedicationStatusCodes>
case -1969347631: /*manufacturer*/ return this.manufacturer == null ? new Base[0] : new Base[] {this.manufacturer}; // Reference
case 1303858817: /*doseForm*/ return this.doseForm == null ? new Base[0] : new Base[] {this.doseForm}; // CodeableConcept
case -1413853096: /*amount*/ return this.amount == null ? new Base[0] : new Base[] {this.amount}; // Ratio
case -206409263: /*ingredient*/ return this.ingredient == null ? new Base[0] : this.ingredient.toArray(new Base[this.ingredient.size()]); // MedicationIngredientComponent
case 93509434: /*batch*/ return this.batch == null ? new Base[0] : new Base[] {this.batch}; // MedicationBatchComponent
default: return super.getProperty(hash, name, checkValid);
}
}
@Override
public Base setProperty(int hash, String name, Base value) throws FHIRException {
switch (hash) {
case -1618432855: // identifier
this.getIdentifier().add(TypeConvertor.castToIdentifier(value)); // Identifier
return value;
case 3059181: // code
this.code = TypeConvertor.castToCodeableConcept(value); // CodeableConcept
return value;
case -892481550: // status
value = new MedicationStatusCodesEnumFactory().fromType(TypeConvertor.castToCode(value));
this.status = (Enumeration) value; // Enumeration<MedicationStatusCodes>
return value;
case -1969347631: // manufacturer
this.manufacturer = TypeConvertor.castToReference(value); // Reference
return value;
case 1303858817: // doseForm
this.doseForm = TypeConvertor.castToCodeableConcept(value); // CodeableConcept
return value;
case -1413853096: // amount
this.amount = TypeConvertor.castToRatio(value); // Ratio
return value;
case -206409263: // ingredient
this.getIngredient().add((MedicationIngredientComponent) value); // MedicationIngredientComponent
return value;
case 93509434: // batch
this.batch = (MedicationBatchComponent) value; // MedicationBatchComponent
return value;
default: return super.setProperty(hash, name, value);
}
}
@Override
public Base setProperty(String name, Base value) throws FHIRException {
if (name.equals("identifier")) {
this.getIdentifier().add(TypeConvertor.castToIdentifier(value));
} else if (name.equals("code")) {
this.code = TypeConvertor.castToCodeableConcept(value); // CodeableConcept
} else if (name.equals("status")) {
value = new MedicationStatusCodesEnumFactory().fromType(TypeConvertor.castToCode(value));
this.status = (Enumeration) value; // Enumeration<MedicationStatusCodes>
} else if (name.equals("manufacturer")) {
this.manufacturer = TypeConvertor.castToReference(value); // Reference
} else if (name.equals("doseForm")) {
this.doseForm = TypeConvertor.castToCodeableConcept(value); // CodeableConcept
} else if (name.equals("amount")) {
this.amount = TypeConvertor.castToRatio(value); // Ratio
} else if (name.equals("ingredient")) {
this.getIngredient().add((MedicationIngredientComponent) value);
} else if (name.equals("batch")) {
this.batch = (MedicationBatchComponent) value; // MedicationBatchComponent
} else
return super.setProperty(name, value);
return value;
}
@Override
public Base makeProperty(int hash, String name) throws FHIRException {
switch (hash) {
case -1618432855: return addIdentifier();
case 3059181: return getCode();
case -892481550: return getStatusElement();
case -1969347631: return getManufacturer();
case 1303858817: return getDoseForm();
case -1413853096: return getAmount();
case -206409263: return addIngredient();
case 93509434: return getBatch();
default: return super.makeProperty(hash, name);
}
}
@Override
public String[] getTypesForProperty(int hash, String name) throws FHIRException {
switch (hash) {
case -1618432855: /*identifier*/ return new String[] {"Identifier"};
case 3059181: /*code*/ return new String[] {"CodeableConcept"};
case -892481550: /*status*/ return new String[] {"code"};
case -1969347631: /*manufacturer*/ return new String[] {"Reference"};
case 1303858817: /*doseForm*/ return new String[] {"CodeableConcept"};
case -1413853096: /*amount*/ return new String[] {"Ratio"};
case -206409263: /*ingredient*/ return new String[] {};
case 93509434: /*batch*/ return new String[] {};
default: return super.getTypesForProperty(hash, name);
}
}
@Override
public Base addChild(String name) throws FHIRException {
if (name.equals("identifier")) {
return addIdentifier();
}
else if (name.equals("code")) {
this.code = new CodeableConcept();
return this.code;
}
else if (name.equals("status")) {
throw new FHIRException("Cannot call addChild on a primitive type Medication.status");
}
else if (name.equals("manufacturer")) {
this.manufacturer = new Reference();
return this.manufacturer;
}
else if (name.equals("doseForm")) {
this.doseForm = new CodeableConcept();
return this.doseForm;
}
else if (name.equals("amount")) {
this.amount = new Ratio();
return this.amount;
}
else if (name.equals("ingredient")) {
return addIngredient();
}
else if (name.equals("batch")) {
this.batch = new MedicationBatchComponent();
return this.batch;
}
else
return super.addChild(name);
}
public String fhirType() {
return "Medication";
}
public Medication copy() {
Medication dst = new Medication();
copyValues(dst);
return dst;
}
public void copyValues(Medication dst) {
super.copyValues(dst);
if (identifier != null) {
dst.identifier = new ArrayList<Identifier>();
for (Identifier i : identifier)
dst.identifier.add(i.copy());
};
dst.code = code == null ? null : code.copy();
dst.status = status == null ? null : status.copy();
dst.manufacturer = manufacturer == null ? null : manufacturer.copy();
dst.doseForm = doseForm == null ? null : doseForm.copy();
dst.amount = amount == null ? null : amount.copy();
if (ingredient != null) {
dst.ingredient = new ArrayList<MedicationIngredientComponent>();
for (MedicationIngredientComponent i : ingredient)
dst.ingredient.add(i.copy());
};
dst.batch = batch == null ? null : batch.copy();
}
protected Medication typedCopy() {
return copy();
}
@Override
public boolean equalsDeep(Base other_) {
if (!super.equalsDeep(other_))
return false;
if (!(other_ instanceof Medication))
return false;
Medication o = (Medication) other_;
return compareDeep(identifier, o.identifier, true) && compareDeep(code, o.code, true) && compareDeep(status, o.status, true)
&& compareDeep(manufacturer, o.manufacturer, true) && compareDeep(doseForm, o.doseForm, true) && compareDeep(amount, o.amount, true)
&& compareDeep(ingredient, o.ingredient, true) && compareDeep(batch, o.batch, true);
}
@Override
public boolean equalsShallow(Base other_) {
if (!super.equalsShallow(other_))
return false;
if (!(other_ instanceof Medication))
return false;
Medication o = (Medication) other_;
return compareValues(status, o.status, true);
}
public boolean isEmpty() {
return super.isEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty(identifier, code, status
, manufacturer, doseForm, amount, ingredient, batch);
}
@Override
public ResourceType getResourceType() {
return ResourceType.Medication;
}
/**
* Search parameter: <b>expiration-date</b>
* <p>
* Description: <b>Returns medications in a batch with this expiration date</b><br>
* Type: <b>date</b><br>
* Path: <b>Medication.batch.expirationDate</b><br>
* </p>
*/
@SearchParamDefinition(name="expiration-date", path="Medication.batch.expirationDate", description="Returns medications in a batch with this expiration date", type="date" )
public static final String SP_EXPIRATION_DATE = "expiration-date";
/**
* <b>Fluent Client</b> search parameter constant for <b>expiration-date</b>
* <p>
* Description: <b>Returns medications in a batch with this expiration date</b><br>
* Type: <b>date</b><br>
* Path: <b>Medication.batch.expirationDate</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.DateClientParam EXPIRATION_DATE = new ca.uhn.fhir.rest.gclient.DateClientParam(SP_EXPIRATION_DATE);
/**
* Search parameter: <b>form</b>
* <p>
* Description: <b>Returns medications for a specific dose form</b><br>
* Type: <b>token</b><br>
* Path: <b>null</b><br>
* </p>
*/
@SearchParamDefinition(name="form", path="", description="Returns medications for a specific dose form", type="token" )
public static final String SP_FORM = "form";
/**
* <b>Fluent Client</b> search parameter constant for <b>form</b>
* <p>
* Description: <b>Returns medications for a specific dose form</b><br>
* Type: <b>token</b><br>
* Path: <b>null</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.TokenClientParam FORM = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_FORM);
/**
* Search parameter: <b>identifier</b>
* <p>
* Description: <b>Returns medications with this external identifier</b><br>
* Type: <b>token</b><br>
* Path: <b>Medication.identifier</b><br>
* </p>
*/
@SearchParamDefinition(name="identifier", path="Medication.identifier", description="Returns medications with this external identifier", type="token" )
public static final String SP_IDENTIFIER = "identifier";
/**
* <b>Fluent Client</b> search parameter constant for <b>identifier</b>
* <p>
* Description: <b>Returns medications with this external identifier</b><br>
* Type: <b>token</b><br>
* Path: <b>Medication.identifier</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.TokenClientParam IDENTIFIER = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_IDENTIFIER);
/**
* Search parameter: <b>ingredient-code</b>
* <p>
* Description: <b>Returns medications for this ingredient code</b><br>
* Type: <b>token</b><br>
* Path: <b>Medication.ingredient.item.concept</b><br>
* </p>
*/
@SearchParamDefinition(name="ingredient-code", path="Medication.ingredient.item.concept", description="Returns medications for this ingredient code", type="token" )
public static final String SP_INGREDIENT_CODE = "ingredient-code";
/**
* <b>Fluent Client</b> search parameter constant for <b>ingredient-code</b>
* <p>
* Description: <b>Returns medications for this ingredient code</b><br>
* Type: <b>token</b><br>
* Path: <b>Medication.ingredient.item.concept</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.TokenClientParam INGREDIENT_CODE = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_INGREDIENT_CODE);
/**
* Search parameter: <b>ingredient</b>
* <p>
* Description: <b>Returns medications for this ingredient reference</b><br>
* Type: <b>reference</b><br>
* Path: <b>Medication.ingredient.item.reference</b><br>
* </p>
*/
@SearchParamDefinition(name="ingredient", path="Medication.ingredient.item.reference", description="Returns medications for this ingredient reference", type="reference" )
public static final String SP_INGREDIENT = "ingredient";
/**
* <b>Fluent Client</b> search parameter constant for <b>ingredient</b>
* <p>
* Description: <b>Returns medications for this ingredient reference</b><br>
* Type: <b>reference</b><br>
* Path: <b>Medication.ingredient.item.reference</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.ReferenceClientParam INGREDIENT = new ca.uhn.fhir.rest.gclient.ReferenceClientParam(SP_INGREDIENT);
/**
* Constant for fluent queries to be used to add include statements. Specifies
* the path value of "<b>Medication:ingredient</b>".
*/
public static final ca.uhn.fhir.model.api.Include INCLUDE_INGREDIENT = new ca.uhn.fhir.model.api.Include("Medication:ingredient").toLocked();
/**
* Search parameter: <b>lot-number</b>
* <p>
* Description: <b>Returns medications in a batch with this lot number</b><br>
* Type: <b>token</b><br>
* Path: <b>Medication.batch.lotNumber</b><br>
* </p>
*/
@SearchParamDefinition(name="lot-number", path="Medication.batch.lotNumber", description="Returns medications in a batch with this lot number", type="token" )
public static final String SP_LOT_NUMBER = "lot-number";
/**
* <b>Fluent Client</b> search parameter constant for <b>lot-number</b>
* <p>
* Description: <b>Returns medications in a batch with this lot number</b><br>
* Type: <b>token</b><br>
* Path: <b>Medication.batch.lotNumber</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.TokenClientParam LOT_NUMBER = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_LOT_NUMBER);
/**
* Search parameter: <b>manufacturer</b>
* <p>
* Description: <b>Returns medications made or sold for this manufacturer</b><br>
* Type: <b>reference</b><br>
* Path: <b>Medication.manufacturer</b><br>
* </p>
*/
@SearchParamDefinition(name="manufacturer", path="Medication.manufacturer", description="Returns medications made or sold for this manufacturer", type="reference", target={Organization.class } )
public static final String SP_MANUFACTURER = "manufacturer";
/**
* <b>Fluent Client</b> search parameter constant for <b>manufacturer</b>
* <p>
* Description: <b>Returns medications made or sold for this manufacturer</b><br>
* Type: <b>reference</b><br>
* Path: <b>Medication.manufacturer</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.ReferenceClientParam MANUFACTURER = new ca.uhn.fhir.rest.gclient.ReferenceClientParam(SP_MANUFACTURER);
/**
* Constant for fluent queries to be used to add include statements. Specifies
* the path value of "<b>Medication:manufacturer</b>".
*/
public static final ca.uhn.fhir.model.api.Include INCLUDE_MANUFACTURER = new ca.uhn.fhir.model.api.Include("Medication:manufacturer").toLocked();
/**
* Search parameter: <b>status</b>
* <p>
* Description: <b>Returns medications for this status</b><br>
* Type: <b>token</b><br>
* Path: <b>Medication.status</b><br>
* </p>
*/
@SearchParamDefinition(name="status", path="Medication.status", description="Returns medications for this status", type="token" )
public static final String SP_STATUS = "status";
/**
* <b>Fluent Client</b> search parameter constant for <b>status</b>
* <p>
* Description: <b>Returns medications for this status</b><br>
* Type: <b>token</b><br>
* Path: <b>Medication.status</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.TokenClientParam STATUS = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_STATUS);
/**
* Search parameter: <b>code</b>
* <p>
* Description: <b>Multiple Resources:
* [AllergyIntolerance](allergyintolerance.html): Code that identifies the allergy or intolerance
* [Condition](condition.html): Code for the condition
* [DeviceRequest](devicerequest.html): Code for what is being requested/ordered
* [DiagnosticReport](diagnosticreport.html): The code for the report, as opposed to codes for the atomic results, which are the names on the observation resource referred to from the result
* [FamilyMemberHistory](familymemberhistory.html): A search by a condition code
* [List](list.html): What the purpose of this list is
* [Medication](medication.html): Returns medications for a specific code
* [MedicationAdministration](medicationadministration.html): Return administrations of this medication code
* [MedicationDispense](medicationdispense.html): Returns dispenses of this medicine code
* [MedicationRequest](medicationrequest.html): Return prescriptions of this medication code
* [MedicationUsage](medicationusage.html): Return statements of this medication code
* [Observation](observation.html): The code of the observation type
* [Procedure](procedure.html): A code to identify a procedure
* [ServiceRequest](servicerequest.html): What is being requested/ordered
</b><br>
* Type: <b>token</b><br>
* Path: <b>AllergyIntolerance.code | AllergyIntolerance.reaction.substance | Condition.code | DeviceRequest.code.concept | DiagnosticReport.code | FamilyMemberHistory.condition.code | List.code | Medication.code | MedicationAdministration.medication.concept | MedicationDispense.medication.concept | MedicationRequest.medication.concept | MedicationUsage.medication.concept | Observation.code | Procedure.code | ServiceRequest.code</b><br>
* </p>
*/
@SearchParamDefinition(name="code", path="AllergyIntolerance.code | AllergyIntolerance.reaction.substance | Condition.code | DeviceRequest.code.concept | DiagnosticReport.code | FamilyMemberHistory.condition.code | List.code | Medication.code | MedicationAdministration.medication.concept | MedicationDispense.medication.concept | MedicationRequest.medication.concept | MedicationUsage.medication.concept | Observation.code | Procedure.code | ServiceRequest.code", description="Multiple Resources: \r\n\r\n* [AllergyIntolerance](allergyintolerance.html): Code that identifies the allergy or intolerance\r\n* [Condition](condition.html): Code for the condition\r\n* [DeviceRequest](devicerequest.html): Code for what is being requested/ordered\r\n* [DiagnosticReport](diagnosticreport.html): The code for the report, as opposed to codes for the atomic results, which are the names on the observation resource referred to from the result\r\n* [FamilyMemberHistory](familymemberhistory.html): A search by a condition code\r\n* [List](list.html): What the purpose of this list is\r\n* [Medication](medication.html): Returns medications for a specific code\r\n* [MedicationAdministration](medicationadministration.html): Return administrations of this medication code\r\n* [MedicationDispense](medicationdispense.html): Returns dispenses of this medicine code\r\n* [MedicationRequest](medicationrequest.html): Return prescriptions of this medication code\r\n* [MedicationUsage](medicationusage.html): Return statements of this medication code\r\n* [Observation](observation.html): The code of the observation type\r\n* [Procedure](procedure.html): A code to identify a procedure\r\n* [ServiceRequest](servicerequest.html): What is being requested/ordered\r\n", type="token" )
public static final String SP_CODE = "code";
/**
* <b>Fluent Client</b> search parameter constant for <b>code</b>
* <p>
* Description: <b>Multiple Resources:
* [AllergyIntolerance](allergyintolerance.html): Code that identifies the allergy or intolerance
* [Condition](condition.html): Code for the condition
* [DeviceRequest](devicerequest.html): Code for what is being requested/ordered
* [DiagnosticReport](diagnosticreport.html): The code for the report, as opposed to codes for the atomic results, which are the names on the observation resource referred to from the result
* [FamilyMemberHistory](familymemberhistory.html): A search by a condition code
* [List](list.html): What the purpose of this list is
* [Medication](medication.html): Returns medications for a specific code
* [MedicationAdministration](medicationadministration.html): Return administrations of this medication code
* [MedicationDispense](medicationdispense.html): Returns dispenses of this medicine code
* [MedicationRequest](medicationrequest.html): Return prescriptions of this medication code
* [MedicationUsage](medicationusage.html): Return statements of this medication code
* [Observation](observation.html): The code of the observation type
* [Procedure](procedure.html): A code to identify a procedure
* [ServiceRequest](servicerequest.html): What is being requested/ordered
</b><br>
* Type: <b>token</b><br>
* Path: <b>AllergyIntolerance.code | AllergyIntolerance.reaction.substance | Condition.code | DeviceRequest.code.concept | DiagnosticReport.code | FamilyMemberHistory.condition.code | List.code | Medication.code | MedicationAdministration.medication.concept | MedicationDispense.medication.concept | MedicationRequest.medication.concept | MedicationUsage.medication.concept | Observation.code | Procedure.code | ServiceRequest.code</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.TokenClientParam CODE = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_CODE);
}
|
package com.ternence.designpattern.decorator;
/**
* create by 陶江航 at 2017/11/5 20:20
*
* @version 1.0
* @email taojianghang@xinzhentech.com
* @description 白衬衫的装饰器
* <p>
* 现在我要利用这个类给白衬衫加一点装饰
*/
public abstract class WhiteShirtDecorator implements Clothes {
private Clothes clothes;
public WhiteShirtDecorator(Clothes clothes) {
if (clothes == null) {
throw new IllegalArgumentException("衣服为null");
}
this.clothes = clothes;
}
public Clothes getClothes() {
return clothes;
}
@Override
public String color() {
return clothes.color();
}
@Override
public int[] size() {
return clothes.size();
}
}
|
/*
* Copyright (C) 2014 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.example.android.uamp;
import android.media.session.PlaybackState;
import android.net.Uri;
import android.text.TextUtils;
import com.example.android.uamp.model.MusicProvider;
import com.example.android.uamp.utils.LogHelper;
import com.example.android.uamp.utils.MediaIDHelper;
import com.google.android.gms.cast.MediaInfo;
import com.google.android.gms.cast.MediaMetadata;
import com.google.android.gms.cast.MediaStatus;
import com.google.android.gms.common.images.WebImage;
import com.google.android.libraries.cast.companionlibrary.cast.VideoCastManager;
import com.google.android.libraries.cast.companionlibrary.cast.callbacks.VideoCastConsumerImpl;
import com.google.android.libraries.cast.companionlibrary.cast.exceptions.CastException;
import com.google.android.libraries.cast.companionlibrary.cast.exceptions.NoConnectionException;
import com.google.android.libraries.cast.companionlibrary.cast.exceptions.TransientNetworkDisconnectionException;
import org.json.JSONException;
import org.json.JSONObject;
import static android.media.session.MediaSession.QueueItem;
/**
* An implementation of Playback that talks to Cast.
*/
public class CastPlayback implements Playback {
private static final String TAG = LogHelper.makeLogTag(CastPlayback.class);
private static final String MIME_TYPE_AUDIO_MPEG = "audio/mpeg";
private static final String ITEM_ID = "itemId";
private final MusicProvider mMusicProvider;
private final VideoCastConsumerImpl mCastConsumer = new VideoCastConsumerImpl() {
@Override
public void onRemoteMediaPlayerMetadataUpdated() {
LogHelper.d(TAG, "onRemoteMediaPlayerMetadataUpdated");
updateMetadata();
}
@Override
public void onRemoteMediaPlayerStatusUpdated() {
LogHelper.d(TAG, "onRemoteMediaPlayerStatusUpdated");
updatePlaybackState();
}
};
/** The current PlaybackState*/
private int mState;
/** Callback for making completion/error calls on */
private Callback mCallback;
private VideoCastManager mCastManager;
private volatile int mCurrentPosition;
private volatile String mCurrentMediaId;
public CastPlayback(MusicProvider musicProvider) {
this.mMusicProvider = musicProvider;
}
@Override
public void start() {
mCastManager = VideoCastManager.getInstance();
mCastManager.addVideoCastConsumer(mCastConsumer);
}
@Override
public void stop(boolean notifyListeners) {
mCastManager.removeVideoCastConsumer(mCastConsumer);
mState = PlaybackState.STATE_STOPPED;
if (notifyListeners && mCallback != null) {
mCallback.onPlaybackStatusChanged(mState);
}
}
@Override
public void setState(int state) {
this.mState = state;
}
@Override
public int getCurrentStreamPosition() {
if (!mCastManager.isConnected()) {
return mCurrentPosition;
}
try {
return (int)mCastManager.getCurrentMediaPosition();
} catch (TransientNetworkDisconnectionException | NoConnectionException e) {
LogHelper.e(TAG, e, "Exception getting media position");
}
return -1;
}
@Override
public void setCurrentStreamPosition(int pos) {
this.mCurrentPosition = pos;
}
@Override
public void play(QueueItem item) {
try {
loadMedia(item.getDescription().getMediaId(), true);
mState = PlaybackState.STATE_BUFFERING;
if (mCallback != null) {
mCallback.onPlaybackStatusChanged(mState);
}
} catch (TransientNetworkDisconnectionException | NoConnectionException | JSONException e) {
LogHelper.e(TAG, "Exception loading media ", e, null);
if (mCallback != null) {
mCallback.onError(e.getMessage());
}
}
}
@Override
public void pause() {
try {
if (mCastManager.isRemoteMediaLoaded()) {
mCastManager.pause();
mCurrentPosition = (int) mCastManager.getCurrentMediaPosition();
} else {
loadMedia(mCurrentMediaId, false);
}
} catch (JSONException | CastException | TransientNetworkDisconnectionException
| NoConnectionException e) {
LogHelper.e(TAG, e, "Exception pausing cast playback");
if (mCallback != null) {
mCallback.onError(e.getMessage());
}
}
}
@Override
public void seekTo(int position) {
if (mCurrentMediaId == null) {
if (mCallback != null) {
mCallback.onError("seekTo cannot be calling in the absence of mediaId.");
}
return;
}
try {
if (mCastManager.isRemoteMediaLoaded()) {
mCastManager.seek(position);
mCurrentPosition = position;
} else {
mCurrentPosition = position;
loadMedia(mCurrentMediaId, false);
}
} catch (TransientNetworkDisconnectionException | NoConnectionException |
JSONException e) {
LogHelper.e(TAG, e, "Exception pausing cast playback");
if (mCallback != null) {
mCallback.onError(e.getMessage());
}
}
}
@Override
public void setCurrentMediaId(String mediaId) {
this.mCurrentMediaId = mediaId;
}
@Override
public String getCurrentMediaId() {
return mCurrentMediaId;
}
@Override
public void setCallback(Callback callback) {
this.mCallback = callback;
}
@Override
public boolean isConnected() {
return mCastManager.isConnected();
}
@Override
public boolean isPlaying() {
try {
return mCastManager.isConnected() && mCastManager.isRemoteMediaPlaying();
} catch (TransientNetworkDisconnectionException | NoConnectionException e) {
LogHelper.e(TAG, e, "Exception calling isRemoteMoviePlaying");
}
return false;
}
@Override
public int getState() {
return mState;
}
private void loadMedia(String mediaId, boolean autoPlay) throws
TransientNetworkDisconnectionException, NoConnectionException, JSONException {
String musicId = MediaIDHelper.extractMusicIDFromMediaID(mediaId);
android.media.MediaMetadata track = mMusicProvider.getMusic(musicId);
if (!TextUtils.equals(mediaId, mCurrentMediaId)) {
mCurrentMediaId = mediaId;
mCurrentPosition = 0;
}
JSONObject customData = new JSONObject();
customData.put(ITEM_ID, mediaId);
MediaInfo media = toCastMediaMetadata(track, customData);
mCastManager.loadMedia(media, autoPlay, mCurrentPosition, customData);
}
/**
* Helper method to convert a {@link android.media.MediaMetadata} to a
* {@link com.google.android.gms.cast.MediaInfo} used for sending media to the receiver app.
*
* @param track {@link com.google.android.gms.cast.MediaMetadata}
* @param customData custom data specifies the local mediaId used by the player.
* @return mediaInfo {@link com.google.android.gms.cast.MediaInfo}
*/
private static MediaInfo toCastMediaMetadata(android.media.MediaMetadata track,
JSONObject customData) {
MediaMetadata mediaMetadata = new MediaMetadata(MediaMetadata.MEDIA_TYPE_MUSIC_TRACK);
mediaMetadata.putString(MediaMetadata.KEY_TITLE,
track.getDescription().getTitle().toString());
mediaMetadata.putString(MediaMetadata.KEY_SUBTITLE,
track.getDescription().getSubtitle().toString());
mediaMetadata.putString(MediaMetadata.KEY_ALBUM_ARTIST,
track.getString(android.media.MediaMetadata.METADATA_KEY_ALBUM_ARTIST));
mediaMetadata.putString(MediaMetadata.KEY_ALBUM_TITLE,
track.getString(android.media.MediaMetadata.METADATA_KEY_ALBUM));
WebImage image = new WebImage(
new Uri.Builder().encodedPath(
track.getString(android.media.MediaMetadata.METADATA_KEY_ALBUM_ART_URI))
.build());
// First image is used by the receiver for showing the audio album art.
mediaMetadata.addImage(image);
// Second image is used by Cast Companion Library on the full screen activity that is shown
// when the cast dialog is clicked.
mediaMetadata.addImage(image);
return new MediaInfo.Builder(track.getString(MusicProvider.CUSTOM_METADATA_TRACK_SOURCE))
.setContentType(MIME_TYPE_AUDIO_MPEG)
.setStreamType(MediaInfo.STREAM_TYPE_BUFFERED)
.setMetadata(mediaMetadata)
.setCustomData(customData)
.build();
}
private void updateMetadata() {
// Sync: We get the customData from the remote media information and update the local
// metadata if it happens to be different from the one we are currently using.
// This can happen when the app was either restarted/disconnected + connected, or if the
// app joins an existing session while the Chromecast was playing a queue.
try {
MediaInfo mediaInfo = mCastManager.getRemoteMediaInformation();
if (mediaInfo == null) {
return;
}
JSONObject customData = mediaInfo.getCustomData();
if (customData != null && customData.has(ITEM_ID)) {
String remoteMediaId = customData.getString(ITEM_ID);
if (!TextUtils.equals(mCurrentMediaId, remoteMediaId)) {
mCurrentMediaId = remoteMediaId;
if (mCallback != null) {
mCallback.onMetadataChanged(remoteMediaId);
}
mCurrentPosition = getCurrentStreamPosition();
}
}
} catch (TransientNetworkDisconnectionException | NoConnectionException | JSONException e) {
LogHelper.e(TAG, e, "Exception processing update metadata");
}
}
private void updatePlaybackState() {
int status = mCastManager.getPlaybackStatus();
int idleReason = mCastManager.getIdleReason();
LogHelper.d(TAG, "onRemoteMediaPlayerStatusUpdated ", status);
// Convert the remote playback states to media playback states.
switch (status) {
case MediaStatus.PLAYER_STATE_IDLE:
if (idleReason == MediaStatus.IDLE_REASON_FINISHED) {
if (mCallback != null) {
mCallback.onCompletion();
}
}
break;
case MediaStatus.PLAYER_STATE_BUFFERING:
mState = PlaybackState.STATE_BUFFERING;
if (mCallback != null) {
mCallback.onPlaybackStatusChanged(mState);
}
break;
case MediaStatus.PLAYER_STATE_PLAYING:
mState = PlaybackState.STATE_PLAYING;
updateMetadata();
if (mCallback != null) {
mCallback.onPlaybackStatusChanged(mState);
}
break;
case MediaStatus.PLAYER_STATE_PAUSED:
mState = PlaybackState.STATE_PAUSED;
updateMetadata();
if (mCallback != null) {
mCallback.onPlaybackStatusChanged(mState);
}
break;
default: // case unknown
LogHelper.d(TAG, "State default : ", status);
break;
}
}
}
|
package org.frameworkset.web.util;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import org.frameworkset.util.Assert;
/**
* Utility class for URI encoding and decoding based on RFC 3986.
* Offers encoding methods for the various URI components.
*
* <p>All {@code encode*(String, String)} methods in this class operate in a similar way:
* <ul>
* <li>Valid characters for the specific URI component as defined in RFC 3986 stay the same.</li>
* <li>All other characters are converted into one or more bytes in the given encoding scheme.
* Each of the resulting bytes is written as a hexadecimal string in the "<code>%<i>xy</i></code>"
* format.</li>
* </ul>
*
* @author Arjen Poutsma
* @since 3.0
* @see <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>
*/
public abstract class UriUtils {
/**
* Encodes the given URI scheme with the given encoding.
* @param scheme the scheme to be encoded
* @param encoding the character encoding to encode to
* @return the encoded scheme
* @throws UnsupportedEncodingException when the given encoding parameter is not supported
*/
public static String encodeScheme(String scheme, String encoding) throws UnsupportedEncodingException {
return HierarchicalUriComponents.encodeUriComponent(scheme, encoding, HierarchicalUriComponents.Type.SCHEME);
}
/**
* Encodes the given URI authority with the given encoding.
* @param authority the authority to be encoded
* @param encoding the character encoding to encode to
* @return the encoded authority
* @throws UnsupportedEncodingException when the given encoding parameter is not supported
*/
public static String encodeAuthority(String authority, String encoding) throws UnsupportedEncodingException {
return HierarchicalUriComponents.encodeUriComponent(authority, encoding, HierarchicalUriComponents.Type.AUTHORITY);
}
/**
* Encodes the given URI user info with the given encoding.
* @param userInfo the user info to be encoded
* @param encoding the character encoding to encode to
* @return the encoded user info
* @throws UnsupportedEncodingException when the given encoding parameter is not supported
*/
public static String encodeUserInfo(String userInfo, String encoding) throws UnsupportedEncodingException {
return HierarchicalUriComponents.encodeUriComponent(userInfo, encoding, HierarchicalUriComponents.Type.USER_INFO);
}
/**
* Encodes the given URI host with the given encoding.
* @param host the host to be encoded
* @param encoding the character encoding to encode to
* @return the encoded host
* @throws UnsupportedEncodingException when the given encoding parameter is not supported
*/
public static String encodeHost(String host, String encoding) throws UnsupportedEncodingException {
return HierarchicalUriComponents.encodeUriComponent(host, encoding, HierarchicalUriComponents.Type.HOST_IPV4);
}
/**
* Encodes the given URI port with the given encoding.
* @param port the port to be encoded
* @param encoding the character encoding to encode to
* @return the encoded port
* @throws UnsupportedEncodingException when the given encoding parameter is not supported
*/
public static String encodePort(String port, String encoding) throws UnsupportedEncodingException {
return HierarchicalUriComponents.encodeUriComponent(port, encoding, HierarchicalUriComponents.Type.PORT);
}
/**
* Encodes the given URI path with the given encoding.
* @param path the path to be encoded
* @param encoding the character encoding to encode to
* @return the encoded path
* @throws UnsupportedEncodingException when the given encoding parameter is not supported
*/
public static String encodePath(String path, String encoding) throws UnsupportedEncodingException {
return HierarchicalUriComponents.encodeUriComponent(path, encoding, HierarchicalUriComponents.Type.PATH);
}
/**
* Encodes the given URI path segment with the given encoding.
* @param segment the segment to be encoded
* @param encoding the character encoding to encode to
* @return the encoded segment
* @throws UnsupportedEncodingException when the given encoding parameter is not supported
*/
public static String encodePathSegment(String segment, String encoding) throws UnsupportedEncodingException {
return HierarchicalUriComponents.encodeUriComponent(segment, encoding, HierarchicalUriComponents.Type.PATH_SEGMENT);
}
/**
* Encodes the given URI query with the given encoding.
* @param query the query to be encoded
* @param encoding the character encoding to encode to
* @return the encoded query
* @throws UnsupportedEncodingException when the given encoding parameter is not supported
*/
public static String encodeQuery(String query, String encoding) throws UnsupportedEncodingException {
return HierarchicalUriComponents.encodeUriComponent(query, encoding, HierarchicalUriComponents.Type.QUERY);
}
/**
* Encodes the given URI query parameter with the given encoding.
* @param queryParam the query parameter to be encoded
* @param encoding the character encoding to encode to
* @return the encoded query parameter
* @throws UnsupportedEncodingException when the given encoding parameter is not supported
*/
public static String encodeQueryParam(String queryParam, String encoding) throws UnsupportedEncodingException {
return HierarchicalUriComponents.encodeUriComponent(queryParam, encoding, HierarchicalUriComponents.Type.QUERY_PARAM);
}
/**
* Encodes the given URI fragment with the given encoding.
* @param fragment the fragment to be encoded
* @param encoding the character encoding to encode to
* @return the encoded fragment
* @throws UnsupportedEncodingException when the given encoding parameter is not supported
*/
public static String encodeFragment(String fragment, String encoding) throws UnsupportedEncodingException {
return HierarchicalUriComponents.encodeUriComponent(fragment, encoding, HierarchicalUriComponents.Type.FRAGMENT);
}
/**
* Encode characters outside the unreserved character set as defined in
* <a href="https://tools.ietf.org/html/rfc3986#section-2">RFC 3986 Section 2</a>.
* <p>This can be used to ensure the given String will not contain any
* characters with reserved URI meaning regardless of URI component.
* @param source the string to be encoded
* @param encoding the character encoding to encode to
* @return the encoded string
* @throws UnsupportedEncodingException when the given encoding parameter is not supported
*/
public static String encode(String source, String encoding) throws UnsupportedEncodingException {
HierarchicalUriComponents.Type type = HierarchicalUriComponents.Type.URI;
return HierarchicalUriComponents.encodeUriComponent(source, encoding, type);
}
// decoding
/**
* Decodes the given encoded source String into an URI. Based on the following rules:
* <ul>
* <li>Alphanumeric characters {@code "a"} through {@code "z"}, {@code "A"} through {@code "Z"}, and
* {@code "0"} through {@code "9"} stay the same.</li>
* <li>Special characters {@code "-"}, {@code "_"}, {@code "."}, and {@code "*"} stay the same.</li>
* <li>A sequence "{@code %<i>xy</i>}" is interpreted as a hexadecimal representation of the character.</li>
* </ul>
* @param source the source string
* @param encoding the encoding
* @return the decoded URI
* @throws IllegalArgumentException when the given source contains invalid encoded sequences
* @throws UnsupportedEncodingException when the given encoding parameter is not supported
* @see java.net.URLDecoder#decode(String, String)
*/
public static String decode(String source, String encoding) throws UnsupportedEncodingException {
Assert.notNull(source, "Source must not be null");
Assert.hasLength(encoding, "Encoding must not be empty");
int length = source.length();
ByteArrayOutputStream bos = new ByteArrayOutputStream(length);
boolean changed = false;
for (int i = 0; i < length; i++) {
int ch = source.charAt(i);
if (ch == '%') {
if ((i + 2) < length) {
char hex1 = source.charAt(i + 1);
char hex2 = source.charAt(i + 2);
int u = Character.digit(hex1, 16);
int l = Character.digit(hex2, 16);
if (u == -1 || l == -1) {
throw new IllegalArgumentException("Invalid encoded sequence \"" + source.substring(i) + "\"");
}
bos.write((char) ((u << 4) + l));
i += 2;
changed = true;
}
else {
throw new IllegalArgumentException("Invalid encoded sequence \"" + source.substring(i) + "\"");
}
}
else {
bos.write(ch);
}
}
return (changed ? new String(bos.toByteArray(), encoding) : source);
}
}
|
// --------------------------------------------------------------------------------
// Copyright 2002-2021 Echo Three, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// --------------------------------------------------------------------------------
package com.echothree.model.control.workflow.server.transfer;
import com.echothree.model.control.security.common.transfer.SecurityRoleTransfer;
import com.echothree.model.control.security.server.control.SecurityControl;
import com.echothree.model.control.workflow.common.transfer.WorkflowDestinationPartyTypeTransfer;
import com.echothree.model.control.workflow.common.transfer.WorkflowDestinationSecurityRoleTransfer;
import com.echothree.model.control.workflow.server.control.WorkflowControl;
import com.echothree.model.data.user.server.entity.UserVisit;
import com.echothree.model.data.workflow.server.entity.WorkflowDestinationSecurityRole;
import com.echothree.util.server.persistence.Session;
public class WorkflowDestinationSecurityRoleTransferCache
extends BaseWorkflowTransferCache<WorkflowDestinationSecurityRole, WorkflowDestinationSecurityRoleTransfer> {
SecurityControl securityControl;
/** Creates a new instance of WorkflowDestinationSecurityRoleTransferCache */
public WorkflowDestinationSecurityRoleTransferCache(UserVisit userVisit, WorkflowControl workflowControl) {
super(userVisit, workflowControl);
securityControl = Session.getModelController(SecurityControl.class);
}
public WorkflowDestinationSecurityRoleTransfer getWorkflowDestinationSecurityRoleTransfer(WorkflowDestinationSecurityRole workflowDestinationSecurityRole) {
WorkflowDestinationSecurityRoleTransfer workflowDestinationSecurityRoleTransfer = get(workflowDestinationSecurityRole);
if(workflowDestinationSecurityRoleTransfer == null) {
WorkflowDestinationPartyTypeTransfer workflowDestinationPartyType = workflowControl.getWorkflowDestinationPartyTypeTransfer(userVisit, workflowDestinationSecurityRole.getWorkflowDestinationPartyType());
SecurityRoleTransfer securityRole = securityControl.getSecurityRoleTransfer(userVisit, workflowDestinationSecurityRole.getSecurityRole());
workflowDestinationSecurityRoleTransfer = new WorkflowDestinationSecurityRoleTransfer(workflowDestinationPartyType, securityRole);
put(workflowDestinationSecurityRole, workflowDestinationSecurityRoleTransfer);
}
return workflowDestinationSecurityRoleTransfer;
}
}
|
/*
* Licensed to ObjectStyle LLC under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ObjectStyle LLC licenses
* this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.bootique.junit5;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Used to annotate static {@link io.bootique.BQRuntime} instances in a unit test to instruct JUnit to start these
* runtimes, and shut them down when all the tests in the class are finished. To activate requires @{@link BQTest}
* annotation on the parent class.
*
* @since 2.0
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface BQApp {
BQTestScope value() default BQTestScope.IMPLIED;
/**
* If true, skips starting up the app. {@link io.bootique.BQRuntime} will still be shutdown at the end of
* the test cycle to clean up any resources.
*/
boolean skipRun() default false;
/**
* If true, shuts down the app {@link io.bootique.BQRuntime} immediately after the command exit. Usually
* appropriate for non-"daemon" apps
*/
boolean immediateShutdown() default false;
}
|
class zWePuftdJqiW {
}
class JenqXz4e {
}
class O0wD7fybfvUjP {
}
class LfY0qU {
}
class S_X7tZQgx {
}
class zIf23SKQ1tMk {
public void[][][][][][] DonSB2e9;
public boolean[][][] EYE (void DkvjfUgnAlgd, int DH_1H) throws hdGOy {
void mv;
{
boolean McNWkdNMev58;
return;
Qy0oC_9cP[][] vWtL;
void[] mDUYi2;
!-!6584.tOcnOpW();
int[] eOoeZ6scEx;
return;
}
return ----new Z[ null.mhzZy].J8;
int NIWLLxYU = !!498498589[ ---!false.IwKyOP_W_JJr()] = false.nycoOlWNZdwwu();
while ( 780535997[ this[ !null.kqnfzX6CaQnS()]]) ;
int[] wLBoU3BziYIl;
int _qCgEyYSlzC = this.G() = !-!!-kIm7lUhPEer[ !null[ ( -!new boolean[ --!!--( q[ -!!true[ !--!new void[ 9.d].nqHKLO5()]])[ tsMt4fOzmKX8V.KWXw()]].sN0lycie0zns).e]];
atvvTjO[][][] EfgIU0RMz;
int vXKZn;
boolean _5i2OIG;
return sjQhxT[ null.LdmTFLJjfwU];
int vnP6Ok2dq = !( true.T70hRke).g5IldU77 = ( 0700673[ !---!--76262.n()]).I;
int cGUebLqG = new InG2EF8B9qin().Ew3zw1UF;
void[] EOOFD;
smHD[][] wt0 = -!3357.vlS() = new abA_c[ null.Ri80ALUFAfd5F][ !Lblw4R6BOwO1Wd().e4H2fH()];
boolean[][] R4VcCCkGfo = null[ -sJqcHZ().gH()] = -----!new int[ null.Od()].y1s0AGvNBnpu();
}
public static void h896hXp (String[] jMSel) {
boolean UE = --331185.o8A7H();
XP7v5[] yAQRnaIkRXOqul = false.SfQQr3m();
NGf_[][][][] hhbBi6SS;
if ( !-null._5ZG1Sj()) while ( new KLYWJ3H[ TRkms().JImtrWZ()].jQ_3VZs_()) !!pByBzP2jf.Rbb;else ;
if ( 2849.zY) while ( -( 922750.EERnbGTJh).VBPi87JYyRY()) return;else new HwNh6muaSw().mjswsv6Mul;
;
int[] _0m = false.RSU();
void[] LTgIxSDBys;
return;
while ( t()[ !-lY7fVw1c4k().RV()]) while ( !!-false.A0()) while ( ( -Bn.p0MdzADr922bSk)[ -true.xGCyNBYGveAY0E]) while ( new NVsVz__aJ7[ ( null.ijZxC).zlCdaSU6].t0QgnLVuh2awa()) {
boolean bVgloeLD8bnQar;
}
RXdPTBz[] tF3Mvt0_;
void HlVQl;
while ( true.m()) if ( !false.IAYv) ;
bUsmPbgq8M_[] gf9;
void[] nkn9f;
int T = false.dWIdoskP4b5ee = true.b5tzFJD;
new int[ -!true[ BfOR()[ !( false.d4rGTJeWFp96).T1elqdbe]]].O5W();
boolean YHpwCx = new qrIzC()[ !LHupcZTg206a[ !true.Y1HILyHD_lt()]] = !false.D48LDHhr();
while ( !null.r2()) while ( QORJRgXZw[ -!true.QhAnh3IRV]) null[ ( true.HAxrbcfC).j1e];
}
public void[][] fQG3J;
}
class vgiXjFh {
}
class OrkUG {
public static void s2HUgb (String[] UkZ) {
boolean S = new xepfSo()[ ( XbsgZ9EO0()[ --647113785[ pZhS[ new int[ ( true[ !272778019[ -!u66Z_8UaqaQIgt().JOX7NIiYAwx9]]).Ei8IR()].w]]])[ ( -!7653297[ -!( false[ ---this.UoTC3()]).nSf4s])[ new void[ false.EbB7][ -null[ true[ true[ !-144.sEJsYLkJ00D]]]]]]] = !new int[ -!--BXgNogo.vw46NR()].xOhYCZuc;
oZ6EZcPI4J[][][] c2yZu;
int[][][][] yu;
return !!new SYBFL_GuyN[ -----!false[ new jYxTEyhbd().jRX4xYkvOe()]][ true.ys()];
jQbbvpYEGHdI_4[] ubfca9S = !!!-null.T6lG_tV();
if ( -!!-new b().gulHFX()) {
return;
}else while ( !new Wb()[ this[ false.Y]]) {
while ( new int[ true.bNsS44a5l1JLAu()][ new HBOUGr()[ -CpbTX().rkOLmC1f0h6()]]) {
void[] u_Uw1oxYAECm;
}
}
return !!-!--new boolean[ --!!---zd3HOfhS.TzwO].Z0ZwC2_nEjp7aX();
void[] X2e;
{
if ( false.ny()) new boolean[ !new void[ new xjv2P556GxCjK[ !!-null.ve4ynBW4cLIl4].XPwWMc()].drnbh_].jF1nzEtG;
return;
while ( D__54LD.Zcjs50EUy2Qkgb()) if ( vzCDxgsup6HesC().t4ddKfIGhP) ;
while ( new aRCxRcI2NfD().ATEh9()) !fNOE7D19il4().rRnM_WrYFyIVJ;
void[] fRxu;
int[][] r7WO1yR;
void M7cD;
int[][] tqI2EmTzxQw2hs;
{
while ( null.HHSHKg7CD4vRu()) while ( -!new int[ new m_beo1x516Zwl()[ --this.ojPyJXSR_uZBj]].ZImE9t69GzE) return;
}
QiWP3weiinN4Tc[] iyYMgiy;
-!!Tr().Eww1aU;
{
while ( null.dbXVpF7()) {
boolean CK;
}
}
if ( !sQWbWjix()[ new boolean[ !this.ordSOXxrn()].SY7kWpebmW()]) while ( !!this.kT()) return;
e8us5EW drtrU;
;
return;
}
while ( ( false.Rq8U1JrLk28D0)[ 612695[ !-!this.Vi66TRz()]]) -5100331.Gm;
int[][] aViF = new void[ ( --( null.e2mmg()).RHCA7bBfqt2).CpBPfMm][ !this[ this.q5wxMzTipYge()]];
-!!( !new void[ --!-( bS0().yfadhEcn())[ -new FuGlHHGbM()[ new HFOT()[ -!new boolean[ -null.aiVem5_u3kEmP()][ !3389.IKp1qM]]]]].xHZ()).HLFkbWeYBjp;
boolean[][][][][][][][][][] RGB;
void RTp4hYIB7h;
}
public static void QC1GMsfz2x (String[] B5npj86) throws wdUUINyz {
int _2Ut;
{
boolean[][][] e17r1l7KRst;
void[] EcGViBuXsXF;
int[] m6k6fc;
while ( !-!-A5eB().ICGWa5n) ;
!!false[ new Zcj6Iw2lKAJeOX()[ true.BU_]];
int[] gWKoAxFZR;
return;
if ( -true[ ( null.EWFTHyP_VRiF()).e]) false[ -new o()[ new LfDPPXkj21qzLk[ new squmi4eYAz7Br6()[ !R2Kt7XE99S.aioBEnqZxjcL]][ false.D()]]];
return;
boolean[] yY;
void[] Wd;
return;
false.WtUxvRvF();
int[][] H9ErsTUUIg;
boolean x7uohn1YOe53HH;
{
int[] eScLtWIAFhp9;
}
{
void[][][][] i;
}
wG8_M15e6[][] yfUg3324OrqK;
int[] xtW5ZxpVzlm;
void gxULIRT;
}
boolean u1Uh0kIONo_0 = -!!!new XklegKv()[ 159[ new void[ this[ this[ !this.yKqsFmygzcT9o()]]].qoih6zccZYRr]];
YZsaFtad5 d0I;
while ( new YgA69dr()[ -!null.EwENPjn0vrW]) _zO7O1()[ -!this.UpWc];
int[][] f45l03OEnmPUy = !!--new AkpF3PskGHMNR3()[ 8364[ u3cSZz0uq9Ghpa().tjArVG()]] = ---( _Fxhlr3kn0SfQ().ykX18iPy).JUWrS5sFslQd2();
if ( ZJX.Scufh) return;
;
while ( YAtwYA4tN().p) return;
void _ = -null.gKL() = false[ -!null.yH];
void[][] lEv74KhpirG9m8 = !--false.MxQmjYjtMob = null[ !-----true.e52A];
boolean WWqxyN5_8;
mf7gXN7 Z3XxSJqaw = new int[ true.PV0vflLecSYd()][ !new mwA4yodeOLhtx()[ false.DZ()]];
}
public static void p (String[] uqIkAFN9zsY) {
return -this.XP;
boolean[][][][] T4Chgo58hK = 18.Oze0_DQS = KlHFa.GGsrF2tukK;
false[ !-new rfQuTLsa1u3kps().XEB7s6U()];
{
void AXLBmirNcXQ;
}
PSL3x5G9LvrYt[] gF72Tz9dzcbeJD = !( !-41.oPNqFM()).K7c() = Nkp[ true.iIS()];
void Ect8J5jFteRGsR = new void[ -pey_h3Borp[ ---( new mjP_1rIneqg[ 264011894.jCtL][ true._v2G6HhMM()]).xq33z]][ -this.eonAIGxuB2x] = new EO8lUL().ddrZ;
while ( true.KZYDf()) return;
if ( 43087601.tUbGR()) return;else {
int[][][][] JwcDv;
}
if ( 28298[ --!!tFSk94xSA.Vft5_V()]) while ( -!true.kLDDzSX) ;else ;
;
boolean[][] m4DNankI3 = !!F[ ( 84918246[ new int[ 70682[ !-new g0760tcQF()[ -new s4gy()[ !-( !new p02HHgLLRh5()[ HxCPv4X4of5A.XPSyt5bq2WJT]).FF]]]].aTyQ5]).gMcQQ7] = BL9hwxlOK0P().AWM;
void ouiPnKpND1rWt = !true.W78() = !HfG4mh148Km()[ !sNcL6preax.sFhuz()];
boolean[][][][] JteTHl3j_IHf = -!( new DVJWH[ !null.aM64GWD2()].QjcvCz()).j6LPZ4yBL() = !!new Qk()[ null.VwdzAD8vC1()];
;
}
public static void WW9LjoE8S9LvV (String[] t63) {
!-true.sTXwL;
int frtZR = !!-new void[ true[ 87908.j2rpcbBLH9]][ !this.Nn4RzDpO8];
-false.e7UtW;
{
{
int[] bdSRXr8FHX;
}
int[] J;
boolean[] U9b4;
int[] qyzZoeX29;
int Z5;
if ( !true[ 7321608[ !new int[ l7B7EFOF7QP().ZnOkSBU8R0p3()].utpUj0Yi()]]) !-!null.MilOJJDt7IzIl;
lvO8[] A_64ZB9VXD5G;
}
return PMw6Gn().T604T1_fH8();
}
public int[][][] BzK3wP () throws ghlJLJ8GC {
int[] sWsERZpMGi2U = bPn.hpe0gIh_y();
while ( !this.Bx7()) ---new int[ -!3.UF]._;
while ( -_[ 159724[ -kpTJ9r57x9().LdZspMZi9d]]) ;
boolean NeuE = l5gos3g[ new int[ false[ !--Meme6Jt[ -!!!false.qM1kgO()]]][ !new boolean[ -null.AY8gm5fDzxsr()].z7J()]];
int vPqDhrrOwys;
void sDpPAHuNk;
boolean iezFQFdM;
int aB2 = true.donwtiZtFWZK = -false.Wl0wustVlLHVu;
AIhTGt82R[] _nm9bgt5O2THtH;
;
;
boolean xB1;
int[] SZlHPcNjOd = !true[ !new boolean[ ( true[ !true[ ccn[ 86.lzl()]]]).H5Kk()][ -this[ --this.NN_l()]]];
UgT GY15P0Blz;
void g = -null.gqnnJLjLmT_sn;
;
;
boolean[][] rsgGCvHbgQDXvr;
}
public boolean[] B (boolean NdjVWLVqf, n0CPRF4wJAlZcf di34v55) throws DdvA71f6ANT7Y {
;
void Zi99wEfhC;
boolean[] TvriUlYLQq = Iu().qXIDz90PgT4L8w;
MFT1[] hGRfTqPr;
if ( !this[ this.ks]) {
{
while ( null[ eAgtTRPQTC45pL().YiKPTbVTj()]) return;
}
}
new k().YuOixgaCiPg;
while ( !null.end_()) ;
boolean[] RaT6dtXrzKy = !475446[ false.jsVF];
void[] xZpsLp;
void TAEmd8vKDWAL6 = ( !new qc5ZSILt8hJi().NIinmjPbMoz())[ -this.Kg8LjiYRt] = -null[ !( !!-!IDMHp.gzX5purzd())[ !-Hq3_a6Hd.aD4JsT7TF9rMi]];
;
int zJAo9Zn;
int[] B5;
void[][] Zf3S_QKTrV = Rza()[ null.vjI0vOYpE()];
while ( !!!null[ vXwOFcqHTj.l_YTvJ1()]) return;
}
}
class XoPPe5t_g {
public void nAIqXg_WoV8G6 () throws i {
boolean K55RJQRlE;
v9O YxnwUtji;
q Xqgl8eS = --!--new gDPq_7UU().cz1K6dhd();
}
public void MP;
public void E () throws kcmAvDjLsDkR {
false.A4dUqeJRxQ;
return true.nStuY6EbsxMf;
int[] Fkz9 = true[ !!( 045.WJ).wmkdeQtpQP9x7g()] = --new FpqWJfhy94()[ !---!!this[ C_5aEKqj.D0jt7cVf57f]];
;
}
public static void afYSN8Fqn (String[] R) {
while ( -!eyfTB().JOCejU8soJWF()) return;
if ( !!!5806.BuvnV()) ;else {
return;
}
int I;
void K0mLxqqlajVu = XZ3ni()[ -h_37p5WOIaaJtp().wBfnQkzIXAbJEJ()] = 19990870.w;
void[][][] shB3cgQUFX2ShK;
}
public int YOq2022w_g;
public BgKtCSj0qD[][][][] Ce () {
;
{
return;
bjm3di qt;
!new fYksAR1e[ !!i.j_J9n4MU].ow0L;
void GXGr1;
int e9hVX5L;
}
boolean e5 = null.H;
void[][] IAkkS8 = !!-new LJkMCUCTvnxr().TVYb7 = true.y9;
this.U9mSxGomjZKeda;
{
if ( new wxe().Kg0_) -Nv()[ this.zFmRK()];
-!null.OueuxEpHsYCU5;
boolean[][][][][][] GcXg;
!null.ulDLAibsTWxSo;
{
while ( false.cw1Isp) return;
}
void k5iTKImyY8L;
}
void[] j_P = fax6H5ki0.Lt = !-!-this.NiIrUN440;
Pgy27v2ry7kE4J[][][] eWGRP9 = 751648080.BWi6RF() = 4853.Rm();
boolean[] CYTbR;
boolean WnZ = --true.LcxVMyV;
return -nZSBtHpL().ULTcz5p();
return;
int nas = az10W48Wpfq[ ( !!!!!!true.WlDimifV3s)[ new boolean[ !-!new Sdejn()[ Ze().Wjyy3t]].y1u5G57Cmeq()]] = null[ ( true.zZgsLlmr).BeSI];
boolean[] cO;
void[] pMg3VBtB;
}
public static void D4NktnDccn (String[] ZdbIrgImxyid) throws SYy {
return;
void[][][][][] PfYV = this.ywZG1EusDcc;
boolean bk = false.t3dOhZWan8mg();
int[] o2xyPz0g_9zH3U;
return ---this.vA0;
int OYIf;
void nQOQOihaK0L = B5qCow71SNZqeU.Fg5Fv0L = !!( TSJ7kZe_xq7o.IMFS2JK_X7).B4aP8();
}
}
|
/*
* The MIT License
*
* Copyright 2013 gburdell.
*
* 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 v2.apfe.peg.generate;
import v2.apfe.peg.Definition;
import v2.apfe.peg.Grammar;
import v2.apfe.runtime.CharBuffer;
import v2.apfe.runtime.InputStream;
import v2.apfe.runtime.ParseError;
import gblib.Util;
import v2.apfe.runtime.CharBufState;
import gblib.MessageMgr;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
/**
*
* @author gburdell
*/
public class Main {
public static void main(String argv[]) {
if ((1 > argv.length) || (2 < argv.length)) {
String usage = "\n"
+ "Usage: generate file.peg ?properties.txt?\n\n"
+ "Process 'file.peg' description and generate parser using\n"
+ "options defined in (optional) 'properties.txt'\n";
System.err.println(usage);
System.exit(1);
}
if (1 < argv.length) {
loadProperties(new File(argv[1]));
}
try {
InputStream istr = new InputStream(argv[0]);
CharBuffer cb = istr.newCharBuffer();
CharBufState.create(cb);
Grammar gram = new Grammar();
gram = Util.downCast(gram.accept());
int numErrs = 0;
if (null != gram) {
System.out.println("grammar:");
System.out.println(gram.toString());
stAnyze = new Analyze(gram);
numErrs = stAnyze.analyze();
} else {
ParseError.printTopMessage();
}
{
//dump memoize stats
long stats[] = CharBufState.getTheOne().getMemoizeStats();
double pcnt = 0;
if (0 < stats[1]) {
pcnt = (100.0 * stats[0]) / stats[1];
}
gblib.Util.info(3, "APFE-STAT-1", stats[0], stats[1], pcnt);
}
if ((0 < numErrs) || (null == gram)) {
System.exit(numErrs);
} else {
Generate.generate(stAnyze);
}
} catch (Exception ex) {
Util.abnormalExit(ex);
}
}
private static Analyze stAnyze;
public static boolean isToken(String idName) {
Definition defn = stAnyze.getDefnByName().get(idName);
return ((null != defn) && defn.isToken());
}
/**
* Get property value.
*
* @param key property name.
* @return user-specified or default value.
*/
public static String getProperty(String key) {
if (! stProps.containsKey(key)) {
Util.abnormalExit(key+": missing property definition");
}
String v = stProps.getProperty(key).trim();
assert null != v;
return v;
}
/**
* Get property value as int.
*
* @param key property name.
* @return user-specified or default value.
*/
public static int getPropertyAsInt(String key) {
return Integer.parseInt(getProperty(key));
}
/**
* Get property value as boolean.
*
* @param key property name.
* @return user-specified or default value.
*/
public static boolean getPropertyAsBoolean(String key) {
return Boolean.parseBoolean(getProperty(key));
}
/**
* Property settings for generate.
*/
private static final Properties stProps = new Properties();
private static void loadProperties(File f) {
try {
stProps.load(new FileReader(f));
} catch (IOException ex) {
Util.abnormalExit(ex);
}
}
static {
loadProperties(new File(".", "generate.props.txt"));
}
public static final boolean stGenMaze = getPropertyAsBoolean("genMaze");
public static final boolean stGenTerminal = getPropertyAsBoolean("genTerminal");
}
|
package poussecafe.domain;
import poussecafe.storage.internal.InternalDataAccess;
public class SimpleAggregateDataAccess extends InternalDataAccess<SimpleAggregateId, SimpleAggregate.Attributes> {
}
|
package com.ydl.iec.util;
import com.ydl.iec.iec104.message.MessageDetail;
import com.ydl.iec.iec104.enums.TypeIdentifierEnum;
import com.ydl.iec.iec104.enums.UControlEnum;
/**
*
* @ClassName: Iec104Util
* @Description: 工具类
* @author YDL
* @date 2020年5月13日
*/
public class Iec104Util {
private static int controlLength = 4;
/**
* I 格式 低位在前
* @param accept 接收序列号
* @param send 发送序列号
* @return
*/
public static byte[] getIcontrol(short accept, short send) {
byte[] control = new byte[4];
// 向左移动一位 保证低位的D0 是0
send = (short) (send << 1);
control[0] = (byte) ((send));
control[1] = (byte) ((send >> 8));
accept = (short) (accept << 1);
control[2] = (byte) ((accept));
control[3] = (byte) ((accept >> 8));
return control;
}
/**
* 返回控制域中的接收序号
* @param control
* @return
*/
public static short getAccept(byte[] control) {
int accept = 0;
short acceptLow = (short) (control[2] & 0xff);
short acceptHigh = (short) (control[3] & 0xff);
accept += acceptLow;
accept += acceptHigh << 8;
accept = accept >> 1;
return (short) accept;
}
/**
* 返回控制域中的发送序号
* @param control
* @return
*/
public static short getSend(byte[] control) {
int send = 0;
short acceptLow = (short) (control[0] & 0xff);
short acceptHigh = (short) (control[1] & 0xff);
send += acceptLow;
send += acceptHigh << 8;
send = send >> 1;
return (short) send;
}
/**
* S 格式
* @param accept
* @return
*/
public static byte[] getScontrol(short accept) {
byte[] control = new byte[4];
// 向左移动一位 保证低位的D0 是0
short send = 1;
control[0] = (byte) ((send));
control[1] = (byte) ((send >> 8));
accept = (short) (accept << 1);
control[2] = (byte) ((accept));
control[3] = (byte) ((accept >> 8));
return control;
}
/**
*
* @Title: 返回U帧
* @Description: 判断是否是
* @param @param control
* @param @return
* @return boolean
* @throws
*/
public static UControlEnum getUcontrol(byte[] control) {
if (control.length < controlLength || control[1] != 0 || control[3] != 0 || control[2] != 0) {
return null;
}
int controlInt = ByteUtil.byteArrayToInt(control);
for (UControlEnum ucontrolEnum : UControlEnum.values()) {
if (ucontrolEnum.getValue() == controlInt) {
return ucontrolEnum;
}
}
return null;
}
/**
* 返回消息地址 其中低位在前
* @param i
* @return
*/
public static byte[] intToMessageAddress(int i) {
byte[] result = new byte[3];
result[0] = (byte) (i & 0xFF);
result[1] = (byte) ((i >> 8) & 0xFF);
result[2] = (byte) ((i >> 16) & 0xFF);
return result;
}
/**
* 消息地址 只有三个
* @param bytes
* @return
*/
public static int messageAddressToInt(byte[] bytes) {
int value = 0;
for (int i = 2; i >= 0; i--) {
int shift = (2 - i) * 8;
value += (bytes[2 - i] & 0xFF) << shift;
}
return value;
}
/**
* 设置可以变限定词
* @param ruleDetail104
* @param byteItem
*/
public static void setChanged(MessageDetail ruleDetail104, byte byteItem) {
// 第一位是 0 则是有序的
ruleDetail104.setContinuous((byteItem & 0x80) == 0 ? false : true);
// 先将第一位数置零 然后转换成int
ruleDetail104.setMeasgLength(byteItem & (byte) 0x7F);
}
/**
* 返回可变限定词数组
* @param ruleDetail104
* @return
*/
public static byte getChangedQualifiers(MessageDetail ruleDetail104) {
// 将长度转换成 byte
byte changedQualifiers = (byte) ruleDetail104.getMeasgLength();
// 判断SQ 置 isContinuous false SQ = 0;否则 SQ =1 , 同时将SQ置 设置在 可变限定词的 D7位置
int sq = ruleDetail104.isContinuous() ? 0x80 : 0;
changedQualifiers = (byte) (sq | changedQualifiers);
return changedQualifiers;
}
public static void setMeaageAttribute(MessageDetail ruleDetail104) {
boolean isMessage = !(TypeIdentifierEnum.generalCall.equals(ruleDetail104.getTypeIdentifier()) //总召唤无此项
|| TypeIdentifierEnum.timeSynchronization.equals(ruleDetail104.getTypeIdentifier()) // 时钟同步
|| TypeIdentifierEnum.resetPprocess.equals(ruleDetail104.getTypeIdentifier()) // 复位进程
|| TypeIdentifierEnum.initEnd.equals(ruleDetail104.getTypeIdentifier()));
ruleDetail104.setMessage(isMessage);
boolean isQualifiers = !(TypeIdentifierEnum.timeSynchronization.equals(ruleDetail104.getTypeIdentifier()) // 时钟同步
|| TypeIdentifierEnum.onePointTeleindication.equals(ruleDetail104.getTypeIdentifier()) //单点摇信
|| TypeIdentifierEnum.twoPointTeleindication.equals(ruleDetail104.getTypeIdentifier()) // 双点摇信
|| TypeIdentifierEnum.onePointTelecontrol.equals(ruleDetail104.getTypeIdentifier()) // 单命令遥控
|| TypeIdentifierEnum.twoPointTelecontrol.equals(ruleDetail104.getTypeIdentifier())); // 双命令遥控
ruleDetail104.setQualifiers(isQualifiers);
boolean isTimeScale = TypeIdentifierEnum.timeSynchronization.equals(ruleDetail104.getTypeIdentifier()) // 时钟同步
|| TypeIdentifierEnum.onePointTimeTeleindication.equals(ruleDetail104.getTypeIdentifier()) // 摇信带时标 单点
|| TypeIdentifierEnum.twoPointTimeTeleindication.equals(ruleDetail104.getTypeIdentifier()); //摇信带时标 双点
ruleDetail104.setTimeScaleExit(isTimeScale);
}
/**
* short 转换成两个 字节后是163 00 也就是 value[1] 中才有值
* test 在D7位置 因此 值应该和 01000000 做与运算
* P/N 0肯定确认 1否定确认
* @return 肯定或否定确认
*/
public static boolean isYes(byte[] values) {
return (values[0] & 1 << 6) == 0;
}
/**
* short 转换成两个 字节后是163 00 也就是 value[1] 中才有值
* test 在D7位置 因此 值应该和 10000000 做与运算
* tets 0 为试验 1 试验
* @return 是否试验
*/
public static boolean isTets(byte[] values) {
return (values[0] & 1 << 7) != 0;
}
/**
* 返回具体的原因
* @param values
* @return
*/
public static short getTransferReasonShort(byte[] values) {
byte transferReason = values[0];
// 前两位置零
transferReason = (byte) (transferReason & 0x3E);
return transferReason;
}
public static short getTransferReasonShort(boolean isTets, boolean isYes, short transferReason) {
int t = isTets ? 1 : 0;
int y = isYes ? 0 : 1;
int transferReasonInt = t << 7 | transferReason;
transferReasonInt = y << 6 | transferReasonInt;
short transferReasonShort = (short) (transferReasonInt << 8);
return transferReasonShort;
}
/**
* 返回终端地址对应的byte数组 其中低位在前
* @param terminalAddress
* @return
*/
public static byte[] getTerminalAddressByte(short terminalAddress) {
byte[] b = new byte[2];
b[1] = (byte) ((terminalAddress >> 8) & 0xff);
b[0] = (byte) (terminalAddress & 0xff);
return b;
}
/**
* 返回回终端地址 其中低位在前
* @param terminalAddress
* @return
*/
public static short getTerminalAddressShort(byte[] terminalAddress) {
short value = 0;
value += (terminalAddress[0] & 0xFF);
value += (terminalAddress[1] & 0xFF) << 8;
return value;
}
}
|
/*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.ballerinalang.plugins.idea.debugger;
import com.intellij.icons.AllIcons;
import com.intellij.xdebugger.frame.XCompositeNode;
import com.intellij.xdebugger.frame.XValueChildrenList;
import com.intellij.xdebugger.frame.XValueGroup;
import org.ballerinalang.plugins.idea.debugger.dto.Frame;
import org.ballerinalang.plugins.idea.debugger.dto.Variable;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import javax.swing.Icon;
/**
* Represents a variable group in debug window.
*/
public class BallerinaXValueGroup extends XValueGroup {
private final BallerinaDebugProcess myProcess;
private final Frame myFrame;
private final Variable myVariable;
protected BallerinaXValueGroup(@NotNull BallerinaDebugProcess myProcess, @NotNull Frame myFrame,
@NotNull String name, @NotNull Variable myVariable) {
super(name);
this.myVariable = myVariable;
this.myProcess = myProcess;
this.myFrame = myFrame;
}
// Todo - Uncomment after required IDEA version is changed to 2017.
// @Override
// public boolean isRestoreExpansion() {
// return true;
// }
@Nullable
@Override
public Icon getIcon() {
return AllIcons.Debugger.Value;
}
@Override
public void computeChildren(@NotNull XCompositeNode node) {
List<Variable> children = myVariable.getChildren();
if (children == null) {
super.computeChildren(node);
} else {
XValueChildrenList list = new XValueChildrenList();
for (Variable child : children) {
list.add(child.getName(), new BallerinaXValue(myProcess, myFrame.getFrameName(), child,
AllIcons.Nodes.Field));
}
node.addChildren(list, true);
}
}
}
|
// Copyright 2017 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 com.google.api.ads.dfp.jaxws.v201705;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
*
* Gets an {@link AvailabilityForecast} for an existing {@link LineItem} object. An availability
* forecast reports the maximum number of available units that the line item can be booked with,
* and also the total number of units matching the line item's targeting.
*
* <p>Only line items having type {@link LineItemType#SPONSORSHIP} or {@link
* LineItemType#STANDARD} are valid. Other types will result in {@link
* ReservationDetailsError.Reason#LINE_ITEM_TYPE_NOT_ALLOWED}.
*
* @param lineItemId the ID of a {@link LineItem} to run the forecast on.
* @param forecastOptions options controlling the forecast
*
*
* <p>Java class for getAvailabilityForecastById element declaration.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <element name="getAvailabilityForecastById">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="lineItemId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
* <element name="forecastOptions" type="{https://www.google.com/apis/ads/publisher/v201705}AvailabilityForecastOptions" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"lineItemId",
"forecastOptions"
})
@XmlRootElement(name = "getAvailabilityForecastById")
public class ForecastServiceInterfacegetAvailabilityForecastById {
protected Long lineItemId;
protected AvailabilityForecastOptions forecastOptions;
/**
* Gets the value of the lineItemId property.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getLineItemId() {
return lineItemId;
}
/**
* Sets the value of the lineItemId property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setLineItemId(Long value) {
this.lineItemId = value;
}
/**
* Gets the value of the forecastOptions property.
*
* @return
* possible object is
* {@link AvailabilityForecastOptions }
*
*/
public AvailabilityForecastOptions getForecastOptions() {
return forecastOptions;
}
/**
* Sets the value of the forecastOptions property.
*
* @param value
* allowed object is
* {@link AvailabilityForecastOptions }
*
*/
public void setForecastOptions(AvailabilityForecastOptions value) {
this.forecastOptions = value;
}
}
|
package com.dbc.pessoaapi.security;
import java.util.Optional;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.dbc.pessoaapi.entity.UsuarioEntity;
import com.dbc.pessoaapi.service.UsuarioService;
import lombok.RequiredArgsConstructor;
@Service
@RequiredArgsConstructor
public class AuthenticationService implements UserDetailsService {
private final UsuarioService usuarioService;
@Override
public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
Optional<UsuarioEntity> optionalUsuario = usuarioService.findByLogin(login);
if(optionalUsuario.isPresent()){
return optionalUsuario.get();
}
throw new UsernameNotFoundException("User not found!");
}
}
|
package com.zkc.barcodescan.activity;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.zkc.Service.CaptureService;
import com.zkc.barcodescan.R;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class ActivityQrcodeSetting extends ListActivity {
private static final String TAG = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_barcode_qrcodesetting);
setListAdapter(new SimpleAdapter(this, getData("simple-list-item-2"),
android.R.layout.simple_list_item_2, new String[] { "title",
"description" }, new int[] { android.R.id.text1,
android.R.id.text2 }));
/*//恢复出厂设置
String str="nls000601;00001000;0006000";
//允许识读所有类型
str="nls0006010;nls0302003;nls0006000";
byte[] buffer=str.getBytes(Charset.forName("US-ASCII"));
Log.i(TAG, "string is:"+bytesToString(buffer).toString());
//CaptureService.serialPort.Write(buffer);
CaptureService.serialPort.Write(new byte[]{0x1b,0x31});*/
}
protected void onListItemClick(ListView listView, View v, int position,
long id) {
switch (position) {
case 0:
if (CaptureService.serialPort != null) {
CaptureService.serialPort
.Write(CaptureService.defaultSetting2D);
Toast toast = Toast.makeText(this,
getResources().getString(R.string.action_setsuccess),
Toast.LENGTH_LONG);
toast.show();
}
break;
case 1:
if (CaptureService.serialPort != null) {
CaptureService.serialPort.Write(CaptureService.dataTypeFor2D);
Toast toast = Toast.makeText(this,
getResources().getString(R.string.action_setsuccess),
Toast.LENGTH_LONG);
toast.show();
}
break;
case 2:
Intent intent = new Intent();
intent.setClass(ActivityQrcodeSetting.this,
DialogEncodingActivity.class);
startActivityForResult(intent, 0);
break;
default:
break;
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// ȡ���ַ�
Bundle bundle = data.getExtras();
String str = bundle.getString("str");
SharedPreferences.Editor editor = CaptureService.sharedPreferences
.edit();
editor.putString("encoding", str);
editor.commit();
CaptureService.str_encoding=str;
}
/**
* ����SimpleAdapter�ĵڶ����������ΪList<Map<?,?>>
*
* @param title
* @return
*/
private List<Map<String, String>> getData(String title) {
List<Map<String, String>> listData = new ArrayList<Map<String, String>>();
// Reset
Map<String, String> map = new HashMap<String, String>();
map.put("title", getResources().getString(R.string.action_reset));
map.put("description",
getResources().getString(R.string.action_reset_desc));
listData.add(map);
// Set data type
map = new HashMap<String, String>();
map.put("title", getResources().getString(R.string.action_datatype));
map.put("description",
getResources().getString(R.string.action_datatype_desc));
listData.add(map);
// Set encoding type
map = new HashMap<String, String>();
map.put("title", getResources().getString(R.string.action_encodingtype));
map.put("description",
getResources().getString(R.string.action_encodingtype_desc));
listData.add(map);
return listData;
}
/**
* 将byte数组转换为字符串形式表示的十六进制数方便查看
*/
public static StringBuffer bytesToString(byte[] bytes)
{
StringBuffer sBuffer = new StringBuffer();
for (int i = 0; i < bytes.length; i++)
{
String s = Integer.toHexString(bytes[i] & 0xff);
if (s.length() < 2)
sBuffer.append('0');
sBuffer.append(s + " ");
}
return sBuffer;
}
private static byte charToByte(char c)
{
return (byte) "0123456789abcdef".indexOf(c);
}
}
|
package wjc.ivan.coolweather.gson;
import com.google.gson.annotations.SerializedName;
public class Now {
@SerializedName("tmp")
public String temperature;
@SerializedName("cond")
public More more;
public class More {
@SerializedName("txt")
public String info;
}
}
|
package de.uni.bielefeld.sc.hterhors.psink.obie.projects.scio.ontology.interfaces;
import de.hterhors.obie.core.ontology.AbstractIndividual;
import de.hterhors.obie.core.ontology.IndividualFactory;
import de.hterhors.obie.core.ontology.annotations.AssignableSubClasses;
import de.hterhors.obie.core.ontology.annotations.AssignableSubInterfaces;
import de.hterhors.obie.core.ontology.annotations.DatatypeProperty;
import de.hterhors.obie.core.ontology.annotations.DirectInterface;
import de.hterhors.obie.core.ontology.annotations.DirectSiblings;
import de.hterhors.obie.core.ontology.annotations.ImplementationClass;
import de.hterhors.obie.core.ontology.annotations.OntologyModelContent;
import de.hterhors.obie.core.ontology.annotations.RelationTypeCollection;
import de.hterhors.obie.core.ontology.annotations.SuperRootClasses;
import de.hterhors.obie.core.ontology.annotations.TextMention;
import de.hterhors.obie.core.ontology.interfaces.IDatatype;
import de.hterhors.obie.core.ontology.interfaces.IOBIEThing;
import de.uni.bielefeld.sc.hterhors.psink.obie.projects.scio.ontology.classes.*;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
/**
<p><b>skos:closeMatch</b>
<p>http://doe-generated-ontology.com/OntoAD#C0220931
<p>
<p><b>rdfs:label</b>
<p>rehabilitative training
<p>
<p><b>rdfs:description</b>
<p>Rehabilitative Training is a therapeutic intervention for spinal cord injury by physical exercise.
<p>
*
* @author hterhors
*
*
*Mar 19, 2019
*/
@AssignableSubInterfaces(get={IEnrichedEnvironment.class, ITreadmillTraining.class, })
@ImplementationClass(get=RehabilitativeTraining.class)
public interface IRehabilitativeTraining
extends IPhysicalTreatment{
}
|
/*
* 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.pdfbox.pdmodel.interactive.form;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget;
import org.apache.pdfbox.rendering.TestPDFToImage;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* Test for the PDButton class.
*
*/
public class PDAcroFormTest
{
private PDDocument document;
private PDAcroForm acroForm;
private static final File OUT_DIR = new File("target/test-output");
private static final File IN_DIR = new File("src/test/resources/org/apache/pdfbox/pdmodel/interactive/form");
@Before
public void setUp()
{
document = new PDDocument();
acroForm = new PDAcroForm(document);
document.getDocumentCatalog().setAcroForm(acroForm);
}
@Test
public void testFieldsEntry()
{
// the /Fields entry has been created with the AcroForm
// as this is a required entry
assertNotNull(acroForm.getFields());
assertEquals(acroForm.getFields().size(),0);
// there shouldn't be an exception if there is no such field
assertNull(acroForm.getField("foo"));
// remove the required entry which is the case for some
// PDFs (see PDFBOX-2965)
acroForm.getCOSObject().removeItem(COSName.FIELDS);
// ensure there is always an empty collection returned
assertNotNull(acroForm.getFields());
assertEquals(acroForm.getFields().size(),0);
// there shouldn't be an exception if there is no such field
assertNull(acroForm.getField("foo"));
}
@Test
public void testAcroFormProperties()
{
assertTrue(acroForm.getDefaultAppearance().isEmpty());
acroForm.setDefaultAppearance("/Helv 0 Tf 0 g");
assertEquals(acroForm.getDefaultAppearance(),"/Helv 0 Tf 0 g");
}
@Test
public void testFlatten() throws IOException
{
PDDocument testPdf = PDDocument.load(new File(IN_DIR, "AlignmentTests.pdf"));
testPdf.getDocumentCatalog().getAcroForm().flatten();
assertTrue(testPdf.getDocumentCatalog().getAcroForm().getFields().isEmpty());
File file = new File(OUT_DIR, "AlignmentTests-flattened.pdf");
testPdf.save(file);
// compare rendering
TestPDFToImage testPDFToImage = new TestPDFToImage(TestPDFToImage.class.getName());
if (!testPDFToImage.doTestFile(file, IN_DIR.getAbsolutePath(), OUT_DIR.getAbsolutePath()))
{
// don't fail, rendering is different on different systems, result must be viewed manually
System.out.println("Rendering of " + file + " failed or is not identical to expected rendering in " + IN_DIR + " directory");
}
}
/*
* Same as above but remove the page reference from the widget annotation
* before doing the flatten() to ensure that the widgets page reference is properly looked up
* (PDFBOX-3301)
*/
@Test
public void testFlattenWidgetNoRef() throws IOException
{
PDDocument testPdf = PDDocument.load(new File(IN_DIR, "AlignmentTests.pdf"));
PDAcroForm acroForm = testPdf.getDocumentCatalog().getAcroForm();
for (PDField field : acroForm.getFieldTree()) {
for (PDAnnotationWidget widget : field.getWidgets()) {
widget.getCOSObject().removeItem(COSName.P);
}
}
testPdf.getDocumentCatalog().getAcroForm().flatten();
assertTrue(testPdf.getDocumentCatalog().getAcroForm().getFields().isEmpty());
File file = new File(OUT_DIR, "AlignmentTests-flattened-noRef.pdf");
testPdf.save(file);
// compare rendering
TestPDFToImage testPDFToImage = new TestPDFToImage(TestPDFToImage.class.getName());
if (!testPDFToImage.doTestFile(file, IN_DIR.getAbsolutePath(), OUT_DIR.getAbsolutePath()))
{
// don't fail, rendering is different on different systems, result must be viewed manually
System.out.println("Rendering of " + file + " failed or is not identical to expected rendering in " + IN_DIR + " directory");
}
}
/*
* Test that we do not modify an AcroForm with missing resource information
* when loading the document only.
* (PDFBOX-3752)
*/
@Test
public void testDontAddMissingInformationOnDocumentLoad()
{
try
{
byte[] pdfBytes = createAcroFormWithMissingResourceInformation();
PDDocument pdfDocument = PDDocument.load(pdfBytes);
// do a low level access to the AcroForm to avoid the generation of missing entries
PDDocumentCatalog documentCatalog = pdfDocument.getDocumentCatalog();
COSDictionary catalogDictionary = documentCatalog.getCOSObject();
COSDictionary acroFormDictionary = (COSDictionary) catalogDictionary.getDictionaryObject(COSName.ACRO_FORM);
// ensure that the missing information has not been generated
assertNull(acroFormDictionary.getDictionaryObject(COSName.DA));
assertNull(acroFormDictionary.getDictionaryObject(COSName.RESOURCES));
pdfDocument.close();
}
catch (IOException e)
{
System.err.println("Couldn't create test document, test skipped");
return;
}
}
/*
* Test that we add missing ressouce information to an AcroForm
* when accessing the AcroForm on the PD level
* (PDFBOX-3752)
*/
@Test
public void testAddMissingInformationOnAcroFormAccess()
{
try
{
byte[] pdfBytes = createAcroFormWithMissingResourceInformation();
PDDocument pdfDocument = PDDocument.load(pdfBytes);
PDDocumentCatalog documentCatalog = pdfDocument.getDocumentCatalog();
// this call shall trigger the generation of missing information
PDAcroForm theAcroForm = documentCatalog.getAcroForm();
// ensure that the missing information has been generated
// DA entry
assertEquals("/Helv 0 Tf 0 g ", theAcroForm.getDefaultAppearance());
assertNotNull(theAcroForm.getDefaultResources());
// DR entry
PDResources acroFormResources = theAcroForm.getDefaultResources();
assertNotNull(acroFormResources.getFont(COSName.getPDFName("Helv")));
assertEquals("Helvetica", acroFormResources.getFont(COSName.getPDFName("Helv")).getName());
assertNotNull(acroFormResources.getFont(COSName.getPDFName("ZaDb")));
assertEquals("ZapfDingbats", acroFormResources.getFont(COSName.getPDFName("ZaDb")).getName());
pdfDocument.close();
}
catch (IOException e)
{
System.err.println("Couldn't create test document, test skipped");
return;
}
}
@After
public void tearDown() throws IOException
{
document.close();
}
private byte[] createAcroFormWithMissingResourceInformation() throws IOException
{
PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
PDAcroForm newAcroForm = new PDAcroForm(document);
document.getDocumentCatalog().setAcroForm(newAcroForm);
PDTextField textBox = new PDTextField(newAcroForm);
textBox.setPartialName("SampleField");
newAcroForm.getFields().add(textBox);
PDAnnotationWidget widget = textBox.getWidgets().get(0);
PDRectangle rect = new PDRectangle(50, 750, 200, 20);
widget.setRectangle(rect);
widget.setPage(page);
page.getAnnotations().add(widget);
// acroForm.setNeedAppearances(true);
// acroForm.getField("SampleField").getCOSObject().setString(COSName.V, "content");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
document.save(baos); // this is a working PDF
document.close();
return baos.toByteArray();
}
}
|
/**
* 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.lucene.util;
import java.util.Arrays;
import java.io.Serializable;
import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.search.DocIdSetIterator;
/** An "open" BitSet implementation that allows direct access to the array of words
* storing the bits.
* <p/>
* Unlike java.util.bitset, the fact that bits are packed into an array of longs
* is part of the interface. This allows efficient implementation of other algorithms
* by someone other than the author. It also allows one to efficiently implement
* alternate serialization or interchange formats.
* <p/>
* <code>OpenBitSet</code> is faster than <code>java.util.BitSet</code> in most operations
* and *much* faster at calculating cardinality of sets and results of set operations.
* It can also handle sets of larger cardinality (up to 64 * 2**32-1)
* <p/>
* The goals of <code>OpenBitSet</code> are the fastest implementation possible, and
* maximum code reuse. Extra safety and encapsulation
* may always be built on top, but if that's built in, the cost can never be removed (and
* hence people re-implement their own version in order to get better performance).
* If you want a "safe", totally encapsulated (and slower and limited) BitSet
* class, use <code>java.util.BitSet</code>.
* <p/>
* <h3>Performance Results</h3>
*
Test system: Pentium 4, Sun Java 1.5_06 -server -Xbatch -Xmx64M
<br/>BitSet size = 1,000,000
<br/>Results are java.util.BitSet time divided by OpenBitSet time.
<table border="1">
<tr>
<th></th> <th>cardinality</th> <th>intersect_count</th> <th>union</th> <th>nextSetBit</th> <th>get</th> <th>iterator</th>
</tr>
<tr>
<th>50% full</th> <td>3.36</td> <td>3.96</td> <td>1.44</td> <td>1.46</td> <td>1.99</td> <td>1.58</td>
</tr>
<tr>
<th>1% full</th> <td>3.31</td> <td>3.90</td> <td> </td> <td>1.04</td> <td> </td> <td>0.99</td>
</tr>
</table>
<br/>
Test system: AMD Opteron, 64 bit linux, Sun Java 1.5_06 -server -Xbatch -Xmx64M
<br/>BitSet size = 1,000,000
<br/>Results are java.util.BitSet time divided by OpenBitSet time.
<table border="1">
<tr>
<th></th> <th>cardinality</th> <th>intersect_count</th> <th>union</th> <th>nextSetBit</th> <th>get</th> <th>iterator</th>
</tr>
<tr>
<th>50% full</th> <td>2.50</td> <td>3.50</td> <td>1.00</td> <td>1.03</td> <td>1.12</td> <td>1.25</td>
</tr>
<tr>
<th>1% full</th> <td>2.51</td> <td>3.49</td> <td> </td> <td>1.00</td> <td> </td> <td>1.02</td>
</tr>
</table>
*/
public class OpenBitSet extends DocIdSet implements Cloneable, Serializable, Bits {
protected long[] bits;
protected int wlen; // number of words (elements) used in the array
// Used only for assert:
private long numBits;
/** Constructs an OpenBitSet large enough to hold numBits.
*
* @param numBits
*/
public OpenBitSet(long numBits) {
this.numBits = numBits;
bits = new long[bits2words(numBits)];
wlen = bits.length;
}
public OpenBitSet() {
this(64);
}
/** Constructs an OpenBitSet from an existing long[].
* <br/>
* The first 64 bits are in long[0],
* with bit index 0 at the least significant bit, and bit index 63 at the most significant.
* Given a bit index,
* the word containing it is long[index/64], and it is at bit number index%64 within that word.
* <p>
* numWords are the number of elements in the array that contain
* set bits (non-zero longs).
* numWords should be <= bits.length, and
* any existing words in the array at position >= numWords should be zero.
*
*/
public OpenBitSet(long[] bits, int numWords) {
this.bits = bits;
this.wlen = numWords;
this.numBits = wlen * 64;
}
@Override
public DocIdSetIterator iterator() {
return new OpenBitSetIterator(bits, wlen);
}
/** This DocIdSet implementation is cacheable. */
@Override
public boolean isCacheable() {
return true;
}
/** Returns the current capacity in bits (1 greater than the index of the last bit) */
public long capacity() { return bits.length << 6; }
/**
* Returns the current capacity of this set. Included for
* compatibility. This is *not* equal to {@link #cardinality}
*/
public long size() {
return capacity();
}
public int length() {
return bits.length << 6;
}
/** Returns true if there are no set bits */
public boolean isEmpty() { return cardinality()==0; }
/** Expert: returns the long[] storing the bits */
public long[] getBits() { return bits; }
/** Expert: sets a new long[] to use as the bit storage */
public void setBits(long[] bits) { this.bits = bits; }
/** Expert: gets the number of longs in the array that are in use */
public int getNumWords() { return wlen; }
/** Expert: sets the number of longs in the array that are in use */
public void setNumWords(int nWords) { this.wlen=nWords; }
/** Returns true or false for the specified bit index. */
public boolean get(int index) {
int i = index >> 6; // div 64
// signed shift will keep a negative index and force an
// array-index-out-of-bounds-exception, removing the need for an explicit check.
if (i>=bits.length) return false;
int bit = index & 0x3f; // mod 64
long bitmask = 1L << bit;
return (bits[i] & bitmask) != 0;
}
/** Returns true or false for the specified bit index.
* The index should be less than the OpenBitSet size
*/
public boolean fastGet(int index) {
assert index >= 0 && index < numBits;
int i = index >> 6; // div 64
// signed shift will keep a negative index and force an
// array-index-out-of-bounds-exception, removing the need for an explicit check.
int bit = index & 0x3f; // mod 64
long bitmask = 1L << bit;
return (bits[i] & bitmask) != 0;
}
/** Returns true or false for the specified bit index
*/
public boolean get(long index) {
int i = (int)(index >> 6); // div 64
if (i>=bits.length) return false;
int bit = (int)index & 0x3f; // mod 64
long bitmask = 1L << bit;
return (bits[i] & bitmask) != 0;
}
/** Returns true or false for the specified bit index.
* The index should be less than the OpenBitSet size.
*/
public boolean fastGet(long index) {
assert index >= 0 && index < numBits;
int i = (int)(index >> 6); // div 64
int bit = (int)index & 0x3f; // mod 64
long bitmask = 1L << bit;
return (bits[i] & bitmask) != 0;
}
/*
// alternate implementation of get()
public boolean get1(int index) {
int i = index >> 6; // div 64
int bit = index & 0x3f; // mod 64
return ((bits[i]>>>bit) & 0x01) != 0;
// this does a long shift and a bittest (on x86) vs
// a long shift, and a long AND, (the test for zero is prob a no-op)
// testing on a P4 indicates this is slower than (bits[i] & bitmask) != 0;
}
*/
/** returns 1 if the bit is set, 0 if not.
* The index should be less than the OpenBitSet size
*/
public int getBit(int index) {
assert index >= 0 && index < numBits;
int i = index >> 6; // div 64
int bit = index & 0x3f; // mod 64
return ((int)(bits[i]>>>bit)) & 0x01;
}
/*
public boolean get2(int index) {
int word = index >> 6; // div 64
int bit = index & 0x0000003f; // mod 64
return (bits[word] << bit) < 0; // hmmm, this would work if bit order were reversed
// we could right shift and check for parity bit, if it was available to us.
}
*/
/** sets a bit, expanding the set size if necessary */
public void set(long index) {
int wordNum = expandingWordNum(index);
int bit = (int)index & 0x3f;
long bitmask = 1L << bit;
bits[wordNum] |= bitmask;
}
/** Sets the bit at the specified index.
* The index should be less than the OpenBitSet size.
*/
public void fastSet(int index) {
assert index >= 0 && index < numBits;
int wordNum = index >> 6; // div 64
int bit = index & 0x3f; // mod 64
long bitmask = 1L << bit;
bits[wordNum] |= bitmask;
}
/** Sets the bit at the specified index.
* The index should be less than the OpenBitSet size.
*/
public void fastSet(long index) {
assert index >= 0 && index < numBits;
int wordNum = (int)(index >> 6);
int bit = (int)index & 0x3f;
long bitmask = 1L << bit;
bits[wordNum] |= bitmask;
}
/** Sets a range of bits, expanding the set size if necessary
*
* @param startIndex lower index
* @param endIndex one-past the last bit to set
*/
public void set(long startIndex, long endIndex) {
if (endIndex <= startIndex) return;
int startWord = (int)(startIndex>>6);
// since endIndex is one past the end, this is index of the last
// word to be changed.
int endWord = expandingWordNum(endIndex-1);
long startmask = -1L << startIndex;
long endmask = -1L >>> -endIndex; // 64-(endIndex&0x3f) is the same as -endIndex due to wrap
if (startWord == endWord) {
bits[startWord] |= (startmask & endmask);
return;
}
bits[startWord] |= startmask;
Arrays.fill(bits, startWord+1, endWord, -1L);
bits[endWord] |= endmask;
}
protected int expandingWordNum(long index) {
int wordNum = (int)(index >> 6);
if (wordNum>=wlen) {
ensureCapacity(index+1);
wlen = wordNum+1;
}
assert (numBits = Math.max(numBits, index+1)) >= 0;
return wordNum;
}
/** clears a bit.
* The index should be less than the OpenBitSet size.
*/
public void fastClear(int index) {
assert index >= 0 && index < numBits;
int wordNum = index >> 6;
int bit = index & 0x03f;
long bitmask = 1L << bit;
bits[wordNum] &= ~bitmask;
// hmmm, it takes one more instruction to clear than it does to set... any
// way to work around this? If there were only 63 bits per word, we could
// use a right shift of 10111111...111 in binary to position the 0 in the
// correct place (using sign extension).
// Could also use Long.rotateRight() or rotateLeft() *if* they were converted
// by the JVM into a native instruction.
// bits[word] &= Long.rotateLeft(0xfffffffe,bit);
}
/** clears a bit.
* The index should be less than the OpenBitSet size.
*/
public void fastClear(long index) {
assert index >= 0 && index < numBits;
int wordNum = (int)(index >> 6); // div 64
int bit = (int)index & 0x3f; // mod 64
long bitmask = 1L << bit;
bits[wordNum] &= ~bitmask;
}
/** clears a bit, allowing access beyond the current set size without changing the size.*/
public void clear(long index) {
int wordNum = (int)(index >> 6); // div 64
if (wordNum>=wlen) return;
int bit = (int)index & 0x3f; // mod 64
long bitmask = 1L << bit;
bits[wordNum] &= ~bitmask;
}
/** Clears a range of bits. Clearing past the end does not change the size of the set.
*
* @param startIndex lower index
* @param endIndex one-past the last bit to clear
*/
public void clear(int startIndex, int endIndex) {
if (endIndex <= startIndex) return;
int startWord = (startIndex>>6);
if (startWord >= wlen) return;
// since endIndex is one past the end, this is index of the last
// word to be changed.
int endWord = ((endIndex-1)>>6);
long startmask = -1L << startIndex;
long endmask = -1L >>> -endIndex; // 64-(endIndex&0x3f) is the same as -endIndex due to wrap
// invert masks since we are clearing
startmask = ~startmask;
endmask = ~endmask;
if (startWord == endWord) {
bits[startWord] &= (startmask | endmask);
return;
}
bits[startWord] &= startmask;
int middle = Math.min(wlen, endWord);
Arrays.fill(bits, startWord+1, middle, 0L);
if (endWord < wlen) {
bits[endWord] &= endmask;
}
}
/** Clears a range of bits. Clearing past the end does not change the size of the set.
*
* @param startIndex lower index
* @param endIndex one-past the last bit to clear
*/
public void clear(long startIndex, long endIndex) {
if (endIndex <= startIndex) return;
int startWord = (int)(startIndex>>6);
if (startWord >= wlen) return;
// since endIndex is one past the end, this is index of the last
// word to be changed.
int endWord = (int)((endIndex-1)>>6);
long startmask = -1L << startIndex;
long endmask = -1L >>> -endIndex; // 64-(endIndex&0x3f) is the same as -endIndex due to wrap
// invert masks since we are clearing
startmask = ~startmask;
endmask = ~endmask;
if (startWord == endWord) {
bits[startWord] &= (startmask | endmask);
return;
}
bits[startWord] &= startmask;
int middle = Math.min(wlen, endWord);
Arrays.fill(bits, startWord+1, middle, 0L);
if (endWord < wlen) {
bits[endWord] &= endmask;
}
}
/** Sets a bit and returns the previous value.
* The index should be less than the OpenBitSet size.
*/
public boolean getAndSet(int index) {
assert index >= 0 && index < numBits;
int wordNum = index >> 6; // div 64
int bit = index & 0x3f; // mod 64
long bitmask = 1L << bit;
boolean val = (bits[wordNum] & bitmask) != 0;
bits[wordNum] |= bitmask;
return val;
}
/** Sets a bit and returns the previous value.
* The index should be less than the OpenBitSet size.
*/
public boolean getAndSet(long index) {
assert index >= 0 && index < numBits;
int wordNum = (int)(index >> 6); // div 64
int bit = (int)index & 0x3f; // mod 64
long bitmask = 1L << bit;
boolean val = (bits[wordNum] & bitmask) != 0;
bits[wordNum] |= bitmask;
return val;
}
/** flips a bit.
* The index should be less than the OpenBitSet size.
*/
public void fastFlip(int index) {
assert index >= 0 && index < numBits;
int wordNum = index >> 6; // div 64
int bit = index & 0x3f; // mod 64
long bitmask = 1L << bit;
bits[wordNum] ^= bitmask;
}
/** flips a bit.
* The index should be less than the OpenBitSet size.
*/
public void fastFlip(long index) {
assert index >= 0 && index < numBits;
int wordNum = (int)(index >> 6); // div 64
int bit = (int)index & 0x3f; // mod 64
long bitmask = 1L << bit;
bits[wordNum] ^= bitmask;
}
/** flips a bit, expanding the set size if necessary */
public void flip(long index) {
int wordNum = expandingWordNum(index);
int bit = (int)index & 0x3f; // mod 64
long bitmask = 1L << bit;
bits[wordNum] ^= bitmask;
}
/** flips a bit and returns the resulting bit value.
* The index should be less than the OpenBitSet size.
*/
public boolean flipAndGet(int index) {
assert index >= 0 && index < numBits;
int wordNum = index >> 6; // div 64
int bit = index & 0x3f; // mod 64
long bitmask = 1L << bit;
bits[wordNum] ^= bitmask;
return (bits[wordNum] & bitmask) != 0;
}
/** flips a bit and returns the resulting bit value.
* The index should be less than the OpenBitSet size.
*/
public boolean flipAndGet(long index) {
assert index >= 0 && index < numBits;
int wordNum = (int)(index >> 6); // div 64
int bit = (int)index & 0x3f; // mod 64
long bitmask = 1L << bit;
bits[wordNum] ^= bitmask;
return (bits[wordNum] & bitmask) != 0;
}
/** Flips a range of bits, expanding the set size if necessary
*
* @param startIndex lower index
* @param endIndex one-past the last bit to flip
*/
public void flip(long startIndex, long endIndex) {
if (endIndex <= startIndex) return;
int startWord = (int)(startIndex>>6);
// since endIndex is one past the end, this is index of the last
// word to be changed.
int endWord = expandingWordNum(endIndex-1);
/*** Grrr, java shifting wraps around so -1L>>>64 == -1
* for that reason, make sure not to use endmask if the bits to flip will
* be zero in the last word (redefine endWord to be the last changed...)
long startmask = -1L << (startIndex & 0x3f); // example: 11111...111000
long endmask = -1L >>> (64-(endIndex & 0x3f)); // example: 00111...111111
***/
long startmask = -1L << startIndex;
long endmask = -1L >>> -endIndex; // 64-(endIndex&0x3f) is the same as -endIndex due to wrap
if (startWord == endWord) {
bits[startWord] ^= (startmask & endmask);
return;
}
bits[startWord] ^= startmask;
for (int i=startWord+1; i<endWord; i++) {
bits[i] = ~bits[i];
}
bits[endWord] ^= endmask;
}
/*
public static int pop(long v0, long v1, long v2, long v3) {
// derived from pop_array by setting last four elems to 0.
// exchanges one pop() call for 10 elementary operations
// saving about 7 instructions... is there a better way?
long twosA=v0 & v1;
long ones=v0^v1;
long u2=ones^v2;
long twosB =(ones&v2)|(u2&v3);
ones=u2^v3;
long fours=(twosA&twosB);
long twos=twosA^twosB;
return (pop(fours)<<2)
+ (pop(twos)<<1)
+ pop(ones);
}
*/
/** @return the number of set bits */
public long cardinality() {
return BitUtil.pop_array(bits,0,wlen);
}
/** Returns the popcount or cardinality of the intersection of the two sets.
* Neither set is modified.
*/
public static long intersectionCount(OpenBitSet a, OpenBitSet b) {
return BitUtil.pop_intersect(a.bits, b.bits, 0, Math.min(a.wlen, b.wlen));
}
/** Returns the popcount or cardinality of the union of the two sets.
* Neither set is modified.
*/
public static long unionCount(OpenBitSet a, OpenBitSet b) {
long tot = BitUtil.pop_union(a.bits, b.bits, 0, Math.min(a.wlen, b.wlen));
if (a.wlen < b.wlen) {
tot += BitUtil.pop_array(b.bits, a.wlen, b.wlen-a.wlen);
} else if (a.wlen > b.wlen) {
tot += BitUtil.pop_array(a.bits, b.wlen, a.wlen-b.wlen);
}
return tot;
}
/** Returns the popcount or cardinality of "a and not b"
* or "intersection(a, not(b))".
* Neither set is modified.
*/
public static long andNotCount(OpenBitSet a, OpenBitSet b) {
long tot = BitUtil.pop_andnot(a.bits, b.bits, 0, Math.min(a.wlen, b.wlen));
if (a.wlen > b.wlen) {
tot += BitUtil.pop_array(a.bits, b.wlen, a.wlen-b.wlen);
}
return tot;
}
/** Returns the popcount or cardinality of the exclusive-or of the two sets.
* Neither set is modified.
*/
public static long xorCount(OpenBitSet a, OpenBitSet b) {
long tot = BitUtil.pop_xor(a.bits, b.bits, 0, Math.min(a.wlen, b.wlen));
if (a.wlen < b.wlen) {
tot += BitUtil.pop_array(b.bits, a.wlen, b.wlen-a.wlen);
} else if (a.wlen > b.wlen) {
tot += BitUtil.pop_array(a.bits, b.wlen, a.wlen-b.wlen);
}
return tot;
}
/** Returns the index of the first set bit starting at the index specified.
* -1 is returned if there are no more set bits.
*/
public int nextSetBit(int index) {
int i = index>>6;
if (i>=wlen) return -1;
int subIndex = index & 0x3f; // index within the word
long word = bits[i] >> subIndex; // skip all the bits to the right of index
if (word!=0) {
return (i<<6) + subIndex + BitUtil.ntz(word);
}
while(++i < wlen) {
word = bits[i];
if (word!=0) return (i<<6) + BitUtil.ntz(word);
}
return -1;
}
/** Returns the index of the first set bit starting at the index specified.
* -1 is returned if there are no more set bits.
*/
public long nextSetBit(long index) {
int i = (int)(index>>>6);
if (i>=wlen) return -1;
int subIndex = (int)index & 0x3f; // index within the word
long word = bits[i] >>> subIndex; // skip all the bits to the right of index
if (word!=0) {
return (((long)i)<<6) + (subIndex + BitUtil.ntz(word));
}
while(++i < wlen) {
word = bits[i];
if (word!=0) return (((long)i)<<6) + BitUtil.ntz(word);
}
return -1;
}
/** Returns the index of the first set bit starting downwards at
* the index specified.
* -1 is returned if there are no more set bits.
*/
public int prevSetBit(int index) {
int i = index >> 6;
final int subIndex;
long word;
if (i >= wlen) {
i = wlen - 1;
if (i < 0) return -1;
subIndex = 63; // last possible bit
word = bits[i];
} else {
if (i < 0) return -1;
subIndex = index & 0x3f; // index within the word
word = (bits[i] << (63-subIndex)); // skip all the bits to the left of index
}
if (word != 0) {
return (i << 6) + subIndex - Long.numberOfLeadingZeros(word); // See LUCENE-3197
}
while (--i >= 0) {
word = bits[i];
if (word !=0 ) {
return (i << 6) + 63 - Long.numberOfLeadingZeros(word);
}
}
return -1;
}
/** Returns the index of the first set bit starting downwards at
* the index specified.
* -1 is returned if there are no more set bits.
*/
public long prevSetBit(long index) {
int i = (int) (index >> 6);
final int subIndex;
long word;
if (i >= wlen) {
i = wlen - 1;
if (i < 0) return -1;
subIndex = 63; // last possible bit
word = bits[i];
} else {
if (i < 0) return -1;
subIndex = (int)index & 0x3f; // index within the word
word = (bits[i] << (63-subIndex)); // skip all the bits to the left of index
}
if (word != 0) {
return (((long)i)<<6) + subIndex - Long.numberOfLeadingZeros(word); // See LUCENE-3197
}
while (--i >= 0) {
word = bits[i];
if (word !=0 ) {
return (((long)i)<<6) + 63 - Long.numberOfLeadingZeros(word);
}
}
return -1;
}
@Override
public Object clone() {
try {
OpenBitSet obs = (OpenBitSet)super.clone();
obs.bits = obs.bits.clone(); // hopefully an array clone is as fast(er) than arraycopy
return obs;
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
/** this = this AND other */
public void intersect(OpenBitSet other) {
int newLen= Math.min(this.wlen,other.wlen);
long[] thisArr = this.bits;
long[] otherArr = other.bits;
// testing against zero can be more efficient
int pos=newLen;
while(--pos>=0) {
thisArr[pos] &= otherArr[pos];
}
if (this.wlen > newLen) {
// fill zeros from the new shorter length to the old length
Arrays.fill(bits,newLen,this.wlen,0);
}
this.wlen = newLen;
}
/** this = this OR other */
public void union(OpenBitSet other) {
int newLen = Math.max(wlen,other.wlen);
ensureCapacityWords(newLen);
assert (numBits = Math.max(other.numBits, numBits)) >= 0;
long[] thisArr = this.bits;
long[] otherArr = other.bits;
int pos=Math.min(wlen,other.wlen);
while(--pos>=0) {
thisArr[pos] |= otherArr[pos];
}
if (this.wlen < newLen) {
System.arraycopy(otherArr, this.wlen, thisArr, this.wlen, newLen-this.wlen);
}
this.wlen = newLen;
}
/** Remove all elements set in other. this = this AND_NOT other */
public void remove(OpenBitSet other) {
int idx = Math.min(wlen,other.wlen);
long[] thisArr = this.bits;
long[] otherArr = other.bits;
while(--idx>=0) {
thisArr[idx] &= ~otherArr[idx];
}
}
/** this = this XOR other */
public void xor(OpenBitSet other) {
int newLen = Math.max(wlen,other.wlen);
ensureCapacityWords(newLen);
assert (numBits = Math.max(other.numBits, numBits)) >= 0;
long[] thisArr = this.bits;
long[] otherArr = other.bits;
int pos=Math.min(wlen,other.wlen);
while(--pos>=0) {
thisArr[pos] ^= otherArr[pos];
}
if (this.wlen < newLen) {
System.arraycopy(otherArr, this.wlen, thisArr, this.wlen, newLen-this.wlen);
}
this.wlen = newLen;
}
// some BitSet compatability methods
//** see {@link intersect} */
public void and(OpenBitSet other) {
intersect(other);
}
//** see {@link union} */
public void or(OpenBitSet other) {
union(other);
}
//** see {@link andNot} */
public void andNot(OpenBitSet other) {
remove(other);
}
/** returns true if the sets have any elements in common */
public boolean intersects(OpenBitSet other) {
int pos = Math.min(this.wlen, other.wlen);
long[] thisArr = this.bits;
long[] otherArr = other.bits;
while (--pos>=0) {
if ((thisArr[pos] & otherArr[pos])!=0) return true;
}
return false;
}
/** Expand the long[] with the size given as a number of words (64 bit longs).
* getNumWords() is unchanged by this call.
*/
public void ensureCapacityWords(int numWords) {
if (bits.length < numWords) {
bits = ArrayUtil.grow(bits, numWords);
}
}
/** Ensure that the long[] is big enough to hold numBits, expanding it if necessary.
* getNumWords() is unchanged by this call.
*/
public void ensureCapacity(long numBits) {
ensureCapacityWords(bits2words(numBits));
}
/** Lowers numWords, the number of words in use,
* by checking for trailing zero words.
*/
public void trimTrailingZeros() {
int idx = wlen-1;
while (idx>=0 && bits[idx]==0) idx--;
wlen = idx+1;
}
/** returns the number of 64 bit words it would take to hold numBits */
public static int bits2words(long numBits) {
return (int)(((numBits-1)>>>6)+1);
}
/** returns true if both sets have the same bits set */
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof OpenBitSet)) return false;
OpenBitSet a;
OpenBitSet b = (OpenBitSet)o;
// make a the larger set.
if (b.wlen > this.wlen) {
a = b; b=this;
} else {
a=this;
}
// check for any set bits out of the range of b
for (int i=a.wlen-1; i>=b.wlen; i--) {
if (a.bits[i]!=0) return false;
}
for (int i=b.wlen-1; i>=0; i--) {
if (a.bits[i] != b.bits[i]) return false;
}
return true;
}
@Override
public int hashCode() {
// Start with a zero hash and use a mix that results in zero if the input is zero.
// This effectively truncates trailing zeros without an explicit check.
long h = 0;
for (int i = bits.length; --i>=0;) {
h ^= bits[i];
h = (h << 1) | (h >>> 63); // rotate left
}
// fold leftmost bits into right and add a constant to prevent
// empty sets from returning 0, which is too common.
return (int)((h>>32) ^ h) + 0x98761234;
}
}
|
package com.tle.web.api.institution.interfaces;
import com.tle.web.api.institution.interfaces.beans.InstitutionBean;
import com.tle.web.api.interfaces.Institutional;
import com.tle.web.api.interfaces.Institutional.Type;
import com.tle.web.api.interfaces.beans.SearchBean;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
@Produces({"application/json"})
@Path("institution")
@Api(value = "/institution", description = "institution")
@Institutional(Type.NON_INSTITUTIONAL)
public interface InstitutionResource {
@POST
@Consumes("application/json")
@ApiOperation(value = "Create a new institution")
public Response newInstitution(
@ApiParam(
value = "Which schema (-1 is the first available)",
defaultValue = "-1",
required = false)
@DefaultValue("-1")
@QueryParam("schemaId")
long schemaId,
@ApiParam(value = "The institution bean") final InstitutionBean institutionBean);
@DELETE
@Path("/{uniqueId}")
@ApiOperation(value = "Delete an institution")
public Response deleteInstitution(
@ApiParam("The intitution unique id") @PathParam("uniqueId") long uniqueId);
@GET
@ApiOperation(value = "List institution")
public SearchBean<InstitutionBean> getInstitutions();
@GET
@Path("/{uniqueId}")
@ApiOperation(value = "Get an institution")
public InstitutionBean getInstitution(
@ApiParam("The intitution unique id") @PathParam("uniqueId") long uniqueId);
@PUT
@Path("/{uniqueId}")
@Consumes("application/json")
@ApiOperation(value = "Edit an institution")
public Response editInstitution(
@ApiParam("The intitution unique id") @PathParam("uniqueId") long uniqueId,
@ApiParam(value = "The institution bean") final InstitutionBean institutionBean);
}
|
package io.github.cexj.declarser.csv.stages.annotations.prevalidations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD,ElementType.TYPE})
public @interface CsvPreValidations {
CsvPreValidation[] value();
}
|
package io.subutai.bazaar.share.dto.environment;
public class EnvironmentTelemetryOperation
{
public enum State
{
FAILED, SUCCESS
}
private String containerId;
private String targetHost;
private String command;
private State state;
private int timeout;
private String logs;
public String getContainerId()
{
return containerId;
}
public void setContainerId( final String containerId )
{
this.containerId = containerId;
}
public String getTargetHost()
{
return targetHost;
}
public void setTargetHost( final String targetHost )
{
this.targetHost = targetHost;
}
public String getCommand()
{
return command;
}
public void setCommand( final String command )
{
this.command = command;
}
public State getState()
{
return state;
}
public void setState( final State state )
{
this.state = state;
}
public int getTimeout()
{
return timeout;
}
public void setTimeout( final int timeout )
{
this.timeout = timeout;
}
public String getLogs()
{
return logs;
}
public void setLogs( final String logs )
{
this.logs = logs;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.