text
stringlengths 7
1.01M
|
|---|
package com.cq;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.cq.service.EthWalletService;
import com.cq.task.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.concurrent.Future;
/**
* Created by lin on 2020-11-06.
*/
@Slf4j
@RequiredArgsConstructor
@Component
public class BlockChainActionInitial implements ApplicationRunner {
private final EthWalletService ethWalletService;
@Override
public void run(ApplicationArguments args) throws Exception {
int poolSize = 8;
try {
poolSize = Integer.parseInt(args.getOptionValues("threadPoolSize").get(0));
} catch (Exception e) {
log.error(e.getMessage(), e);
}
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(poolSize);
scheduler.initialize();
String actionName = args.getOptionValues("name").get(0);
if (StrUtil.isEmpty(actionName)) {
throw new RuntimeException("must Set cmd line name");
}
List<String> params = args.getOptionValues("params");
if (actionName.equals(Eth_CreateAddress.class.getSimpleName())) {
scheduler.submit(new Eth_CreateAddress(ethWalletService));
} else if (actionName.equals(Eth_AnalyzeBalance.class.getSimpleName())) {
scheduler.submit(new Eth_AnalyzeBalance(ethWalletService));
} else if (actionName.equals(Eth_Transfer.class.getSimpleName())) {
if (CollectionUtil.isEmpty(params)) {
throw new RuntimeException("Eth_Transfer params is empty. --name=Eth_Transfer --params=\"[from, to, amount, isContract]\" (0 - eth, 1 - contract)");
}
JSONArray ja = JSONUtil.parseArray(params.get(0));
scheduler.submit(new Eth_Transfer(ethWalletService, ja.toArray()));
} else if (actionName.equals(Eth_CollectMain.class.getSimpleName())) {
if (CollectionUtil.isEmpty(params)) {
throw new RuntimeException("Eth_CollectMain params is empty. 0 - eth, 1 - token");
}
Integer type = Integer.parseInt(params.get(0));
scheduler.submit(new Eth_CollectMain(ethWalletService, type));
} else if (actionName.equals(Eth_Obfuscate.class.getSimpleName())) {
scheduler.submit(new Eth_Obfuscate(ethWalletService));
}
}
}
|
package tech.ufun.ranger.system.entity;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
/**
* 字典数据表(SysDictData)实体类
*
* @author zhanglei
* @since 2020-03-12 10:53:00
*/
@Data
@TableName("sys_dict_data")
public class SysDictData {
/**
* 字典数据id
*/
@TableId("dict_data_id")
private Long dictDataId;
/**
* 字典标签
*/
@TableField("dict_label")
private String dictLabel;
/**
* 字典标识
*/
@TableField("dict_key")
private String dictKey;
/**
* 字典值
*/
@TableField("dict_value")
private String dictValue;
/**
* 显示顺序
*/
@TableField("list_order")
private Integer listOrder;
/**
* 是否禁用
*/
@TableField("is_disabled")
private Integer isDisabled;
/**
* 创建人
*/
@TableField("create_by")
private String createBy;
/**
* 创建时间
*/
@TableField("create_time")
private Date createTime;
/**
* 更新人
*/
@TableField("update_by")
private String updateBy;
/**
* 更新时间
*/
@TableField("update_time")
private Date updateTime;
}
|
package edu.hm.chat.persistence.model;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
@Entity
@Table(name = "user_account")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class User {
@Id
@Column(unique = true, nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
@Size(max = 255)
private String firstName;
@NotNull
@Size(max = 255)
private String lastName;
@NotNull
@Size(max = 255)
private String email;
@NotNull
@Size(min = 5, max = 255)
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String password;
@ManyToMany
@JoinTable(
name = "users_roles",
joinColumns = @JoinColumn(
name = "user_id", referencedColumnName = "id"
),
inverseJoinColumns = @JoinColumn(
name = "role_id", referencedColumnName = "id"
)
)
private List<Role> roles;
public User() {
}
public User(User from) {
id = from.id;
firstName = from.firstName;
lastName = from.lastName;
email = from.email;
password = from.password;
roles = from.roles;
}
public Long getId() {
return id;
}
public void setId(final Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(final String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(final String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(final String username) {
this.email = username;
}
public String getPassword() {
return password;
}
public void setPassword(final String password) {
this.password = password;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(final List<Role> roles) {
this.roles = roles;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = (prime * result) + ((email == null) ? 0 : email.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final User user = (User) obj;
return email.equals(user.email);
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", password='" + password + '\'' +
", roles=" + roles +
'}';
}
}
|
// 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.doris.common;
import org.apache.doris.analysis.Analyzer;
import com.google.common.base.Preconditions;
public class TableAliasGenerator extends AliasGenerator {
private static final String DEFAULT_TBL_ALIAS_PREFIX = "$a$";
public TableAliasGenerator(Analyzer analyzer, String prefix) {
Preconditions.checkNotNull(analyzer);
aliasPrefix = prefix != null ? prefix : DEFAULT_TBL_ALIAS_PREFIX;
usedAliases.addAll(analyzer.getAliases());
// Analyzer currentAnalyzer = analyzer;
// do {
// usedAliases.addAll(currentAnalyzer.getAliases());
// usedAliases.addAll(currentAnalyzer.getLocalViews().keySet());
// currentAnalyzer = currentAnalyzer.getParentAnalyzer();
// } while (currentAnalyzer != null);
}
}
|
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2016-2016 Karl Griesser (fullref@gmail.com)
* Copyright (C) 2010-2020 DBeaver Corp and others
*
* 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.jkiss.dbeaver.ext.exasol.model.cache;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.ext.exasol.model.*;
import org.jkiss.dbeaver.ext.exasol.tools.ExasolUtils;
import org.jkiss.dbeaver.model.DBPEvaluationContext;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCSession;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCStatement;
import org.jkiss.dbeaver.model.impl.jdbc.JDBCUtils;
import org.jkiss.dbeaver.model.impl.jdbc.cache.JDBCCompositeCache;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import java.sql.SQLException;
import java.util.List;
/**
* @author Karl
*/
public final class ExasolTableForeignKeyCache
extends JDBCCompositeCache<ExasolSchema, ExasolTable, ExasolTableForeignKey, ExasolTableForeignKeyColumn> {
private static final String SQL_FK_TAB =
"/*snapshot execution*/ select\r\n" +
" CONSTRAINT_NAME,CONSTRAINT_TABLE,CONSTRAINT_SCHEMA,constraint_owner,c.constraint_enabled,constraint_Type," +
"cc.column_name,cc.ordinal_position,cc.referenced_schema,cc.referenced_table,cc.referenced_column" +
" from\r\n" +
" (SELECT * FROM EXA_ALL_CONSTRAINTS " +
" where\r\n" +
" CONSTRAINT_SCHEMA = '%s' and\r\n" +
" CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_TABLE = '%s' \r\n" +
" ORDER BY 1,2,3 \r\n" +
" )c\r\n" +
" inner join\r\n" +
" (SELECT * FROM EXA_ALL_CONSTRAINT_COLUMNS " +
" where\r\n" +
" CONSTRAINT_SCHEMA = '%s' and\r\n" +
" CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_TABLE = '%s' \r\n" +
" ORDER BY 1,2,3 \r\n" +
" ) cc\r\n" +
" using\r\n" +
" (\r\n" +
" CONSTRAINT_SCHEMA, CONSTRAINT_TABLE, CONSTRAINT_NAME, CONSTRAINT_OWNER, CONSTRAINT_TYPE\r\n" +
" )\r\n" +
" where\r\n" +
" CONSTRAINT_SCHEMA = '%s' and\r\n" +
" CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_TABLE = '%s' \r\n" +
" order by\r\n" +
" ORDINAL_POSITION";
private static final String SQL_FK_ALL =
"/*snapshot execution*/ select\r\n" +
" CONSTRAINT_NAME,CONSTRAINT_TABLE,CONSTRAINT_SCHEMA,constraint_owner,c.constraint_enabled,constraint_Type," +
"cc.column_name,cc.ordinal_position,cc.referenced_schema,cc.referenced_table,cc.referenced_column" +
" from\r\n" +
" (SELECT * FROM EXA_ALL_CONSTRAINTS " +
" where\r\n" +
" CONSTRAINT_SCHEMA = '%s' and\r\n" +
" CONSTRAINT_TYPE = 'FOREIGN KEY'\r\n" +
" ORDER BY 1,2,3 \r\n" +
" )c\r\n" +
" inner join\r\n" +
" (SELECT * FROM EXA_ALL_CONSTRAINT_COLUMNS " +
" where\r\n" +
" CONSTRAINT_SCHEMA = '%s' and\r\n" +
" CONSTRAINT_TYPE = 'FOREIGN KEY' \r\n" +
" ORDER BY 1,2,3 \r\n" +
" ) cc\r\n" +
" using\r\n" +
" (\r\n" +
" CONSTRAINT_SCHEMA, CONSTRAINT_TABLE, CONSTRAINT_NAME, CONSTRAINT_OWNER, CONSTRAINT_TYPE\r\n" +
" )\r\n" +
" where\r\n" +
" CONSTRAINT_SCHEMA = '%s' and\r\n" +
" CONSTRAINT_TYPE = 'FOREIGN KEY' \r\n" +
" order by\r\n" +
" ORDINAL_POSITION";
public ExasolTableForeignKeyCache(ExasolTableCache tableCache) {
super(tableCache, ExasolTable.class, "CONSTRAINT_TABLE", "CONSTRAINT_NAME");
}
@NotNull
@Override
protected JDBCStatement prepareObjectsStatement(JDBCSession session, ExasolSchema exasolSchema, ExasolTable forTable)
throws SQLException {
String sql;
if (forTable != null) {
sql = String.format(SQL_FK_TAB,ExasolUtils.quoteString(exasolSchema.getName()),ExasolUtils.quoteString(forTable.getName()),ExasolUtils.quoteString(exasolSchema.getName()),ExasolUtils.quoteString(forTable.getName()),ExasolUtils.quoteString(exasolSchema.getName()),ExasolUtils.quoteString(forTable.getName()));
} else {
sql = String.format(SQL_FK_ALL,ExasolUtils.quoteString(exasolSchema.getName()),ExasolUtils.quoteString(exasolSchema.getName()),ExasolUtils.quoteString(exasolSchema.getName()));
}
JDBCStatement dbStat = session.createStatement();
dbStat.setQueryString(sql);
return dbStat;
}
@Nullable
@Override
protected ExasolTableForeignKey fetchObject(
JDBCSession session, ExasolSchema ExasolSchema, ExasolTable ExasolTable,
String constName, JDBCResultSet dbResult) throws SQLException, DBException
{
return new ExasolTableForeignKey(session.getProgressMonitor(), ExasolTable, dbResult);
}
@Nullable
@Override
protected ExasolTableForeignKeyColumn[] fetchObjectRow(
JDBCSession session, ExasolTable table, ExasolTableForeignKey object,
JDBCResultSet dbResult) throws SQLException, DBException {
String colName = JDBCUtils.safeGetString(dbResult, "COLUMN_NAME");
ExasolTableColumn tableColumn = table.getAttribute(session.getProgressMonitor(), colName);
if (tableColumn == null) {
log.error("ExasolTableForeignKeyCache : Column '" + colName + "' not found in table '" + table.getFullyQualifiedName(DBPEvaluationContext.UI) + "' ??");
return null;
}
ExasolTable refTable = object.getReferencedConstraint() == null ? null : object.getReferencedConstraint().getTable();
if (refTable == null) {
log.error("ExasolTableForeignKeyCache : RefTable not found for FK '" + object.getFullyQualifiedName(DBPEvaluationContext.UI) + "' ??");
return null;
}
String refColName = JDBCUtils.safeGetString(dbResult, "REFERENCED_COLUMN");
ExasolTableColumn refColumn = refTable.getAttribute(session.getProgressMonitor(), refColName);
if (refColumn == null) {
log.error("ExasolTableForeignKeyCache : RefColumn '" + refColName + "' not found in table '" + table.getFullyQualifiedName(DBPEvaluationContext.UI) + "' ??");
return null;
}
return new ExasolTableForeignKeyColumn[]{
new ExasolTableForeignKeyColumn(
object,
tableColumn,
refColumn,
JDBCUtils.safeGetInt(dbResult, "ORDINAL_POSITION"))
};
}
@Override
protected void cacheChildren(DBRProgressMonitor monitor, ExasolTableForeignKey constraint, List<ExasolTableForeignKeyColumn> rows) {
constraint.setColumns(rows);
}
}
|
package com.adventofcode;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import java.io.BufferedReader;
import java.io.FileReader;
import java.nio.charset.Charset;
/**
* Unit test for simple App.
*/
public class AppTest extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest(String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testExamplePartOne() throws Exception {
var file = getClass().getClassLoader().getResource("inputs.txt").getFile();
try(var reader = new BufferedReader(new FileReader(file, Charset.forName("UTF-8")))) {
var rules = BagRuleSet.parse(reader);
assertEquals(4, rules.howManyBagsCanContain("shiny gold"));
}
}
public void testProblemPartOne() throws Exception {
var file = getClass().getClassLoader().getResource("problem.txt").getFile();
try(var reader = new BufferedReader(new FileReader(file, Charset.forName("UTF-8")))) {
var rules = BagRuleSet.parse(reader);
assertEquals(161, rules.howManyBagsCanContain("shiny gold"));
}
}
public void testExamplePartTwo() throws Exception {
var file = getClass().getClassLoader().getResource("inputs.txt").getFile();
try(var reader = new BufferedReader(new FileReader(file, Charset.forName("UTF-8")))) {
var rules = BagRuleSet.parse(reader);
assertEquals(32, rules.howManyBagsAreIn("shiny gold"));
}
}
public void testProblemPartTwo() throws Exception {
var file = getClass().getClassLoader().getResource("problem.txt").getFile();
try(var reader = new BufferedReader(new FileReader(file, Charset.forName("UTF-8")))) {
var rules = BagRuleSet.parse(reader);
assertEquals(30899, rules.howManyBagsAreIn("shiny gold"));
}
}
}
|
/**
* Autogenerated by Thrift Compiler (0.9.3)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package alluxio.thrift;
import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;
import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.protocol.TProtocolException;
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.TException;
import org.apache.thrift.async.AsyncMethodCallback;
import org.apache.thrift.server.AbstractNonblockingServer.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import javax.annotation.Generated;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.3)", date = "2016-05-05")
public class AlluxioService {
public interface Iface {
/**
* Returns the version of the master service.
* NOTE: The version should be updated every time a backwards incompatible API change occurs.
*/
public long getServiceVersion() throws org.apache.thrift.TException;
}
public interface AsyncIface {
public void getServiceVersion(org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException;
}
public static class Client extends org.apache.thrift.TServiceClient implements Iface {
public static class Factory implements org.apache.thrift.TServiceClientFactory<Client> {
public Factory() {}
public Client getClient(org.apache.thrift.protocol.TProtocol prot) {
return new Client(prot);
}
public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
return new Client(iprot, oprot);
}
}
public Client(org.apache.thrift.protocol.TProtocol prot)
{
super(prot, prot);
}
public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
super(iprot, oprot);
}
public long getServiceVersion() throws org.apache.thrift.TException
{
send_getServiceVersion();
return recv_getServiceVersion();
}
public void send_getServiceVersion() throws org.apache.thrift.TException
{
getServiceVersion_args args = new getServiceVersion_args();
sendBase("getServiceVersion", args);
}
public long recv_getServiceVersion() throws org.apache.thrift.TException
{
getServiceVersion_result result = new getServiceVersion_result();
receiveBase(result, "getServiceVersion");
if (result.isSetSuccess()) {
return result.success;
}
throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "getServiceVersion failed: unknown result");
}
}
public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface {
public static class Factory implements org.apache.thrift.async.TAsyncClientFactory<AsyncClient> {
private org.apache.thrift.async.TAsyncClientManager clientManager;
private org.apache.thrift.protocol.TProtocolFactory protocolFactory;
public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) {
this.clientManager = clientManager;
this.protocolFactory = protocolFactory;
}
public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) {
return new AsyncClient(protocolFactory, clientManager, transport);
}
}
public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) {
super(protocolFactory, clientManager, transport);
}
public void getServiceVersion(org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {
checkReady();
getServiceVersion_call method_call = new getServiceVersion_call(resultHandler, this, ___protocolFactory, ___transport);
this.___currentMethod = method_call;
___manager.call(method_call);
}
public static class getServiceVersion_call extends org.apache.thrift.async.TAsyncMethodCall {
public getServiceVersion_call(org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {
super(client, protocolFactory, transport, resultHandler, false);
}
public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {
prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("getServiceVersion", org.apache.thrift.protocol.TMessageType.CALL, 0));
getServiceVersion_args args = new getServiceVersion_args();
args.write(prot);
prot.writeMessageEnd();
}
public long getResult() throws org.apache.thrift.TException {
if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {
throw new IllegalStateException("Method call not finished!");
}
org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());
org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);
return (new Client(prot)).recv_getServiceVersion();
}
}
}
public static class Processor<I extends Iface> extends org.apache.thrift.TBaseProcessor<I> implements org.apache.thrift.TProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(Processor.class.getName());
public Processor(I iface) {
super(iface, getProcessMap(new HashMap<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>>()));
}
protected Processor(I iface, Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {
super(iface, getProcessMap(processMap));
}
private static <I extends Iface> Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> getProcessMap(Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {
processMap.put("getServiceVersion", new getServiceVersion());
return processMap;
}
public static class getServiceVersion<I extends Iface> extends org.apache.thrift.ProcessFunction<I, getServiceVersion_args> {
public getServiceVersion() {
super("getServiceVersion");
}
public getServiceVersion_args getEmptyArgsInstance() {
return new getServiceVersion_args();
}
protected boolean isOneway() {
return false;
}
public getServiceVersion_result getResult(I iface, getServiceVersion_args args) throws org.apache.thrift.TException {
getServiceVersion_result result = new getServiceVersion_result();
result.success = iface.getServiceVersion();
result.setSuccessIsSet(true);
return result;
}
}
}
public static class AsyncProcessor<I extends AsyncIface> extends org.apache.thrift.TBaseAsyncProcessor<I> {
private static final Logger LOGGER = LoggerFactory.getLogger(AsyncProcessor.class.getName());
public AsyncProcessor(I iface) {
super(iface, getProcessMap(new HashMap<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>>()));
}
protected AsyncProcessor(I iface, Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {
super(iface, getProcessMap(processMap));
}
private static <I extends AsyncIface> Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase,?>> getProcessMap(Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {
processMap.put("getServiceVersion", new getServiceVersion());
return processMap;
}
public static class getServiceVersion<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, getServiceVersion_args, Long> {
public getServiceVersion() {
super("getServiceVersion");
}
public getServiceVersion_args getEmptyArgsInstance() {
return new getServiceVersion_args();
}
public AsyncMethodCallback<Long> getResultHandler(final AsyncFrameBuffer fb, final int seqid) {
final org.apache.thrift.AsyncProcessFunction fcall = this;
return new AsyncMethodCallback<Long>() {
public void onComplete(Long o) {
getServiceVersion_result result = new getServiceVersion_result();
result.success = o;
result.setSuccessIsSet(true);
try {
fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);
return;
} catch (Exception e) {
LOGGER.error("Exception writing to internal frame buffer", e);
}
fb.close();
}
public void onError(Exception e) {
byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;
org.apache.thrift.TBase msg;
getServiceVersion_result result = new getServiceVersion_result();
{
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());
}
try {
fcall.sendResponse(fb,msg,msgType,seqid);
return;
} catch (Exception ex) {
LOGGER.error("Exception writing to internal frame buffer", ex);
}
fb.close();
}
};
}
protected boolean isOneway() {
return false;
}
public void start(I iface, getServiceVersion_args args, org.apache.thrift.async.AsyncMethodCallback<Long> resultHandler) throws TException {
iface.getServiceVersion(resultHandler);
}
}
}
public static class getServiceVersion_args implements org.apache.thrift.TBase<getServiceVersion_args, getServiceVersion_args._Fields>, java.io.Serializable, Cloneable, Comparable<getServiceVersion_args> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getServiceVersion_args");
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new getServiceVersion_argsStandardSchemeFactory());
schemes.put(TupleScheme.class, new getServiceVersion_argsTupleSchemeFactory());
}
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
;
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getServiceVersion_args.class, metaDataMap);
}
public getServiceVersion_args() {
}
/**
* Performs a deep copy on <i>other</i>.
*/
public getServiceVersion_args(getServiceVersion_args other) {
}
public getServiceVersion_args deepCopy() {
return new getServiceVersion_args(this);
}
@Override
public void clear() {
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof getServiceVersion_args)
return this.equals((getServiceVersion_args)that);
return false;
}
public boolean equals(getServiceVersion_args that) {
if (that == null)
return false;
return true;
}
@Override
public int hashCode() {
List<Object> list = new ArrayList<Object>();
return list.hashCode();
}
@Override
public int compareTo(getServiceVersion_args other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("getServiceVersion_args(");
boolean first = true;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class getServiceVersion_argsStandardSchemeFactory implements SchemeFactory {
public getServiceVersion_argsStandardScheme getScheme() {
return new getServiceVersion_argsStandardScheme();
}
}
private static class getServiceVersion_argsStandardScheme extends StandardScheme<getServiceVersion_args> {
public void read(org.apache.thrift.protocol.TProtocol iprot, getServiceVersion_args struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, getServiceVersion_args struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class getServiceVersion_argsTupleSchemeFactory implements SchemeFactory {
public getServiceVersion_argsTupleScheme getScheme() {
return new getServiceVersion_argsTupleScheme();
}
}
private static class getServiceVersion_argsTupleScheme extends TupleScheme<getServiceVersion_args> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, getServiceVersion_args struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, getServiceVersion_args struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
}
}
}
public static class getServiceVersion_result implements org.apache.thrift.TBase<getServiceVersion_result, getServiceVersion_result._Fields>, java.io.Serializable, Cloneable, Comparable<getServiceVersion_result> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("getServiceVersion_result");
private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.I64, (short)0);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new getServiceVersion_resultStandardSchemeFactory());
schemes.put(TupleScheme.class, new getServiceVersion_resultTupleSchemeFactory());
}
private long success; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
SUCCESS((short)0, "success");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 0: // SUCCESS
return SUCCESS;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final int __SUCCESS_ISSET_ID = 0;
private byte __isset_bitfield = 0;
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64)));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getServiceVersion_result.class, metaDataMap);
}
public getServiceVersion_result() {
}
public getServiceVersion_result(
long success)
{
this();
this.success = success;
setSuccessIsSet(true);
}
/**
* Performs a deep copy on <i>other</i>.
*/
public getServiceVersion_result(getServiceVersion_result other) {
__isset_bitfield = other.__isset_bitfield;
this.success = other.success;
}
public getServiceVersion_result deepCopy() {
return new getServiceVersion_result(this);
}
@Override
public void clear() {
setSuccessIsSet(false);
this.success = 0;
}
public long getSuccess() {
return this.success;
}
public getServiceVersion_result setSuccess(long success) {
this.success = success;
setSuccessIsSet(true);
return this;
}
public void unsetSuccess() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __SUCCESS_ISSET_ID);
}
/** Returns true if field success is set (has been assigned a value) and false otherwise */
public boolean isSetSuccess() {
return EncodingUtils.testBit(__isset_bitfield, __SUCCESS_ISSET_ID);
}
public void setSuccessIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __SUCCESS_ISSET_ID, value);
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case SUCCESS:
if (value == null) {
unsetSuccess();
} else {
setSuccess((Long)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case SUCCESS:
return getSuccess();
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case SUCCESS:
return isSetSuccess();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof getServiceVersion_result)
return this.equals((getServiceVersion_result)that);
return false;
}
public boolean equals(getServiceVersion_result that) {
if (that == null)
return false;
boolean this_present_success = true;
boolean that_present_success = true;
if (this_present_success || that_present_success) {
if (!(this_present_success && that_present_success))
return false;
if (this.success != that.success)
return false;
}
return true;
}
@Override
public int hashCode() {
List<Object> list = new ArrayList<Object>();
boolean present_success = true;
list.add(present_success);
if (present_success)
list.add(success);
return list.hashCode();
}
@Override
public int compareTo(getServiceVersion_result other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetSuccess()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("getServiceVersion_result(");
boolean first = true;
sb.append("success:");
sb.append(this.success);
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
// it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
__isset_bitfield = 0;
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class getServiceVersion_resultStandardSchemeFactory implements SchemeFactory {
public getServiceVersion_resultStandardScheme getScheme() {
return new getServiceVersion_resultStandardScheme();
}
}
private static class getServiceVersion_resultStandardScheme extends StandardScheme<getServiceVersion_result> {
public void read(org.apache.thrift.protocol.TProtocol iprot, getServiceVersion_result struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 0: // SUCCESS
if (schemeField.type == org.apache.thrift.protocol.TType.I64) {
struct.success = iprot.readI64();
struct.setSuccessIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, getServiceVersion_result struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.isSetSuccess()) {
oprot.writeFieldBegin(SUCCESS_FIELD_DESC);
oprot.writeI64(struct.success);
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class getServiceVersion_resultTupleSchemeFactory implements SchemeFactory {
public getServiceVersion_resultTupleScheme getScheme() {
return new getServiceVersion_resultTupleScheme();
}
}
private static class getServiceVersion_resultTupleScheme extends TupleScheme<getServiceVersion_result> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, getServiceVersion_result struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
BitSet optionals = new BitSet();
if (struct.isSetSuccess()) {
optionals.set(0);
}
oprot.writeBitSet(optionals, 1);
if (struct.isSetSuccess()) {
oprot.writeI64(struct.success);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, getServiceVersion_result struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
BitSet incoming = iprot.readBitSet(1);
if (incoming.get(0)) {
struct.success = iprot.readI64();
struct.setSuccessIsSet(true);
}
}
}
}
}
|
package com.juhyang.memo.post;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.juhyang.memo.post.bo.PostBO;
@RestController
@RequestMapping("/post")
public class PostRestController {
@Autowired
PostBO postBO;
@PostMapping("/create")
public Map<String, String> create(
@RequestParam("content") String content,
@RequestParam("subject") String subject,
@RequestParam(value ="file",required = false )MultipartFile file,
HttpServletRequest request
) {
// 현재 로그인된 사용자의 user table id (pk)
HttpSession session = request.getSession();
int userId = (Integer)session.getAttribute("userId");
int count = postBO.addPost(userId, subject, content, file);
Map<String, String> result = new HashMap<>();
if(count ==1)
{
result.put("result","success");
}
else {
result.put("result", "fail");
}
return result;
}
@GetMapping("/delete")
public Map<String, String> postDelete(@RequestParam("postId") int postId){
Map<String,String> result = new HashMap<>();
int count = postBO.deletePost(postId);
if(count ==1)
{
result.put("result","success");
}
else {
result.put("result", "fail");
}
return result;
}
}
|
package ee.ut.bpmn.utils;
import hub.top.petrinet.PetriNet;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.deckfour.xes.model.XLog;
import org.deckfour.xes.model.XTrace;
import org.jbpt.utils.IOUtils;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.junit.Test;
import utilities.FES.ComparatorFreq;
import utilities.FES.FreqEventStructure;
import utilities.FES.ReducedPrimeEventStructure;
import utilities.FES.Unfolding2ReducedPES;
import ee.ut.bpmn.BPMNProcess;
import ee.ut.eventstr.freq.FrequencyAwarePrimeEventStructure;
import ee.ut.mining.log.AlphaRelations;
import ee.ut.mining.log.XLogReader;
import ee.ut.mining.log.poruns.PORun;
import ee.ut.mining.log.poruns.PORuns;
import ee.ut.mining.log.poruns.fpes.PORuns2FPES;
import ee.ut.nets.unfolding.BPstructBP.MODE;
import ee.ut.nets.unfolding.Unfolder_PetriNet;
public class FPESExample1Test {
private String model =
//"cycle10.bpmn"
//"simpleloop_short"
//"motorlog_short"
//"SyncLoopModel1a"
//"RealExampleGenerated"
//"unbalancedDiagnosisNO"
"Windscreen-GIOManual"
;
private String fileNameTemplate =
//"E:/JavaProjects/workspace/eventstr-confcheck/eventstr-confchecking/logs/%s.mxml.gz"
//"E:/JavaProjects/workspace/eventstr-confcheck/eventstr-confchecking/models/RunningExample/%s.mxml"//.gz"
//"E:/Documents/NICTA/Experimental Logs/Additional logs/%s.mxml"
//"E:/Documents/NICTA/Experimental Logs/BPI-DCC/%s.mxml"
"E:/Documents/NICTA/Experimental Logs/SClogs/%s.xes"
;
@Test
public void test() throws Exception {
//ReducedPrimeEventStructure<Integer> rpes = getUnfoldingPESExample().getRPES();
//printBRMatrix(rpes);
//FreqEventStructure festest = new FreqEventStructure(rpes, rpes.getLabels().toArray(new String[0])); //printBRMatrix(getUnfoldingPESExample().getRPES());
//printFreqMatrix(festest);
FrequencyAwarePrimeEventStructure<Integer> pes1 = getLogPESExample();
System.out.println("PES1 created");
model =
//"simpleloop_short2"
//"motorlog_long"
//"SyncLoopModel1"
//"RealExampleGenerated2"
//"unbalancedDiagnosisYES"
"Windscreen-GIOSkin"
;
FrequencyAwarePrimeEventStructure<Integer> pes2 = getLogPESExample();
//changeFPES(pes2);
System.out.println("PES2 created");
FreqEventStructure fes1 = new FreqEventStructure(pes1.getFreqMatrix(), pes1.getLabels().toArray(new String[0]));
FreqEventStructure fes2 = new FreqEventStructure(pes2.getFreqMatrix(), pes2.getLabels().toArray(new String[0]));
System.out.println("FES1 and 2 created");
//printMatrix(pes1);
//System.out.println();
//printFreqMatrix(pes2);
ComparatorFreq diff = new ComparatorFreq(fes1, fes2);
diff.setZeroThreshold(0.05); //combined values should be at least 5%
diff.setDiffThreshold(0.2); //0.1 means that there should be at least 10% differences
//in the reported frequencies, in order to be counted as a difference
diff.combineValues();
System.out.println(diff.getDifferences(true));
System.out.println("Comparison done");
IOUtils.toFile("fpes.dot", pes1.toDot());
}
public FrequencyAwarePrimeEventStructure<Integer> getLogPESExample() throws Exception {
XLog log = XLogReader.openLog(String.format(fileNameTemplate, model));
AlphaRelations alphaRelations = new AlphaRelations(log);
File target = new File("target");
if (!target.exists())
target.mkdirs();
PORuns runs = new PORuns();
for (XTrace trace: log) {
PORun porun = new PORun(alphaRelations, trace);
runs.add(porun);
}
IOUtils.toFile(model + "_prefix.dot", runs.toDot());
runs.mergePrefix();
IOUtils.toFile(model + "_merged.dot", runs.toDot());
return PORuns2FPES.getPrimeEventStructure(runs, model);
}
public Unfolding2ReducedPES getUnfoldingPESExample() throws JDOMException, IOException {
BPMNProcess<Element> model = BPMN2Reader.parse(new File("eventstr-confchecking/models/AtomicLoopTest/baseLoop.bpmn"));
Petrifier<Element> petrifier = new Petrifier<Element>(model);
PetriNet net = petrifier.petrify(model.getSources().iterator().next(), model.getSinks().iterator().next());
System.out.println(model.getLabels());
Set<String> labels = new HashSet<>();
for (Integer node: model.getVisibleNodes())
labels.add(model.getName(node));
Unfolder_PetriNet unfolder = new Unfolder_PetriNet(net, MODE.ONEUNFOLDING);
unfolder.computeUnfolding();
PetriNet bp = unfolder.getUnfoldingAsPetriNet();
IOUtils.toFile("net.dot", net.toDot());
IOUtils.toFile("bp.dot", bp.toDot());
Unfolding2ReducedPES pes = new Unfolding2ReducedPES(unfolder.getSys(), unfolder.getBP(), labels);
IOUtils.toFile("bpmnpes.dot", pes.getPES().toDot());
return pes;
}
public void changeFPES(FrequencyAwarePrimeEventStructure<Integer> pes) {
for (int i = 0; i < pes.getFreqMatrix().length; i++) {
for (int j = 0; j < pes.getFreqMatrix().length; j++) {
if ((pes.getFreqMatrix()[i][j] > 0) && (pes.getFreqMatrix()[i][j] < 1)) {
if (pes.getFreqMatrix()[i][j] > 0.5) {
pes.getFreqMatrix()[i][j] -= 0.3;
}
else {
pes.getFreqMatrix()[i][j] += 0.3;
}
}
}
}
}
public void printNet(Unfolder_PetriNet uf) {
for (int i = 0; i < uf.getBP().getBranchingProcess().allEvents.size(); i++) {
//uf.getBP().getBranchingProcess().allEvents.get(i).post
System.out.print(uf.getSys().properNames[uf.getBP().getBranchingProcess().allEvents.get(i).id] + " ");
}
System.out.println();
}
public void printBRMatrix(ReducedPrimeEventStructure<Integer> pes) {
System.out.println(pes.getLabels());
for (int i = 0; i < pes.getBRelMatrix().length; i++) {
for (int j = 0; j < pes.getBRelMatrix().length; j++) {
System.out.print(pes.getBRelMatrix()[i][j] + " ");
}
System.out.println();
}
}
public void printFreqMatrix(FrequencyAwarePrimeEventStructure<Integer> pes) {
System.out.println(pes.getLabels());
for (int i = 0; i < pes.getFreqMatrix().length; i++) {
for (int j = 0; j < pes.getFreqMatrix().length; j++) {
System.out.print(pes.getFreqMatrix()[i][j] + " ");
}
System.out.println();
}
}
public void printFreqMatrix(FreqEventStructure fes) {
for (int i = 0; i < fes.getLabels().length; i++) {
System.out.print(fes.getLabels()[i] + " ");
}
System.out.println();
for (int i = 0; i < fes.getMatrix().length; i++) {
for (int j = 0; j < fes.getMatrix().length; j++) {
System.out.print(fes.getMatrix()[i][j] + " ");
}
System.out.println();
}
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.hyracks.storage.am.common.impls;
import java.util.ArrayList;
import java.util.List;
import org.apache.hyracks.api.dataflow.value.IValueReference;
import org.apache.hyracks.api.exceptions.ErrorCode;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.storage.am.common.api.IPageManager;
import org.apache.hyracks.storage.am.common.api.ITreeIndex;
import org.apache.hyracks.storage.am.common.api.ITreeIndexFrame;
import org.apache.hyracks.storage.am.common.api.ITreeIndexFrameFactory;
import org.apache.hyracks.storage.am.common.api.ITreeIndexMetadataFrame;
import org.apache.hyracks.storage.am.common.api.ITreeIndexTupleWriter;
import org.apache.hyracks.storage.common.IIndexBulkLoader;
import org.apache.hyracks.storage.common.MultiComparator;
import org.apache.hyracks.storage.common.buffercache.IBufferCache;
import org.apache.hyracks.storage.common.buffercache.ICachedPage;
import org.apache.hyracks.storage.common.buffercache.IFIFOPageWriter;
import org.apache.hyracks.storage.common.buffercache.IPageWriteCallback;
import org.apache.hyracks.storage.common.buffercache.PageWriteFailureCallback;
import org.apache.hyracks.storage.common.compression.file.ICompressedPageWriter;
import org.apache.hyracks.storage.common.file.BufferedFileHandle;
public abstract class AbstractTreeIndexBulkLoader extends PageWriteFailureCallback implements IIndexBulkLoader {
protected final IBufferCache bufferCache;
protected final IPageManager freePageManager;
protected final AbstractTreeIndex treeIndex;
protected final int fileId;
protected final MultiComparator cmp;
protected final int slotSize;
protected final int leafMaxBytes;
protected final int interiorMaxBytes;
protected final ArrayList<NodeFrontier> nodeFrontiers = new ArrayList<>();
protected final ITreeIndexMetadataFrame metaFrame;
protected final ITreeIndexTupleWriter tupleWriter;
protected ITreeIndexFrame leafFrame;
protected ITreeIndexFrame interiorFrame;
// Immutable bulk loaders write their root page at page -2, as needed e.g. by append-only file systems such as
// HDFS. Since loading this tree relies on the root page actually being at that point, no further inserts into
// that tree are allowed. Currently, this is not enforced.
protected boolean releasedLatches;
private final IFIFOPageWriter pageWriter;
protected List<ICachedPage> pagesToWrite;
private final ICompressedPageWriter compressedPageWriter;
public AbstractTreeIndexBulkLoader(float fillFactor, IPageWriteCallback callback, ITreeIndex index)
throws HyracksDataException {
this(fillFactor, callback, index, index.getLeafFrameFactory());
}
public AbstractTreeIndexBulkLoader(float fillFactor, IPageWriteCallback callback, ITreeIndex index,
ITreeIndexFrameFactory leafFrameFactory) throws HyracksDataException {
this.bufferCache = index.getBufferCache();
this.freePageManager = index.getPageManager();
this.fileId = index.getFileId();
this.treeIndex = (AbstractTreeIndex) index;
leafFrame = leafFrameFactory.createFrame();
interiorFrame = treeIndex.getInteriorFrameFactory().createFrame();
metaFrame = freePageManager.createMetadataFrame();
pageWriter = bufferCache.createFIFOWriter(callback, this);
compressedPageWriter = bufferCache.getCompressedPageWriter(fileId);
if (!treeIndex.isEmptyTree(leafFrame)) {
throw HyracksDataException.create(ErrorCode.CANNOT_BULK_LOAD_NON_EMPTY_TREE);
}
this.cmp = MultiComparator.create(treeIndex.getCmpFactories());
leafFrame.setMultiComparator(cmp);
interiorFrame.setMultiComparator(cmp);
tupleWriter = getTupleWriter();
NodeFrontier leafFrontier = new NodeFrontier(tupleWriter.createTupleReference());
leafFrontier.pageId = freePageManager.takePage(metaFrame);
leafFrontier.page = bufferCache.confiscatePage(BufferedFileHandle.getDiskPageId(fileId, leafFrontier.pageId));
interiorFrame.setPage(leafFrontier.page);
interiorMaxBytes = (int) (interiorFrame.getBuffer().capacity() * fillFactor);
leafFrame.setPage(leafFrontier.page);
leafMaxBytes = (int) (leafFrame.getBuffer().capacity() * fillFactor);
slotSize = leafFrame.getSlotSize();
nodeFrontiers.add(leafFrontier);
pagesToWrite = new ArrayList<>();
}
@Override
public void init(IValueReference writerMetadata) throws HyracksDataException {
interiorFrame.initBuffer((byte) 0);
leafFrame.initBuffer((byte) 0);
}
protected void handleException() {
// Unlatch and unpin pages that weren't in the queue to avoid leaking memory.
compressedPageWriter.abort();
for (NodeFrontier nodeFrontier : nodeFrontiers) {
ICachedPage frontierPage = nodeFrontier.page;
if (frontierPage.confiscated()) {
bufferCache.returnPage(frontierPage, false);
}
}
for (ICachedPage pageToDiscard : pagesToWrite) {
bufferCache.returnPage(pageToDiscard, false);
}
releasedLatches = true;
}
@Override
public void end() throws HyracksDataException {
if (hasFailed()) {
throw HyracksDataException.create(getFailure());
}
freePageManager.setRootPageId(treeIndex.getRootPageId());
}
protected void setRootPageId(int rootPage) {
treeIndex.rootPage = rootPage;
}
protected void addLevel() throws HyracksDataException {
NodeFrontier frontier = new NodeFrontier(tupleWriter.createTupleReference());
frontier.page = bufferCache.confiscatePage(IBufferCache.INVALID_DPID);
frontier.pageId = -1;
frontier.lastTuple.setFieldCount(cmp.getKeyFieldCount());
interiorFrame.setPage(frontier.page);
interiorFrame.initBuffer((byte) nodeFrontiers.size());
nodeFrontiers.add(frontier);
}
protected ITreeIndexTupleWriter getTupleWriter() {
return leafFrame.getTupleWriter();
}
public ITreeIndexFrame getLeafFrame() {
return leafFrame;
}
public void setLeafFrame(ITreeIndexFrame leafFrame) {
this.leafFrame = leafFrame;
}
public void write(ICachedPage cPage) throws HyracksDataException {
compressedPageWriter.prepareWrite(cPage);
pageWriter.write(cPage);
}
@Override
public void force() throws HyracksDataException {
bufferCache.force(fileId, false);
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.jmeter.gui.action;
import java.awt.event.ActionEvent;
import java.util.HashSet;
import java.util.Set;
import org.apache.logging.log4j.core.config.Configurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.event.Level;
/**
* Implements log level setting menu item.
* @since 3.2
*/
public class LogLevelCommand extends AbstractAction {
private static final Logger log = LoggerFactory.getLogger(LogLevelCommand.class);
private static final Set<String> commands = new HashSet<>();
static {
for (Level level : Level.values()) {
commands.add(ActionNames.LOG_LEVEL_PREFIX + level.toString());
}
}
public LogLevelCommand() {
super();
}
@Override
public void doAction(ActionEvent ev) {
String levelString = ev.getActionCommand().substring(ActionNames.LOG_LEVEL_PREFIX.length());
log.warn("Setting root log level: {}", levelString);
Configurator.setRootLevel(org.apache.logging.log4j.Level.toLevel(levelString));
}
@Override
public Set<String> getActionNames() {
return commands;
}
}
|
/*
*
* Copyright (c) 2014, RWTH Aachen University.
* For a list of contributors see the AUTHORS file at the top-level directory
* of this distribution.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* /
*/
package de.rwth.dbis.acis.bazaar.service.dal.entities;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* @author Adam Gavronek <gavronek@dbis.rwth-aachen.de>
* @since 9/16/2014
*/
public abstract class EntityBase implements IdentifiedById {
public String toJSON() throws JsonProcessingException {
return new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL).writeValueAsString(this);
}
}
|
package com.knight.wanandroid.library_network.config;
import com.knight.wanandroid.library_network.data.BodyType;
import com.knight.wanandroid.library_network.data.CacheMode;
/**
* @author created by knight
* @organize wanandroid
* @Date 2020/12/25 17:30
* @descript:请求服务配置
*/
public interface IRequestServer extends
IRequestHost, IRequestPath, IRequestClient,IRequestType,IRequestCache {
@Override
default BodyType getType() {
// 默认以Json的方式提交
return BodyType.FORM;
}
@Override
default CacheMode getMode() {
// 默认的缓存方式
return CacheMode.DEFAULT;
}
@Override
default String getPath() {
// 服务器路径可填可不填
return "";
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.containers.containerregistry.implementation.models;
import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.OffsetDateTime;
import java.util.HashMap;
import java.util.Map;
/** Additional information provided through arbitrary metadata. */
@Fluent
public final class Annotations {
/*
* Date and time on which the image was built (string, date-time as defined
* by https://tools.ietf.org/html/rfc3339#section-5.6)
*/
@JsonProperty(value = "org.opencontainers.image.created")
private OffsetDateTime created;
/*
* Contact details of the people or organization responsible for the image.
*/
@JsonProperty(value = "org.opencontainers.image.authors")
private String authors;
/*
* URL to find more information on the image.
*/
@JsonProperty(value = "org.opencontainers.image.url")
private String url;
/*
* URL to get documentation on the image.
*/
@JsonProperty(value = "org.opencontainers.image.documentation")
private String documentation;
/*
* URL to get source code for building the image.
*/
@JsonProperty(value = "org.opencontainers.image.source")
private String source;
/*
* Version of the packaged software. The version MAY match a label or tag
* in the source code repository, may also be Semantic
* versioning-compatible
*/
@JsonProperty(value = "org.opencontainers.image.version")
private String version;
/*
* Source control revision identifier for the packaged software.
*/
@JsonProperty(value = "org.opencontainers.image.revision")
private String revision;
/*
* Name of the distributing entity, organization or individual.
*/
@JsonProperty(value = "org.opencontainers.image.vendor")
private String vendor;
/*
* License(s) under which contained software is distributed as an SPDX
* License Expression.
*/
@JsonProperty(value = "org.opencontainers.image.licenses")
private String licenses;
/*
* Name of the reference for a target.
*/
@JsonProperty(value = "org.opencontainers.image.ref.name")
private String name;
/*
* Human-readable title of the image
*/
@JsonProperty(value = "org.opencontainers.image.title")
private String title;
/*
* Human-readable description of the software packaged in the image
*/
@JsonProperty(value = "org.opencontainers.image.description")
private String description;
/*
* Additional information provided through arbitrary metadata.
*/
@JsonIgnore private Map<String, Object> additionalProperties;
/**
* Get the created property: Date and time on which the image was built (string, date-time as defined by
* https://tools.ietf.org/html/rfc3339#section-5.6).
*
* @return the created value.
*/
public OffsetDateTime getCreated() {
return this.created;
}
/**
* Set the created property: Date and time on which the image was built (string, date-time as defined by
* https://tools.ietf.org/html/rfc3339#section-5.6).
*
* @param created the created value to set.
* @return the Annotations object itself.
*/
public Annotations setCreated(OffsetDateTime created) {
this.created = created;
return this;
}
/**
* Get the authors property: Contact details of the people or organization responsible for the image.
*
* @return the authors value.
*/
public String getAuthors() {
return this.authors;
}
/**
* Set the authors property: Contact details of the people or organization responsible for the image.
*
* @param authors the authors value to set.
* @return the Annotations object itself.
*/
public Annotations setAuthors(String authors) {
this.authors = authors;
return this;
}
/**
* Get the url property: URL to find more information on the image.
*
* @return the url value.
*/
public String getUrl() {
return this.url;
}
/**
* Set the url property: URL to find more information on the image.
*
* @param url the url value to set.
* @return the Annotations object itself.
*/
public Annotations setUrl(String url) {
this.url = url;
return this;
}
/**
* Get the documentation property: URL to get documentation on the image.
*
* @return the documentation value.
*/
public String getDocumentation() {
return this.documentation;
}
/**
* Set the documentation property: URL to get documentation on the image.
*
* @param documentation the documentation value to set.
* @return the Annotations object itself.
*/
public Annotations setDocumentation(String documentation) {
this.documentation = documentation;
return this;
}
/**
* Get the source property: URL to get source code for building the image.
*
* @return the source value.
*/
public String getSource() {
return this.source;
}
/**
* Set the source property: URL to get source code for building the image.
*
* @param source the source value to set.
* @return the Annotations object itself.
*/
public Annotations setSource(String source) {
this.source = source;
return this;
}
/**
* Get the version property: Version of the packaged software. The version MAY match a label or tag in the source
* code repository, may also be Semantic versioning-compatible.
*
* @return the version value.
*/
public String getVersion() {
return this.version;
}
/**
* Set the version property: Version of the packaged software. The version MAY match a label or tag in the source
* code repository, may also be Semantic versioning-compatible.
*
* @param version the version value to set.
* @return the Annotations object itself.
*/
public Annotations setVersion(String version) {
this.version = version;
return this;
}
/**
* Get the revision property: Source control revision identifier for the packaged software.
*
* @return the revision value.
*/
public String getRevision() {
return this.revision;
}
/**
* Set the revision property: Source control revision identifier for the packaged software.
*
* @param revision the revision value to set.
* @return the Annotations object itself.
*/
public Annotations setRevision(String revision) {
this.revision = revision;
return this;
}
/**
* Get the vendor property: Name of the distributing entity, organization or individual.
*
* @return the vendor value.
*/
public String getVendor() {
return this.vendor;
}
/**
* Set the vendor property: Name of the distributing entity, organization or individual.
*
* @param vendor the vendor value to set.
* @return the Annotations object itself.
*/
public Annotations setVendor(String vendor) {
this.vendor = vendor;
return this;
}
/**
* Get the licenses property: License(s) under which contained software is distributed as an SPDX License
* Expression.
*
* @return the licenses value.
*/
public String getLicenses() {
return this.licenses;
}
/**
* Set the licenses property: License(s) under which contained software is distributed as an SPDX License
* Expression.
*
* @param licenses the licenses value to set.
* @return the Annotations object itself.
*/
public Annotations setLicenses(String licenses) {
this.licenses = licenses;
return this;
}
/**
* Get the name property: Name of the reference for a target.
*
* @return the name value.
*/
public String getName() {
return this.name;
}
/**
* Set the name property: Name of the reference for a target.
*
* @param name the name value to set.
* @return the Annotations object itself.
*/
public Annotations setName(String name) {
this.name = name;
return this;
}
/**
* Get the title property: Human-readable title of the image.
*
* @return the title value.
*/
public String getTitle() {
return this.title;
}
/**
* Set the title property: Human-readable title of the image.
*
* @param title the title value to set.
* @return the Annotations object itself.
*/
public Annotations setTitle(String title) {
this.title = title;
return this;
}
/**
* Get the description property: Human-readable description of the software packaged in the image.
*
* @return the description value.
*/
public String getDescription() {
return this.description;
}
/**
* Set the description property: Human-readable description of the software packaged in the image.
*
* @param description the description value to set.
* @return the Annotations object itself.
*/
public Annotations setDescription(String description) {
this.description = description;
return this;
}
/**
* Get the additionalProperties property: Additional information provided through arbitrary metadata.
*
* @return the additionalProperties value.
*/
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
/**
* Set the additionalProperties property: Additional information provided through arbitrary metadata.
*
* @param additionalProperties the additionalProperties value to set.
* @return the Annotations object itself.
*/
public Annotations setAdditionalProperties(Map<String, Object> additionalProperties) {
this.additionalProperties = additionalProperties;
return this;
}
@JsonAnySetter
void setAdditionalProperties(String key, Object value) {
if (additionalProperties == null) {
additionalProperties = new HashMap<>();
}
additionalProperties.put(key, value);
}
}
|
package org.mage.test.cards.mana;
import mage.constants.PhaseStep;
import mage.constants.Zone;
import org.junit.Test;
import org.mage.test.serverside.base.CardTestPlayerBase;
/**
* Added this test class to test issue #5880.
* https://github.com/magefree/mage/issues/5880
*
* Chandra's Embercat's effect could not be used on Chandra planeswalkers.
*
* Card Type: Creature — Elemental Cat
* P/T: 2 / 2
* Description: T: Add R. Spend this mana only to cast an Elemental spell or a Chandra planeswalker spell.
* @author jgray1206
*/
public class ChandrasEmbercatTest extends CardTestPlayerBase {
// Make sure we can use the mana to cast elementals
@Test
public void testCanCastElementalWithMana() {
addCard(Zone.BATTLEFIELD, playerA, "Plains", 1);
addCard(Zone.BATTLEFIELD, playerA, "Chandra's Embercat", 1);
//An elemental creature that costs {1}{R}
addCard(Zone.HAND, playerA, "Chandra's Embercat", 1);
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Chandra's Embercat");
setStopAt(1, PhaseStep.BEGIN_COMBAT);
execute();
assertPermanentCount(playerA, "Chandra's Embercat", 2);
}
// Make sure we can use the mana to cast Chandra Planeswalkers
@Test
public void testCanCastChandraPlaneswalkerWithMana() {
addCard(Zone.BATTLEFIELD, playerA, "Plains", 3);
addCard(Zone.BATTLEFIELD, playerA, "Chandra's Embercat", 1);
//A Chandra Planeswalker that costs {3}{R}
addCard(Zone.HAND, playerA, "Chandra, Novice Pyromancer", 1);
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Chandra, Novice Pyromancer");
setStopAt(1, PhaseStep.BEGIN_COMBAT);
execute();
assertPermanentCount(playerA, "Chandra, Novice Pyromancer", 1);
}
// Make sure we cant use the mana to cast non-Chandra Planeswalkers
@Test
public void testCantCastNonChandraPlaneswalkerWithMana() {
addCard(Zone.BATTLEFIELD, playerA, "Island", 3);
addCard(Zone.BATTLEFIELD, playerA, "Chandra's Embercat", 1);
//A non-Chandra planeswalker that costs {2}{U}{U}
addCard(Zone.HAND, playerA, "Jace, the Mind Sculptor", 1);
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Jace, the Mind Sculptor");
setStopAt(1, PhaseStep.BEGIN_COMBAT);
execute();
assertPermanentCount(playerA, "Jace, the Mind Sculptor", 0);
}
// Make sure we cant use the mana to cast non-Elemental creatures
@Test
public void testCantCastNonElementalCreatureWithMana() {
addCard(Zone.BATTLEFIELD, playerA, "Island", 1);
addCard(Zone.BATTLEFIELD, playerA, "Chandra's Embercat", 1);
//A non-elemental creature that costs {1}{R}
addCard(Zone.HAND, playerA, "Raptor Hatchling", 1);
castSpell(1, PhaseStep.PRECOMBAT_MAIN, playerA, "Raptor Hatchling");
setStopAt(1, PhaseStep.BEGIN_COMBAT);
execute();
assertPermanentCount(playerA, "Raptor Hatchling", 0);
}
}
|
package daniele.state;
import it.unibo.ai.didattica.competition.tablut.domain.State;
public class ExtendedState extends State{
public void setPawn(int row, int column,Pawn p) {
this.board[row][column] = p;
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.opensymphony.xwork2.config.providers;
import com.opensymphony.xwork2.ObjectFactory;
import com.opensymphony.xwork2.SimpleAction;
import com.opensymphony.xwork2.config.ConfigurationException;
import com.opensymphony.xwork2.config.ConfigurationProvider;
import com.opensymphony.xwork2.config.entities.*;
import com.opensymphony.xwork2.mock.MockInterceptor;
import com.opensymphony.xwork2.mock.MockResult;
import org.apache.struts2.interceptor.NoOpInterceptor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Mike
* @author Rainer Hermanns
*/
public class XmlConfigurationProviderActionsTest extends ConfigurationTestBase {
private List<InterceptorMapping> interceptors;
private List<ExceptionMappingConfig> exceptionMappings;
private Map<String, String> params;
private Map<String, ResultConfig> results;
private ObjectFactory objectFactory;
public void testActions() throws Exception {
final String filename = "com/opensymphony/xwork2/config/providers/xwork-test-actions.xml";
ConfigurationProvider provider = buildConfigurationProvider(filename);
// setup expectations
// bar action is very simple, just two params
params.put("foo", "17");
params.put("bar", "23");
params.put("testXW412", "foo.jspa?fooID=${fooID}&something=bar");
params.put("testXW412Again", "something");
ActionConfig barAction = new ActionConfig.Builder("", "Bar", SimpleAction.class.getName())
.addParams(params).build();
// foo action is a little more complex, two params, a result and an interceptor stack
results = new HashMap<>();
params = new HashMap<>();
params.put("foo", "18");
params.put("bar", "24");
results.put("success", new ResultConfig.Builder("success", MockResult.class.getName()).build());
InterceptorConfig noopInterceptorConfig = new InterceptorConfig.Builder("noop", NoOpInterceptor.class.getName()).build();
interceptors.add(new InterceptorMapping("noop", objectFactory.buildInterceptor(noopInterceptorConfig, new HashMap<String, String>())));
ActionConfig fooAction = new ActionConfig.Builder("", "Foo", SimpleAction.class.getName())
.addParams(params)
.addResultConfigs(results)
.addInterceptors(interceptors)
.build();
// wildcard action is simple wildcard example
results = new HashMap<>();
results.put("*", new ResultConfig.Builder("*", MockResult.class.getName()).build());
ActionConfig wildcardAction = new ActionConfig.Builder("", "WildCard", SimpleAction.class.getName())
.addResultConfigs(results)
.addInterceptors(interceptors)
.build();
// fooBar action is a little more complex, two params, a result and an interceptor stack
params = new HashMap<String, String>();
params.put("foo", "18");
params.put("bar", "24");
results = new HashMap<>();
results.put("success", new ResultConfig.Builder("success", MockResult.class.getName()).build());
ExceptionMappingConfig exceptionConfig = new ExceptionMappingConfig.Builder("runtime", "java.lang.RuntimeException", "exception")
.build();
exceptionMappings.add(exceptionConfig);
ActionConfig fooBarAction = new ActionConfig.Builder("", "FooBar", SimpleAction.class.getName())
.addParams(params)
.addResultConfigs(results)
.addInterceptors(interceptors)
.addExceptionMappings(exceptionMappings)
.build();
// TestInterceptorParam action tests that an interceptor worked
HashMap<String, String> interceptorParams = new HashMap<>();
interceptorParams.put("expectedFoo", "expectedFooValue");
interceptorParams.put("foo", MockInterceptor.DEFAULT_FOO_VALUE);
InterceptorConfig mockInterceptorConfig = new InterceptorConfig.Builder("test", MockInterceptor.class.getName()).build();
interceptors = new ArrayList<>();
interceptors.add(new InterceptorMapping("test", objectFactory.buildInterceptor(mockInterceptorConfig, interceptorParams)));
ActionConfig intAction = new ActionConfig.Builder("", "TestInterceptorParam", SimpleAction.class.getName())
.addInterceptors(interceptors)
.build();
// TestInterceptorParamOverride action tests that an interceptor with a param override worked
interceptorParams = new HashMap<>();
interceptorParams.put("expectedFoo", "expectedFooValue");
interceptorParams.put("foo", "foo123");
interceptors = new ArrayList<>();
interceptors.add(new InterceptorMapping("test", objectFactory.buildInterceptor(mockInterceptorConfig, interceptorParams)));
ActionConfig intOverAction = new ActionConfig.Builder("", "TestInterceptorParamOverride", SimpleAction.class.getName())
.addInterceptors(interceptors)
.build();
// execute the configuration
provider.init(configuration);
provider.loadPackages();
PackageConfig pkg = configuration.getPackageConfig("default");
Map actionConfigs = pkg.getActionConfigs();
// assertions
assertEquals(7, actionConfigs.size());
assertEquals(barAction, actionConfigs.get("Bar"));
assertEquals(fooAction, actionConfigs.get("Foo"));
assertEquals(wildcardAction, actionConfigs.get("WildCard"));
assertEquals(fooBarAction, actionConfigs.get("FooBar"));
assertEquals(intAction, actionConfigs.get("TestInterceptorParam"));
assertEquals(intOverAction, actionConfigs.get("TestInterceptorParamOverride"));
}
public void testInvalidActions() throws Exception {
final String filename = "com/opensymphony/xwork2/config/providers/xwork-test-action-invalid.xml";
try {
ConfigurationProvider provider = buildConfigurationProvider(filename);
fail("Should have thrown an exception");
} catch (ConfigurationException ex) {
// it worked correctly
}
}
public void testPackageDefaultClassRef() throws Exception {
final String filename = "com/opensymphony/xwork2/config/providers/xwork-test-actions-packagedefaultclassref.xml";
final String testDefaultClassName = "com.opensymphony.xwork2.UserSpecifiedDefaultAction";
ConfigurationProvider provider = buildConfigurationProvider(filename);
// setup expectations
params.put("foo", "17");
params.put("bar", "23");
ActionConfig barWithPackageDefaultClassRefConfig =
new ActionConfig.Builder("", "Bar", "")
.addParams(params)
.build();
// execute the configuration
provider.init(configuration);
PackageConfig pkg = configuration.getPackageConfig("default");
Map actionConfigs = pkg.getActionConfigs();
// assertions
assertEquals(1, actionConfigs.size());
assertEquals(barWithPackageDefaultClassRefConfig, actionConfigs.get("Bar"));
}
public void testDefaultActionClass() throws Exception {
final String filename = "com/opensymphony/xwork2/config/providers/xwork-test-actions.xml";
final String testDefaultClassName = "com.opensymphony.xwork2.ActionSupport";
ConfigurationProvider provider = buildConfigurationProvider(filename);
// setup expectations
params.put("foo", "17");
params.put("bar", "23");
ActionConfig barWithoutClassNameConfig =
new ActionConfig.Builder("", "BarWithoutClassName", "")
.addParams(params)
.build();
// execute the configuration
provider.init(configuration);
PackageConfig pkg = configuration.getPackageConfig("default");
Map actionConfigs = pkg.getActionConfigs();
// assertions
assertEquals(7, actionConfigs.size());
assertEquals(barWithoutClassNameConfig, actionConfigs.get("BarWithoutClassName"));
}
@Override
protected void setUp() throws Exception {
super.setUp();
params = new HashMap<>();
results = new HashMap<>();
interceptors = new ArrayList<>();
exceptionMappings = new ArrayList<>();
this.objectFactory = container.getInstance(ObjectFactory.class);
}
}
|
/*
* Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. 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.tencentcloudapi.dcdb.v20180411.models;
import com.tencentcloudapi.common.AbstractModel;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import java.util.HashMap;
public class CreateAccountRequest extends AbstractModel{
/**
* 实例 ID,形如:dcdbt-ow728lmc,可以通过 DescribeDCDBInstances 查询实例详情获得。
*/
@SerializedName("InstanceId")
@Expose
private String InstanceId;
/**
* AccountName
*/
@SerializedName("UserName")
@Expose
private String UserName;
/**
* 可以登录的主机,与mysql 账号的 host 格式一致,可以支持通配符,例如 %,10.%,10.20.%。
*/
@SerializedName("Host")
@Expose
private String Host;
/**
* 账号密码,由字母、数字或常见符号组成,不能包含分号、单引号和双引号,长度为6~32位。
*/
@SerializedName("Password")
@Expose
private String Password;
/**
* 是否创建为只读账号,0:否, 1:该账号的sql请求优先选择备机执行,备机不可用时选择主机执行,2:优先选择备机执行,备机不可用时操作失败,3:只从备机读取。
*/
@SerializedName("ReadOnly")
@Expose
private Long ReadOnly;
/**
* 账号备注,可以包含中文、英文字符、常见符号和数字,长度为0~256字符
*/
@SerializedName("Description")
@Expose
private String Description;
/**
* 如果备机延迟超过本参数设置值,系统将认为备机发生故障
建议该参数值大于10。当ReadOnly选择1、2时该参数生效。
*/
@SerializedName("DelayThresh")
@Expose
private Long DelayThresh;
/**
* Get 实例 ID,形如:dcdbt-ow728lmc,可以通过 DescribeDCDBInstances 查询实例详情获得。
* @return InstanceId 实例 ID,形如:dcdbt-ow728lmc,可以通过 DescribeDCDBInstances 查询实例详情获得。
*/
public String getInstanceId() {
return this.InstanceId;
}
/**
* Set 实例 ID,形如:dcdbt-ow728lmc,可以通过 DescribeDCDBInstances 查询实例详情获得。
* @param InstanceId 实例 ID,形如:dcdbt-ow728lmc,可以通过 DescribeDCDBInstances 查询实例详情获得。
*/
public void setInstanceId(String InstanceId) {
this.InstanceId = InstanceId;
}
/**
* Get AccountName
* @return UserName AccountName
*/
public String getUserName() {
return this.UserName;
}
/**
* Set AccountName
* @param UserName AccountName
*/
public void setUserName(String UserName) {
this.UserName = UserName;
}
/**
* Get 可以登录的主机,与mysql 账号的 host 格式一致,可以支持通配符,例如 %,10.%,10.20.%。
* @return Host 可以登录的主机,与mysql 账号的 host 格式一致,可以支持通配符,例如 %,10.%,10.20.%。
*/
public String getHost() {
return this.Host;
}
/**
* Set 可以登录的主机,与mysql 账号的 host 格式一致,可以支持通配符,例如 %,10.%,10.20.%。
* @param Host 可以登录的主机,与mysql 账号的 host 格式一致,可以支持通配符,例如 %,10.%,10.20.%。
*/
public void setHost(String Host) {
this.Host = Host;
}
/**
* Get 账号密码,由字母、数字或常见符号组成,不能包含分号、单引号和双引号,长度为6~32位。
* @return Password 账号密码,由字母、数字或常见符号组成,不能包含分号、单引号和双引号,长度为6~32位。
*/
public String getPassword() {
return this.Password;
}
/**
* Set 账号密码,由字母、数字或常见符号组成,不能包含分号、单引号和双引号,长度为6~32位。
* @param Password 账号密码,由字母、数字或常见符号组成,不能包含分号、单引号和双引号,长度为6~32位。
*/
public void setPassword(String Password) {
this.Password = Password;
}
/**
* Get 是否创建为只读账号,0:否, 1:该账号的sql请求优先选择备机执行,备机不可用时选择主机执行,2:优先选择备机执行,备机不可用时操作失败,3:只从备机读取。
* @return ReadOnly 是否创建为只读账号,0:否, 1:该账号的sql请求优先选择备机执行,备机不可用时选择主机执行,2:优先选择备机执行,备机不可用时操作失败,3:只从备机读取。
*/
public Long getReadOnly() {
return this.ReadOnly;
}
/**
* Set 是否创建为只读账号,0:否, 1:该账号的sql请求优先选择备机执行,备机不可用时选择主机执行,2:优先选择备机执行,备机不可用时操作失败,3:只从备机读取。
* @param ReadOnly 是否创建为只读账号,0:否, 1:该账号的sql请求优先选择备机执行,备机不可用时选择主机执行,2:优先选择备机执行,备机不可用时操作失败,3:只从备机读取。
*/
public void setReadOnly(Long ReadOnly) {
this.ReadOnly = ReadOnly;
}
/**
* Get 账号备注,可以包含中文、英文字符、常见符号和数字,长度为0~256字符
* @return Description 账号备注,可以包含中文、英文字符、常见符号和数字,长度为0~256字符
*/
public String getDescription() {
return this.Description;
}
/**
* Set 账号备注,可以包含中文、英文字符、常见符号和数字,长度为0~256字符
* @param Description 账号备注,可以包含中文、英文字符、常见符号和数字,长度为0~256字符
*/
public void setDescription(String Description) {
this.Description = Description;
}
/**
* Get 如果备机延迟超过本参数设置值,系统将认为备机发生故障
建议该参数值大于10。当ReadOnly选择1、2时该参数生效。
* @return DelayThresh 如果备机延迟超过本参数设置值,系统将认为备机发生故障
建议该参数值大于10。当ReadOnly选择1、2时该参数生效。
*/
public Long getDelayThresh() {
return this.DelayThresh;
}
/**
* Set 如果备机延迟超过本参数设置值,系统将认为备机发生故障
建议该参数值大于10。当ReadOnly选择1、2时该参数生效。
* @param DelayThresh 如果备机延迟超过本参数设置值,系统将认为备机发生故障
建议该参数值大于10。当ReadOnly选择1、2时该参数生效。
*/
public void setDelayThresh(Long DelayThresh) {
this.DelayThresh = DelayThresh;
}
public CreateAccountRequest() {
}
/**
* NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy,
* and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy.
*/
public CreateAccountRequest(CreateAccountRequest source) {
if (source.InstanceId != null) {
this.InstanceId = new String(source.InstanceId);
}
if (source.UserName != null) {
this.UserName = new String(source.UserName);
}
if (source.Host != null) {
this.Host = new String(source.Host);
}
if (source.Password != null) {
this.Password = new String(source.Password);
}
if (source.ReadOnly != null) {
this.ReadOnly = new Long(source.ReadOnly);
}
if (source.Description != null) {
this.Description = new String(source.Description);
}
if (source.DelayThresh != null) {
this.DelayThresh = new Long(source.DelayThresh);
}
}
/**
* Internal implementation, normal users should not use it.
*/
public void toMap(HashMap<String, String> map, String prefix) {
this.setParamSimple(map, prefix + "InstanceId", this.InstanceId);
this.setParamSimple(map, prefix + "UserName", this.UserName);
this.setParamSimple(map, prefix + "Host", this.Host);
this.setParamSimple(map, prefix + "Password", this.Password);
this.setParamSimple(map, prefix + "ReadOnly", this.ReadOnly);
this.setParamSimple(map, prefix + "Description", this.Description);
this.setParamSimple(map, prefix + "DelayThresh", this.DelayThresh);
}
}
|
/*
* 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.jena.tdb.sys;
import java.util.Iterator ;
import java.util.concurrent.atomic.AtomicLong ;
import org.apache.jena.tdb.TDBException ;
/** A policy that provide read-only access */
public class DatasetControlReadOnly implements DatasetControl
{
private final AtomicLong readCounter = new AtomicLong(0) ;
public DatasetControlReadOnly()
{ }
@Override
public void startRead()
{
readCounter.getAndIncrement() ;
}
@Override
public void finishRead()
{
readCounter.decrementAndGet() ;
}
@Override
public void startUpdate()
{
throw new TDBException("Read-only") ;
}
@Override
public void finishUpdate()
{
throw new TDBException("Read-only") ;
}
@Override
public <T> Iterator<T> iteratorControl(Iterator<T> iter) { return iter ; }
}
|
/*
* Copyright (C) 2014-2022 Philip Helger (www.helger.com)
* philip[at]helger[dot]com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.helger.html.hc.config;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.OverridingMethodsMustInvokeSuper;
import javax.annotation.concurrent.NotThreadSafe;
import com.helger.commons.ValueEnforcer;
import com.helger.commons.annotation.ReturnsMutableCopy;
import com.helger.commons.annotation.ReturnsMutableObject;
import com.helger.commons.string.ToStringGenerator;
import com.helger.css.ECSSVersion;
import com.helger.css.ICSSWriterSettings;
import com.helger.css.writer.CSSWriterSettings;
import com.helger.html.EHTMLVersion;
import com.helger.html.hc.IHCConversionSettings;
import com.helger.html.hc.IHCCustomizer;
import com.helger.html.js.IJSWriterSettings;
import com.helger.html.js.JSWriterSettings;
import com.helger.xml.serialize.write.EXMLIncorrectCharacterHandling;
import com.helger.xml.serialize.write.EXMLSerializeIndent;
import com.helger.xml.serialize.write.IXMLWriterSettings;
import com.helger.xml.serialize.write.XMLWriterSettings;
/**
* The default implementation of {@link IHCConversionSettings} containing the
* real settings for HTML output.
*
* @author Philip Helger
*/
@NotThreadSafe
public class HCConversionSettings implements IHCConversionSettings
{
/** Default indent and align HTML: true */
public static final boolean DEFAULT_INDENT_AND_ALIGN_HTML = true;
/** Default CSS version 3.0 */
public static final ECSSVersion DEFAULT_CSS_VERSION = ECSSVersion.CSS30;
/** Default indent and align CSS: true */
public static final boolean DEFAULT_INDENT_AND_ALIGN_CSS = true;
/** Default indent and align JS: true */
public static final boolean DEFAULT_INDENT_AND_ALIGN_JS = true;
/** Default consistency checks: true */
public static final boolean DEFAULT_CONSISTENCY_CHECKS = true;
/** Default extract out-of-band nodes: true */
public static final boolean DEFAULT_EXTRACT_OUT_OF_BAND_NODES = true;
private EHTMLVersion m_eHTMLVersion;
private String m_sHTMLNamespaceURI;
private XMLWriterSettings m_aXMLWriterSettings;
private CSSWriterSettings m_aCSSWriterSettings;
private JSWriterSettings m_aJSWriterSettings;
private boolean m_bConsistencyChecksEnabled;
private boolean m_bExtractOutOfBandNodes;
private IHCCustomizer m_aCustomizer;
@Nonnull
public static XMLWriterSettings createDefaultXMLWriterSettings (@Nonnull final EHTMLVersion eHTMLVersion)
{
final XMLWriterSettings ret = eHTMLVersion.isAtLeastHTML5 () ? XMLWriterSettings.createForHTML5 ()
: XMLWriterSettings.createForXHTML ();
return ret.setIncorrectCharacterHandling (EXMLIncorrectCharacterHandling.DO_NOT_WRITE_LOG_WARNING)
.setIndent (DEFAULT_INDENT_AND_ALIGN_HTML ? EXMLSerializeIndent.INDENT_AND_ALIGN : EXMLSerializeIndent.NONE);
}
@Nonnull
public static CSSWriterSettings createDefaultCSSWriterSettings ()
{
return new CSSWriterSettings (DEFAULT_CSS_VERSION).setOptimizedOutput (!DEFAULT_INDENT_AND_ALIGN_CSS);
}
@Nonnull
public static JSWriterSettings createDefaultJSWriterSettings ()
{
return new JSWriterSettings ().setIndentAndAlign (DEFAULT_INDENT_AND_ALIGN_JS);
}
/**
* @return The default customizer. Currently <code>null</code>.
* @see #isDefaultCustomizer(IHCCustomizer)
*/
@Nullable
public static IHCCustomizer createDefaultCustomizer ()
{
return null;
}
/**
* Check if the passed customizer is a default customizer.
*
* @param aCustomizer
* Customizer to check.
* @return <code>true</code> if the passed customizer is the default
* customizer, <code>false</code> otherwise.
* @see #createDefaultCustomizer()
*/
public static boolean isDefaultCustomizer (@Nullable final IHCCustomizer aCustomizer)
{
return aCustomizer == null;
}
/**
* Constructor
*
* @param eHTMLVersion
* The HTML version to use. May not be <code>null</code>.
*/
public HCConversionSettings (@Nonnull final EHTMLVersion eHTMLVersion)
{
setHTMLVersion (eHTMLVersion);
setToDefault ();
}
/**
* Copy constructor. Also creates a copy of the {@link XMLWriterSettings} and
* the {@link CSSWriterSettings}.
*
* @param aBase
* Object to copy the settings from. May not be <code>null</code>.
*/
public HCConversionSettings (@Nonnull final IHCConversionSettings aBase)
{
this (aBase, aBase.getHTMLVersion ());
}
/**
* Kind of copy constructor. Also creates a copy of the
* {@link XMLWriterSettings} and the {@link CSSWriterSettings}.
*
* @param aBase
* Object to copy the settings from. May not be <code>null</code>.
* @param eHTMLVersion
* A different HTML version to use than the one from the base settings
*/
public HCConversionSettings (@Nonnull final IHCConversionSettings aBase, @Nonnull final EHTMLVersion eHTMLVersion)
{
ValueEnforcer.notNull (aBase, "Base");
ValueEnforcer.notNull (eHTMLVersion, "HTMLVersion");
setHTMLVersion (eHTMLVersion);
m_aXMLWriterSettings = aBase.getMutableXMLWriterSettings ().getClone ();
m_aCSSWriterSettings = aBase.getMutableCSSWriterSettings ().getClone ();
m_aJSWriterSettings = aBase.getMutableJSWriterSettings ().getClone ();
m_bConsistencyChecksEnabled = aBase.areConsistencyChecksEnabled ();
m_bExtractOutOfBandNodes = aBase.isExtractOutOfBandNodes ();
m_aCustomizer = aBase.getCustomizer ();
}
/**
* Change the HTML version. Note: this does NOT change the
* {@link XMLWriterSettings}!
*
* @param eHTMLVersion
* The HTML version to use.
* @return this
*/
@Nonnull
public HCConversionSettings setHTMLVersion (@Nonnull final EHTMLVersion eHTMLVersion)
{
ValueEnforcer.notNull (eHTMLVersion, "HTMLVersion");
m_eHTMLVersion = eHTMLVersion;
m_sHTMLNamespaceURI = eHTMLVersion.getNamespaceURI ();
return this;
}
@Nonnull
public EHTMLVersion getHTMLVersion ()
{
return m_eHTMLVersion;
}
@Nullable
public String getHTMLNamespaceURI ()
{
return m_sHTMLNamespaceURI;
}
@Nonnull
public HCConversionSettings setXMLWriterSettingsOptimized (final boolean bOptimized)
{
m_aXMLWriterSettings.setIndent (bOptimized ? EXMLSerializeIndent.NONE
: DEFAULT_INDENT_AND_ALIGN_HTML ? EXMLSerializeIndent.INDENT_AND_ALIGN
: EXMLSerializeIndent.NONE);
// WRITE_TO_FILE_NO_LOG is the quickest version
m_aXMLWriterSettings.setIncorrectCharacterHandling (bOptimized ? EXMLIncorrectCharacterHandling.WRITE_TO_FILE_NO_LOG
: EXMLIncorrectCharacterHandling.DO_NOT_WRITE_LOG_WARNING);
return this;
}
/**
* Set the XML writer settings to be used. By default values equivalent to
* {@link XMLWriterSettings#DEFAULT_XML_SETTINGS} are used.
*
* @param aXMLWriterSettings
* The XML writer settings to be used. May not be <code>null</code>.
* @return this
*/
@Nonnull
public HCConversionSettings setXMLWriterSettings (@Nonnull final IXMLWriterSettings aXMLWriterSettings)
{
ValueEnforcer.notNull (aXMLWriterSettings, "XMLWriterSettings");
// The objects are cached with indent and no-indent for performance reasons
m_aXMLWriterSettings = new XMLWriterSettings (aXMLWriterSettings);
return this;
}
@Nonnull
@ReturnsMutableObject ("Design")
public XMLWriterSettings getXMLWriterSettings ()
{
return m_aXMLWriterSettings;
}
@Nonnull
@ReturnsMutableCopy
public XMLWriterSettings getMutableXMLWriterSettings ()
{
return m_aXMLWriterSettings.getClone ();
}
@Nonnull
public HCConversionSettings setCSSWriterSettingsOptimized (final boolean bOptimized)
{
m_aCSSWriterSettings.setOptimizedOutput (bOptimized).setRemoveUnnecessaryCode (bOptimized);
return this;
}
/**
* Set the CSS writer settings to be used.
*
* @param aCSSWriterSettings
* The settings. May not be <code>null</code>.
* @return this
*/
@Nonnull
public HCConversionSettings setCSSWriterSettings (@Nonnull final ICSSWriterSettings aCSSWriterSettings)
{
ValueEnforcer.notNull (aCSSWriterSettings, "CSSWriterSettings");
m_aCSSWriterSettings = new CSSWriterSettings (aCSSWriterSettings);
return this;
}
@Nonnull
@ReturnsMutableObject ("Design")
public CSSWriterSettings getCSSWriterSettings ()
{
return m_aCSSWriterSettings;
}
@Nonnull
@ReturnsMutableCopy
public CSSWriterSettings getMutableCSSWriterSettings ()
{
return new CSSWriterSettings (m_aCSSWriterSettings);
}
@Nonnull
public HCConversionSettings setJSWriterSettingsOptimized (final boolean bOptimized)
{
m_aJSWriterSettings.setMinimumCodeSize (bOptimized);
return this;
}
/**
* Set the JS formatter settings to be used.
*
* @param aJSWriterSettings
* The settings. May not be <code>null</code>.
* @return this
*/
@Nonnull
public HCConversionSettings setJSWriterSettings (@Nonnull final IJSWriterSettings aJSWriterSettings)
{
ValueEnforcer.notNull (aJSWriterSettings, "JSWriterSettings");
m_aJSWriterSettings = new JSWriterSettings (aJSWriterSettings);
return this;
}
@Nonnull
@ReturnsMutableObject ("Design")
public JSWriterSettings getJSWriterSettings ()
{
return m_aJSWriterSettings;
}
@Nonnull
@ReturnsMutableCopy
public JSWriterSettings getMutableJSWriterSettings ()
{
return m_aJSWriterSettings.getClone ();
}
/**
* Enable or disable the consistency checks. It is recommended that the
* consistency checks are only run in debug mode!
*
* @param bConsistencyChecksEnabled
* The new value.
* @return this
*/
@Nonnull
public HCConversionSettings setConsistencyChecksEnabled (final boolean bConsistencyChecksEnabled)
{
m_bConsistencyChecksEnabled = bConsistencyChecksEnabled;
return this;
}
public boolean areConsistencyChecksEnabled ()
{
return m_bConsistencyChecksEnabled;
}
/**
* Enable or disable the extraction of out-of-band nodes.
*
* @param bExtractOutOfBandNodes
* The new value.
* @return this
*/
@Nonnull
public HCConversionSettings setExtractOutOfBandNodes (final boolean bExtractOutOfBandNodes)
{
m_bExtractOutOfBandNodes = bExtractOutOfBandNodes;
return this;
}
public boolean isExtractOutOfBandNodes ()
{
return m_bExtractOutOfBandNodes;
}
/**
* Set the global customizer to be used to globally customize created
* elements.
*
* @param aCustomizer
* The customizer to be used. May not be <code>null</code>.
* @return this
*/
@Nonnull
public HCConversionSettings setCustomizer (@Nullable final IHCCustomizer aCustomizer)
{
m_aCustomizer = aCustomizer;
return this;
}
@Nullable
public IHCCustomizer getCustomizer ()
{
return m_aCustomizer;
}
@OverridingMethodsMustInvokeSuper
@Nonnull
public HCConversionSettings setToDefault ()
{
// There is no such thing as a default HTML version
m_aXMLWriterSettings = createDefaultXMLWriterSettings (m_eHTMLVersion);
m_aCSSWriterSettings = createDefaultCSSWriterSettings ();
m_aJSWriterSettings = createDefaultJSWriterSettings ();
m_bConsistencyChecksEnabled = DEFAULT_CONSISTENCY_CHECKS;
m_bExtractOutOfBandNodes = DEFAULT_EXTRACT_OUT_OF_BAND_NODES;
m_aCustomizer = createDefaultCustomizer ();
return this;
}
@OverridingMethodsMustInvokeSuper
public HCConversionSettings setToOptimized ()
{
setXMLWriterSettingsOptimized (true);
setCSSWriterSettingsOptimized (true);
setJSWriterSettingsOptimized (true);
m_bConsistencyChecksEnabled = false;
return this;
}
@Nonnull
public HCConversionSettings getClone ()
{
return new HCConversionSettings (this);
}
@Nonnull
public HCConversionSettings getClone (@Nonnull final EHTMLVersion eHTMLVersion)
{
return new HCConversionSettings (this, eHTMLVersion);
}
@Nonnull
public HCConversionSettings getCloneIfNecessary (@Nonnull final EHTMLVersion eHTMLVersion)
{
return m_eHTMLVersion.equals (eHTMLVersion) ? this : getClone (eHTMLVersion);
}
@Override
public String toString ()
{
return new ToStringGenerator (this).append ("HTMLVersion", m_eHTMLVersion)
.append ("XMLWriterSettings", m_aXMLWriterSettings)
.append ("CSSWriterSettings", m_aCSSWriterSettings)
.append ("JSWriterSettings", m_aJSWriterSettings)
.append ("consistencyChecksEnabled", m_bConsistencyChecksEnabled)
.append ("extractOutOfBandNodes", m_bExtractOutOfBandNodes)
.appendIfNotNull ("customizer", m_aCustomizer)
.getToString ();
}
}
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.compute.v2017_12_01.implementation;
import java.util.List;
import com.microsoft.azure.SubResource;
import com.microsoft.azure.management.compute.v2017_12_01.InstanceViewStatus;
import com.microsoft.azure.management.compute.v2017_12_01.Sku;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.rest.serializer.JsonFlatten;
import com.microsoft.azure.Resource;
/**
* Specifies information about the availability set that the virtual machine
* should be assigned to. Virtual machines specified in the same availability
* set are allocated to different nodes to maximize availability. For more
* information about availability sets, see [Manage the availability of virtual
* machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-manage-availability?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json).
* <br><br> For more information on Azure planned maintainance, see
* [Planned maintenance for virtual machines in
* Azure](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-planned-maintenance?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json)
* <br><br> Currently, a VM can only be added to availability set
* at creation time. An existing VM cannot be added to an availability set.
*/
@JsonFlatten
public class AvailabilitySetInner extends Resource {
/**
* Update Domain count.
*/
@JsonProperty(value = "properties.platformUpdateDomainCount")
private Integer platformUpdateDomainCount;
/**
* Fault Domain count.
*/
@JsonProperty(value = "properties.platformFaultDomainCount")
private Integer platformFaultDomainCount;
/**
* A list of references to all virtual machines in the availability set.
*/
@JsonProperty(value = "properties.virtualMachines")
private List<SubResource> virtualMachines;
/**
* The resource status information.
*/
@JsonProperty(value = "properties.statuses", access = JsonProperty.Access.WRITE_ONLY)
private List<InstanceViewStatus> statuses;
/**
* Sku of the availability set.
*/
@JsonProperty(value = "sku")
private Sku sku;
/**
* Get the platformUpdateDomainCount value.
*
* @return the platformUpdateDomainCount value
*/
public Integer platformUpdateDomainCount() {
return this.platformUpdateDomainCount;
}
/**
* Set the platformUpdateDomainCount value.
*
* @param platformUpdateDomainCount the platformUpdateDomainCount value to set
* @return the AvailabilitySetInner object itself.
*/
public AvailabilitySetInner withPlatformUpdateDomainCount(Integer platformUpdateDomainCount) {
this.platformUpdateDomainCount = platformUpdateDomainCount;
return this;
}
/**
* Get the platformFaultDomainCount value.
*
* @return the platformFaultDomainCount value
*/
public Integer platformFaultDomainCount() {
return this.platformFaultDomainCount;
}
/**
* Set the platformFaultDomainCount value.
*
* @param platformFaultDomainCount the platformFaultDomainCount value to set
* @return the AvailabilitySetInner object itself.
*/
public AvailabilitySetInner withPlatformFaultDomainCount(Integer platformFaultDomainCount) {
this.platformFaultDomainCount = platformFaultDomainCount;
return this;
}
/**
* Get the virtualMachines value.
*
* @return the virtualMachines value
*/
public List<SubResource> virtualMachines() {
return this.virtualMachines;
}
/**
* Set the virtualMachines value.
*
* @param virtualMachines the virtualMachines value to set
* @return the AvailabilitySetInner object itself.
*/
public AvailabilitySetInner withVirtualMachines(List<SubResource> virtualMachines) {
this.virtualMachines = virtualMachines;
return this;
}
/**
* Get the statuses value.
*
* @return the statuses value
*/
public List<InstanceViewStatus> statuses() {
return this.statuses;
}
/**
* Get the sku value.
*
* @return the sku value
*/
public Sku sku() {
return this.sku;
}
/**
* Set the sku value.
*
* @param sku the sku value to set
* @return the AvailabilitySetInner object itself.
*/
public AvailabilitySetInner withSku(Sku sku) {
this.sku = sku;
return this;
}
}
|
package org.jabref.logic.layout.format;
import org.jabref.logic.layout.LayoutFormatter;
import org.jabref.model.entry.AuthorList;
/**
* <ul>
* <li>Names are given as first name, von and last name.</li>
* <li>First names will not be abbreviated.</li>
* <li>Individual authors separated by comma.</li>
* <li>There is no comma before the and of a list of three or more authors.</li>
* </ul>
*/
public class AuthorFirstLastCommas implements LayoutFormatter {
@Override
public String format(String fieldText) {
return AuthorList.fixAuthorFirstNameFirstCommas(fieldText, false, false);
}
}
|
package com.sample;
import com.sample.data.Data;
import com.sample.data.Patient;
import com.vaadin.data.Binder;
import com.vaadin.data.converter.StringToFloatConverter;
import com.vaadin.ui.*;
import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import java.util.Map;
import static com.sample.DataDay.*;
import static com.sample.Punkt2.exclude;
import static com.sample.Punkt2.twoCheckBoxes;
import static com.sample.Punkt9.setNestedClassFromName;
public class Punkt10 {
public static void punkt10(Layout layout, Binder<Data> binder) {
add_label(layout, "10. Żywienie");
zywienieEN(layout, binder);
zywienieTPN(layout, binder);
zywienieDoustna(layout, binder);
zywienieNPO(layout, binder);
zywienieDodatkowaWoda(layout, binder);
Label labelMessage = new Label("Miejsce Zgłębnika");
layout.addComponent(labelMessage);
CheckBox nos = new CheckBox("Nos");
binder.forField(nos).bind(Data::isZglebnikNos, Data::setZglebnikNos);
CheckBox usta = new CheckBox("Usta");
binder.forField(usta).bind(Data::isZglebnikUsta, Data::setZglebnikUsta);
CheckBox PEG = new CheckBox("PEG");
binder.forField(PEG).bind(Data::isZglebnikPEG, Data::setZglebnikPEG);
CheckBox brak = new CheckBox("Brak");
binder.forField(brak).bind(Data::isZglebnikBrak, Data::setZglebnikBrak);
exclude(nos, usta, PEG, brak);
exclude(usta, PEG, brak, nos);
exclude(PEG, brak, nos, usta);
exclude(brak, nos, usta, PEG);
HorizontalLayout horizontalLayout = new HorizontalLayout();
horizontalLayout.setSpacing(true);
horizontalLayout.addComponent(nos);
horizontalLayout.addComponent(usta);
horizontalLayout.addComponent(PEG);
horizontalLayout.addComponent(brak);
layout.addComponent(horizontalLayout);
}
private static void zywienieDodatkowaWoda(Layout layout, Binder<Data> binder) {
CheckBox zywienie = twoCheckBoxes(layout, "dodatkowa woda");
binder.forField(zywienie).bind(Data::isZywienieDodatkowaWoda, Data::setZywienieDodatkowaWoda);
VerticalLayout h1 = new VerticalLayout();
h1.setVisible(false);
LinkedHashMap<String, String> map1 = new LinkedHashMap();
map1.put("ileMl", "ilość w ml");
addZywienieENFloat(binder, h1, "ZywienieDodatkowaWoda", map1);
layout.addComponent(h1);
zywienie.addValueChangeListener(
event ->{
if(zywienie.getValue()) {
h1.setVisible(true);
}
else {
h1.setVisible(false);
}
}
);
}
private static void zywienieNPO(Layout layout, Binder<Data> binder) {
CheckBox zywienie = twoCheckBoxes(layout, "NPO");
binder.forField(zywienie).bind(Data::isZywienieNPO, Data::setZywienieNPO);
CheckBox jesc = twoCheckBoxes(layout, "Czy może jeść");
binder.forField(jesc).bind(Data::isJesc, Data::setJesc);
CheckBox pic = twoCheckBoxes(layout, "Czy może pić");
binder.forField(pic).bind(Data::isPic, Data::setPic);
}
private static void zywienieDoustna(Layout layout, Binder<Data> binder) {
CheckBox zywienie = twoCheckBoxes(layout, "Zywienie Doustne");
binder.forField(zywienie).bind(Data::isZywienieDoustna, Data::setZywienieDoustna);
VerticalLayout h1 = new VerticalLayout();
h1.setVisible(false);
LinkedHashMap<String, String> map1 = new LinkedHashMap();
map1.put("iloscZywienia", "ilość w ml");
addZywienieENFloat(binder, h1, "ZywienieDoustna", map1);
layout.addComponent(h1);
zywienie.addValueChangeListener(
event ->{
if(zywienie.getValue()) {
h1.setVisible(true);
}
else {
h1.setVisible(false);
}
}
);
}
private static void zywienieTPN(Layout layout, Binder<Data> binder) {
CheckBox zywienie = twoCheckBoxes(layout, "Zywienie TPN");
binder.forField(zywienie).bind(Data::isZywienieTPN, Data::setZywienieTPN);
VerticalLayout h1 = new VerticalLayout();
h1.setVisible(false);
LinkedHashMap<String, String> map1 = new LinkedHashMap();
map1.put("iloscZywienia", "ilość żywienia wml na 24 h");
map1.put("Przeplyw", "przepływ ml/h");
addZywienieENFloat(binder, h1, "ZywienieTPN", map1);
LinkedHashMap<String, String> map2 = new LinkedHashMap();
map2.put( "Standard01", "Standard 01");
map2.put("Standard02", "Standard 02");
map2.put("Standard03", "Standard 03");
map2.put("Standard04", "Standard 04");
map2.put( "Hepa01", "Hepa 01");
map2.put("Hepa02", "Hepa 02");
map2.put("Hepa03", "Hepa 03");
map2.put("Hepa04", "Hepa 04");
map2.put( "Nephro01", "Nephro 01");
map2.put("Nephro02", "Nephro 02");
map2.put("Nephro03", "Nephro 03");
map2.put("Nephro04", "Nephro 04");
map2.put("StartStandard", "Start Standard");
map2.put("StartNephro", "Start Nephro");
map2.put("StartHepa", "Start Hepa");
addPreparaty(binder, h1, "ZywienieTPN", map2);
layout.addComponent(h1);
zywienie.addValueChangeListener(
event ->{
if(zywienie.getValue()) {
h1.setVisible(true);
}
else {
h1.setVisible(false);
}
}
);
}
private static void zywienieEN(Layout layout, Binder<Data> binder) {
CheckBox zywienie = twoCheckBoxes(layout, "Zywienie EN");
binder.forField(zywienie).bind(Data::isZywienieEN, Data::setZywienieEN);
VerticalLayout h1 = new VerticalLayout();
h1.setVisible(false);
LinkedHashMap<String, String> map1 = new LinkedHashMap();
map1.put("dojelitowego", "cel żywienia dojelitowego w ml");
map1.put("procentCelu", "% osiągniętego celu");
map1.put("iloscWMl", "ilość żywienia w ml na 24 h");
map1.put("PrzeplywWMl", "przepływ ml/h");
addZywienieENFloat(binder, h1, "ZywienieEN", map1);
addZaburzeniaKarmienia(binder, h1);
LinkedHashMap<String, String> map2 = new LinkedHashMap();
map2.put("Peptamen", "Peptamen");
map2.put("Diason", "Diason");
map2.put("FresubinHPFibre", "Fresubin HP Fibre");
map2.put("NutrisonProtein", "Nutrison Protein");
map2.put("glukoza5", "glukoza 5%");
map2.put("Peptisorb", "Peptisorb");
map2.put("Impact", "Impact");
map2.put("FresubinHPEnergy", "Fresubin HP Energy");
addPreparaty(binder, h1, "ZywienieEN", map2);
layout.addComponent(h1);
zywienie.addValueChangeListener(
event ->{
if(zywienie.getValue()) {
h1.setVisible(true);
}
else {
h1.setVisible(false);
}
}
);
}
private static void addPreparaty(Binder<Data> binder, Layout h1, String fieldName, LinkedHashMap<String, String> map ) {
add_label(h1, "Preparat");
for(Map.Entry<String, String> name : map.entrySet()) {
CheckBox check = twoCheckBoxes(h1, name.getValue());
setNestedClassFromName(check, binder, fieldName, name.getKey());
}
TextField text = new TextField();
addToLayout(h1, text, "Inne", "0");
setNestedClassFromName(text, binder, fieldName, "Inne");
}
private static void addZywienieENFloat(Binder<Data> binder, Layout h1, String fieldName, LinkedHashMap<String, String> map ) {
for(Map.Entry<String, String> name : map.entrySet()) {
setNestedClassFromNameFloat(h1, name.getValue(), binder, fieldName, name.getKey());
}
}
private static void addZaburzeniaKarmienia(Binder<Data> binder, Layout h1) {
CheckBox karmienia = twoCheckBoxes(h1, "Przerwanie/zaburzenie karmienia");
VerticalLayout h2 = new VerticalLayout();
h2.setVisible(false);
LinkedHashMap<String, String> map2 = new LinkedHashMap();
map2.put("wymioty", "wymioty");
map2.put("zalegania", "zalegania");
map2.put("naCzczo", "na czczo");
map2.put("krwawienie", "krwawienie z przewodu pokarmowego");
map2.put("inneZaburzenia", "inne Zaburzenia");
for(Map.Entry<String, String> name : map2.entrySet()) {
CheckBox badanie = twoCheckBoxes(h2, name.getValue());
setNestedClassFromName(badanie, binder,"ZywienieEN", name.getKey());
}
karmienia.addValueChangeListener(
event ->{
if(karmienia.getValue()) {
h2.setVisible(true);
}
else {
h2.setVisible(false);
}
}
);
h1.addComponent(h2);
}
public static void setNestedClassFromNameFloat(Layout layout, String showText, Binder<Data> binder, String dataField, String fieldName) {
TextField field = new TextField();
addToLayout(layout, field,showText, "0.0");
binder.forField(field)
.withConverter(
new StringToFloatConverter(String.format("%s musi być liczbą", fieldName)))
.bind(x-> {
try {
Field f = x.getClass().getField(dataField);
Object thisClass = f.get(x);
Field f1 = thisClass.getClass().getField(fieldName);
return (Float)f1.get(thisClass);
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
return null;
}, (x, y)->{
try {
Field f = x.getClass().getField(dataField);
Object thisClass = f.get(x);
Field f1 = thisClass.getClass().getField(fieldName);
f1.set(thisClass, y);
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}});
}
}
|
/*
* Copyright 2009 Inspire-Software.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yes.cart.domain.dto.impl;
import com.inspiresoftware.lib.dto.geda.annotations.Dto;
import com.inspiresoftware.lib.dto.geda.annotations.DtoCollection;
import com.inspiresoftware.lib.dto.geda.annotations.DtoField;
import org.yes.cart.domain.dto.AttrValueCustomerDTO;
import org.yes.cart.domain.dto.CustomerDTO;
import org.yes.cart.domain.dto.CustomerShopDTO;
import org.yes.cart.domain.dto.matcher.impl.IdentifiableMatcher;
import org.yes.cart.domain.dto.matcher.impl.NoopMatcher;
import org.yes.cart.domain.entity.AttrValueCustomer;
import org.yes.cart.domain.entity.CustomerShop;
import java.time.Instant;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* User: Igor Azarny iazarny@yahoo.com
* Date: 09-May-2011
* Time: 14:12:54
*/
@Dto
public class CustomerDTOImpl implements CustomerDTO {
@DtoField(value = "customerId", readOnly = true)
private long customerId;
@DtoField(value = "email")
private String email;
@DtoField(value = "salutation")
private String salutation;
@DtoField(value = "firstname")
private String firstname;
@DtoField(value = "lastname")
private String lastname;
@DtoField(value = "middlename")
private String middlename;
@DtoField(value = "tag")
private String tag;
@DtoField(value = "customerType")
private String customerType;
@DtoField(value = "pricingPolicy")
private String pricingPolicy;
@DtoField(value = "companyName1")
private String companyName1;
@DtoField(value = "companyName2")
private String companyName2;
@DtoField(value = "companyDepartment")
private String companyDepartment;
@DtoCollection(
value="shops",
dtoBeanKey="org.yes.cart.domain.dto.CustomerShopDTO",
entityGenericType = CustomerShop.class,
entityCollectionClass = HashSet.class,
dtoCollectionClass = HashSet.class,
dtoToEntityMatcher = NoopMatcher.class,
readOnly = true
)
private Set<CustomerShopDTO> assignedShops;
@DtoCollection(
value="attributes",
dtoBeanKey="org.yes.cart.domain.dto.AttrValueCustomerDTO",
entityGenericType = AttrValueCustomer.class,
entityCollectionClass = HashSet.class,
dtoCollectionClass = HashSet.class,
dtoToEntityMatcher = IdentifiableMatcher.class,
readOnly = true
)
private Set<AttrValueCustomerDTO> attributes;
@DtoField(readOnly = true)
private Instant createdTimestamp;
@DtoField(readOnly = true)
private Instant updatedTimestamp;
@DtoField(readOnly = true)
private String createdBy;
@DtoField(readOnly = true)
private String updatedBy;
/** {@inheritDoc} */
@Override
public long getCustomerId() {
return customerId;
}
/**
* {@inheritDoc}
*/
@Override
public long getId() {
return customerId;
}
/** {@inheritDoc} */
@Override
public void setCustomerId(final long customerId) {
this.customerId = customerId;
}
/** {@inheritDoc} */
@Override
public String getEmail() {
return email;
}
/** {@inheritDoc} */
@Override
public void setEmail(final String email) {
this.email = email;
}
/** {@inheritDoc} */
@Override
public String getFirstname() {
return firstname;
}
/** {@inheritDoc} */
@Override
public void setFirstname(final String firstname) {
this.firstname = firstname;
}
/** {@inheritDoc} */
@Override
public String getLastname() {
return lastname;
}
/** {@inheritDoc} */
@Override
public void setLastname(final String lastname) {
this.lastname = lastname;
}
/** {@inheritDoc} */
@Override
public String getMiddlename() {
return middlename;
}
/** {@inheritDoc} */
@Override
public void setMiddlename(final String middlename) {
this.middlename = middlename;
}
/** {@inheritDoc} */
@Override
public String getSalutation() {
return salutation;
}
/** {@inheritDoc} */
@Override
public void setSalutation(final String salutation) {
this.salutation = salutation;
}
/** {@inheritDoc} */
@Override
public Set<AttrValueCustomerDTO> getAttributes() {
return attributes;
}
/** {@inheritDoc} */
@Override
public void setAttributes(final Set<AttrValueCustomerDTO> attributes) {
this.attributes = attributes;
}
/** {@inheritDoc} */
@Override
public String getTag() {
return tag;
}
/** {@inheritDoc} */
@Override
public void setTag(final String tag) {
this.tag = tag;
}
/** {@inheritDoc} */
@Override
public String getCustomerType() {
return customerType;
}
/** {@inheritDoc} */
@Override
public void setCustomerType(final String customerType) {
this.customerType = customerType;
}
/** {@inheritDoc} */
@Override
public String getPricingPolicy() {
return pricingPolicy;
}
/** {@inheritDoc} */
@Override
public void setPricingPolicy(final String pricingPolicy) {
this.pricingPolicy = pricingPolicy;
}
/** {@inheritDoc} */
@Override
public String getCompanyName1() {
return companyName1;
}
/** {@inheritDoc} */
@Override
public void setCompanyName1(final String companyName1) {
this.companyName1 = companyName1;
}
/** {@inheritDoc} */
@Override
public String getCompanyName2() {
return companyName2;
}
/** {@inheritDoc} */
@Override
public void setCompanyName2(final String companyName2) {
this.companyName2 = companyName2;
}
/** {@inheritDoc} */
@Override
public String getCompanyDepartment() {
return companyDepartment;
}
/** {@inheritDoc} */
@Override
public void setCompanyDepartment(final String companyDepartment) {
this.companyDepartment = companyDepartment;
}
/** {@inheritDoc} */
@Override
public Set<CustomerShopDTO> getAssignedShops() {
return assignedShops;
}
/** {@inheritDoc} */
@Override
public void setAssignedShops(final Set<CustomerShopDTO> assignedShops) {
this.assignedShops = assignedShops;
}
/** {@inheritDoc} */
@Override
public Instant getCreatedTimestamp() {
return createdTimestamp;
}
/** {@inheritDoc} */
@Override
public void setCreatedTimestamp(final Instant createdTimestamp) {
this.createdTimestamp = createdTimestamp;
}
/** {@inheritDoc} */
@Override
public Instant getUpdatedTimestamp() {
return updatedTimestamp;
}
/** {@inheritDoc} */
@Override
public void setUpdatedTimestamp(final Instant updatedTimestamp) {
this.updatedTimestamp = updatedTimestamp;
}
/** {@inheritDoc} */
@Override
public String getCreatedBy() {
return createdBy;
}
/** {@inheritDoc} */
@Override
public void setCreatedBy(final String createdBy) {
this.createdBy = createdBy;
}
/** {@inheritDoc} */
@Override
public String getUpdatedBy() {
return updatedBy;
}
/** {@inheritDoc} */
@Override
public void setUpdatedBy(final String updatedBy) {
this.updatedBy = updatedBy;
}
@Override
public String toString() {
return "CustomerDTOImpl{" +
"customerId=" + customerId +
", email='" + email + '\'' +
", salutation='" + salutation + '\'' +
", firstname='" + firstname + '\'' +
", lastname='" + lastname + '\'' +
", middlename='" + middlename + '\'' +
", tag='" + tag + '\'' +
", customerType='" + customerType + '\'' +
", pricingPolicy='" + pricingPolicy + '\'' +
", companyName1='" + companyName1 + '\'' +
", companyName2='" + companyName2 + '\'' +
", companyDepartment='" + companyDepartment + '\'' +
", attributes=" + attributes +
'}';
}
}
|
package com.atguigu.gmall.sms.dao;
import com.atguigu.gmall.sms.entity.SkuLadderEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 商品阶梯价格
*
* @author nyf828
* @email niuyangfan@outlook.com
* @date 2020-03-25 13:05:16
*/
@Mapper
public interface SkuLadderDao extends BaseMapper<SkuLadderEntity> {
}
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*
*/
package com.microsoft.azure.management.operationsmanagement.v2015_11_01_preview.implementation;
import com.microsoft.azure.management.operationsmanagement.v2015_11_01_preview.ManagementConfiguration;
import com.microsoft.azure.arm.model.implementation.CreatableUpdatableImpl;
import rx.Observable;
import com.microsoft.azure.management.operationsmanagement.v2015_11_01_preview.ManagementConfigurationProperties;
class ManagementConfigurationImpl extends CreatableUpdatableImpl<ManagementConfiguration, ManagementConfigurationInner, ManagementConfigurationImpl> implements ManagementConfiguration, ManagementConfiguration.Definition, ManagementConfiguration.Update {
private String resourceGroupName;
private String managementConfigurationName;
private final OperationsManagementManager manager;
ManagementConfigurationImpl(String name, OperationsManagementManager manager) {
super(name, new ManagementConfigurationInner());
this.manager = manager;
// Set resource name
this.managementConfigurationName = name;
//
}
ManagementConfigurationImpl(ManagementConfigurationInner inner, OperationsManagementManager manager) {
super(inner.name(), inner);
this.manager = manager;
// Set resource name
this.managementConfigurationName = inner.name();
// set resource ancestor and positional variables
this.resourceGroupName = IdParsingUtils.getValueFromIdByName(inner.id(), "resourcegroups");
this.managementConfigurationName = IdParsingUtils.getValueFromIdByName(inner.id(), "ManagementConfigurations");
// set other parameters for create and update
}
@Override
public OperationsManagementManager manager() {
return this.manager;
}
@Override
public Observable<ManagementConfiguration> createResourceAsync() {
ManagementConfigurationsInner client = this.manager().inner().managementConfigurations();
return client.createOrUpdateAsync(this.resourceGroupName, this.managementConfigurationName, this.inner())
.map(innerToFluentMap(this));
}
@Override
public Observable<ManagementConfiguration> updateResourceAsync() {
ManagementConfigurationsInner client = this.manager().inner().managementConfigurations();
return client.createOrUpdateAsync(this.resourceGroupName, this.managementConfigurationName, this.inner())
.map(innerToFluentMap(this));
}
@Override
protected Observable<ManagementConfigurationInner> getInnerAsync() {
ManagementConfigurationsInner client = this.manager().inner().managementConfigurations();
return client.getByResourceGroupAsync(this.resourceGroupName, this.managementConfigurationName);
}
@Override
public boolean isInCreateMode() {
return this.inner().id() == null;
}
@Override
public String id() {
return this.inner().id();
}
@Override
public String location() {
return this.inner().location();
}
@Override
public String name() {
return this.inner().name();
}
@Override
public ManagementConfigurationProperties properties() {
return this.inner().properties();
}
@Override
public String type() {
return this.inner().type();
}
@Override
public ManagementConfigurationImpl withResourceGroupName(String resourceGroupName) {
this.resourceGroupName = resourceGroupName;
return this;
}
@Override
public ManagementConfigurationImpl withLocation(String location) {
this.inner().withLocation(location);
return this;
}
@Override
public ManagementConfigurationImpl withProperties(ManagementConfigurationProperties properties) {
this.inner().withProperties(properties);
return this;
}
}
|
/*
Copyright (c) 2017 Ahome' Innovation Technologies. 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.ait.lienzo.shared.core.types;
import com.ait.tooling.common.api.types.IStringValued;
/**
* ShapeType is an extensible enumeration of all Shape types.
*/
public class ShapeType implements IStringValued
{
public static final ShapeType ARC = new ShapeType("Arc");
public static final ShapeType ARROW = new ShapeType("Arrow");
public static final ShapeType BEZIER_CURVE = new ShapeType("BezierCurve");
public static final ShapeType CIRCLE = new ShapeType("Circle");
public static final ShapeType ELLIPTICAL_ARC = new ShapeType("EllipticalArc");
public static final ShapeType ELLIPSE = new ShapeType("Ellipse");
public static final ShapeType LINE = new ShapeType("Line");
public static final ShapeType MOVIE = new ShapeType("Movie");
public static final ShapeType PARALLELOGRAM = new ShapeType("Parallelogram");
public static final ShapeType PICTURE = new ShapeType("Picture");
public static final ShapeType POLYGON = new ShapeType("Polygon");
public static final ShapeType POLYLINE = new ShapeType("Polyline");
public static final ShapeType ORTHOGONAL_POLYLINE = new ShapeType("OrthogonalPolyline");
public static final ShapeType QUADRATIC_CURVE = new ShapeType("QuadraticCurve");
public static final ShapeType RECTANGLE = new ShapeType("Rectangle");
public static final ShapeType REGULAR_POLYGON = new ShapeType("RegularPolygon");
public static final ShapeType SLICE = new ShapeType("Slice");
public static final ShapeType STAR = new ShapeType("Star");
public static final ShapeType TEXT = new ShapeType("Text");
public static final ShapeType TRIANGLE = new ShapeType("Triangle");
public static final ShapeType SPLINE = new ShapeType("Spline");
public static final ShapeType BOW = new ShapeType("Bow");
public static final ShapeType RING = new ShapeType("Ring");
public static final ShapeType CHORD = new ShapeType("Chord");
public static final ShapeType ISOSCELES_TRAPEZOID = new ShapeType("IsoscelesTrapezoid");
public static final ShapeType SVG_PATH = new ShapeType("SVGPath");
public static final ShapeType MULTI_PATH = new ShapeType("MultiPath");
public static final ShapeType SPRITE = new ShapeType("Sprite");
private final String m_value;
protected ShapeType(final String value)
{
m_value = value;
}
@Override
public final String toString()
{
return m_value;
}
@Override
public final String getValue()
{
return m_value;
}
@Override
public boolean equals(final Object other)
{
if ((other == null) || (false == (other instanceof ShapeType)))
{
return false;
}
if (this == other)
{
return true;
}
ShapeType that = ((ShapeType) other);
return that.getValue().equals(getValue());
}
@Override
public int hashCode()
{
return getValue().hashCode();
}
}
|
package by.degree.learn.disinfector.impl;
import by.degree.learn.disinfector.infrastructure.Announce;
import by.degree.learn.disinfector.model.Disinfector;
import by.degree.learn.disinfector.model.Enforcer;
import by.degree.learn.disinfector.model.Room;
import by.degree.learn.nano.framework.Inject;
import by.degree.learn.nano.framework.Singleton;
@Singleton
public class DisinfectorImpl implements Disinfector {
@Inject
private Enforcer enforcer;
@Override
@Announce
public void disinfect(Room room) {
enforcer.enforce();
doDisinfection(room);
}
private void doDisinfection(Room room) {
System.out.println("Disinfecting " + room);
}
}
|
package com.monkeyframework.boot.tomcat;
import java.net.URL;
import org.apache.catalina.Executor;
import org.apache.catalina.startup.Tomcat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author cruise.xu
* */
public class EmbeddedTomcat {
private static Logger logger = LoggerFactory.getLogger(EmbeddedTomcat.class);
private static Tomcat tomcat = null;
private static String ENCODING = "UTF-8";
private static String CONTEXT_PATH = "/";
// 启动嵌入式Tomcat服务器
private static int TOMCAT_PORT = 8080;
private int tomcatPort = TOMCAT_PORT;
private String contextPath;
private String webAppPath;
private Executor executor;
public void startTomcat() throws Exception {
try {
long startTime = System.currentTimeMillis();
tomcat = new Tomcat();
// 设置Tomcat的工作目录
//tomcat.setBaseDir(tomcatHome);
tomcat.setPort(tomcatPort);
tomcat.addWebapp(contextPath, getWebAppPath());
// tomcat.enableNaming();//执行这句才能支持JDNI查找
tomcat.getConnector().setURIEncoding(ENCODING);
if(null != executor) {
tomcat.getService().addExecutor(executor);
}
tomcat.start();
logger.warn("Tomcat started in " + (System.currentTimeMillis() - startTime) + " ms.");
tomcat.getServer().await();// 让服务器一直跑
/*Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
stop();
}
});*/
} catch (Exception e) {
e.printStackTrace();
}
}
public void init() {
URL url = Thread.currentThread().getContextClassLoader().getResource("");
String path = url.getPath();
if(path.indexOf("target") > -1 && path.indexOf("classes") > -1) {
path = path.replaceAll("target", "src").replaceAll("classes", "main");
String webapp = path + "webapp";
logger.error(webapp);
this.webAppPath = webapp;
}
else {
int indexConf = path.lastIndexOf("/conf");
if(indexConf > -1) {
String webapp = path.substring(0, indexConf) + "/webapp";
logger.error(webapp);
this.webAppPath = webapp;
}
}
}
public void setTomcatPort(int tomcatPort) {
this.tomcatPort = tomcatPort;
}
public void setContextPath(String contextPath) {
if (null != contextPath) {
this.contextPath = contextPath;
} else {
this.contextPath = CONTEXT_PATH;
}
}
public void stop() {
try {
if (null != tomcat) {
tomcat.stop();
}
} catch (Exception e) {
logger.error(e.getMessage());
}
}
public void destroy() {
try {
if (null != tomcat) {
tomcat.destroy();
}
} catch (Exception e) {
logger.error(e.getMessage());
}
}
public int getTomcatPort() {
return tomcatPort;
}
public String getContextPath() {
return contextPath;
}
public String getWebAppPath() {
return this.webAppPath;
}
public void setExecutor(Executor executor) {
this.executor = executor;
}
public static void main(String[] args) {
try {
new EmbeddedTomcat().startTomcat();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package com.google.impactdashboard.configuration;
/** A class to hold the column names in the Recommendations Table. */
public class RecommendationsSchema {
/** The name of the column holding the project id. */
public static final String RECOMMENDATIONS_PROJECT_ID_COLUMN = "ProjectId";
/** The name of the column holding the organization id. */
public static final String RECOMMENDATIONS_ORGANIZATION_ID_COLUMN = "OrganizationId";
/** The name of the column holding the recommender type. */
public static final String RECOMMENDER_COLUMN = "Recommender";
/** The name of the column holding the name of the user that accepted the recommendation. */
public static final String ACTOR_COLUMN = "Actor";
/** The name of the column holding the actions taken by the recommendation. */
public static final String ACTIONS_COLUMN = "Actions";
/**
* The name of the field of the recommendation action struct that
* indicates which user account was affected by the action.
*/
public static final String ACCOUNT_AFFECTED_FIELD = "AffectedAccount";
/**
* The name of the field of the recommendation action struct that
* indicates Which role this user previously had.
*/
public static final String PREVIOUS_ROLE_FIELD = "PreviousRole";
/**
* The name of the field of the recommendation action struct that
* indicates which role this user currently has.
*/
public static final String NEW_ROLE_FIELD = "NewRole";
/** The name of the column holding the accepted timestamp of the recommendation. */
public static final String ACCEPTED_TIMESTAMP_COLUMN = "AcceptedTimestamp";
/** The name of the column holding the IAM bindings impact of the recommendation. */
public static final String IAM_IMPACT_COLUMN = "IAMBindingsImpact";
}
|
/*
*
* Apache License
* Version 2.0, January 2004
* http://www.apache.org/licenses/
*
* TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
*
* 1. Definitions.
*
* "License" shall mean the terms and conditions for use, reproduction,
* and distribution as defined by Sections 1 through 9 of this document.
*
* "Licensor" shall mean the copyright owner or entity authorized by
* the copyright owner that is granting the License.
*
* "Legal Entity" shall mean the union of the acting entity and all
* other entities that control, are controlled by, or are under common
* control with that entity. For the purposes of this definition,
* "control" means (i) the power, direct or indirect, to cause the
* direction or management of such entity, whether by contract or
* otherwise, or (ii) ownership of fifty percent (50%) or more of the
* outstanding shares, or (iii) beneficial ownership of such entity.
*
* "You" (or "Your") shall mean an individual or Legal Entity
* exercising permissions granted by this License.
*
* "Source" form shall mean the preferred form for making modifications,
* including but not limited to software source code, documentation
* source, and configuration files.
*
* "Object" form shall mean any form resulting from mechanical
* transformation or translation of a Source form, including but
* not limited to compiled object code, generated documentation,
* and conversions to other media types.
*
* "Work" shall mean the work of authorship, whether in Source or
* Object form, made available under the License, as indicated by a
* copyright notice that is included in or attached to the work
* (an example is provided in the Appendix below).
*
* "Derivative Works" shall mean any work, whether in Source or Object
* form, that is based on (or derived from) the Work and for which the
* editorial revisions, annotations, elaborations, or other modifications
* represent, as a whole, an original work of authorship. For the purposes
* of this License, Derivative Works shall not include works that remain
* separable from, or merely link (or bind by name) to the interfaces of,
* the Work and Derivative Works thereof.
*
* "Contribution" shall mean any work of authorship, including
* the original version of the Work and any modifications or additions
* to that Work or Derivative Works thereof, that is intentionally
* submitted to Licensor for inclusion in the Work by the copyright owner
* or by an individual or Legal Entity authorized to submit on behalf of
* the copyright owner. For the purposes of this definition, "submitted"
* means any form of electronic, verbal, or written communication sent
* to the Licensor or its representatives, including but not limited to
* communication on electronic mailing lists, source code control systems,
* and issue tracking systems that are managed by, or on behalf of, the
* Licensor for the purpose of discussing and improving the Work, but
* excluding communication that is conspicuously marked or otherwise
* designated in writing by the copyright owner as "Not a Contribution."
*
* "Contributor" shall mean Licensor and any individual or Legal Entity
* on behalf of whom a Contribution has been received by Licensor and
* subsequently incorporated within the Work.
*
* 2. Grant of Copyright License. Subject to the terms and conditions of
* this License, each Contributor hereby grants to You a perpetual,
* worldwide, non-exclusive, no-charge, royalty-free, irrevocable
* copyright license to reproduce, prepare Derivative Works of,
* publicly display, publicly perform, sublicense, and distribute the
* Work and such Derivative Works in Source or Object form.
*
* 3. Grant of Patent License. Subject to the terms and conditions of
* this License, each Contributor hereby grants to You a perpetual,
* worldwide, non-exclusive, no-charge, royalty-free, irrevocable
* (except as stated in this section) patent license to make, have made,
* use, offer to sell, sell, import, and otherwise transfer the Work,
* where such license applies only to those patent claims licensable
* by such Contributor that are necessarily infringed by their
* Contribution(s) alone or by combination of their Contribution(s)
* with the Work to which such Contribution(s) was submitted. If You
* institute patent litigation against any entity (including a
* cross-claim or counterclaim in a lawsuit) alleging that the Work
* or a Contribution incorporated within the Work constitutes direct
* or contributory patent infringement, then any patent licenses
* granted to You under this License for that Work shall terminate
* as of the date such litigation is filed.
*
* 4. Redistribution. You may reproduce and distribute copies of the
* Work or Derivative Works thereof in any medium, with or without
* modifications, and in Source or Object form, provided that You
* meet the following conditions:
*
* (a) You must give any other recipients of the Work or
* Derivative Works a copy of this License; and
*
* (b) You must cause any modified files to carry prominent notices
* stating that You changed the files; and
*
* (c) You must retain, in the Source form of any Derivative Works
* that You distribute, all copyright, patent, trademark, and
* attribution notices from the Source form of the Work,
* excluding those notices that do not pertain to any part of
* the Derivative Works; and
*
* (d) If the Work includes a "NOTICE" text file as part of its
* distribution, then any Derivative Works that You distribute must
* include a readable copy of the attribution notices contained
* within such NOTICE file, excluding those notices that do not
* pertain to any part of the Derivative Works, in at least one
* of the following places: within a NOTICE text file distributed
* as part of the Derivative Works; within the Source form or
* documentation, if provided along with the Derivative Works; or,
* within a display generated by the Derivative Works, if and
* wherever such third-party notices normally appear. The contents
* of the NOTICE file are for informational purposes only and
* do not modify the License. You may add Your own attribution
* notices within Derivative Works that You distribute, alongside
* or as an addendum to the NOTICE text from the Work, provided
* that such additional attribution notices cannot be construed
* as modifying the License.
*
* You may add Your own copyright statement to Your modifications and
* may provide additional or different license terms and conditions
* for use, reproduction, or distribution of Your modifications, or
* for any such Derivative Works as a whole, provided Your use,
* reproduction, and distribution of the Work otherwise complies with
* the conditions stated in this License.
*
* 5. Submission of Contributions. Unless You explicitly state otherwise,
* any Contribution intentionally submitted for inclusion in the Work
* by You to the Licensor shall be under the terms and conditions of
* this License, without any additional terms or conditions.
* Notwithstanding the above, nothing herein shall supersede or modify
* the terms of any separate license agreement you may have executed
* with Licensor regarding such Contributions.
*
* 6. Trademarks. This License does not grant permission to use the trade
* names, trademarks, service marks, or product names of the Licensor,
* except as required for reasonable and customary use in describing the
* origin of the Work and reproducing the content of the NOTICE file.
*
* 7. Disclaimer of Warranty. Unless required by applicable law or
* agreed to in writing, Licensor provides the Work (and each
* Contributor provides its Contributions) on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied, including, without limitation, any warranties or conditions
* of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
* PARTICULAR PURPOSE. You are solely responsible for determining the
* appropriateness of using or redistributing the Work and assume any
* risks associated with Your exercise of permissions under this License.
*
* 8. Limitation of Liability. In no event and under no legal theory,
* whether in tort (including negligence), contract, or otherwise,
* unless required by applicable law (such as deliberate and grossly
* negligent acts) or agreed to in writing, shall any Contributor be
* liable to You for damages, including any direct, indirect, special,
* incidental, or consequential damages of any character arising as a
* result of this License or out of the use or inability to use the
* Work (including but not limited to damages for loss of goodwill,
* work stoppage, computer failure or malfunction, or any and all
* other commercial damages or losses), even if such Contributor
* has been advised of the possibility of such damages.
*
* 9. Accepting Warranty or Additional Liability. While redistributing
* the Work or Derivative Works thereof, You may choose to offer,
* and charge a fee for, acceptance of support, warranty, indemnity,
* or other liability obligations and/or rights consistent with this
* License. However, in accepting such obligations, You may act only
* on Your own behalf and on Your sole responsibility, not on behalf
* of any other Contributor, and only if You agree to indemnify,
* defend, and hold each Contributor harmless for any liability
* incurred by, or claims asserted against, such Contributor by reason
* of your accepting any such warranty or additional liability.
*
* END OF TERMS AND CONDITIONS
*
* APPENDIX: How to apply the Apache License to your work.
*
* To apply the Apache License to your work, attach the following
* boilerplate notice, with the fields enclosed by brackets "[]"
* replaced with your own identifying information. (Don't include
* the brackets!) The text should be enclosed in the appropriate
* comment syntax for the file format. We also recommend that a
* file or class name and description of purpose be included on the
* same "printed page" as the copyright notice for easier
* identification within third-party archives.
*
* Copyright 2016 Ian Kelly
*
* 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 cognitivej.core.error.exceptions;
import org.jetbrains.annotations.NotNull;
public class SubscriptionKeyNotAuthorizedException extends RuntimeException {
public SubscriptionKeyNotAuthorizedException(@NotNull String message) {
super(message);
}
}
|
/*
* Copyright 2010-2021 James Pether Sörling
*
* 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.
*
* $Id$
* $HeadURL$
*/
package com.hack23.cia.web.impl.ui.application.views.user.goverment.pagemode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Service;
import com.hack23.cia.model.internal.application.system.impl.ApplicationEventGroup;
import com.hack23.cia.web.impl.ui.application.action.ViewAction;
import com.hack23.cia.web.impl.ui.application.views.common.chartfactory.api.ChartDataManager;
import com.hack23.cia.web.impl.ui.application.views.common.dataseriesfactory.api.MinistryDataSeriesFactory;
import com.hack23.cia.web.impl.ui.application.views.common.viewnames.ChartIndicators;
import com.hack23.cia.web.impl.ui.application.views.common.viewnames.PageMode;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Layout;
import com.vaadin.ui.MenuBar;
import com.vaadin.ui.Panel;
import com.vaadin.ui.VerticalLayout;
/**
* The Class MinistryRankingAllPartiesChartsPageModContentFactoryImpl.
*/
@Service
public final class MinistryRankingAllPartiesChartsPageModContentFactoryImpl
extends AbstractMinistryRankingPageModContentFactoryImpl {
/** The Constant CHARTS. */
private static final String CHARTS = "Charts: All Parties, total days served";
/** The chart data manager. */
@Autowired
private ChartDataManager chartDataManager;
/** The data series factory. */
@Autowired
private MinistryDataSeriesFactory dataSeriesFactory;
/**
* Instantiates a new ministry ranking all parties charts page mod content
* factory impl.
*/
public MinistryRankingAllPartiesChartsPageModContentFactoryImpl() {
super();
}
@Secured({ "ROLE_ANONYMOUS", "ROLE_USER", "ROLE_ADMIN" })
@Override
public Layout createContent(final String parameters, final MenuBar menuBar, final Panel panel) {
final VerticalLayout panelContent = createPanelContent();
getMinistryRankingMenuItemFactory().createMinistryRankingMenuBar(menuBar);
final String pageId = getPageId(parameters);
final HorizontalLayout chartLayout = new HorizontalLayout();
chartLayout.setSizeFull();
chartDataManager.createChartPanel(chartLayout,
dataSeriesFactory.createChartTimeSeriesTotalDaysServedGovernmentByParty(),
"All Parties, total days served");
panelContent.addComponent(chartLayout);
panel.setCaption(NAME + "::" + CHARTS + parameters);
getPageActionEventHelper().createPageEvent(ViewAction.VISIT_MINISTRY_RANKING_VIEW, ApplicationEventGroup.USER,
NAME, parameters, pageId);
return panelContent;
}
@Override
public boolean matches(final String page, final String parameters) {
return NAME.equals(page) && StringUtils.contains(parameters, PageMode.CHARTS.toString())
&& parameters.contains(ChartIndicators.ALLMINISTRIESPARTYBYTOTALDAYS.toString());
}
}
|
package com.ss.editor.ui.controller.filter.property.control;
import static com.ss.editor.ui.controller.filter.property.control.FilterPropertyControl.newChangeHandler;
import com.jme3.math.Vector3f;
import com.ss.editor.model.undo.editor.SceneChangeConsumer;
import com.ss.editor.ui.controller.property.AbstractPropertyControl;
import com.ss.editor.ui.controller.property.impl.AbstractVector3fPropertyControl;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* The implementation of the {@link AbstractPropertyControl} to edit vector3f values.
*
* @param <T> the type parameter
* @author JavaSaBr
*/
public class Vector3fFilterPropertyControl<T> extends AbstractVector3fPropertyControl<SceneChangeConsumer, T> {
/**
* Instantiates a new Vector 3 f filter property controller.
*
* @param propertyValue the property value
* @param propertyName the property name
* @param changeConsumer the change consumer
*/
public Vector3fFilterPropertyControl(@Nullable final Vector3f propertyValue, @NotNull final String propertyName,
@NotNull final SceneChangeConsumer changeConsumer) {
super(propertyValue, propertyName, changeConsumer, newChangeHandler());
}
}
|
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.javascript;
/**
* This class implements the "arguments" object.
*
* See ECMA 10.1.8
*
* @see org.mozilla.javascript.NativeCall
* @author Norris Boyd
*/
final class Arguments extends IdScriptableObject
{
static final long serialVersionUID = 4275508002492040609L;
private static final String FTAG = "Arguments";
public Arguments(NativeCall activation)
{
this.activation = activation;
Scriptable parent = activation.getParentScope();
setParentScope(parent);
setPrototype(ScriptableObject.getObjectPrototype(parent));
args = activation.originalArgs;
lengthObj = Integer.valueOf(args.length);
NativeFunction f = activation.function;
calleeObj = f;
Scriptable topLevel = getTopLevelScope(parent);
constructor = getProperty(topLevel, "Object");
int version = f.getLanguageVersion();
if (version <= Context.VERSION_1_3
&& version != Context.VERSION_DEFAULT)
{
callerObj = null;
} else {
callerObj = NOT_FOUND;
}
}
@Override
public String getClassName()
{
return FTAG;
}
private Object arg(int index) {
if (index < 0 || args.length <= index) return NOT_FOUND;
return args[index];
}
// the following helper methods assume that 0 < index < args.length
private void putIntoActivation(int index, Object value) {
String argName = activation.function.getParamOrVarName(index);
activation.put(argName, activation, value);
}
private Object getFromActivation(int index) {
String argName = activation.function.getParamOrVarName(index);
return activation.get(argName, activation);
}
private void replaceArg(int index, Object value) {
if (sharedWithActivation(index)) {
putIntoActivation(index, value);
}
synchronized (this) {
if (args == activation.originalArgs) {
args = args.clone();
}
args[index] = value;
}
}
private void removeArg(int index) {
synchronized (this) {
if (args[index] != NOT_FOUND) {
if (args == activation.originalArgs) {
args = args.clone();
}
args[index] = NOT_FOUND;
}
}
}
// end helpers
@Override
public boolean has(int index, Scriptable start)
{
if (arg(index) != NOT_FOUND) {
return true;
}
return super.has(index, start);
}
@Override
public Object get(int index, Scriptable start)
{
final Object value = arg(index);
if (value == NOT_FOUND) {
return super.get(index, start);
} else {
if (sharedWithActivation(index)) {
return getFromActivation(index);
} else {
return value;
}
}
}
private boolean sharedWithActivation(int index)
{
NativeFunction f = activation.function;
int definedCount = f.getParamCount();
if (index < definedCount) {
// Check if argument is not hidden by later argument with the same
// name as hidden arguments are not shared with activation
if (index < definedCount - 1) {
String argName = f.getParamOrVarName(index);
for (int i = index + 1; i < definedCount; i++) {
if (argName.equals(f.getParamOrVarName(i))) {
return false;
}
}
}
return true;
}
return false;
}
@Override
public void put(int index, Scriptable start, Object value)
{
if (arg(index) == NOT_FOUND) {
super.put(index, start, value);
} else {
replaceArg(index, value);
}
}
@Override
public void delete(int index)
{
if (0 <= index && index < args.length) {
removeArg(index);
}
super.delete(index);
}
// #string_id_map#
private static final int
Id_callee = 1,
Id_length = 2,
Id_caller = 3,
Id_constructor = 4,
MAX_INSTANCE_ID = Id_constructor;
@Override
protected int getMaxInstanceId()
{
return MAX_INSTANCE_ID;
}
@Override
protected int findInstanceIdInfo(String s)
{
int id;
// #generated# Last update: 2010-01-06 05:48:21 ARST
L0: { id = 0; String X = null; int c;
int s_length = s.length();
if (s_length==6) {
c=s.charAt(5);
if (c=='e') { X="callee";id=Id_callee; }
else if (c=='h') { X="length";id=Id_length; }
else if (c=='r') { X="caller";id=Id_caller; }
}
else if (s_length==11) { X="constructor";id=Id_constructor; }
if (X!=null && X!=s && !X.equals(s)) id = 0;
break L0;
}
// #/generated#
if (id == 0) return super.findInstanceIdInfo(s);
int attr;
switch (id) {
case Id_callee:
case Id_caller:
case Id_length:
case Id_constructor:
attr = DONTENUM;
break;
default: throw new IllegalStateException();
}
return instanceIdInfo(attr, id);
}
// #/string_id_map#
@Override
protected String getInstanceIdName(int id)
{
switch (id) {
case Id_callee: return "callee";
case Id_length: return "length";
case Id_caller: return "caller";
case Id_constructor: return "constructor";
}
return null;
}
@Override
protected Object getInstanceIdValue(int id)
{
switch (id) {
case Id_callee: return calleeObj;
case Id_length: return lengthObj;
case Id_caller: {
Object value = callerObj;
if (value == UniqueTag.NULL_VALUE) { value = null; }
else if (value == null) {
NativeCall caller = activation.parentActivationCall;
if (caller != null) {
value = caller.get("arguments", caller);
}
}
return value;
}
case Id_constructor:
return constructor;
}
return super.getInstanceIdValue(id);
}
@Override
protected void setInstanceIdValue(int id, Object value)
{
switch (id) {
case Id_callee: calleeObj = value; return;
case Id_length: lengthObj = value; return;
case Id_caller:
callerObj = (value != null) ? value : UniqueTag.NULL_VALUE;
return;
case Id_constructor: constructor = value; return;
}
super.setInstanceIdValue(id, value);
}
@Override
Object[] getIds(boolean getAll)
{
Object[] ids = super.getIds(getAll);
if (args.length != 0) {
boolean[] present = new boolean[args.length];
int extraCount = args.length;
for (int i = 0; i != ids.length; ++i) {
Object id = ids[i];
if (id instanceof Integer) {
int index = ((Integer)id).intValue();
if (0 <= index && index < args.length) {
if (!present[index]) {
present[index] = true;
extraCount--;
}
}
}
}
if (!getAll) { // avoid adding args which were redefined to non-enumerable
for (int i = 0; i < present.length; i++) {
if (!present[i] && super.has(i, this)) {
present[i] = true;
extraCount--;
}
}
}
if (extraCount != 0) {
Object[] tmp = new Object[extraCount + ids.length];
System.arraycopy(ids, 0, tmp, extraCount, ids.length);
ids = tmp;
int offset = 0;
for (int i = 0; i != args.length; ++i) {
if (present == null || !present[i]) {
ids[offset] = Integer.valueOf(i);
++offset;
}
}
if (offset != extraCount) Kit.codeBug();
}
}
return ids;
}
@Override
protected ScriptableObject getOwnPropertyDescriptor(Context cx, Object id) {
double d = ScriptRuntime.toNumber(id);
int index = (int) d;
if (d != index) {
return super.getOwnPropertyDescriptor(cx, id);
}
Object value = arg(index);
if (value == NOT_FOUND) {
return super.getOwnPropertyDescriptor(cx, id);
}
if (sharedWithActivation(index)) {
value = getFromActivation(index);
}
if (super.has(index, this)) { // the descriptor has been redefined
ScriptableObject desc = super.getOwnPropertyDescriptor(cx, id);
desc.put("value", desc, value);
return desc;
} else {
Scriptable scope = getParentScope();
if (scope == null) scope = this;
return buildDataDescriptor(scope, value, EMPTY);
}
}
@Override
protected void defineOwnProperty(Context cx, Object id,
ScriptableObject desc,
boolean checkValid) {
super.defineOwnProperty(cx, id, desc, checkValid);
double d = ScriptRuntime.toNumber(id);
int index = (int) d;
if (d != index) return;
Object value = arg(index);
if (value == NOT_FOUND) return;
if (isAccessorDescriptor(desc)) {
removeArg(index);
return;
}
Object newValue = getProperty(desc, "value");
if (newValue == NOT_FOUND) return;
replaceArg(index, newValue);
if (isFalse(getProperty(desc, "writable"))) {
removeArg(index);
}
}
// Fields to hold caller, callee and length properties,
// where NOT_FOUND value tags deleted properties.
// In addition if callerObj == NULL_VALUE, it tags null for scripts, as
// initial callerObj == null means access to caller arguments available
// only in JS <= 1.3 scripts
private Object callerObj;
private Object calleeObj;
private Object lengthObj;
private Object constructor;
private NativeCall activation;
// Initially args holds activation.getOriginalArgs(), but any modification
// of its elements triggers creation of a copy. If its element holds NOT_FOUND,
// it indicates deleted index, in which case super class is queried.
private Object[] args;
}
|
package com.example.first.ui;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import com.example.first.R;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
/**
* @ClassName: UiActivity
* @Description: 描述
* @Author: 范琳琳
* @CreateDate: 2019/4/2 21:36
* @Version: 1.0
*/
public class UiActivity extends AppCompatActivity implements View.OnClickListener {
private Button btn;
private ProgressBar progressBar;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ui);
btn = findViewById(R.id.btn_show);
btn.setOnClickListener(this);
progressBar = findViewById(R.id. progress_bar);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_show:
break;
default:
break;
}
}
public void showAlertDialog(){
AlertDialog.Builder dialog = new AlertDialog.Builder(UiActivity.this);
dialog.setTitle("This is a Dialog");
dialog.setMessage("Do you want delete the picture?");
dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
dialog.show();
}
}
|
// 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.v201708;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for GrpTargetGender.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="GrpTargetGender">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="UNKNOWN"/>
* <enumeration value="MALE"/>
* <enumeration value="FEMALE"/>
* <enumeration value="BOTH"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "GrpTargetGender")
@XmlEnum
public enum GrpTargetGender {
/**
*
* The value returned if the actual value is not exposed by the requested API version.
*
*
*/
UNKNOWN,
/**
*
* Indicates that the GRP target gender is Male.
*
*
*/
MALE,
/**
*
* Indicates that the GRP target gender is Female.
*
*
*/
FEMALE,
/**
*
* Indicates that the GRP target gender is both male and female.
*
*
*/
BOTH;
public String value() {
return name();
}
public static GrpTargetGender fromValue(String v) {
return valueOf(v);
}
}
|
package com.springbootpoc.springbootservices;
import java.io.IOException;
import java.util.Dictionary;
import java.util.Hashtable;
import javax.servlet.ServletException;
import com.springbootpoc.springbootservices.jersey.JerseyApplication;
import com.springbootpoc.springbootservices.springboot.Application;
import org.glassfish.jersey.servlet.ServletContainer;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import org.osgi.service.http.HttpService;
import org.osgi.service.http.NamespaceException;
import org.osgi.util.tracker.ServiceTracker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class Activator implements BundleActivator {
private static final Logger LOGGER = LoggerFactory.getLogger(Activator.class);
private static final String JERSEY_SERVICE_PREFIX = "/jersey";
private static final String SPRING_SERVICE_PREFIX = "/spring";
private static final String PROPERTY_CONTEXT_PATH = "context.path";
private BundleContext bundleContext;
private HttpService httpService = null;
private JerseyApplication jerseyApplication;
ApplicationContext appContext;
private ServiceTracker tracker;
@Override
public void start(BundleContext bundleContext) throws IOException {
this.bundleContext = bundleContext;
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
appContext = new SpringApplication(Application.class).run();
tracker = new ServiceTracker(bundleContext, HttpService.class.getName(), null) {
@Override
public Object addingService(ServiceReference serviceRef) {
httpService = (HttpService) super.addingService(serviceRef);
Dictionary<String, String> servletParams = new Hashtable<>();
jerseyApplication = new JerseyApplication(bundleContext);
try {
LOGGER.info("registering jersey at {}", JERSEY_SERVICE_PREFIX);
httpService.registerServlet(JERSEY_SERVICE_PREFIX, new ServletContainer(jerseyApplication),
servletParams, null);
LOGGER.info("deployed jersey");
LOGGER.info("registering springboot at {}", SPRING_SERVICE_PREFIX);
httpService.registerServlet(SPRING_SERVICE_PREFIX, appContext.getBean(DispatcherServlet.class) ,servletParams, null);
} catch (ServletException | NamespaceException e) {
LOGGER.error("Failed to initialize Jersey servlet", e);
}
Dictionary<String, String> props = new Hashtable<>();
props.put(PROPERTY_CONTEXT_PATH, JERSEY_SERVICE_PREFIX);
sendEvent("EVENT_JERSEY_DEPLOYED", props);
return httpService;
}
@Override
public void removedService(ServiceReference serviceReference, Object service) {
if (httpService == service) {
httpService.unregister(JERSEY_SERVICE_PREFIX);
httpService.unregister(SPRING_SERVICE_PREFIX);
if (jerseyApplication != null) {
jerseyApplication.shutdown();
jerseyApplication = null;
}
httpService = null;
Dictionary<String, String> props = new Hashtable<>();
props.put(PROPERTY_CONTEXT_PATH, JERSEY_SERVICE_PREFIX);
sendEvent("EVENT_JERSEY_UNDEPLOYED", props);
LOGGER.info("Unregistered Jersey servlet at {}", JERSEY_SERVICE_PREFIX);
}
super.removedService(serviceReference, service);
}
};
tracker.open();
}
private void sendEvent(String eventId, Dictionary<String, String> properties) {
ServiceReference serviceReference = bundleContext.getServiceReference(EventAdmin.class.getName());
if (serviceReference != null) {
EventAdmin eventAdmin = (EventAdmin) bundleContext.getService(serviceReference);
eventAdmin.sendEvent(new Event(eventId, properties));
bundleContext.ungetService(serviceReference);
}
}
@Override
public void stop(BundleContext bundleContext) {
SpringApplication.exit(appContext, () -> 0);
}
}
|
public class Gerente extends Funcionario {
private int senha;
@Override
public double getBonificacao() {
return super.getBonificacao() + super.getSalario();
}
public void setSenha(int senha) {
this.senha = senha;
}
public boolean autentica(int senha) {
if (this.senha == senha) {
return true;
} else {
return false;
}
}
}
|
/*
* Copyright 2013-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.support.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
* <p>
* The AWS Support case ID returned by a successful completion of the <a>CreateCase</a> operation.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/support-2013-04-15/CreateCase" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CreateCaseResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* The AWS Support case ID requested or returned in the call. The case ID is an alphanumeric string formatted as
* shown in this example: case-<i>12345678910-2013-c4c1d2bf33c5cf47</i>
* </p>
*/
private String caseId;
/**
* <p>
* The AWS Support case ID requested or returned in the call. The case ID is an alphanumeric string formatted as
* shown in this example: case-<i>12345678910-2013-c4c1d2bf33c5cf47</i>
* </p>
*
* @param caseId
* The AWS Support case ID requested or returned in the call. The case ID is an alphanumeric string formatted
* as shown in this example: case-<i>12345678910-2013-c4c1d2bf33c5cf47</i>
*/
public void setCaseId(String caseId) {
this.caseId = caseId;
}
/**
* <p>
* The AWS Support case ID requested or returned in the call. The case ID is an alphanumeric string formatted as
* shown in this example: case-<i>12345678910-2013-c4c1d2bf33c5cf47</i>
* </p>
*
* @return The AWS Support case ID requested or returned in the call. The case ID is an alphanumeric string
* formatted as shown in this example: case-<i>12345678910-2013-c4c1d2bf33c5cf47</i>
*/
public String getCaseId() {
return this.caseId;
}
/**
* <p>
* The AWS Support case ID requested or returned in the call. The case ID is an alphanumeric string formatted as
* shown in this example: case-<i>12345678910-2013-c4c1d2bf33c5cf47</i>
* </p>
*
* @param caseId
* The AWS Support case ID requested or returned in the call. The case ID is an alphanumeric string formatted
* as shown in this example: case-<i>12345678910-2013-c4c1d2bf33c5cf47</i>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateCaseResult withCaseId(String caseId) {
setCaseId(caseId);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getCaseId() != null)
sb.append("CaseId: ").append(getCaseId());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof CreateCaseResult == false)
return false;
CreateCaseResult other = (CreateCaseResult) obj;
if (other.getCaseId() == null ^ this.getCaseId() == null)
return false;
if (other.getCaseId() != null && other.getCaseId().equals(this.getCaseId()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getCaseId() == null) ? 0 : getCaseId().hashCode());
return hashCode;
}
@Override
public CreateCaseResult clone() {
try {
return (CreateCaseResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
|
/*******************************************************************************
* Copyright (c) <2013>, California Institute of Technology ("Caltech").
* U.S. Government sponsorship acknowledged.
*
* 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 Caltech nor its operating division, the Jet Propulsion Laboratory,
* nor the names of its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package gov.nasa.jpl.ocl;
import gov.nasa.jpl.mbee.lib.Debug;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import org.eclipse.emf.ecore.EAnnotation;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EEnumLiteral;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EOperation;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EParameter;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.EcoreFactory;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.ocl.Environment;
import org.eclipse.ocl.EnvironmentFactory;
import org.eclipse.ocl.ecore.CallOperationAction;
import org.eclipse.ocl.ecore.Constraint;
import org.eclipse.ocl.ecore.EcoreEnvironment;
import org.eclipse.ocl.ecore.EcoreEnvironmentFactory;
import org.eclipse.ocl.ecore.SendSignalAction;
import org.eclipse.ocl.ecore.internal.OCLStandardLibraryImpl;
public class DgEnvironment extends EcoreEnvironment {
Set<String> operationNames = new HashSet<String>();
Set<DgOperationInstance> operations = new LinkedHashSet<DgOperationInstance>();
// this constructor is used to initialize the root environment
DgEnvironment(EPackage.Registry registry) {
super(registry);
}
public DgEnvironment(EcoreEnvironmentFactory fac, Resource resource) {
super(fac, resource);
}
// this constructor is used to initialize child environments
DgEnvironment(DgEnvironment parent) {
super(parent);
}
public DgEnvironment(
Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> createEnvironment) {
super(createEnvironment);
}
// override this to provide visibility of the inherited protected method
@Override
protected void setFactory(
EnvironmentFactory<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> factory) {
super.setFactory(factory);
}
// override this to provide visibility of the inherited protected method
@Override
public EnvironmentFactory<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> getFactory() {
return super.getFactory();
}
/**
* Utility for adding custom OCL operations (defined by a DgOperation)
*
* @param dgOperation
*/
public void addDgOperation(DgOperationInstance dgOperation) {
// check that the operation has not already been added
if (!operations.contains(dgOperation)) {
EOperation eoperation = EcoreFactory.eINSTANCE.createEOperation();
eoperation.setName(dgOperation.getName());
EClassifier type = dgOperation.getReturnType();
if (type == null)
type = OCLStandardLibraryImpl.INSTANCE.getOclAny();
eoperation.setEType(type);
for (EParameter parm: dgOperation.getParameters()) {
eoperation.getEParameters().add(parm);
}
EAnnotation annotation = EcoreFactory.eINSTANCE.createEAnnotation();
annotation.setSource(dgOperation.getAnnotationName());
eoperation.getEAnnotations().add(annotation);
type = dgOperation.getCallerType();
if (type == null)
type = OCLStandardLibraryImpl.INSTANCE.getOclAny();
try {
if (dgOperation.getCallerType() == null) {
Debug.error(false, "Error! Null callerType for DgOperation " + dgOperation
+ "! Setting to OclAny.");
dgOperation.setCallerType(OCLStandardLibraryImpl.INSTANCE.getOclAny());
}
addHelperOperation(dgOperation.getCallerType(), eoperation);
operationNames.add(dgOperation.getName());
operations.add(dgOperation);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
|
/**
* Copyright 2019 ForgeRock AS.
*
* 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 uk.org.openbanking.datamodel.service.converter.payment;
import uk.org.openbanking.datamodel.payment.*;
import static uk.org.openbanking.datamodel.service.converter.payment.OBConsentAuthorisationConverter.toOBAuthorisation1;
import static uk.org.openbanking.datamodel.service.converter.payment.OBConsentAuthorisationConverter.toOBWriteDomesticConsent4DataAuthorisation;
import static uk.org.openbanking.datamodel.service.converter.payment.OBDomesticStandingOrderConverter.*;
import static uk.org.openbanking.datamodel.service.converter.payment.OBWriteDomesticConsentConverter.toOBSCASupportData1;
public class OBWriteDomesticStandingOrderConsentConverter {
public static OBWriteDomesticStandingOrder1 toOBWriteDomesticStandingOrder1(OBWriteDomesticStandingOrder2 obWriteDomesticStandingOrder2) {
return (new OBWriteDomesticStandingOrder1())
.data(toOBWriteDataDomesticStandingOrder1(obWriteDomesticStandingOrder2.getData()))
.risk(obWriteDomesticStandingOrder2.getRisk());
}
public static OBWriteDomesticStandingOrder2 toOBWriteDomesticStandingOrder2(OBWriteDomesticStandingOrder1 obWriteDomesticStandingOrder1) {
return (new OBWriteDomesticStandingOrder2())
.data(toOBWriteDataDomesticStandingOrder2(obWriteDomesticStandingOrder1.getData()))
.risk(obWriteDomesticStandingOrder1.getRisk());
}
public static OBWriteDomesticStandingOrder3 toOBWriteDomesticStandingOrder3(OBWriteDomesticStandingOrder1 obWriteDomesticStandingOrder1) {
return (new OBWriteDomesticStandingOrder3())
.data(toOBWriteDomesticStandingOrder3Data(obWriteDomesticStandingOrder1.getData()))
.risk(obWriteDomesticStandingOrder1.getRisk());
}
public static OBWriteDomesticStandingOrder3 toOBWriteDomesticStandingOrder3(OBWriteDomesticStandingOrder2 obWriteDomesticStandingOrder2) {
return (new OBWriteDomesticStandingOrder3())
.data(toOBWriteDomesticStandingOrder3Data(obWriteDomesticStandingOrder2.getData()))
.risk(obWriteDomesticStandingOrder2.getRisk());
}
public static OBWriteDomesticStandingOrderConsent1 toOBWriteDomesticStandingOrderConsent1(OBWriteDomesticStandingOrderConsent2 obWriteDomesticStandingOrderConsent2) {
return (new OBWriteDomesticStandingOrderConsent1())
.data(toOBWriteDataDomesticStandingOrderConsent1(obWriteDomesticStandingOrderConsent2.getData()))
.risk(obWriteDomesticStandingOrderConsent2.getRisk());
}
public static OBWriteDomesticStandingOrderConsent1 toOBWriteDomesticStandingOrderConsent1(OBWriteDomesticStandingOrderConsent3 obWriteDomesticStandingOrderConsent3) {
return (new OBWriteDomesticStandingOrderConsent1())
.data(toOBWriteDataDomesticStandingOrderConsent1(obWriteDomesticStandingOrderConsent3.getData()))
.risk(obWriteDomesticStandingOrderConsent3.getRisk());
}
public static OBWriteDomesticStandingOrderConsent1 toOBWriteDomesticStandingOrderConsent1(OBWriteDomesticStandingOrderConsent5 domesticStandingOrderConsent) {
return (new OBWriteDomesticStandingOrderConsent1())
.data(toOBWriteDataDomesticStandingOrderConsent1(domesticStandingOrderConsent.getData()))
.risk(domesticStandingOrderConsent.getRisk());
}
public static OBWriteDomesticStandingOrderConsent2 toOBWriteDomesticStandingOrderConsent2(OBWriteDomesticStandingOrderConsent5 domesticStandingOrderConsent) {
return (new OBWriteDomesticStandingOrderConsent2())
.data(toOBWriteDataDomesticStandingOrderConsent2(domesticStandingOrderConsent.getData()))
.risk(domesticStandingOrderConsent.getRisk());
}
public static OBWriteDomesticStandingOrderConsent2 toOBWriteDomesticStandingOrderConsent2(OBWriteDomesticStandingOrderConsent3 domesticStandingOrderConsent) {
return (new OBWriteDomesticStandingOrderConsent2())
.data(toOBWriteDataDomesticStandingOrderConsent2(domesticStandingOrderConsent.getData()))
.risk(domesticStandingOrderConsent.getRisk());
}
public static OBWriteDomesticStandingOrderConsent2 toOBWriteDomesticStandingOrderConsent2(OBWriteDomesticStandingOrderConsent1 obWriteDomesticStandingOrderConsent1) {
return (new OBWriteDomesticStandingOrderConsent2())
.data(toOBWriteDataDomesticStandingOrderConsent2(obWriteDomesticStandingOrderConsent1.getData()))
.risk(obWriteDomesticStandingOrderConsent1.getRisk());
}
public static OBWriteDomesticStandingOrderConsent3 toOBWriteDomesticStandingOrderConsent3(OBWriteDomesticStandingOrderConsent1 obWriteDomesticStandingOrderConsent1) {
return obWriteDomesticStandingOrderConsent1 == null ? null : (new OBWriteDomesticStandingOrderConsent3())
.data(toOBWriteDataDomesticStandingOrderConsent3(obWriteDomesticStandingOrderConsent1.getData()))
.risk(obWriteDomesticStandingOrderConsent1.getRisk());
}
public static OBWriteDomesticStandingOrderConsent3 toOBWriteDomesticStandingOrderConsent3(OBWriteDomesticStandingOrderConsent2 obWriteDomesticStandingOrderConsent2) {
return (new OBWriteDomesticStandingOrderConsent3())
.data(toOBWriteDataDomesticStandingOrderConsent3(obWriteDomesticStandingOrderConsent2.getData()))
.risk(obWriteDomesticStandingOrderConsent2.getRisk());
}
public static OBWriteDomesticStandingOrderConsent3 toOBWriteDomesticStandingOrderConsent3(OBWriteDomesticStandingOrderConsent4 obWriteDomesticStandingOrderConsent4) {
return (new OBWriteDomesticStandingOrderConsent3())
.data(toOBWriteDataDomesticStandingOrderConsent3(obWriteDomesticStandingOrderConsent4.getData()))
.risk(obWriteDomesticStandingOrderConsent4.getRisk());
}
public static OBWriteDomesticScheduledConsent4 toOBWriteDomesticScheduledConsent4(OBWriteDomesticScheduledConsent3 obWriteDomesticScheduledConsent3) {
return obWriteDomesticScheduledConsent3 == null ? null : (new OBWriteDomesticScheduledConsent4())
.data(toOBWriteDomesticScheduledConsent4Data(obWriteDomesticScheduledConsent3.getData()))
.risk(obWriteDomesticScheduledConsent3.getRisk());
}
public static OBWriteDomesticStandingOrderConsent5 toOBWriteDomesticStandingOrderConsent5(OBWriteDomesticStandingOrderConsent1 obWriteDomesticStandingOrderConsent1) {
return (new OBWriteDomesticStandingOrderConsent5())
.data(toOBWriteDomesticStandingOrderConsent5Data(obWriteDomesticStandingOrderConsent1.getData()))
.risk(obWriteDomesticStandingOrderConsent1.getRisk());
}
public static OBWriteDomesticStandingOrderConsent5 toOBWriteDomesticStandingOrderConsent5(OBWriteDomesticStandingOrderConsent2 obWriteDomesticStandingOrderConsent2) {
return (new OBWriteDomesticStandingOrderConsent5())
.data(toOBWriteDomesticStandingOrderConsent5Data(obWriteDomesticStandingOrderConsent2.getData()))
.risk(obWriteDomesticStandingOrderConsent2.getRisk());
}
public static OBWriteDomesticStandingOrderConsent5 toOBWriteDomesticStandingOrderConsent5(OBWriteDomesticStandingOrderConsent3 obWriteDomesticStandingOrderConsent3) {
return (new OBWriteDomesticStandingOrderConsent5())
.data(toOBWriteDomesticStandingOrderConsent5Data(obWriteDomesticStandingOrderConsent3.getData()))
.risk(obWriteDomesticStandingOrderConsent3.getRisk());
}
public static OBWriteDomesticStandingOrderConsent5 toOBWriteDomesticStandingOrderConsent5(OBWriteDomesticStandingOrderConsent4 obWriteDomesticStandingOrderConsent4) {
return (new OBWriteDomesticStandingOrderConsent5())
.data(toOBWriteDomesticStandingOrderConsent5Data(obWriteDomesticStandingOrderConsent4.getData()))
.risk(obWriteDomesticStandingOrderConsent4.getRisk());
}
public static OBWriteDataDomesticStandingOrder1 toOBWriteDataDomesticStandingOrder1(OBWriteDataDomesticStandingOrder2 data) {
return data == null ? null : (new OBWriteDataDomesticStandingOrder1())
.consentId(data.getConsentId())
.initiation(toOBDomesticStandingOrder1(data.getInitiation()));
}
public static OBWriteDataDomesticStandingOrder2 toOBWriteDataDomesticStandingOrder2(OBWriteDataDomesticStandingOrder1 data) {
return data == null ? null : (new OBWriteDataDomesticStandingOrder2())
.consentId(data.getConsentId())
.initiation(toOBDomesticStandingOrder2(data.getInitiation()));
}
public static OBWriteDataDomesticStandingOrder3 toOBWriteDataDomesticStandingOrder3(OBWriteDataDomesticStandingOrder1 data) {
return data == null ? null : (new OBWriteDataDomesticStandingOrder3())
.consentId(data.getConsentId())
.initiation(toOBDomesticStandingOrder3(data.getInitiation()));
}
public static OBWriteDomesticStandingOrder3Data toOBWriteDomesticStandingOrder3Data(OBWriteDataDomesticStandingOrder1 data) {
return data == null ? null : (new OBWriteDomesticStandingOrder3Data())
.consentId(data.getConsentId())
.initiation(toOBWriteDomesticStandingOrder3DataInitiation(data.getInitiation()));
}
public static OBWriteDomesticStandingOrder3Data toOBWriteDomesticStandingOrder3Data(OBWriteDataDomesticStandingOrder2 data) {
return data == null ? null : (new OBWriteDomesticStandingOrder3Data())
.consentId(data.getConsentId())
.initiation(toOBWriteDomesticStandingOrder3DataInitiation(data.getInitiation()));
}
public static OBWriteDataDomesticStandingOrder3 toOBWriteDataDomesticStandingOrder3(OBWriteDataDomesticStandingOrder2 data) {
return data == null ? null : (new OBWriteDataDomesticStandingOrder3())
.consentId(data.getConsentId())
.initiation(toOBDomesticStandingOrder3(data.getInitiation()));
}
public static OBWriteDataDomesticStandingOrderConsent1 toOBWriteDataDomesticStandingOrderConsent1(OBWriteDataDomesticStandingOrderConsent2 data) {
return data == null ? null : (new OBWriteDataDomesticStandingOrderConsent1())
.permission(data.getPermission())
.initiation(toOBDomesticStandingOrder1(data.getInitiation()))
.authorisation(data.getAuthorisation());
}
public static OBWriteDataDomesticStandingOrderConsent1 toOBWriteDataDomesticStandingOrderConsent1(OBWriteDataDomesticStandingOrderConsent3 data) {
return data == null ? null : (new OBWriteDataDomesticStandingOrderConsent1())
.permission(data.getPermission())
.initiation(toOBDomesticStandingOrder1(data.getInitiation()))
.authorisation(data.getAuthorisation());
}
public static OBWriteDataDomesticStandingOrderConsent1 toOBWriteDataDomesticStandingOrderConsent1(OBWriteDomesticStandingOrderConsent5Data data) {
return data == null ? null : (new OBWriteDataDomesticStandingOrderConsent1())
.permission(data.getPermission())
.initiation(toOBDomesticStandingOrder1(data.getInitiation()))
.authorisation(toOBAuthorisation1(data.getAuthorisation()));
}
public static OBWriteDataDomesticStandingOrderConsent2 toOBWriteDataDomesticStandingOrderConsent2(OBWriteDomesticStandingOrderConsent5Data data) {
return data == null ? null : (new OBWriteDataDomesticStandingOrderConsent2())
.permission(data.getPermission())
.initiation(toOBDomesticStandingOrder2(data.getInitiation()))
.authorisation(toOBAuthorisation1(data.getAuthorisation()));
}
public static OBWriteDataDomesticStandingOrderConsent2 toOBWriteDataDomesticStandingOrderConsent2(OBWriteDataDomesticStandingOrderConsent1 data) {
return data == null ? null : (new OBWriteDataDomesticStandingOrderConsent2())
.permission(data.getPermission())
.initiation(toOBDomesticStandingOrder2(data.getInitiation()))
.authorisation(data.getAuthorisation());
}
public static OBWriteDataDomesticStandingOrderConsent2 toOBWriteDataDomesticStandingOrderConsent2(OBWriteDataDomesticStandingOrderConsent3 data) {
return data == null ? null : (new OBWriteDataDomesticStandingOrderConsent2())
.permission(data.getPermission())
.initiation(toOBDomesticStandingOrder2(data.getInitiation()))
.authorisation(data.getAuthorisation());
}
public static OBWriteDataDomesticStandingOrderConsent3 toOBWriteDataDomesticStandingOrderConsent3(OBWriteDataDomesticStandingOrderConsent1 data) {
return data == null ? null : (new OBWriteDataDomesticStandingOrderConsent3())
.permission(data.getPermission())
.initiation(toOBDomesticStandingOrder3(data.getInitiation()))
.authorisation(data.getAuthorisation());
}
public static OBWriteDataDomesticStandingOrderConsent3 toOBWriteDataDomesticStandingOrderConsent3(OBWriteDataDomesticStandingOrderConsent2 data) {
return data == null ? null : (new OBWriteDataDomesticStandingOrderConsent3())
.permission(data.getPermission())
.initiation(toOBDomesticStandingOrder3(data.getInitiation()))
.authorisation(data.getAuthorisation());
}
public static OBWriteDataDomesticStandingOrderConsent3 toOBWriteDataDomesticStandingOrderConsent3(OBWriteDomesticStandingOrderConsent4Data data) {
return data == null ? null : (new OBWriteDataDomesticStandingOrderConsent3())
.permission(data.getPermission())
.initiation(toOBDomesticStandingOrder3(data.getInitiation()))
.authorisation(toOBAuthorisation1(data.getAuthorisation()));
}
public static OBWriteDomesticScheduledConsent4Data toOBWriteDomesticScheduledConsent4Data(OBWriteDomesticScheduledConsent3Data data) {
return data == null ? null : (new OBWriteDomesticScheduledConsent4Data())
.permission(data.getPermission())
.readRefundAccount(null)
.initiation(data.getInitiation())
.authorisation(toOBWriteDomesticConsent4DataAuthorisation(data.getAuthorisation()))
.scASupportData(toOBSCASupportData1(data.getScASupportData()));
}
public static OBWriteDomesticStandingOrderConsent5Data toOBWriteDomesticStandingOrderConsent5Data(OBWriteDataDomesticStandingOrderConsent1 data) {
return data == null ? null : (new OBWriteDomesticStandingOrderConsent5Data())
.permission(data.getPermission())
.readRefundAccount(null)
.initiation(toOBWriteDomesticStandingOrder3DataInitiation(data.getInitiation()))
.authorisation(toOBWriteDomesticConsent4DataAuthorisation(data.getAuthorisation()))
.scASupportData(null);
}
public static OBWriteDomesticStandingOrderConsent5Data toOBWriteDomesticStandingOrderConsent5Data(OBWriteDataDomesticStandingOrderConsent2 data) {
return data == null ? null : (new OBWriteDomesticStandingOrderConsent5Data())
.permission(data.getPermission())
.readRefundAccount(null)
.initiation(toOBWriteDomesticStandingOrder3DataInitiation(data.getInitiation()))
.authorisation(toOBWriteDomesticConsent4DataAuthorisation(data.getAuthorisation()))
.scASupportData(null);
}
public static OBWriteDomesticStandingOrderConsent5Data toOBWriteDomesticStandingOrderConsent5Data(OBWriteDataDomesticStandingOrderConsent3 data) {
return data == null ? null : (new OBWriteDomesticStandingOrderConsent5Data())
.permission(data.getPermission())
.readRefundAccount(null)
.initiation(toOBWriteDomesticStandingOrder3DataInitiation(data.getInitiation()))
.authorisation(toOBWriteDomesticConsent4DataAuthorisation(data.getAuthorisation()))
.scASupportData(null);
}
public static OBWriteDomesticStandingOrderConsent5Data toOBWriteDomesticStandingOrderConsent5Data(OBWriteDomesticStandingOrderConsent4Data data) {
return data == null ? null : (new OBWriteDomesticStandingOrderConsent5Data())
.permission(data.getPermission())
.readRefundAccount(null)
.initiation(data.getInitiation())
.authorisation(toOBWriteDomesticConsent4DataAuthorisation(data.getAuthorisation()))
.scASupportData(toOBSCASupportData1(data.getScASupportData()));
}
}
|
/* GENERATED SOURCE. DO NOT MODIFY. */
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html#License
/*
*******************************************************************************
* Copyright (C) 1996-2011, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package android.icu.impl;
/**
* @hide Only a subset of ICU is exposed in Android
* @hide draft / provisional / internal are hidden on Android
*/
public class CalendarCache
{
/**
* @hide draft / provisional / internal are hidden on Android
*/
public CalendarCache() {
makeArrays(arraySize);
}
private void makeArrays(int newSize) {
keys = new long[newSize];
values = new long[newSize];
for (int i = 0; i < newSize; i++) {
values[i] = EMPTY;
}
arraySize = newSize;
threshold = (int)(arraySize * 0.75);
size = 0;
}
/**
* @hide draft / provisional / internal are hidden on Android
*/
public synchronized long get(long key) {
return values[findIndex(key)];
}
/**
* @hide draft / provisional / internal are hidden on Android
*/
public synchronized void put(long key, long value)
{
if (size >= threshold) {
rehash();
}
int index = findIndex(key);
keys[index] = key;
values[index] = value;
size++;
}
private final int findIndex(long key) {
int index = hash(key);
int delta = 0;
while (values[index] != EMPTY && keys[index] != key)
{
if (delta == 0) {
delta = hash2(key);
}
index = (index + delta) % arraySize;
}
return index;
}
private void rehash()
{
int oldSize = arraySize;
long[] oldKeys = keys;
long[] oldValues = values;
if (pIndex < primes.length - 1) {
arraySize = primes[++pIndex];
} else {
arraySize = arraySize * 2 + 1;
}
size = 0;
makeArrays(arraySize);
for (int i = 0; i < oldSize; i++) {
if (oldValues[i] != EMPTY) {
put(oldKeys[i], oldValues[i]);
}
}
}
/**
* Produce a uniformly-distributed hash value from an integer key.
* This is essentially a linear congruential random number generator
* that uses the key as its seed value.
*/
private final int hash(long key)
{
int h = (int)((key * 15821 + 1) % arraySize);
if (h < 0) {
h += arraySize;
}
return h;
}
private final int hash2(long key) {
return arraySize - 2 - (int)(key % (arraySize-2) );
}
static private final int primes[] = { // 5, 17, 31, 47, // for testing
61, 127, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521,
131071, 262139,
};
private int pIndex = 0;
private int size = 0;
private int arraySize = primes[pIndex];
private int threshold = (arraySize * 3) / 4;
private long[] keys = new long[arraySize];
private long[] values = new long[arraySize];
/**
* @hide draft / provisional / internal are hidden on Android
*/
static public long EMPTY = Long.MIN_VALUE;
}
|
/*
* The MIT License
*
* Copyright (c) 2018-2022, qinglangtech Ltd
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.qlangtech.tis.hdfs.client.process;
import java.util.Map;
import com.qlangtech.tis.hdfs.util.Constants;
/*
* @description
* @since 2011-8-26 04:21:26
* @version 1.0
* @param <V>
* @param <K>
*
* @author 百岁(baisui@qlangtech.com)
* @date 2019年1月17日
*/
public abstract class BoostDataProcessor implements DataProcessor<String, String> {
public static final String BOOST_NAME = "!$boost";
protected void setBoost(Map<String, String> map, float boost) {
map.put(Constants.BOOST_COLUMN, String.valueOf(boost));
}
}
|
package joist.domain.orm.queries;
import joist.util.Join;
import org.junit.Assert;
import org.junit.Test;
public class WhereTest {
@Test
public void testAnd() {
Where w1 = new Where("a = ?", 1);
Where w2 = new Where("b = ?", 2);
Assert.assertEquals(Join.lines(//
"a = ?",
" AND b = ?"), w1.and(w2).getSql());
Where w3 = new Where("c = ?", 3);
Assert.assertEquals(Join.lines(//
"a = ?",
" AND b = ?",
" AND c = ?"), w1.and(w2).and(w3).getSql());
}
@Test
public void testOr() {
Where w1 = new Where("a = ?", 1);
Where w2 = new Where("b = ?", 2);
Assert.assertEquals(Join.lines(//
"a = ?",
" OR b = ?"), w1.or(w2).getSql());
Where w3 = new Where("c = ?", 3);
Assert.assertEquals(Join.lines(//
"a = ?",
" OR b = ?",
" OR c = ?"), w1.or(w2).or(w3).getSql());
}
@Test
public void testAndThenOr() {
Where w1 = new Where("a = ?", 1);
Where w2 = new Where("b = ?", 2);
Assert.assertEquals(Join.lines(//
"a = ?",
" AND b = ?"), w1.and(w2).getSql());
Where w3 = new Where("c = ?", 3);
Assert.assertEquals(Join.lines(//
"(",
" a = ?",
" AND b = ?",
" ) OR (",
" c = ?",
" )"), w1.and(w2).or(w3).getSql());
Where w4 = new Where("d = ?", 4);
Assert.assertEquals(Join.lines(//
"(",
" a = ?",
" AND b = ?",
" ) OR (",
" c = ?",
" )",
" OR d = ?"), w1.and(w2).or(w3).or(w4).getSql());
}
@Test
public void testOrTwoAnds() {
Where w1 = new Where("a = ?", 1).and(new Where("b = ?", 2));
Where w2 = new Where("c = ?", 3).and(new Where("d = ?", 4));
Assert.assertEquals(Join.lines(//
"(",
" a = ?",
" AND b = ?",
" ) OR (",
" c = ?",
" AND d = ?",
" )"), w1.or(w2).getSql());
}
@Test
public void testOrTwoComplexAnds() {
Where w1 = new Where("a = ?", 1).and(new Where("b = ?", 2).or(new Where("b = ?", 6)));
Where w2 = new Where("c = ?", 3).and(new Where("d = ?", 4).or(new Where("d = ?", 5)));
Assert.assertEquals(Join.lines(//
"(",
" a = ?",
" AND (",
" b = ?",
" OR b = ?",
" )",
" ) OR (",
" c = ?",
" AND (",
" d = ?",
" OR d = ?",
" )",
" )"), w1.or(w2).getSql());
}
}
|
package cn.com.sise.ca.castore.services;
import android.content.ComponentName;
import android.content.ServiceConnection;
import android.os.IBinder;
import java.util.LinkedList;
import java.util.Queue;
import cn.com.sise.ca.castore.server.ServerAction;
public class ServerActionServiceConnection implements ServiceConnection{
private ServerActionService.ActionServiceBinder binder;
private Queue<ServerAction> waitingQueue = new LinkedList<>();
public void addServerAction(ServerAction action) {
//当添加过快的时候,放到等待队列。
if (binder != null) {
binder.add(action);
} else {
waitingQueue.add(action);
}
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
binder = (ServerActionService.ActionServiceBinder) service;
//把等待队列的服务器动作放到 ServerActionService 中。
ServerAction action = null;
while ((action = waitingQueue.poll()) != null) {
binder.add(action);
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
|
package com.builtbroken.stonebucket;
import com.builtbroken.mc.fluids.api.reg.BucketMaterialRegistryEvent;
import com.builtbroken.mc.fluids.bucket.BucketMaterialHandler;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.oredict.OreDictionary;
import net.minecraftforge.oredict.ShapedOreRecipe;
/**
* Created by Dark on 7/21/2017.
*/
@Mod(modid = StoneBucket.DOMAIN, name = "Stone Bucket", version = "@MAJOR@.@MINOR@.@REVIS@.@BUILD@", dependencies = "after:vefluids")
@Mod.EventBusSubscriber(modid = StoneBucket.DOMAIN)
public class StoneBucket
{
public static final String DOMAIN = "stonebucket";
public static final String PREFIX = DOMAIN + ":";
public StoneBucket()
{
MinecraftForge.EVENT_BUS.register(this);
}
@SubscribeEvent
public void registerBucketMaterials(BucketMaterialRegistryEvent.Pre event)
{
for (BucketTypes type : BucketTypes.values())
{
type.material = new StoneBucketMaterial(type);
BucketMaterialHandler.addMaterial(type.name().toLowerCase(), type.material, type.ordinal());
}
}
@SubscribeEvent
public static void registerRecipes(RegistryEvent.Register<IRecipe> event)
{
//TODO add crafting recipes for milk bucket
ResourceLocation location = new ResourceLocation(DOMAIN, "woodenbucket");
for (BucketTypes type : BucketTypes.values())
{
event.getRegistry().register(new ShapedOreRecipe(location, type.getBucket(),
" s ",
"wcw",
" w ",
'w', type.getCraftingMaterial(),
's', "stickWood", 'c', "dye")
.setRegistryName("bucket." + type.name().toLowerCase()));
}
for (ItemStack itemstack : OreDictionary.getOres("stone"))
{
if (itemstack != null && itemstack.getItem() != Item.getItemFromBlock(Blocks.STONE))
{
event.getRegistry().register(new ShapedOreRecipe(location, BucketTypes.STONE.getBucket(),
" s ",
"wcw",
" w ",
'w', itemstack,
's', "stickWood", 'c', "dye")
.setRegistryName("bucket.stone.z" + itemstack.getUnlocalizedName()));
}
}
}
}
|
package ${packageName};
import java.net.URISyntaxException;
import org.junit.jupiter.api.DynamicContainer;
import org.junit.jupiter.api.TestFactory;
import de.tum.in.test.api.BlacklistPath;
import de.tum.in.test.api.PathType;
import de.tum.in.test.api.StrictTimeout;
import de.tum.in.test.api.WhitelistPath;
import de.tum.in.test.api.jupiter.Public;
import de.tum.in.test.api.structural.AttributeTestProvider;
/**
* @author Stephan Krusche (krusche@in.tum.de)
* @version 5.0 (11.11.2020)
* <br><br>
* This test evaluates if the specified attributes in the structure oracle are correctly implemented with the expected type, visibility modifiers and annotations,
* based on its definition in the structure oracle (test.json).
*/
@WhitelistPath("target")
@BlacklistPath(value = "**Test*.{java,class}", type = PathType.GLOB)
@Public
public class AttributeTest extends AttributeTestProvider {
/**
* This method collects the classes in the structure oracle file for which attributes are specified.
* These classes are then transformed into JUnit 5 dynamic tests.
* @return A dynamic test container containing the test for each class which is then executed by JUnit.
*/
@StrictTimeout(10)
@TestFactory
public DynamicContainer generateTestsForAllClasses() throws URISyntaxException {
structureOracleJSON = retrieveStructureOracleJSON(this.getClass().getResource("test.json"));
return super.generateTestsForAllClasses();
}
}
|
package net.minecraft.util;
import com.google.common.base.Predicate;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityArmorStand;
import net.minecraft.entity.player.Player;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
public final class EntitySelectors
{
public static final Predicate<Entity> selectAnything = new Predicate<Entity>()
{
public boolean apply(Entity p_apply_1_)
{
return p_apply_1_.isEntityAlive();
}
};
public static final Predicate<Entity> IS_STANDALONE = new Predicate<Entity>()
{
public boolean apply(Entity p_apply_1_)
{
return p_apply_1_.isEntityAlive() && p_apply_1_.riddenByEntity == null && p_apply_1_.ridingEntity == null;
}
};
public static final Predicate<Entity> selectInventories = new Predicate<Entity>()
{
public boolean apply(Entity p_apply_1_)
{
return p_apply_1_ instanceof IInventory && p_apply_1_.isEntityAlive();
}
};
public static final Predicate<Entity> NOT_SPECTATING = new Predicate<Entity>()
{
public boolean apply(Entity p_apply_1_)
{
return !(p_apply_1_ instanceof Player) || !((Player)p_apply_1_).isSpectator();
}
};
public static class ArmoredMob implements Predicate<Entity>
{
private final ItemStack armor;
public ArmoredMob(ItemStack armor)
{
this.armor = armor;
}
public boolean apply(Entity p_apply_1_)
{
if (!p_apply_1_.isEntityAlive())
{
return false;
}
else if (!(p_apply_1_ instanceof EntityLivingBase))
{
return false;
}
else
{
EntityLivingBase entitylivingbase = (EntityLivingBase)p_apply_1_;
return entitylivingbase.getEquipmentInSlot(EntityLiving.getArmorPosition(this.armor)) != null ? false : (entitylivingbase instanceof EntityLiving ? ((EntityLiving)entitylivingbase).canPickUpLoot() : (entitylivingbase instanceof EntityArmorStand ? true : entitylivingbase instanceof Player));
}
}
}
}
|
/*
* #%L
* Wisdom-Framework
* %%
* Copyright (C) 2013 - 2014 Wisdom Framework
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.wisdom.test.assertions;
import org.wisdom.api.cookies.SessionCookie;
import org.wisdom.api.http.Context;
import org.wisdom.test.http.HttpResponse;
import org.wisdom.test.parents.Action;
/**
* Wisdom specific AssertJ assertions.
*/
public class WisdomAssertions {
/**
* Give access to {@link org.wisdom.test.parents.Action.ActionResult} assertion.
* @param actual The tested ActionResult.
* @return an ActionResultAssert assert.
*/
public static ActionResultAssert assertThat(Action.ActionResult actual){
return ActionResultAssert.assertThat(actual);
}
/**
* Give access to {@link org.wisdom.api.http.Context} assertion.
* @param actual The tested Context.
* @return a ContextAssert assert.
*/
public static ContextAssert assertThat(Context actual){
return ContextAssert.assertThat(actual);
}
/**
* Give access to {@link org.wisdom.api.cookies.SessionCookie} assertion.
* @param actual The tested SessionCookie
* @return a SessionCookieAssert assert.
*/
public static SessionCookieAssert assertThat(SessionCookie actual){
return SessionCookieAssert.assertThat(actual);
}
/**
* Give access to {@link org.wisdom.test.http.HttpResponse} assertion.
* @param actual The tested HttpResponse.
* @param <T> The HttpResponse type.
* @return a HttpResponseAssert assert.
*/
public static<T> HttpResponseAssert<T> assertThat(HttpResponse<T> actual){
return HttpResponseAssert.assertThat(actual);
}
/**
* Give access to {@link org.wisdom.api.http.Status} assertion.
* @param actual The tested Status.
* @return a StatusAssert assert.
*/
public static StatusAssert assertStatus(Integer actual){
return StatusAssert.assertThat(actual);
}
}
|
package com.neo.caption.ocr.service.impl;
import com.neo.caption.ocr.pojo.AppHolder;
import com.neo.caption.ocr.service.StageService;
import javafx.scene.Node;
import javafx.stage.Stage;
import javafx.stage.Window;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
@Slf4j
public class StageServiceImpl implements StageService {
private final AppHolder appHolder;
public StageServiceImpl(AppHolder appHolder) {
this.appHolder = appHolder;
}
@Override
public Stage add(Node node) {
Stage stage = (Stage) node.getScene().getWindow();
add(stage);
return stage;
}
@Override
public void add(Stage stage) {
if (stage == null) {
return;
}
appHolder.getStageList().add(stage);
}
@Override
public void remove(Stage stage) {
if (stage == null) {
return;
}
appHolder.getStageList().remove(stage);
}
@Override
public Stage getFocusedStage() {
Optional<Stage> optional = appHolder.getStageList()
.stream()
.filter(Window::isFocused)
.findFirst();
if (optional.isEmpty()) {
return null;
}
return optional.get();
}
}
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.sync.ui;
import android.support.test.InstrumentationRegistry;
import android.widget.CheckedTextView;
import android.widget.HeaderViewListAdapter;
import android.widget.ListView;
import androidx.test.filters.SmallTest;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.base.test.util.CommandLineFlags;
import org.chromium.base.test.util.Feature;
import org.chromium.base.test.util.FlakyTest;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.flags.ChromeSwitches;
import org.chromium.chrome.browser.sync.SyncTestRule;
import org.chromium.chrome.test.ChromeJUnit4ClassRunner;
import org.chromium.components.sync.PassphraseType;
/**
* Tests to make sure that PassphraseTypeDialogFragment presents the correct options.
*/
@RunWith(ChromeJUnit4ClassRunner.class)
@CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE})
public class PassphraseTypeDialogFragmentTest {
@Rule
public SyncTestRule mSyncTestRule = new SyncTestRule();
private static final String TAG = "PassphraseTypeDialogFragmentTest";
private static final boolean ENABLED = true;
private static final boolean DISABLED = false;
private static final boolean CHECKED = true;
private static final boolean UNCHECKED = false;
private static class TypeOptions {
public final @PassphraseType int type;
public final boolean isEnabled;
public final boolean isChecked;
public TypeOptions(@PassphraseType int type, boolean isEnabled, boolean isChecked) {
this.type = type;
this.isEnabled = isEnabled;
this.isChecked = isChecked;
}
}
private PassphraseTypeDialogFragment mTypeFragment;
@Test
@SmallTest
@Feature({"Sync"})
public void testKeystoreEncryptionOptions() {
createFragment(PassphraseType.KEYSTORE_PASSPHRASE, true);
assertPassphraseTypeOptions(false,
new TypeOptions(PassphraseType.CUSTOM_PASSPHRASE, ENABLED, UNCHECKED),
new TypeOptions(PassphraseType.KEYSTORE_PASSPHRASE, ENABLED, CHECKED));
}
@Test
@SmallTest
@Feature({"Sync"})
public void testCustomEncryptionOptions() {
createFragment(PassphraseType.CUSTOM_PASSPHRASE, true);
assertPassphraseTypeOptions(true,
new TypeOptions(PassphraseType.CUSTOM_PASSPHRASE, DISABLED, CHECKED),
new TypeOptions(PassphraseType.KEYSTORE_PASSPHRASE, DISABLED, UNCHECKED));
}
/*
* @SmallTest
* @Feature({"Sync"})
*/
@Test
@FlakyTest(message = "crbug.com/588050")
public void testFrozenImplicitEncryptionOptions() {
createFragment(PassphraseType.FROZEN_IMPLICIT_PASSPHRASE, true);
assertPassphraseTypeOptions(true,
new TypeOptions(PassphraseType.FROZEN_IMPLICIT_PASSPHRASE, DISABLED, CHECKED),
new TypeOptions(PassphraseType.KEYSTORE_PASSPHRASE, DISABLED, UNCHECKED));
}
@Test
@SmallTest
@Feature({"Sync"})
public void testImplicitEncryptionOptions() {
createFragment(PassphraseType.IMPLICIT_PASSPHRASE, true);
assertPassphraseTypeOptions(false,
new TypeOptions(PassphraseType.CUSTOM_PASSPHRASE, ENABLED, UNCHECKED),
new TypeOptions(PassphraseType.IMPLICIT_PASSPHRASE, ENABLED, CHECKED));
}
@Test
@SmallTest
@Feature({"Sync"})
public void testKeystoreEncryptionOptionsCustomPassphraseDisallowed() {
createFragment(PassphraseType.KEYSTORE_PASSPHRASE, false);
assertPassphraseTypeOptions(false,
new TypeOptions(PassphraseType.CUSTOM_PASSPHRASE, DISABLED, UNCHECKED),
new TypeOptions(PassphraseType.KEYSTORE_PASSPHRASE, ENABLED, CHECKED));
}
@Test
@SmallTest
@Feature({"Sync"})
public void testImplicitEncryptionOptionsCustomPassphraseDisallowed() {
createFragment(PassphraseType.IMPLICIT_PASSPHRASE, false);
assertPassphraseTypeOptions(false,
new TypeOptions(PassphraseType.CUSTOM_PASSPHRASE, DISABLED, UNCHECKED),
new TypeOptions(PassphraseType.IMPLICIT_PASSPHRASE, ENABLED, CHECKED));
}
public void createFragment(@PassphraseType int type, boolean isCustomPassphraseAllowed) {
mTypeFragment = PassphraseTypeDialogFragment.create(type, isCustomPassphraseAllowed);
mTypeFragment.show(mSyncTestRule.getActivity().getSupportFragmentManager(), TAG);
InstrumentationRegistry.getInstrumentation().waitForIdleSync();
}
public void assertPassphraseTypeOptions(boolean hasFooter, TypeOptions... optionsList) {
ListView listView =
(ListView) mTypeFragment.getDialog().findViewById(R.id.passphrase_type_list);
PassphraseTypeDialogFragment.Adapter adapter;
if (hasFooter) {
HeaderViewListAdapter headerAdapter = (HeaderViewListAdapter) listView.getAdapter();
adapter = (PassphraseTypeDialogFragment.Adapter) headerAdapter.getWrappedAdapter();
} else {
adapter = (PassphraseTypeDialogFragment.Adapter) listView.getAdapter();
}
Assert.assertEquals(
"Number of options doesn't match.", optionsList.length, adapter.getCount());
for (int i = 0; i < optionsList.length; i++) {
TypeOptions options = optionsList[i];
Assert.assertEquals(
"Option " + i + " type is wrong.", options.type, adapter.getType(i));
CheckedTextView checkedView = (CheckedTextView) listView.getChildAt(i);
Assert.assertEquals("Option " + i + " enabled state is wrong.", options.isEnabled,
checkedView.isEnabled());
Assert.assertEquals("Option " + i + " checked state is wrong.", options.isChecked,
checkedView.isChecked());
}
}
}
|
package net.whg.we.ui.font;
public interface TextSelection
{
int selStart();
int selOrigin();
int selEnd();
boolean hasSelection();
void clearSelection();
void setSelection(int start, int origin, int end);
}
|
// Template Source: BaseEntityRequest.java.tt
// ------------------------------------------------------------------------------
// 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.http.IRequestBuilder;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.concurrency.ICallback;
import com.microsoft.graph.models.extensions.MicrosoftStoreForBusinessContainedApp;
import java.util.Arrays;
import java.util.EnumSet;
import com.microsoft.graph.core.IBaseClient;
import com.microsoft.graph.http.BaseRequest;
import com.microsoft.graph.http.HttpMethod;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Microsoft Store For Business Contained App Request.
*/
public class MicrosoftStoreForBusinessContainedAppRequest extends BaseRequest implements IMicrosoftStoreForBusinessContainedAppRequest {
/**
* The request for the MicrosoftStoreForBusinessContainedApp
*
* @param requestUrl the request URL
* @param client the service client
* @param requestOptions the options for this request
*/
public MicrosoftStoreForBusinessContainedAppRequest(final String requestUrl, final IBaseClient client, final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
super(requestUrl, client, requestOptions, MicrosoftStoreForBusinessContainedApp.class);
}
/**
* Gets the MicrosoftStoreForBusinessContainedApp from the service
*
* @param callback the callback to be called after success or failure
*/
public void get(final ICallback<? super MicrosoftStoreForBusinessContainedApp> callback) {
send(HttpMethod.GET, callback, null);
}
/**
* Gets the MicrosoftStoreForBusinessContainedApp from the service
*
* @return the MicrosoftStoreForBusinessContainedApp from the request
* @throws ClientException this exception occurs if the request was unable to complete for any reason
*/
public MicrosoftStoreForBusinessContainedApp get() throws ClientException {
return send(HttpMethod.GET, null);
}
/**
* Delete this item from the service
*
* @param callback the callback when the deletion action has completed
*/
public void delete(final ICallback<? super MicrosoftStoreForBusinessContainedApp> callback) {
send(HttpMethod.DELETE, callback, null);
}
/**
* Delete this item from the service
*
* @throws ClientException if there was an exception during the delete operation
*/
public void delete() throws ClientException {
send(HttpMethod.DELETE, null);
}
/**
* Patches this MicrosoftStoreForBusinessContainedApp with a source
*
* @param sourceMicrosoftStoreForBusinessContainedApp the source object with updates
* @param callback the callback to be called after success or failure
*/
public void patch(final MicrosoftStoreForBusinessContainedApp sourceMicrosoftStoreForBusinessContainedApp, final ICallback<? super MicrosoftStoreForBusinessContainedApp> callback) {
send(HttpMethod.PATCH, callback, sourceMicrosoftStoreForBusinessContainedApp);
}
/**
* Patches this MicrosoftStoreForBusinessContainedApp with a source
*
* @param sourceMicrosoftStoreForBusinessContainedApp the source object with updates
* @return the updated MicrosoftStoreForBusinessContainedApp
* @throws ClientException this exception occurs if the request was unable to complete for any reason
*/
public MicrosoftStoreForBusinessContainedApp patch(final MicrosoftStoreForBusinessContainedApp sourceMicrosoftStoreForBusinessContainedApp) throws ClientException {
return send(HttpMethod.PATCH, sourceMicrosoftStoreForBusinessContainedApp);
}
/**
* Creates a MicrosoftStoreForBusinessContainedApp with a new object
*
* @param newMicrosoftStoreForBusinessContainedApp the new object to create
* @param callback the callback to be called after success or failure
*/
public void post(final MicrosoftStoreForBusinessContainedApp newMicrosoftStoreForBusinessContainedApp, final ICallback<? super MicrosoftStoreForBusinessContainedApp> callback) {
send(HttpMethod.POST, callback, newMicrosoftStoreForBusinessContainedApp);
}
/**
* Creates a MicrosoftStoreForBusinessContainedApp with a new object
*
* @param newMicrosoftStoreForBusinessContainedApp the new object to create
* @return the created MicrosoftStoreForBusinessContainedApp
* @throws ClientException this exception occurs if the request was unable to complete for any reason
*/
public MicrosoftStoreForBusinessContainedApp post(final MicrosoftStoreForBusinessContainedApp newMicrosoftStoreForBusinessContainedApp) throws ClientException {
return send(HttpMethod.POST, newMicrosoftStoreForBusinessContainedApp);
}
/**
* Creates a MicrosoftStoreForBusinessContainedApp with a new object
*
* @param newMicrosoftStoreForBusinessContainedApp the object to create/update
* @param callback the callback to be called after success or failure
*/
public void put(final MicrosoftStoreForBusinessContainedApp newMicrosoftStoreForBusinessContainedApp, final ICallback<? super MicrosoftStoreForBusinessContainedApp> callback) {
send(HttpMethod.PUT, callback, newMicrosoftStoreForBusinessContainedApp);
}
/**
* Creates a MicrosoftStoreForBusinessContainedApp with a new object
*
* @param newMicrosoftStoreForBusinessContainedApp the object to create/update
* @return the created MicrosoftStoreForBusinessContainedApp
* @throws ClientException this exception occurs if the request was unable to complete for any reason
*/
public MicrosoftStoreForBusinessContainedApp put(final MicrosoftStoreForBusinessContainedApp newMicrosoftStoreForBusinessContainedApp) throws ClientException {
return send(HttpMethod.PUT, newMicrosoftStoreForBusinessContainedApp);
}
/**
* Sets the select clause for the request
*
* @param value the select clause
* @return the updated request
*/
public IMicrosoftStoreForBusinessContainedAppRequest select(final String value) {
getQueryOptions().add(new com.microsoft.graph.options.QueryOption("$select", value));
return (MicrosoftStoreForBusinessContainedAppRequest)this;
}
/**
* Sets the expand clause for the request
*
* @param value the expand clause
* @return the updated request
*/
public IMicrosoftStoreForBusinessContainedAppRequest expand(final String value) {
getQueryOptions().add(new com.microsoft.graph.options.QueryOption("$expand", value));
return (MicrosoftStoreForBusinessContainedAppRequest)this;
}
}
|
/*
* This file is part of Industrial Foregoing.
*
* Copyright 2019, Buuz135
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in the
* Software without restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.buuz135.industrial.utils.apihandlers.straw;
import com.buuz135.industrial.module.ModuleCore;
import net.minecraft.entity.item.ExperienceOrbEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.fluid.Fluid;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import javax.annotation.ParametersAreNonnullByDefault;
@ParametersAreNonnullByDefault
public class EssenceStrawHandler extends StrawHandlerBase {
public EssenceStrawHandler() {
super(ModuleCore.ESSENCE.getSourceFluid());
setRegistryName("essence");
}
@Override
public void onDrink(World world, BlockPos pos, Fluid stack, PlayerEntity player, boolean fromFluidContainer) {
world.addEntity(new ExperienceOrbEntity(world, player.getPosition().getX(), player.getPosition().getY(), player.getPosition().getZ(), world.rand.nextInt(10) + 8));
}
}
|
package eu.doppel_helix.jna.tlb.excel1;
import com.sun.jna.platform.win32.COM.util.annotation.ComInterface;
import com.sun.jna.platform.win32.COM.util.annotation.ComMethod;
import com.sun.jna.platform.win32.COM.util.annotation.ComProperty;
import com.sun.jna.platform.win32.COM.util.IDispatch;
import com.sun.jna.platform.win32.COM.util.IUnknown;
import com.sun.jna.platform.win32.COM.util.IRawDispatchHandle;
import com.sun.jna.platform.win32.Variant.VARIANT;
/**
* <p>uuid({000208B9-0000-0000-C000-000000000046})</p>
*/
@ComInterface(iid="{000208B9-0000-0000-C000-000000000046}")
public interface Name extends IUnknown, IRawDispatchHandle, IDispatch {
/**
* <p>id(0x94)</p>
* <p>vtableId(7)</p>
*/
@ComProperty(name = "Application", dispId = 0x94)
Application getApplication();
/**
* <p>id(0x95)</p>
* <p>vtableId(8)</p>
*/
@ComProperty(name = "Creator", dispId = 0x95)
XlCreator getCreator();
/**
* <p>id(0x96)</p>
* <p>vtableId(9)</p>
*/
@ComProperty(name = "Parent", dispId = 0x96)
com.sun.jna.platform.win32.COM.util.IDispatch getParent();
/**
* <p>id(0x0)</p>
* <p>vtableId(10)</p>
*/
@ComProperty(name = "_Default", dispId = 0x0)
String get_Default();
/**
* <p>id(0x1e6)</p>
* <p>vtableId(11)</p>
*/
@ComProperty(name = "Index", dispId = 0x1e6)
Integer getIndex();
/**
* <p>id(0x3a6)</p>
* <p>vtableId(12)</p>
*/
@ComProperty(name = "Category", dispId = 0x3a6)
String getCategory();
/**
* <p>id(0x3a6)</p>
* <p>vtableId(13)</p>
* @param param0 [in] {@code String}
*/
@ComProperty(name = "Category", dispId = 0x3a6)
void setCategory(String param0);
/**
* <p>id(0x3a7)</p>
* <p>vtableId(14)</p>
*/
@ComProperty(name = "CategoryLocal", dispId = 0x3a7)
String getCategoryLocal();
/**
* <p>id(0x3a7)</p>
* <p>vtableId(15)</p>
* @param param0 [in] {@code String}
*/
@ComProperty(name = "CategoryLocal", dispId = 0x3a7)
void setCategoryLocal(String param0);
/**
* <p>id(0x75)</p>
* <p>vtableId(16)</p>
*/
@ComMethod(name = "Delete", dispId = 0x75)
void Delete();
/**
* <p>id(0x3a8)</p>
* <p>vtableId(17)</p>
*/
@ComProperty(name = "MacroType", dispId = 0x3a8)
XlXLMMacroType getMacroType();
/**
* <p>id(0x3a8)</p>
* <p>vtableId(18)</p>
* @param param0 [in] {@code XlXLMMacroType}
*/
@ComProperty(name = "MacroType", dispId = 0x3a8)
void setMacroType(XlXLMMacroType param0);
/**
* <p>id(0x6e)</p>
* <p>vtableId(19)</p>
*/
@ComProperty(name = "Name", dispId = 0x6e)
String getName();
/**
* <p>id(0x6e)</p>
* <p>vtableId(20)</p>
* @param param0 [in] {@code String}
*/
@ComProperty(name = "Name", dispId = 0x6e)
void setName(String param0);
/**
* <p>id(0x3aa)</p>
* <p>vtableId(21)</p>
*/
@ComProperty(name = "RefersTo", dispId = 0x3aa)
Object getRefersTo();
/**
* <p>id(0x3aa)</p>
* <p>vtableId(22)</p>
* @param param0 [in] {@code Object}
*/
@ComProperty(name = "RefersTo", dispId = 0x3aa)
void setRefersTo(Object param0);
/**
* <p>id(0x255)</p>
* <p>vtableId(23)</p>
*/
@ComProperty(name = "ShortcutKey", dispId = 0x255)
String getShortcutKey();
/**
* <p>id(0x255)</p>
* <p>vtableId(24)</p>
* @param param0 [in] {@code String}
*/
@ComProperty(name = "ShortcutKey", dispId = 0x255)
void setShortcutKey(String param0);
/**
* <p>id(0x6)</p>
* <p>vtableId(25)</p>
*/
@ComProperty(name = "Value", dispId = 0x6)
String getValue();
/**
* <p>id(0x6)</p>
* <p>vtableId(26)</p>
* @param param0 [in] {@code String}
*/
@ComProperty(name = "Value", dispId = 0x6)
void setValue(String param0);
/**
* <p>id(0x22e)</p>
* <p>vtableId(27)</p>
*/
@ComProperty(name = "Visible", dispId = 0x22e)
Boolean getVisible();
/**
* <p>id(0x22e)</p>
* <p>vtableId(28)</p>
* @param param0 [in] {@code Boolean}
*/
@ComProperty(name = "Visible", dispId = 0x22e)
void setVisible(Boolean param0);
/**
* <p>id(0x3a9)</p>
* <p>vtableId(29)</p>
*/
@ComProperty(name = "NameLocal", dispId = 0x3a9)
String getNameLocal();
/**
* <p>id(0x3a9)</p>
* <p>vtableId(30)</p>
* @param param0 [in] {@code String}
*/
@ComProperty(name = "NameLocal", dispId = 0x3a9)
void setNameLocal(String param0);
/**
* <p>id(0x3ab)</p>
* <p>vtableId(31)</p>
*/
@ComProperty(name = "RefersToLocal", dispId = 0x3ab)
Object getRefersToLocal();
/**
* <p>id(0x3ab)</p>
* <p>vtableId(32)</p>
* @param param0 [in] {@code Object}
*/
@ComProperty(name = "RefersToLocal", dispId = 0x3ab)
void setRefersToLocal(Object param0);
/**
* <p>id(0x3ac)</p>
* <p>vtableId(33)</p>
*/
@ComProperty(name = "RefersToR1C1", dispId = 0x3ac)
Object getRefersToR1C1();
/**
* <p>id(0x3ac)</p>
* <p>vtableId(34)</p>
* @param param0 [in] {@code Object}
*/
@ComProperty(name = "RefersToR1C1", dispId = 0x3ac)
void setRefersToR1C1(Object param0);
/**
* <p>id(0x3ad)</p>
* <p>vtableId(35)</p>
*/
@ComProperty(name = "RefersToR1C1Local", dispId = 0x3ad)
Object getRefersToR1C1Local();
/**
* <p>id(0x3ad)</p>
* <p>vtableId(36)</p>
* @param param0 [in] {@code Object}
*/
@ComProperty(name = "RefersToR1C1Local", dispId = 0x3ad)
void setRefersToR1C1Local(Object param0);
/**
* <p>id(0x488)</p>
* <p>vtableId(37)</p>
*/
@ComProperty(name = "RefersToRange", dispId = 0x488)
Range getRefersToRange();
/**
* <p>id(0x38e)</p>
* <p>vtableId(38)</p>
*/
@ComProperty(name = "Comment", dispId = 0x38e)
String getComment();
/**
* <p>id(0x38e)</p>
* <p>vtableId(39)</p>
* @param param0 [in] {@code String}
*/
@ComProperty(name = "Comment", dispId = 0x38e)
void setComment(String param0);
/**
* <p>id(0xa2f)</p>
* <p>vtableId(40)</p>
*/
@ComProperty(name = "WorkbookParameter", dispId = 0xa2f)
Boolean getWorkbookParameter();
/**
* <p>id(0xa2f)</p>
* <p>vtableId(41)</p>
* @param param0 [in] {@code Boolean}
*/
@ComProperty(name = "WorkbookParameter", dispId = 0xa2f)
void setWorkbookParameter(Boolean param0);
/**
* <p>id(0xa30)</p>
* <p>vtableId(42)</p>
*/
@ComProperty(name = "ValidWorkbookParameter", dispId = 0xa30)
Boolean getValidWorkbookParameter();
}
|
/*
* 3D City Database - The Open Source CityGML Database
* http://www.3dcitydb.org/
*
* Copyright 2013 - 2019
* Chair of Geoinformatics
* Technical University of Munich, Germany
* https://www.gis.bgu.tum.de/
*
* The 3D City Database is jointly developed with the following
* cooperation partners:
*
* virtualcitySYSTEMS GmbH, Berlin <http://www.virtualcitysystems.de/>
* M.O.S.S. Computer Grafik Systeme GmbH, Taufkirchen <http://www.moss.de/>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.citydb.database.adapter.h2;
import org.citydb.config.geometry.GeometryObject;
import org.citydb.database.adapter.AbstractDatabaseAdapter;
import org.citydb.database.adapter.AbstractSQLAdapter;
import org.citydb.database.adapter.BlobExportAdapter;
import org.citydb.database.adapter.BlobImportAdapter;
import org.citydb.database.adapter.BlobType;
import org.citydb.query.filter.selection.operator.spatial.SpatialOperatorName;
import org.citydb.sqlbuilder.schema.Column;
import org.citydb.sqlbuilder.select.PredicateToken;
import org.citydb.sqlbuilder.select.projection.Function;
import java.sql.Connection;
import java.sql.SQLException;
public class SQLAdapter extends AbstractSQLAdapter {
protected SQLAdapter(AbstractDatabaseAdapter databaseAdapter) {
super(databaseAdapter);
}
@Override
public String getInteger() {
return "BIGINT";
}
@Override
public String getSmallInt() {
return "SMALLINT";
}
@Override
public String getBigInt() {
return "BIGINT";
}
@Override
public String getNumeric() {
return "BIGINT";
}
@Override
public String getNumeric(int precision) {
if (precision <= 3)
return "SMALLINT";
return "BIGINT";
}
@Override
public String getNumeric(int precision, int scale) {
if (precision == 1 && scale == 0)
return "TINYINT";
return "DECIMAL";
}
@Override
public String getReal() {
return "REAL";
}
@Override
public String getDoublePrecision() {
return "DOUBLE";
}
@Override
public String getCharacter(int nrOfChars) {
return "VARCHAR(" + nrOfChars + ")";
}
@Override
public String getCharacterVarying(int nrOfChars) {
return "VARCHAR(" + nrOfChars + ")";
}
@Override
public String getPolygon2D() {
return "GEOMETRY";
}
@Override
public String getCreateUnloggedTable(String tableName, String columns) {
return "create table " + tableName + " " + columns;
}
@Override
public String getCreateUnloggedTableAsSelect(String tableName, String select) {
return "create table " + tableName + " as " + select;
}
@Override
public String getUnloggedIndexProperty() {
return "";
}
@Override
public boolean requiresPseudoTableInSelect() {
return false;
}
@Override
public String getPseudoTableName() {
return "";
}
@Override
public int getMaximumNumberOfItemsForInOperator() {
// not required for cache tables
return 0;
}
@Override
public boolean spatialPredicateRequiresNoIndexHint() {
return false;
}
@Override
public String getHierarchicalGeometryQuery() {
// not required for cache tables
return "";
}
@Override
public String getNextSequenceValue(String sequence) {
// not required for cache tables
return "";
}
@Override
public String getCurrentSequenceValue(String sequence) {
// not required for cache tables
return "";
}
@Override
public String getNextSequenceValuesQuery(String sequence) {
// not required for cache tables
return "";
}
@Override
public BlobImportAdapter getBlobImportAdapter(Connection connection, BlobType type) throws SQLException {
// not required for cache tables
return null;
}
@Override
public BlobExportAdapter getBlobExportAdapter(Connection connection, BlobType type) {
// not required for cache tables
return null;
}
@Override
public PredicateToken getBinarySpatialPredicate(SpatialOperatorName operator, Column targetColumn, GeometryObject geometry, boolean negate) {
// not required for cache tables
return null;
}
@Override
public PredicateToken getDistancePredicate(SpatialOperatorName operator, Column targetColumn, GeometryObject geometry, double distance, boolean negate) {
// not required for cache tables
return null;
}
@Override
public Function getAggregateExtentFunction(Column envelope) {
// not required for cache tables
return null;
}
}
|
package com.stylefeng.guns.rest;
public class Singleton {
private volatile static Singleton uniqueInstance;
private Singleton(){
}
public static Singleton getUniqueInstance(){
if (uniqueInstance == null) {
synchronized (Singleton.class) {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}
|
package chylex.hee.game.integration;
@FunctionalInterface
public interface IIntegrationHandler{
void integrate() throws Throwable;
}
|
package utils;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class CalendarJoinCodeIdQuery implements CalendarIdQuery {
private static String CID_COLUMN = "ID";
private static String JOIN_CODE_COLUMN = "JOIN_CODE";
private String joinCode;
private int cid;
public CalendarJoinCodeIdQuery(String joinCode) {
this.joinCode = joinCode;
}
@Override
public String getSQLQuery() {
return String.format("SELECT \"%s\" FROM \"CALENDAR\" WHERE \"%s\"=?;",
CID_COLUMN, JOIN_CODE_COLUMN);
}
@Override
public void formatSQLQuery(PreparedStatement prepared) throws SQLException {
prepared.setString(1, joinCode);
}
@Override
public void setResult(ResultSet result) {
try {
if (result.next()) {
cid = result.getInt(CID_COLUMN);
}
} catch (SQLException e) {
System.err.println("Data base error occured while retrieving the " +
"calndar ID given the join code.");
e.printStackTrace();
}
}
@Override
public int getCalendarId() {
return cid;
}
}
|
package com.yash.logger;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import com.yash.logging.LogHelper;
import com.yash.logging.LogViewerActivity;
import com.yash.logging.R;
import com.yash.logging.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
ActivityMainBinding mainBinding;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainBinding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(mainBinding.getRoot());
LogHelper.d(TAG, "onCreate: ");
LogHelper.d(TAG, "onCreate: ");
LogHelper.d(TAG, "onCreate: ");
LogHelper.d(TAG, "onCreate: ");
LogHelper.d(TAG, "onCreate: ");
LogHelper.d(TAG, "onCreate: ");
LogHelper.d(TAG, "onCreate: ");
LogHelper.d(TAG, "onCreate: ");
LogHelper.d(TAG, "onCreate: ");
LogHelper.d(TAG, "onCreate: ");
LogHelper.d(TAG, "onCreate: ");
context = this;
mainBinding.showLogs.setOnClickListener(v->{
// AlertDialog.Builder builder = new AlertDialog.Builder(context);
// builder.setTitle("App Logs")
// .setMessage(LogHelper.getLogs())
// .setCancelable(false)
// .setPositiveButton("CANCEL",(dialog, which) -> {
// dialog.dismiss();
// });
// AlertDialog alertDialog = builder.create();
// alertDialog.show();
startActivity(new Intent(this, LogViewerActivity.class));
});
}
}
|
/*******************************************************************************
* Copyright (c) 1991, 2021 IBM Corp. and others
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License 2.0 which accompanies this
* distribution and is available at https://www.eclipse.org/legal/epl-2.0/
* or the Apache License, Version 2.0 which accompanies this distribution
* and is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* This Source Code may also be made available under the following
* Secondary Licenses when the conditions for such availability set
* forth in the Eclipse Public License, v. 2.0 are satisfied: GNU
* General Public License, version 2 with the GNU Classpath
* Exception [1] and GNU General Public License, version 2 with the
* OpenJDK Assembly Exception [2].
*
* [1] https://www.gnu.org/software/classpath/license.html
* [2] http://openjdk.java.net/legal/assembly-exception.html
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception
*******************************************************************************/
/**
* WARNING!!! GENERATED FILE
*
* This class is generated.
* Do not use the Eclipse "Organize Imports" feature on this class.
*
* It can contain user content, but that content must be delimited with the
* the tags
* [BEGIN USER IMPORTS]
* [END USER IMPORTS]
*
* or
*
* [BEGIN USER CODE]
* [END USER CODE]
*
* These tags are entered as comments. Characters before [ and after ] are ignored.
* Lines between the tags are inserted into the newly generated file.
*
* IMPORTS are combined and inserted above newly generated imports. CODE is combined
* and inserted immediately after the class declaration
*
* All lines outside these tags are lost and replaced with newly generated code.
*/
package com.ibm.j9ddr.vm29.pointer.generated;
/*[BEGIN USER IMPORTS]*/
/*[END USER IMPORTS]*/
import com.ibm.j9ddr.CorruptDataException;
import com.ibm.j9ddr.vm29.pointer.*;
import com.ibm.j9ddr.vm29.structure.*;
import com.ibm.j9ddr.vm29.types.*;
/**
* Structure: MM_CompactDelegatePointer
*
* A generated implementation of a VM structure
*
* This class contains generated code and MAY contain hand written user code.
*
* Hand written user code must be contained at the top of
* the class file, specifically above
* the comment line containing WARNING!!! GENERATED CODE
*
* ALL code below the GENERATED warning will be replaced with new generated code
* each time the PointerGenerator utility is run.
*
* The generated code will provide getters for all elements in the MM_CompactDelegatePointer
* structure. Where possible, meaningful return types are inferred.
*
* The user may add methods to provide meaningful return types where only pointers
* could be automatically inferred.
*/
@com.ibm.j9ddr.GeneratedPointerClass(structureClass=MM_CompactDelegate.class)
public class MM_CompactDelegatePointer extends StructurePointer {
// NULL
public static final MM_CompactDelegatePointer NULL = new MM_CompactDelegatePointer(0);
/*[BEGIN USER CODE]*/
/*[END USER CODE]*/
// Do not call this constructor. Use static method cast instead.
protected MM_CompactDelegatePointer(long address) {
super(address);
}
public static MM_CompactDelegatePointer cast(AbstractPointer structure) {
return cast(structure.getAddress());
}
public static MM_CompactDelegatePointer cast(UDATA udata) {
return cast(udata.longValue());
}
public static MM_CompactDelegatePointer cast(long address) {
if (address == 0) {
return NULL;
}
return new MM_CompactDelegatePointer(address);
}
public MM_CompactDelegatePointer add(long count) {
return MM_CompactDelegatePointer.cast(address + (MM_CompactDelegate.SIZEOF * count));
}
public MM_CompactDelegatePointer add(Scalar count) {
return add(count.longValue());
}
public MM_CompactDelegatePointer addOffset(long offset) {
return MM_CompactDelegatePointer.cast(address + offset);
}
public MM_CompactDelegatePointer addOffset(Scalar offset) {
return addOffset(offset.longValue());
}
public MM_CompactDelegatePointer sub(long count) {
return MM_CompactDelegatePointer.cast(address - (MM_CompactDelegate.SIZEOF * count));
}
public MM_CompactDelegatePointer sub(Scalar count) {
return sub(count.longValue());
}
public MM_CompactDelegatePointer subOffset(long offset) {
return MM_CompactDelegatePointer.cast(address - offset);
}
public MM_CompactDelegatePointer subOffset(Scalar offset) {
return subOffset(offset.longValue());
}
public MM_CompactDelegatePointer untag(long mask) {
return MM_CompactDelegatePointer.cast(address & ~mask);
}
public MM_CompactDelegatePointer untag() {
return untag(UDATA.SIZEOF - 1);
}
protected long sizeOfBaseType() {
return MM_CompactDelegate.SIZEOF;
}
// Implementation methods
// MM_CompactScheme* _compactScheme
@com.ibm.j9ddr.GeneratedFieldAccessor(offsetFieldName="__compactSchemeOffset_", declaredType="MM_CompactScheme*")
public MM_CompactSchemePointer _compactScheme() throws CorruptDataException {
return MM_CompactSchemePointer.cast(getPointerAtOffset(MM_CompactDelegate.__compactSchemeOffset_));
}
// MM_CompactScheme* _compactScheme
public PointerPointer _compactSchemeEA() throws CorruptDataException {
return PointerPointer.cast(nonNullFieldEA(MM_CompactDelegate.__compactSchemeOffset_));
}
// MM_MarkMap* _markMap
@com.ibm.j9ddr.GeneratedFieldAccessor(offsetFieldName="__markMapOffset_", declaredType="MM_MarkMap*")
public MM_MarkMapPointer _markMap() throws CorruptDataException {
return MM_MarkMapPointer.cast(getPointerAtOffset(MM_CompactDelegate.__markMapOffset_));
}
// MM_MarkMap* _markMap
public PointerPointer _markMapEA() throws CorruptDataException {
return PointerPointer.cast(nonNullFieldEA(MM_CompactDelegate.__markMapOffset_));
}
// OMR_VM* _omrVM
@com.ibm.j9ddr.GeneratedFieldAccessor(offsetFieldName="__omrVMOffset_", declaredType="OMR_VM*")
public OMR_VMPointer _omrVM() throws CorruptDataException {
return OMR_VMPointer.cast(getPointerAtOffset(MM_CompactDelegate.__omrVMOffset_));
}
// OMR_VM* _omrVM
public PointerPointer _omrVMEA() throws CorruptDataException {
return PointerPointer.cast(nonNullFieldEA(MM_CompactDelegate.__omrVMOffset_));
}
}
|
/*
* 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.thrift;
import junit.framework.TestCase;
import org.apache.thrift.Option;
// Tests and documents behavior for the "Option<T>" type
public class TestOptionType extends TestCase {
public void testSome() throws Exception {
String name = "Chuck Norris";
Option<String> option = Option.fromNullable(name);
assertTrue(option instanceof Option.Some);
assertTrue(option.isDefined());
assertEquals("Some(Chuck Norris)", option.toString());
assertEquals(option.or("default value"), "Chuck Norris");
assertEquals(option.get(),"Chuck Norris");
}
public void testNone() throws Exception {
String name = null;
Option<String> option = Option.fromNullable(name);
assertTrue(option instanceof Option.None);
assertFalse(option.isDefined());
assertEquals("None", option.toString());
assertEquals(option.or("default value"), "default value");
// Expect exception
try {
Object value = option.get();
fail("Expected IllegalStateException, got no exception");
} catch (IllegalStateException ex) {
} catch(Exception ex) {
fail("Expected IllegalStateException, got some other exception: "+ex.toString());
}
}
public void testMakeSome() throws Exception {
Option<String> some = Option.some("wee");
assertTrue(some instanceof Option.Some);
}
public void testMakeNone() throws Exception {
Option<Integer> none = Option.none();
assertTrue(none instanceof Option.None);
}
}
|
/*
* 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.kylin.cube.upgrade.common;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.kylin.common.KylinConfig;
import org.apache.kylin.common.persistence.ResourceStore;
import org.apache.kylin.cube.CubeDescManager;
import org.apache.kylin.cube.CubeManager;
import org.apache.kylin.metadata.MetadataConstants;
import org.apache.kylin.metadata.MetadataManager;
import org.apache.kylin.metadata.project.ProjectManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;
public abstract class CubeMetadataUpgrade {
private static final Logger logger = LoggerFactory.getLogger(CubeMetadataUpgrade.class);
protected KylinConfig config = null;
protected ResourceStore store;
protected List<String> updatedResources = Lists.newArrayList();
protected List<String> errorMsgs = Lists.newArrayList();
public CubeMetadataUpgrade(String newMetadataUrl) {
KylinConfig.destroyInstance();
config = KylinConfig.createInstanceFromUri(newMetadataUrl);
store = ResourceStore.getStore(config);
}
protected List<String> listResourceStore(String pathRoot) {
List<String> paths = null;
try {
paths = store.collectResourceRecursively(pathRoot, MetadataConstants.FILE_SURFIX);
} catch (IOException e1) {
logger.error("error", e1);
errorMsgs.add("Get IOException when scan resource store at: " + ResourceStore.CUBE_DESC_RESOURCE_ROOT);
}
return paths;
}
public void clear() {
MetadataManager.clearCache();
CubeDescManager.clearCache();
CubeManager.clearCache();
ProjectManager.clearCache();
}
public void verify() {
logger.info("=================================================================");
logger.info("The changes are applied, now it's time to verify the new metadata store by reloading all metadata:");
logger.info("=================================================================");
MetadataManager.clearCache();
MetadataManager.getInstance(config);
CubeDescManager.clearCache();
CubeDescManager.getInstance(config);
CubeManager.clearCache();
CubeManager.getInstance(config);
ProjectManager.clearCache();
ProjectManager.getInstance(config);
//cleanup();
}
public abstract void upgradeNonCompatibleMeta();
public abstract void upgradeCompatibleMeta();
public static void upgradeOrVerify(Class upgradeClass, String[] args, boolean firstStepInChain, boolean lastStepInChain) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
if (!(args != null && (args.length == 1))) {
System.out.println("Usage: java CubeMetadataUpgrade <metadata_export_folder>");
System.out.println(", where metadata_export_folder is the folder containing your current metadata's dump (Upgrade program will not modify it directly, relax.");
return;
}
String currentMetaDumpFolderPath = args[0];
CubeMetadataUpgrade instance;
File currentMetaDumpFolder = new File(currentMetaDumpFolderPath);
if (!currentMetaDumpFolder.exists()) {
System.out.println("Provided folder doesn't exist: '" + currentMetaDumpFolderPath + "'");
return;
}
if (!currentMetaDumpFolder.isDirectory()) {
System.out.println("Provided folder is not a directory: '" + currentMetaDumpFolderPath + "'");
return;
}
String newMetadataUrl;
if (firstStepInChain) {
newMetadataUrl = currentMetaDumpFolder.getAbsolutePath() + "_workspace";//upgrades metadata store in a copy named xx_workspace
try {
FileUtils.deleteDirectory(new File(newMetadataUrl));
FileUtils.copyDirectory(currentMetaDumpFolder, new File(newMetadataUrl));
} catch (IOException e) {
throw new RuntimeException(e);
}
} else {
newMetadataUrl = currentMetaDumpFolder.getAbsolutePath();
}
instance = (CubeMetadataUpgrade) upgradeClass.getConstructor(String.class).newInstance(newMetadataUrl);
instance.upgradeNonCompatibleMeta();
logger.info("=================================================================");
logger.info("Run {} completed", upgradeClass.toString());
logger.info("=================================================================");
if (instance.errorMsgs.size() > 0) {
logger.info("Here are the error/warning messages, you may need check:");
for (String s : instance.errorMsgs) {
logger.error(s);
}
} else {
logger.info("No error or warning messages; The migration is success.");
}
if (lastStepInChain) {
instance.upgradeCompatibleMeta();
instance.verify();
}
}
}
|
package com.taibai.common.data.cache;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Collections;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
import org.springframework.dao.PessimisticLockingFailureException;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStringCommands.SetOption;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* {@link RedisCacheWriter} implementation capable of reading/writing binary
* data from/to Redis in {@literal standalone} and {@literal cluster}
* environments. Works upon a given {@link RedisConnectionFactory} to obtain the
* actual {@link RedisConnection}. <br />
* {@link DefaultRedisCacheWriter} can be used in
* {@link RedisCacheWriter#lockingRedisCacheWriter(RedisConnectionFactory)
* locking} or
* {@link RedisCacheWriter#nonLockingRedisCacheWriter(RedisConnectionFactory)
* non-locking} mode. While {@literal non-locking} aims for maximum performance
* it may result in overlapping, non atomic, command execution for operations
* spanning multiple Redis interactions like {@code putIfAbsent}. The
* {@literal locking} counterpart prevents command overlap by setting an
* explicit lock key and checking against presence of this key which leads to
* additional requests and potential command wait times.
*
* @author Taibai
* @since 2.0
*/
class DefaultRedisCacheWriter implements RedisCacheWriter {
private final RedisConnectionFactory connectionFactory;
private final Duration sleepTime;
/**
* @param connectionFactory must not be {@literal null}.
*/
DefaultRedisCacheWriter(RedisConnectionFactory connectionFactory) {
this(connectionFactory, Duration.ZERO);
}
/**
* @param connectionFactory must not be {@literal null}.
* @param sleepTime sleep time between lock request attempts. Must not
* be {@literal null}. Use {@link Duration#ZERO} to
* disable locking.
*/
private DefaultRedisCacheWriter(RedisConnectionFactory connectionFactory, Duration sleepTime) {
Assert.notNull(connectionFactory, "ConnectionFactory must not be null!");
Assert.notNull(sleepTime, "SleepTime must not be null!");
this.connectionFactory = connectionFactory;
this.sleepTime = sleepTime;
}
@Override
public void put(String name, byte[] key, byte[] value, @Nullable Duration ttl) {
Assert.notNull(name, "Name must not be null!");
Assert.notNull(key, "Key must not be null!");
Assert.notNull(value, "Value must not be null!");
execute(name, connection -> {
if (shouldExpireWithin(ttl)) {
connection.set(key, value, Expiration.from(ttl.toMillis(), TimeUnit.MILLISECONDS), SetOption.upsert());
} else {
connection.set(key, value);
}
return "OK";
});
}
@Override
public byte[] get(String name, byte[] key) {
Assert.notNull(name, "Name must not be null!");
Assert.notNull(key, "Key must not be null!");
return execute(name, connection -> connection.get(key));
}
@Override
public byte[] putIfAbsent(String name, byte[] key, byte[] value, @Nullable Duration ttl) {
Assert.notNull(name, "Name must not be null!");
Assert.notNull(key, "Key must not be null!");
Assert.notNull(value, "Value must not be null!");
return execute(name, connection -> {
if (isLockingCacheWriter()) {
doLock(name, connection);
}
try {
if (connection.setNX(key, value)) {
if (shouldExpireWithin(ttl)) {
connection.pExpire(key, ttl.toMillis());
}
return null;
}
return connection.get(key);
} finally {
if (isLockingCacheWriter()) {
doUnlock(name, connection);
}
}
});
}
@Override
public void remove(String name, byte[] key) {
Assert.notNull(name, "Name must not be null!");
Assert.notNull(key, "Key must not be null!");
execute(name, connection -> connection.del(key));
}
@Override
public void clean(String name, byte[] pattern) {
Assert.notNull(name, "Name must not be null!");
Assert.notNull(pattern, "Pattern must not be null!");
execute(name, connection -> {
boolean wasLocked = false;
try {
if (isLockingCacheWriter()) {
doLock(name, connection);
wasLocked = true;
}
byte[][] keys = Optional.ofNullable(connection.keys(pattern)).orElse(Collections.emptySet())
.toArray(new byte[0][]);
if (keys.length > 0) {
connection.del(keys);
}
} finally {
if (wasLocked && isLockingCacheWriter()) {
doUnlock(name, connection);
}
}
return "OK";
});
}
/**
* Explicitly set a write lock on a cache.
*
* @param name the name of the cache to lock.
*/
void lock(String name) {
execute(name, connection -> doLock(name, connection));
}
/**
* Explicitly remove a write lock from a cache.
*
* @param name the name of the cache to unlock.
*/
void unlock(String name) {
executeLockFree(connection -> doUnlock(name, connection));
}
private Boolean doLock(String name, RedisConnection connection) {
return connection.setNX(createCacheLockKey(name), new byte[0]);
}
private Long doUnlock(String name, RedisConnection connection) {
return connection.del(createCacheLockKey(name));
}
boolean doCheckLock(String name, RedisConnection connection) {
return connection.exists(createCacheLockKey(name));
}
/**
* @return {@literal true} if {@link RedisCacheWriter} uses locks.
*/
private boolean isLockingCacheWriter() {
return !sleepTime.isZero() && !sleepTime.isNegative();
}
private <T> T execute(String name, Function<RedisConnection, T> callback) {
RedisConnection connection = connectionFactory.getConnection();
try {
checkAndPotentiallyWaitUntilUnlocked(name, connection);
return callback.apply(connection);
} finally {
connection.close();
}
}
private void executeLockFree(Consumer<RedisConnection> callback) {
RedisConnection connection = connectionFactory.getConnection();
try {
callback.accept(connection);
} finally {
connection.close();
}
}
private void checkAndPotentiallyWaitUntilUnlocked(String name, RedisConnection connection) {
if (!isLockingCacheWriter()) {
return;
}
try {
while (doCheckLock(name, connection)) {
Thread.sleep(sleepTime.toMillis());
}
} catch (InterruptedException ex) {
// Re-interrupt current thread, to allow other participants to react.
Thread.currentThread().interrupt();
throw new PessimisticLockingFailureException(
String.format("Interrupted while waiting to unlock cache %s", name), ex);
}
}
private static boolean shouldExpireWithin(@Nullable Duration ttl) {
return ttl != null && !ttl.isZero() && !ttl.isNegative();
}
private static byte[] createCacheLockKey(String name) {
return (name + "~lock").getBytes(StandardCharsets.UTF_8);
}
}
|
/*
* 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.tester;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* Exercise basic forwarding functionality.
*
* @author Craig R. McClanahan
* @version $Id$
*/
public class Forward00 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// Prepare this response
StringBuffer sb = new StringBuffer();
response.setContentType("text/plain");
PrintWriter writer = response.getWriter();
// Acquire the path to which we will issue a forward
String path = request.getParameter("path");
if (path == null)
path = "/Forward00a";
// Create a request dispatcher and call forward() on it
RequestDispatcher rd = null;
if (path.startsWith("!"))
rd = getServletContext().getNamedDispatcher(path.substring(1));
else
rd = getServletContext().getRequestDispatcher(path);
if (rd == null) {
sb.append(" No RequestDispatcher returned/");
} else {
if (sb.length() < 1)
rd.forward(request, response);
}
// Write our response if an error occurred
if (sb.length() >= 1) {
writer.print("Forward00 FAILED -");
writer.println(sb.toString());
while (true) {
String message = StaticLogger.read();
if (message == null)
break;
writer.println(message);
}
}
StaticLogger.reset();
}
}
|
package org.lechuga.jdbc;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
public class ResultSetUtils {
public static <T extends Enum<T>> T getEnum(final Class<T> enumClass, final ResultSet rs) throws SQLException {
final String v = rs.getString(1);
if (v == null) {
return null;
}
return Enum.valueOf(enumClass, v);
}
public static <T extends Enum<T>> T getEnum(final Class<T> enumClass, final ResultSet rs, String columnLabel)
throws SQLException {
final String v = rs.getString(columnLabel);
if (v == null) {
return null;
}
return Enum.valueOf(enumClass, v);
}
public static Byte getByte(final ResultSet rs) throws SQLException {
final byte v = rs.getByte(1);
if (rs.wasNull()) {
return null;
}
return v;
}
public static Short getShort(final ResultSet rs) throws SQLException {
final short v = rs.getShort(1);
if (rs.wasNull()) {
return null;
}
return v;
}
public static Integer getInteger(final ResultSet rs) throws SQLException {
final int v = rs.getInt(1);
if (rs.wasNull()) {
return null;
}
return v;
}
public static Long getLong(final ResultSet rs) throws SQLException {
final long v = rs.getLong(1);
if (rs.wasNull()) {
return null;
}
return v;
}
public static Float getFloat(final ResultSet rs) throws SQLException {
final float v = rs.getFloat(1);
if (rs.wasNull()) {
return null;
}
return v;
}
public static Double getDouble(final ResultSet rs) throws SQLException {
final double v = rs.getDouble(1);
if (rs.wasNull()) {
return null;
}
return v;
}
public static Byte getByte(final ResultSet rs, final String columnLabel) throws SQLException {
final byte v = rs.getByte(columnLabel);
if (rs.wasNull()) {
return null;
}
return v;
}
public static Short getShort(final ResultSet rs, final String columnLabel) throws SQLException {
final short v = rs.getShort(columnLabel);
if (rs.wasNull()) {
return null;
}
return v;
}
public static Integer getInteger(final ResultSet rs, final String columnLabel) throws SQLException {
final int v = rs.getInt(columnLabel);
if (rs.wasNull()) {
return null;
}
return v;
}
public static Long getLong(final ResultSet rs, final String columnLabel) throws SQLException {
final long v = rs.getLong(columnLabel);
if (rs.wasNull()) {
return null;
}
return v;
}
public static Float getFloat(final ResultSet rs, final String columnLabel) throws SQLException {
final float v = rs.getFloat(columnLabel);
if (rs.wasNull()) {
return null;
}
return v;
}
public static Double getDouble(final ResultSet rs, final String columnLabel) throws SQLException {
final double v = rs.getDouble(columnLabel);
if (rs.wasNull()) {
return null;
}
return v;
}
public static String getString(final ResultSet rs) throws SQLException {
return rs.getString(1);
}
public static boolean getBoolean(final ResultSet rs) throws SQLException {
return rs.getBoolean(1);
}
public static byte[] getBytes(final ResultSet rs) throws SQLException {
return rs.getBytes(1);
}
public static Timestamp getTimestamp(final ResultSet rs) throws SQLException {
return rs.getTimestamp(1);
}
public static String getString(final ResultSet rs, final String columnLabel) throws SQLException {
return rs.getString(columnLabel);
}
public static boolean getBoolean(final ResultSet rs, final String columnLabel) throws SQLException {
return rs.getBoolean(columnLabel);
}
public static byte[] getBytes(final ResultSet rs, final String columnLabel) throws SQLException {
return rs.getBytes(columnLabel);
}
public static Timestamp getTimestamp(final ResultSet rs, final String columnLabel) throws SQLException {
return rs.getTimestamp(columnLabel);
}
public static BigDecimal getBigDecimal(final ResultSet rs) throws SQLException {
return rs.getBigDecimal(1);
}
public static BigDecimal getBigDecimal(final ResultSet rs, final String columnLabel) throws SQLException {
return rs.getBigDecimal(columnLabel);
}
public static Character getChar(final ResultSet rs) throws SQLException {
String v = rs.getString(1);
if (v == null || v.isEmpty()) {
return null;
}
return v.charAt(0);
}
public static Character getChar(final ResultSet rs, final String columnLabel) throws SQLException {
String v = rs.getString(columnLabel);
if (v == null || v.isEmpty()) {
return null;
}
return v.charAt(0);
}
}
|
/*
* Copyright 2007-2021, CIIC Guanaitong, Co., Ltd.
* All rights reserved.
*/
package com.ciicgat.grus.boot.autoconfigure.redis;
import com.ciicgat.grus.boot.autoconfigure.core.GrusCoreContextInitializer;
import com.ciicgat.sdk.redis.RedisExecutor;
import com.ciicgat.sdk.redis.RedisService;
import com.ciicgat.sdk.redis.config.RedisSetting;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.data.redis.core.StringRedisTemplate;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Created by August.Zhou on 2020-04-22 10:38.
*/
public class GrusRedisAutoConfigurationTests {
private static final String TEST_REDIS_KEY = "test-for-java";
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withInitializer(new GrusCoreContextInitializer())
.withUserConfiguration(GrusRedisAutoConfiguration.class);
@Test
public void test() {
final String randomValue = System.currentTimeMillis() + "";
this.contextRunner
.withSystemProperties()
.withPropertyValues("spring.application.name=grus-demo")
.run(context -> {
RedisSetting redisSetting = context.getBean(RedisSetting.class);
assertThat(redisSetting).isInstanceOf(RedisSetting.class);
RedisService redisService = context.getBean(RedisService.class);
StringRedisTemplate stringRedisTemplate = context.getBean(StringRedisTemplate.class);
RedisExecutor redisExecutor = context.getBean(RedisExecutor.class);
redisService.set(TEST_REDIS_KEY, randomValue);
String result = stringRedisTemplate.opsForValue().get(TEST_REDIS_KEY);
String resultFromExecute = redisExecutor.execute(jedis -> jedis.get(TEST_REDIS_KEY));
assertThat(result).isEqualTo(randomValue);
assertThat(resultFromExecute).isEqualTo(randomValue);
});
}
}
|
package com.Hospital.Core_Classes;
public class Patient extends PersonalDetails{
private String Covid,Admitted,Service,Time;
//Constructor for Patient class-------------------------------------------------------------------------------------
public Patient(String id, String name, String cnic, String phone, String address, String covid, String admitted, String service, String gender, String age,String time) {
super(id, name, cnic, phone, address, gender, age);
this.Covid = covid;
this.Admitted = admitted;
this.Service = service;
this.Time = time;
}
// Getter's for Patient Class---------------------------------------------------------------------------------------
public String getCovid() { return Covid; }
public String getAdmitted() { return Admitted; }
public String getService() { return Service; }
public String getTime() { return Time; }
//Setter's for Patient Class----------------------------------------------------------------------------------------
public void setCovid(String covid) { Covid = covid; }
public void setAdmitted(String admitted) { Admitted = admitted; }
public void setService(String service) { Service = service; }
//==================================================================================================================
}
|
/*
* 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.pig.impl.eval;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.pig.impl.FunctionInstantiator;
import org.apache.pig.impl.eval.collector.DataCollector;
import org.apache.pig.impl.logicalLayer.schema.Schema;
/**
* Follows the composite design pattern
* @author utkarsh
*
*/
public class CompositeEvalSpec extends EvalSpec {
private static final long serialVersionUID = 1L;
private List<EvalSpec> specs = new ArrayList<EvalSpec>();
public CompositeEvalSpec(EvalSpec spec){
specs.add(spec);
properties.putAll(spec.getProperties());
}
@Override
protected DataCollector setupDefaultPipe(Properties properties,
DataCollector endOfPipe){
for (int i=specs.size()-1; i>=0; i--){
endOfPipe = specs.get(i).setupDefaultPipe(properties, endOfPipe);
}
return endOfPipe;
}
@Override
public List<String> getFuncs(){
List<String> funcs = new ArrayList<String>();
for(EvalSpec spec: specs){
funcs.addAll(spec.getFuncs());
}
return funcs;
}
@Override
public EvalSpec addSpec(EvalSpec spec){
specs.add(spec);
properties.putAll(spec.getProperties());
return this;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
int i=0;
for (EvalSpec spec: specs){
sb.append(spec.toString());
i++;
if (i != specs.size())
sb.append("->");
}
return sb.toString();
}
@Override
public boolean isAsynchronous() {
for (EvalSpec spec: specs)
if (spec.isAsynchronous())
return true;
return false;
}
@Override
protected Schema mapInputSchema(Schema schema) {
for (EvalSpec spec: specs)
schema = spec.mapInputSchema(schema);
return schema;
}
@Override
public void instantiateFunc(FunctionInstantiator fInstantiaor)
throws IOException {
super.instantiateFunc(fInstantiaor);
for (EvalSpec spec: specs)
spec.instantiateFunc(fInstantiaor);
}
public List<EvalSpec> getSpecs() {
return specs;
}
@Override
public void visit(EvalSpecVisitor v) {
v.visitCompositeEval(this);
}
}
|
package com.sequenceiq.datalake.service.sdx.database;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.verify;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import com.sequenceiq.redbeams.api.endpoint.v4.stacks.DatabaseServerV4StackRequest;
import com.sequenceiq.redbeams.api.endpoint.v4.stacks.aws.AwsDatabaseServerV4Parameters;
import com.sequenceiq.sdx.api.model.SdxDatabaseAvailabilityType;
@ExtendWith(MockitoExtension.class)
public class AwsDatabaseServerParameterSetterTest {
@Mock
private DatabaseServerV4StackRequest request;
@Captor
private ArgumentCaptor<AwsDatabaseServerV4Parameters> captor;
private DatabaseServerParameterSetter underTest;
@BeforeEach
public void setUp() {
underTest = new AwsDatabaseServerParameterSetter();
}
@Test
public void testHAServer() {
underTest.setParameters(request, SdxDatabaseAvailabilityType.HA);
verify(request).setAws(captor.capture());
AwsDatabaseServerV4Parameters awsDatabaseServerV4Parameters = captor.getValue();
assertEquals("true", awsDatabaseServerV4Parameters.getMultiAZ());
assertEquals(1, awsDatabaseServerV4Parameters.getBackupRetentionPeriod());
}
@Test
public void testNonHAServer() {
underTest.setParameters(request, SdxDatabaseAvailabilityType.NON_HA);
verify(request).setAws(captor.capture());
AwsDatabaseServerV4Parameters awsDatabaseServerV4Parameters = captor.getValue();
assertEquals("false", awsDatabaseServerV4Parameters.getMultiAZ());
assertEquals(0, awsDatabaseServerV4Parameters.getBackupRetentionPeriod());
}
@Test
public void shouldThrowExceptionWhenAvailabilityTypeIsNotSupported() {
IllegalArgumentException result =
Assertions.assertThrows(IllegalArgumentException.class, () -> underTest.setParameters(request, SdxDatabaseAvailabilityType.NONE));
assertEquals("NONE database availability type is not supported on AWS.", result.getMessage());
}
}
|
/**
* Copyright (C) 2010-2018 Gordon Fraser, Andrea Arcuri and EvoSuite
* contributors
*
* This file is part of EvoSuite.
*
* EvoSuite is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3.0 of the License, or
* (at your option) any later version.
*
* EvoSuite is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>.
*/
package org.evosuite.symbolic.vm.string;
import java.util.ArrayList;
import java.util.Collections;
import org.evosuite.symbolic.expr.Expression;
import org.evosuite.symbolic.expr.Operator;
import org.evosuite.symbolic.expr.bv.IntegerValue;
import org.evosuite.symbolic.expr.ref.ReferenceConstant;
import org.evosuite.symbolic.expr.ref.ReferenceExpression;
import org.evosuite.symbolic.expr.str.StringMultipleExpression;
import org.evosuite.symbolic.expr.str.StringValue;
import org.evosuite.symbolic.vm.SymbolicEnvironment;
import org.evosuite.symbolic.vm.SymbolicFunction;
import org.evosuite.symbolic.vm.SymbolicHeap;
public abstract class Replace extends SymbolicFunction {
private static final String REPLACE = "replace";
public Replace(SymbolicEnvironment env, String desc) {
super(env, Types.JAVA_LANG_STRING, REPLACE, desc);
}
public static final class Replace_C extends Replace {
public Replace_C(SymbolicEnvironment env) {
super(env, Types.CHAR_CHAR_TO_STR_DESCRIPTOR);
}
@Override
public Object executeFunction() {
// string receiver
ReferenceConstant symb_receiver = this.getSymbReceiver();
String conc_receiver = (String) this.getConcReceiver();
// old char
IntegerValue oldCharExpr = this.getSymbIntegerArgument(0);
// new char
IntegerValue newCharExpr = this.getSymbIntegerArgument(1);
// return value
ReferenceExpression symb_ret_val = this.getSymbRetVal();
String conc_ret_val = (String) this.getConcRetVal();
StringValue stringReceiverExpr = env.heap.getField(
Types.JAVA_LANG_STRING, SymbolicHeap.$STRING_VALUE,
conc_receiver, symb_receiver, conc_receiver);
if (symb_ret_val instanceof ReferenceConstant) {
ReferenceConstant non_null_symb_ret_val = (ReferenceConstant) symb_ret_val;
StringMultipleExpression symb_value = new StringMultipleExpression(
stringReceiverExpr, Operator.REPLACEC, oldCharExpr,
new ArrayList<Expression<?>>(Collections
.singletonList(newCharExpr)),
conc_ret_val);
env.heap.putField(Types.JAVA_LANG_STRING,
SymbolicHeap.$STRING_VALUE, conc_ret_val,
non_null_symb_ret_val, symb_value);
}
return this.getSymbRetVal();
}
}
public static final class Replace_CS extends Replace {
public Replace_CS(SymbolicEnvironment env) {
super(env, Types.CHARSEQ_CHARSEQ_TO_STR_DESCRIPTOR);
}
@Override
public Object executeFunction() {
// string receiver
ReferenceConstant symb_receiver = this.getSymbReceiver();
String conc_receiver = (String) this.getConcReceiver();
// old string
ReferenceExpression symb_old_str = this.getSymbArgument(0);
CharSequence conc_old_char_seq = (CharSequence) this
.getConcArgument(0);
// new string
ReferenceExpression symb_new_str = this.getSymbArgument(1);
CharSequence conc_new_char_seq = (CharSequence) this
.getConcArgument(1);
// return value
ReferenceExpression symb_ret_val = this.getSymbRetVal();
String conc_ret_val = (String) this.getConcRetVal();
StringValue stringReceiverExpr = env.heap.getField(
Types.JAVA_LANG_STRING, SymbolicHeap.$STRING_VALUE,
conc_receiver, symb_receiver, conc_receiver);
if (symb_old_str instanceof ReferenceConstant
&& symb_new_str instanceof ReferenceConstant
&& symb_ret_val instanceof ReferenceConstant) {
ReferenceConstant non_null_symb_old_str = (ReferenceConstant) symb_old_str;
ReferenceConstant non_null_symb_new_str = (ReferenceConstant) symb_new_str;
ReferenceConstant non_null_symb_ret_val = (ReferenceConstant) symb_ret_val;
if (conc_old_char_seq instanceof String
&& conc_new_char_seq instanceof String) {
String conc_old_str = (String) conc_old_char_seq;
StringValue oldStringExpr = env.heap.getField(
Types.JAVA_LANG_STRING, SymbolicHeap.$STRING_VALUE,
conc_old_str, non_null_symb_old_str, conc_old_str);
String conc_new_str = (String) conc_new_char_seq;
StringValue newStringExpr = env.heap.getField(
Types.JAVA_LANG_STRING, SymbolicHeap.$STRING_VALUE,
conc_new_str, non_null_symb_new_str, conc_new_str);
StringMultipleExpression symb_value = new StringMultipleExpression(
stringReceiverExpr, Operator.REPLACECS,
oldStringExpr, new ArrayList<Expression<?>>(
Collections.singletonList(newStringExpr)),
conc_ret_val);
env.heap.putField(Types.JAVA_LANG_STRING,
SymbolicHeap.$STRING_VALUE, conc_ret_val,
non_null_symb_ret_val, symb_value);
}
}
return symb_ret_val;
}
}
}
|
/* */ package com.hundsun.network.gates.genshan.web.validator;
/* */
/* */ import com.hundsun.network.gates.genshan.biz.domain.baseset.SystemServicechargeSpecial;
/* */ import com.hundsun.network.gates.genshan.biz.domain.project.ProjectType;
/* */ import com.hundsun.network.gates.genshan.biz.domain.query.SystemServicechargeSpecialQuery;
/* */ import com.hundsun.network.gates.genshan.biz.domain.user.UserAccount;
/* */ import com.hundsun.network.gates.genshan.biz.service.baseset.SystemServiceCSpecialService;
/* */ import com.hundsun.network.gates.genshan.biz.service.project.ProjectTypeService;
/* */ import com.hundsun.network.gates.genshan.biz.service.user.UserAccountService;
/* */ import com.hundsun.network.melody.common.util.StringUtil;
/* */ import java.util.List;
/* */ import org.springframework.beans.factory.annotation.Autowired;
/* */ import org.springframework.validation.Errors;
/* */ import org.springmodules.validation.valang.ValangValidator;
/* */
/* */ public class SysSerCSpecialEditValidator extends ValangValidator
/* */ {
/* */
/* */ @Autowired
/* */ private UserAccountService userAccountService;
/* */
/* */ @Autowired
/* */ private ProjectTypeService projectTypeService;
/* */
/* */ @Autowired
/* */ private SystemServiceCSpecialService systemServiceCSpecialService;
/* */
/* */ public void validate(Object obj, Errors errors)
/* */ {
/* 34 */ super.validate(obj, errors);
/* 35 */ SystemServicechargeSpecial sscSpecial = (SystemServicechargeSpecial)obj;
/* 36 */ String userAccount = sscSpecial.getUserAccount();
/* 37 */ String proTypeCode = sscSpecial.getProTypeCode();
/* 38 */ String isSystem = sscSpecial.getIsSystem();
/* 39 */ if ("Y".equals(isSystem)) {
/* 40 */ if ((StringUtil.isNotBlank(userAccount)) || (StringUtil.isNotBlank(proTypeCode)))
/* 41 */ errors.rejectValue("userAccount", "", "该项目是系统配置,'会员'和'项目类型编码'都不用填写!");
/* */ }
/* */ else {
/* 44 */ if ((StringUtil.isBlank(userAccount)) && (StringUtil.isBlank(proTypeCode))) {
/* 45 */ errors.rejectValue("userAccount", "", "'会员'和'项目类型编码'至少填写一项!");
/* */ }
/* 47 */ if (StringUtil.isNotBlank(sscSpecial.getUserAccount()))
/* */ {
/* 49 */ UserAccount ua = this.userAccountService.getUserByAccount(sscSpecial.getUserAccount());
/* 50 */ if (ua == null) {
/* 51 */ errors.rejectValue("userAccount", "", "会员不存在!");
/* */ }
/* */ }
/* */
/* 55 */ if (StringUtil.isNotBlank(sscSpecial.getProTypeCode())) {
/* 56 */ ProjectType proType = this.projectTypeService.getProjectTypeByCode(sscSpecial.getProTypeCode());
/* 57 */ if (proType == null) {
/* 58 */ errors.rejectValue("proTypeCode", "", "项目类型编码不存在!");
/* */ }
/* */
/* */ }
/* */
/* 63 */ if ((StringUtil.isNotBlank(userAccount)) && (StringUtil.isNotBlank(proTypeCode))) {
/* 64 */ SystemServicechargeSpecialQuery query = new SystemServicechargeSpecialQuery();
/* 65 */ query.setUserAccount(userAccount);
/* 66 */ query.setProTypeCode(proTypeCode);
/* 67 */ query.setNoneId(sscSpecial.getId());
/* 68 */ List list = this.systemServiceCSpecialService.selectRepeatConfig(query);
/* 69 */ if ((list != null) && (list.size() > 0)) {
/* 70 */ errors.rejectValue("userAccount", "", "'会员'和'项目类型编码'已经提交过相同配置!");
/* */ }
/* */
/* */ }
/* */
/* 75 */ if ((StringUtil.isNotBlank(userAccount)) && (StringUtil.isBlank(proTypeCode))) {
/* 76 */ SystemServicechargeSpecialQuery query = new SystemServicechargeSpecialQuery();
/* 77 */ query.setUserAccount(userAccount);
/* 78 */ query.setNoneId(sscSpecial.getId());
/* 79 */ List list = this.systemServiceCSpecialService.selectRepeatConfig(query);
/* 80 */ if ((list != null) && (list.size() > 0)) {
/* 81 */ errors.rejectValue("userAccount", "", "'会员'已经提交过相同配置!");
/* */ }
/* */
/* */ }
/* */
/* 86 */ if ((StringUtil.isBlank(userAccount)) && (StringUtil.isNotBlank(proTypeCode))) {
/* 87 */ SystemServicechargeSpecialQuery query = new SystemServicechargeSpecialQuery();
/* 88 */ query.setProTypeCode(proTypeCode);
/* 89 */ query.setNoneId(sscSpecial.getId());
/* 90 */ List list = this.systemServiceCSpecialService.selectRepeatConfig(query);
/* 91 */ if ((list != null) && (list.size() > 0)) {
/* 92 */ errors.rejectValue("proTypeCode", "", "'项目类型编码'已经提交过相同配置!");
/* */ }
/* */ }
/* */ }
/* */
/* 97 */ if ((sscSpecial.getListTurnover() == null) && (sscSpecial.getListUnturnover() == null) && (sscSpecial.getOrderTurnover() == null) && (sscSpecial.getOrderUnturnover() == null))
/* */ {
/* 99 */ errors.rejectValue("listTurnover", "", "设置值不允许都是空!");
/* 100 */ errors.rejectValue("listUnturnover", "", "设置值不允许都是空!");
/* 101 */ errors.rejectValue("orderTurnover", "", "设置值不允许都是空!");
/* 102 */ errors.rejectValue("orderUnturnover", "", "设置值不允许都是空!");
/* */ }
/* */ }
/* */ }
/* Location: E:\__安装归档\linquan-20161112\deploy15\genshan\webroot\WEB-INF\classes\
* Qualified Name: com.hundsun.network.gates.genshan.web.validator.SysSerCSpecialEditValidator
* JD-Core Version: 0.6.0
*/
|
/*
* 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.tugraz.sysds.test.functions.unary.matrix;
import org.junit.Test;
import org.tugraz.sysds.test.AutomatedTestBase;
import org.tugraz.sysds.test.TestConfiguration;
public class CastAsScalarTest extends AutomatedTestBase
{
private final static String TEST_DIR = "functions/unary/matrix/";
private static final String TEST_CLASS_DIR = TEST_DIR + CastAsScalarTest.class.getSimpleName() + "/";
private final static String TEST_GENERAL = "General";
@Override
public void setUp() {
addTestConfiguration(TEST_GENERAL, new TestConfiguration(TEST_CLASS_DIR, "CastAsScalarTest", new String[] { "b" }));
}
@Test
public void testGeneral() {
TestConfiguration config = getTestConfiguration(TEST_GENERAL);
loadTestConfiguration(config);
createHelperMatrix();
writeInputMatrix("a", new double[][] { { 2 } });
writeExpectedHelperMatrix("b", 2);
runTest();
compareResults();
}
}
|
package com.img.load;
import android.graphics.drawable.Drawable;
import android.widget.ImageView;
/***********
*
* @Author rape flower
* @Date 2016-09-19 16:27
* @Describe 加载图片参数对象封装
* <p>
* LoaderParameter.Builder builder = LoaderParameter.newBuilder();
* builder.setUrl("");
* builder.setPlaceHolder(DrawableHolder.mPlaceholderDrawable);
* builder.setErrorHolder(DrawableHolder.mErrorDrawable);
* builder.setImageView(null);
* LoaderParameter loaderParameter = builder.build();
* </p>
*/
public class LoaderParameter {
private String url; //需要解析的url
private Drawable placeHolder; //当加载中的时候显示的图片
private Drawable errorHolder; //当加载过程中失败时显示的图片
private ImageView imageView; //ImageView的实例
private boolean asGif;//是否是要显示的Gif图片
private boolean asResource;//是不是加载的资源,true: 是,false: 反之
private Integer resourceId;//资源Id
private BaseProxy target;//重新设置图片大小的接口
private LoaderParameter(Builder builder) {
this.url = builder.url;
this.placeHolder = builder.placeHolder;
this.errorHolder = builder.errorHolder;
this.imageView = builder.imageView;
this.asGif = builder.asGif;
this.asResource = builder.asResource;
this.resourceId = builder.resourceId;
this.target = builder.target;
}
public static Builder newBuilder() {
return Builder.create();
}
public String getUrl() {
return url;
}
public Drawable getPlaceHolder() {
return placeHolder;
}
public Drawable getErrorHolder() {
return errorHolder;
}
public ImageView getImageView() {
return imageView;
}
public boolean isAsGif() {
return asGif;
}
public boolean isAsResource() {
return asResource;
}
public Integer getResourceId() {
return resourceId;
}
public BaseProxy getTarget() {
return target;
}
public static class Builder {
private String url; //需要解析的url
private Drawable placeHolder; //当没有成功加载的时候显示的图片
private Drawable errorHolder; //当加载过程中出现error时显示的图片
private ImageView imageView; //ImageView的实例
private boolean asGif;//是否是要显示的Gif图片
private boolean asResource;//是不是加载的本地资源,true: 是,false: 反之
private Integer resourceId;//本地资源Id
private BaseProxy target;//重新设置图片大小的接口
private Builder() {
this.url = "";
this.placeHolder = null;
this.errorHolder = null;
this.imageView = null;
this.asGif = false;
this.asResource = false;
this.resourceId = 0;
this.target = null;
}
private static Builder create() {
return new Builder();
}
public Builder setUrl(String url) {
this.url = url;
return this;
}
public Builder setPlaceHolder(Drawable placeHolder) {
this.placeHolder = placeHolder;
return this;
}
public Builder setErrorHolder(Drawable errorHolder) {
this.errorHolder = errorHolder;
return this;
}
public Builder setImageView(ImageView imageView) {
this.imageView = imageView;
return this;
}
public Builder setAsGif(boolean asGif) {
this.asGif = asGif;
return this;
}
public Builder setAsResource(boolean asResource) {
this.asResource = asResource;
return this;
}
public Builder setResourceId(Integer resourceId) {
this.resourceId = resourceId;
return this;
}
public Builder setTarget(BaseProxy target) {
this.target = target;
return this;
}
public LoaderParameter build() {
return new LoaderParameter(this);
}
}
}
|
package com.example.plugintest.manymethods.i.a;
public class A5 {
public static void a0(String msg) { System.out.println("msg=" + msg + 0); }
public static void a1(String msg) { System.out.println("msg=" + msg + 1); }
public static void a2(String msg) { System.out.println("msg=" + msg + 2); }
public static void a3(String msg) { System.out.println("msg=" + msg + 3); }
public static void a4(String msg) { System.out.println("msg=" + msg + 4); }
public static void a5(String msg) { System.out.println("msg=" + msg + 5); }
public static void a6(String msg) { System.out.println("msg=" + msg + 6); }
public static void a7(String msg) { System.out.println("msg=" + msg + 7); }
public static void a8(String msg) { System.out.println("msg=" + msg + 8); }
public static void a9(String msg) { System.out.println("msg=" + msg + 9); }
public static void a10(String msg) { System.out.println("msg=" + msg + 10); }
public static void a11(String msg) { System.out.println("msg=" + msg + 11); }
public static void a12(String msg) { System.out.println("msg=" + msg + 12); }
public static void a13(String msg) { System.out.println("msg=" + msg + 13); }
public static void a14(String msg) { System.out.println("msg=" + msg + 14); }
public static void a15(String msg) { System.out.println("msg=" + msg + 15); }
public static void a16(String msg) { System.out.println("msg=" + msg + 16); }
public static void a17(String msg) { System.out.println("msg=" + msg + 17); }
public static void a18(String msg) { System.out.println("msg=" + msg + 18); }
public static void a19(String msg) { System.out.println("msg=" + msg + 19); }
public static void a20(String msg) { System.out.println("msg=" + msg + 20); }
public static void a21(String msg) { System.out.println("msg=" + msg + 21); }
public static void a22(String msg) { System.out.println("msg=" + msg + 22); }
public static void a23(String msg) { System.out.println("msg=" + msg + 23); }
public static void a24(String msg) { System.out.println("msg=" + msg + 24); }
public static void a25(String msg) { System.out.println("msg=" + msg + 25); }
public static void a26(String msg) { System.out.println("msg=" + msg + 26); }
public static void a27(String msg) { System.out.println("msg=" + msg + 27); }
public static void a28(String msg) { System.out.println("msg=" + msg + 28); }
public static void a29(String msg) { System.out.println("msg=" + msg + 29); }
public static void a30(String msg) { System.out.println("msg=" + msg + 30); }
public static void a31(String msg) { System.out.println("msg=" + msg + 31); }
public static void a32(String msg) { System.out.println("msg=" + msg + 32); }
public static void a33(String msg) { System.out.println("msg=" + msg + 33); }
public static void a34(String msg) { System.out.println("msg=" + msg + 34); }
public static void a35(String msg) { System.out.println("msg=" + msg + 35); }
public static void a36(String msg) { System.out.println("msg=" + msg + 36); }
public static void a37(String msg) { System.out.println("msg=" + msg + 37); }
public static void a38(String msg) { System.out.println("msg=" + msg + 38); }
public static void a39(String msg) { System.out.println("msg=" + msg + 39); }
public static void a40(String msg) { System.out.println("msg=" + msg + 40); }
public static void a41(String msg) { System.out.println("msg=" + msg + 41); }
public static void a42(String msg) { System.out.println("msg=" + msg + 42); }
public static void a43(String msg) { System.out.println("msg=" + msg + 43); }
public static void a44(String msg) { System.out.println("msg=" + msg + 44); }
public static void a45(String msg) { System.out.println("msg=" + msg + 45); }
public static void a46(String msg) { System.out.println("msg=" + msg + 46); }
public static void a47(String msg) { System.out.println("msg=" + msg + 47); }
public static void a48(String msg) { System.out.println("msg=" + msg + 48); }
public static void a49(String msg) { System.out.println("msg=" + msg + 49); }
public static void a50(String msg) { System.out.println("msg=" + msg + 50); }
public static void a51(String msg) { System.out.println("msg=" + msg + 51); }
public static void a52(String msg) { System.out.println("msg=" + msg + 52); }
public static void a53(String msg) { System.out.println("msg=" + msg + 53); }
public static void a54(String msg) { System.out.println("msg=" + msg + 54); }
public static void a55(String msg) { System.out.println("msg=" + msg + 55); }
public static void a56(String msg) { System.out.println("msg=" + msg + 56); }
public static void a57(String msg) { System.out.println("msg=" + msg + 57); }
public static void a58(String msg) { System.out.println("msg=" + msg + 58); }
public static void a59(String msg) { System.out.println("msg=" + msg + 59); }
public static void a60(String msg) { System.out.println("msg=" + msg + 60); }
public static void a61(String msg) { System.out.println("msg=" + msg + 61); }
public static void a62(String msg) { System.out.println("msg=" + msg + 62); }
public static void a63(String msg) { System.out.println("msg=" + msg + 63); }
public static void a64(String msg) { System.out.println("msg=" + msg + 64); }
public static void a65(String msg) { System.out.println("msg=" + msg + 65); }
public static void a66(String msg) { System.out.println("msg=" + msg + 66); }
public static void a67(String msg) { System.out.println("msg=" + msg + 67); }
public static void a68(String msg) { System.out.println("msg=" + msg + 68); }
public static void a69(String msg) { System.out.println("msg=" + msg + 69); }
public static void a70(String msg) { System.out.println("msg=" + msg + 70); }
public static void a71(String msg) { System.out.println("msg=" + msg + 71); }
public static void a72(String msg) { System.out.println("msg=" + msg + 72); }
public static void a73(String msg) { System.out.println("msg=" + msg + 73); }
public static void a74(String msg) { System.out.println("msg=" + msg + 74); }
public static void a75(String msg) { System.out.println("msg=" + msg + 75); }
public static void a76(String msg) { System.out.println("msg=" + msg + 76); }
public static void a77(String msg) { System.out.println("msg=" + msg + 77); }
public static void a78(String msg) { System.out.println("msg=" + msg + 78); }
public static void a79(String msg) { System.out.println("msg=" + msg + 79); }
public static void a80(String msg) { System.out.println("msg=" + msg + 80); }
public static void a81(String msg) { System.out.println("msg=" + msg + 81); }
public static void a82(String msg) { System.out.println("msg=" + msg + 82); }
public static void a83(String msg) { System.out.println("msg=" + msg + 83); }
public static void a84(String msg) { System.out.println("msg=" + msg + 84); }
public static void a85(String msg) { System.out.println("msg=" + msg + 85); }
public static void a86(String msg) { System.out.println("msg=" + msg + 86); }
public static void a87(String msg) { System.out.println("msg=" + msg + 87); }
public static void a88(String msg) { System.out.println("msg=" + msg + 88); }
public static void a89(String msg) { System.out.println("msg=" + msg + 89); }
public static void a90(String msg) { System.out.println("msg=" + msg + 90); }
public static void a91(String msg) { System.out.println("msg=" + msg + 91); }
public static void a92(String msg) { System.out.println("msg=" + msg + 92); }
public static void a93(String msg) { System.out.println("msg=" + msg + 93); }
public static void a94(String msg) { System.out.println("msg=" + msg + 94); }
public static void a95(String msg) { System.out.println("msg=" + msg + 95); }
public static void a96(String msg) { System.out.println("msg=" + msg + 96); }
public static void a97(String msg) { System.out.println("msg=" + msg + 97); }
public static void a98(String msg) { System.out.println("msg=" + msg + 98); }
public static void a99(String msg) { System.out.println("msg=" + msg + 99); }
}
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.picketlink.json.jose;
import static org.picketlink.json.JsonConstants.COMMON.ALG;
import static org.picketlink.json.JsonConstants.COMMON.ENC;
import static org.picketlink.json.JsonConstants.COMMON.HEADER_CONTENT_TYPE;
import static org.picketlink.json.JsonConstants.COMMON.HEADER_JSON_WEB_KEY;
import static org.picketlink.json.JsonConstants.COMMON.HEADER_JWK_SET_URL;
import static org.picketlink.json.JsonConstants.COMMON.HEADER_TYPE;
import static org.picketlink.json.JsonConstants.COMMON.KEY_ID;
import static org.picketlink.json.JsonConstants.JWE.CEK_BITLENGTH;
import static org.picketlink.json.JsonConstants.JWE.COMPRESSION_ALG;
import static org.picketlink.json.JsonConstants.JWE.HEADER_CRITICAL_PARAMETER;
import static org.picketlink.json.JsonConstants.JWK.X509_CERTIFICATE_CHAIN;
import static org.picketlink.json.JsonConstants.JWK.X509_CERTIFICATE_SHA1_THUMBPRINT;
import static org.picketlink.json.JsonConstants.JWK.X509_CERTIFICATE_SHA256_THUMBPRINT;
import static org.picketlink.json.JsonConstants.JWK.X509_URL;
import static org.picketlink.json.util.Base64Util.b64Encode;
import java.io.StringWriter;
import java.util.List;
import javax.json.Json;
import javax.json.JsonObject;
import org.picketlink.json.util.JsonUtil;
/**
* JSON Web Encryption (JWE) header.
*
* <p>
* Supports all Principal Registered Parameter Names of the JWE specification:
*
* <ul>
* <li>{@link #getType() alg}</li>
* <li>{@link #getContentType() typ}</li>
* <li>{@link #getAlgorithm() cty}</li>
* <li>{@link #getEncryptionAlgorithm() enc}</li>
* <li>{@link #getCompressionAlgorithm() zip}</li>
* <li>{@link #getJWK() keys}</li>
* <li>{@link #getJWKSet() jku}</li>
* <li>{@link #getX509Url() x5u}</li>
* <li>{@link #getX509CertificateChain() x5c}</li>
* <li>{@link #getX509SHA1CertificateThumbprint() x5t}</li>
* <li>{@link #getX509SHA256CertificateThumbprint() x5t#S256}</li>
* </ul>
*
* <p>
* Example header:
*
* <pre>
* {
* "alg":"RSA1_5",
* "kid":"2011-04-29",
* "enc":"A128CBC-HS256",
* "jku":"https://server.example.com/keys.jwks"
* }
* </pre>
*
* @author Giriraj Sharma
*/
public class JWE {
/** The JOSE headers for JWE. */
private JsonObject headers;
/**
* Instantiates a new JWE.
*
* @param headers the headers
*/
protected JWE(JsonObject headers) {
this.headers = headers;
}
/**
* <p>
* Encodes the JSON representation of headers of a JWE according to the specification.
* </p>
*
* <p>
* In order to decode, refer to the corresponding {@link JWEBuilder} of this class.
* </p>
*
* @return the string
*/
public String encode() {
return b64Encode(getPlainHeaders());
}
/**
* Gets the type of JOSE Header.
*
* @return the string
*/
public String getType() {
return getHeader(HEADER_TYPE);
}
/**
* Gets the content type of JOSE Header.
*
* @return the content type
*/
public String getContentType() {
return getHeader(HEADER_CONTENT_TYPE);
}
/**
* Gets the algorithm used to encrypt or determine the value of the Content Encryption Key (CEK).
*
*
* <ul>
* <li>{@link #RSA1_5}
* <li>{@link #RSA_OAEP RSA-OAEP}
* <li>{@link #RSA_OAEP_256 RSA-OAEP-256}
* </ul>
*
* @return the algorithm
*/
public String getAlgorithm() {
return getHeader(ALG);
}
/**
* Gets the encryption algorithm used to encrypt the Plaintext to produce the Ciphertext.
*
* <ul>
* <li>{@link #A128CBC_HS256 A128CBC-HS256}
* <li>{@link #A192CBC_HS384 A192CBC-HS384}
* <li>{@link #A256CBC_HS512 A256CBC-HS512}
* <li>{@link #A128GCM}
* <li>{@link #A192GCM}
* <li>{@link #A256GCM}
* </ul>
*
* @return the encryption algorithm
*/
public String getEncryptionAlgorithm() {
return getHeader(ENC);
}
/**
* Gets the Content Encryption Key bit length.
*
* @return the Content Encryption Key bit length
*/
public String getCEKBitLength() {
return getHeader(CEK_BITLENGTH);
}
/**
* Gets the key identifier used to determine the private key needed to decrypt the JWE.
*
* @return the key identifier
*/
public String getKeyIdentifier() {
return getHeader(KEY_ID);
}
/**
* Gets the compression algorithm. The zip (compression algorithm) applied to the Plaintext before encryption, if any. The
* zip value defined by this specification is:
*
* <ul>
* DEF - Compression with the DEFLATE [RFC1951] algorithm
* </ul>
*
* @return the compression algorithm
*/
public String getCompressionAlgorithm() {
return getHeader(COMPRESSION_ALG);
}
/**
* Gets the JWK Set.
*
* <p>
* The JWK Set resource contains the public key to which the JWE was encrypted; this can be used to determine the private
* key needed to decrypt the JWE.
*
* @return the JWK Set
*/
public String getJWKSet() {
return getHeader(HEADER_JWK_SET_URL);
}
/**
* Gets the JWK.
*
* <p>
* JWK key is the public key to which the JWE was encrypted; this can be used to determine the private key needed to decrypt
* the JWE.
*
* @return the JWK
*/
public String getJWK() {
return getHeader(HEADER_JSON_WEB_KEY);
}
/**
* Gets the x509 URL.
*
* <p>
* X.509 public key certificate or certificate chain [RFC5280] contains the public key to which the JWE was encrypted; this
* can be used to determine the private key needed to decrypt the JWE.
*
* @return the x509 URL
*/
public String getX509Url() {
return getHeader(X509_URL);
}
/**
* Gets the x509 certificate chain.
*
* <p>
* The X.509 public key certificate or certificate chain [RFC5280] contains the public key to which the JWE was encrypted;
* this can be used to determine the private key needed to decrypt the JWE.
*
* @return the x509 certificate chain
*/
public List<String> getX509CertificateChain() {
return getHeaderValues(X509_CERTIFICATE_CHAIN);
}
/**
* Gets the x509 SHA1 certificate thumbprint.
*
* <p>
* The certificate referenced by the thumbprint contains the public key to which the JWE was encrypted; this can be used to
* determine the private key needed to decrypt the JWE.
*
* @return the x509 SHA1 certificate thumbprint
*/
public String getX509SHA1CertificateThumbprint() {
return getHeader(X509_CERTIFICATE_SHA1_THUMBPRINT);
}
/**
* Gets the x509 SHA256 certificate thumbprint.
*
* <p>
* The certificate referenced by the thumbprint contains the public key to which the JWE was encrypted; this can be used to
* determine the private key needed to decrypt the JWE.
*
* @return the x509 SHA256 certificate thumbprint
*/
public String getX509SHA256CertificateThumbprint() {
return getHeader(X509_CERTIFICATE_SHA256_THUMBPRINT);
}
/**
* Gets the critical header.
*
* <p>
* The "crit" (critical) Header Parameter indicates that extensions to the initial RFC versions of [[ this specification ]]
* and [JWA] are being used that MUST be understood and processed. Its value is an array listing the Header Parameter names
* present in the JOSE Header that use those extensions.
*
* @return the critical header
*/
public List<String> getCriticalHeader() {
return getHeaderValues(HEADER_CRITICAL_PARAMETER);
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return getPlainHeaders();
}
/**
* Gets the {@link javax.json.JsonObject} headers.
*
* @return the headers
*/
public JsonObject getHeaders() {
return this.headers;
}
/**
* Gets the string representation of headers.
*
* @param name the name
* @return the header
*/
public String getHeader(String name) {
return JsonUtil.getValue(name, this.headers);
}
/**
* Gets the header values for the specified name.
*
* @param name the name
* @return the header values
*/
public List<String> getHeaderValues(String name) {
return JsonUtil.getValues(name, this.headers);
}
/**
* Gets the {@link javax.json.JsonObject}.
*
* @return the JSON object
*/
public JsonObject getJsonObject() {
return this.headers;
}
/**
* Gets the plain headers.
*
* @return the plain headers
*/
private String getPlainHeaders() {
StringWriter keyParameterWriter = new StringWriter();
Json.createWriter(keyParameterWriter).writeObject(this.headers);
return keyParameterWriter.getBuffer().toString();
}
}
|
package com.oracle.jsonloader.command.mongodbbsontoajdosonloading;
import com.oracle.jsonloader.util.BlockingQueueCallback;
import oracle.jdbc.internal.OracleConnection;
import oracle.soda.OracleCollection;
import oracle.soda.OracleDatabase;
import oracle.soda.OracleDocument;
import oracle.soda.rdbms.OracleRDBMSClient;
import oracle.ucp.jdbc.PoolDataSource;
import org.bson.BSONObject;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
public class BSONFileConsumer implements Runnable {
private final BlockingQueue<List<byte[]>> queue;
private final PoolDataSource pds;
private final String collectionName;
private final CountDownLatch consumerCountDownLatch;
private final BlockingQueueCallback callback;
private final boolean outputOsonFormat;
private final int id;
private MyBSONDecoder decoder;
private EnumSet<OracleConnection.CommitOption> commitOptions;
private static final boolean ASYNC_COMMIT = true;
public BSONFileConsumer(int id, String collectionName, BlockingQueue<List<byte[]>> queue,
PoolDataSource pds, CountDownLatch consumerCountDownLatch,
BlockingQueueCallback callback, boolean outputOsonFormat) {
this.id = id;
this.collectionName = collectionName;
this.queue = queue;
this.pds = pds;
this.consumerCountDownLatch = consumerCountDownLatch;
this.callback = callback;
this.outputOsonFormat = outputOsonFormat;
commitOptions = ASYNC_COMMIT ?
EnumSet.of(
OracleConnection.CommitOption.WRITEBATCH,
OracleConnection.CommitOption.NOWAIT)
:
EnumSet.of(
OracleConnection.CommitOption.WRITEIMMED,
OracleConnection.CommitOption.WAIT);
}
public void run() {
try {
//decoder = (id == 0 ? new MyBSONDecoderWithMetadata(outputOsonFormat) : new MyBSONDecoder(outputOsonFormat));
decoder = new MyBSONDecoderWithMetadata(outputOsonFormat);
long count = 0;
long bsonSize = 0;
long osonSize = 0;
try (Connection c = pds.getConnection()) {
c.setAutoCommit(false);
final OracleConnection realConnection = (OracleConnection) c;
//========================================================
// JDBC START
// try (PreparedStatement p = c.prepareStatement(
// "insert /*+ append */ into " + collectionName + " (ID,JSON_DOCUMENT,VERSION) values (?,?,'1')")) {
// while (true) {
// final List<byte[]> batch = queue.take();
// if (batch.size() == 0) {
// callback.addConsumed(0, 0, true);
// break;
// }
//
// //System.out.println("Treating "+batch.size()+" docs");
//
// for (byte[] data : batch) {
// final BSONObject obj = decoder.readObject(data);
// if (obj != null) {
// count++;
// bsonSize += decoder.getBsonLength();
// final byte[] osonData = decoder.getOSONData();
// osonSize += osonData.length;
//
// p.setString(1, decoder.getOid());
// p.setBytes(2, osonData);
// p.addBatch();
// }
// }
//
// //System.out.println("Running batch...("+osonSize+")");
//
// p.executeLargeBatch();
// c.commit();
//
// callback.addConsumed(batch.size(),osonSize);
// osonSize = 0;
// }
// }
// JDBC END
//========================================================
// SODA START
final Properties props = new Properties();
props.put("oracle.soda.sharedMetadataCache", "true");
props.put("oracle.soda.localMetadataCache", "true");
final OracleRDBMSClient cl = new OracleRDBMSClient(props);
final OracleDatabase db = cl.getDatabase(c);
final OracleCollection collection = db.openCollection(collectionName.toUpperCase());
//try (PreparedStatement p = c.prepareStatement("insert /*+ append */ into " + collectionName + " (ID,JSON_DOCUMENT,VERSION) values (?,?,'1')")) {
final List<OracleDocument> batchDocuments = new ArrayList<>(MongoDBBSONToAJDOSONLoading.BATCH_SIZE);
final Map<String, String> insertOptions = new HashMap<>();
insertOptions.put("hint", "append");
final boolean USE_JDBC = true;
if (USE_JDBC && MongoDBBSONToAJDOSONLoading.KEEP_MONGODB_OBJECTIDS) {
// optim:
// - rely on default for CREATED_ON and LAST_UPDATED columns
// - disable lock for table
// - commit batch nowait
// - disable JSON constraint
// - drop Primary Key constraint and its index
// - No Append hint
// - Version set to '1'
boolean thread_id_partitioned = false;
try(PreparedStatement p = c.prepareStatement("select 1 from user_tab_cols where table_name=? and column_name='THREAD_ID'")) {
p.setString(1,collectionName.toUpperCase());
try(ResultSet r = p.executeQuery()) {
thread_id_partitioned = r.next();
}
}
// insert /*+ append */ into "MOVIESTREAM"."SALES" ("ID","JSON_DOCUMENT","LAST_MODIFIED","CREATED_ON","VERSION") values (:1 ,:2 ,to_timestamp(:3 ,'SYYYY-MM-DD"T"HH24:MI:SS.FFTZH:TZM'),to_timestamp(:4 ,'SYYYY-MM-DD"T"HH24:MI:SS.FFTZH:TZM'),:5 )
try (PreparedStatement p = c.prepareStatement(String.format("insert /*+ append */ into \"%s\" (ID,JSON_DOCUMENT,VERSION"+(thread_id_partitioned?",THREAD_ID":"") +") " +
"VALUES(?,?,'1'"+(thread_id_partitioned?",?":"")+")", collectionName.toUpperCase()))) {
if(thread_id_partitioned) {
p.setInt(3, id);
}
while (true) {
final List<byte[]> batch = queue.take();
if (batch.size() == 0) {
callback.addConsumed(0, 0, true);
break;
}
//System.out.println("Treating "+batch.size()+" docs");
for (byte[] data : batch) {
final BSONObject obj = decoder.readObject(data);
if (obj != null) {
count++;
bsonSize += decoder.getBsonLength();
final byte[] osonData = decoder.getOSONData();
osonSize += osonData.length;
//System.out.println("ObjectId: "+decoder.getOid()+", BSON: "+decoder.getBsonLength()+", OSON: "+osonData.length);
p.setString(1, decoder.getOid());
p.setBytes(2, osonData);
p.addBatch();
}
}
//System.out.println("Running batch...("+osonSize+")");
p.executeLargeBatch();
realConnection.commit(commitOptions);
callback.addConsumed(batch.size(), osonSize, false);
osonSize = 0;
}
realConnection.commit(commitOptions);
}
}
// else if (MongoDBBSONToAJDOSONLoading.KEEP_MONGODB_OBJECTIDS) {
// while (true) {
// final List<byte[]> batch = queue.take();
// if (batch.size() == 0) {
// callback.addConsumed(0, 0, true);
// break;
// }
//
// //System.out.println("Treating "+batch.size()+" docs");
//
// for (byte[] data : batch) {
// final BSONObject obj = decoder.readObject(data);
// if (obj != null) {
// count++;
//
// bsonSize += decoder.getBsonLength();
// final byte[] osonData = decoder.getOSONData();
// osonSize += osonData.length;
//
// //System.out.println("ObjectId: "+decoder.getOid()+", BSON: "+decoder.getBsonLength()+", OSON: "+osonData.length);
//
// batchDocuments.add(db.createDocumentFrom(decoder.getOid(), osonData));
//
// //p.setString(1, decoder.getOid());
// //p.setBytes(2, osonData);
// //p.addBatch();
// }
// }
//
// //System.out.println("Running batch...("+osonSize+")");
//
// //p.executeLargeBatch();
// collection.insertAndGet(batchDocuments.iterator(), insertOptions);
//
// batchDocuments.clear();
// c.commit();
//
// callback.addConsumed(batch.size(), osonSize, false);
// osonSize = 0;
// }
// } else {
// while (true) {
// final List<byte[]> batch = queue.take();
// if (batch.size() == 0) {
// callback.addConsumed(0, 0, true);
// break;
// }
//
// //System.out.println("Treating "+batch.size()+" docs");
//
// for (byte[] data : batch) {
// final BSONObject obj = decoder.readObject(data);
// if (obj != null) {
// count++;
//
// bsonSize += decoder.getBsonLength();
// final byte[] osonData = decoder.getOSONData();
// osonSize += osonData.length;
//
//
// batchDocuments.add(db.createDocumentFrom(osonData));
//
// //p.setString(1, decoder.getOid());
// //p.setBytes(2, osonData);
// //p.addBatch();
// }
// }
//
// //System.out.println("Running batch...("+osonSize+")");
//
// //p.executeLargeBatch();
// collection.insertAndGet(batchDocuments.iterator(), insertOptions);
//
// batchDocuments.clear();
// c.commit();
//
// callback.addConsumed(batch.size(), osonSize, false);
// osonSize = 0;
// }
// }
//
// for (byte[] data : batch) {
// final BSONObject obj = decoder.readObject(data);
// if (obj != null) {
// count++;
//
// bsonSize += decoder.getBsonLength();
// final byte[] osonData = decoder.getOSONData();
// osonSize += osonData.length;
//
// //System.out.println("ObjectId: "+decoder.getOid()+", BSON: "+decoder.getBsonLength()+", OSON: "+osonData.length);
// p.setString(1, decoder.getOid());
// p.setBytes(2, osonData);
// p.addBatch();
//
// if(count % 200 == 0) {
// p.executeLargeBatch();
// }
// }
// }
//
// //System.out.println("Running batch...("+osonSize+")");
//
// p.executeLargeBatch();
//
// c.commit();
//
// callback.addConsumed(batch.size(), osonSize, false);
// osonSize = 0;
// }
//
// p.executeLargeBatch();
// c.commit();
// }
// } else if (MongoDBBSONToAJDOSONLoading.KEEP_MONGODB_OBJECTIDS) {
// while (true) {
// final List<byte[]> batch = queue.take();
// if (batch.size() == 0) {
// callback.addConsumed(0, 0, true);
// break;
// }
//
// //System.out.println("Treating "+batch.size()+" docs");
//
// for (byte[] data : batch) {
// final BSONObject obj = decoder.readObject(data);
// if (obj != null) {
// count++;
//
// bsonSize += decoder.getBsonLength();
// final byte[] osonData = decoder.getOSONData();
// osonSize += osonData.length;
//
// //System.out.println("ObjectId: "+decoder.getOid()+", BSON: "+decoder.getBsonLength()+", OSON: "+osonData.length);
//
// batchDocuments.add(db.createDocumentFrom(decoder.getOid(), osonData));
//
// //p.setString(1, decoder.getOid());
// //p.setBytes(2, osonData);
// //p.addBatch();
// }
// }
//
// //System.out.println("Running batch...("+osonSize+")");
//
// //p.executeLargeBatch();
// collection.insertAndGet(batchDocuments.iterator(), insertOptions);
//
// batchDocuments.clear();
// c.commit();
//
// callback.addConsumed(batch.size(), osonSize, false);
// osonSize = 0;
// }
// } else {
// while (true) {
// final List<byte[]> batch = queue.take();
// if (batch.size() == 0) {
// callback.addConsumed(0, 0, true);
// break;
// }
//
// //System.out.println("Treating "+batch.size()+" docs");
//
// for (byte[] data : batch) {
// final BSONObject obj = decoder.readObject(data);
// if (obj != null) {
// count++;
//
// bsonSize += decoder.getBsonLength();
// final byte[] osonData = decoder.getOSONData();
// osonSize += osonData.length;
//
//
// batchDocuments.add(db.createDocumentFrom(osonData));
//
// //p.setString(1, decoder.getOid());
// //p.setBytes(2, osonData);
// //p.addBatch();
// }
// }
//
// //System.out.println("Running batch...("+osonSize+")");
//
// //p.executeLargeBatch();
// collection.insertAndGet(batchDocuments.iterator(), insertOptions);
//
// batchDocuments.clear();
// c.commit();
//
// callback.addConsumed(batch.size(), osonSize, false);
// osonSize = 0;
// }
}
//}
// SODA END
//========================================================
} catch (Exception e) {
e.printStackTrace();
Thread.currentThread().interrupt();
} finally {
consumerCountDownLatch.countDown();
}
}
public void mergeMaxLengths(Map<String, Integer> aggregatedMaxLengths) {
final Map<String, Integer> maxLengths = ((MyBSONDecoderWithMetadata) this.decoder).getMaxLengths();
for (String key : maxLengths.keySet()) {
if (aggregatedMaxLengths.containsKey(key)) {
aggregatedMaxLengths.put(key, Math.max(maxLengths.get(key), aggregatedMaxLengths.get(key)));
} else {
aggregatedMaxLengths.put(key, maxLengths.get(key));
}
}
}
public void mergeFieldsDataTypes(Map<String, Set<String>> aggregatedFieldsDataTypes) {
final Map<String, Set<String>> fieldsDataTypes = ((MyBSONDecoderWithMetadata) this.decoder).getFieldsDataTypes();
for (String key : fieldsDataTypes.keySet()) {
if (aggregatedFieldsDataTypes.containsKey(key)) {
aggregatedFieldsDataTypes.get(key).addAll(fieldsDataTypes.get(key));
} else {
aggregatedFieldsDataTypes.put(key, fieldsDataTypes.get(key));
}
}
}
public void mergeCantIndex(Set<String> aggregatedCantIndex) {
aggregatedCantIndex.addAll(((MyBSONDecoderWithMetadata) this.decoder).getCantIndex());
}
}
|
package org.hisp.dhis.webapi.documentation.controller;
/*
* Copyright (c) 2004-2016, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import org.apache.http.HttpStatus;
import org.hisp.dhis.chart.ChartType;
import org.hisp.dhis.color.Color;
import org.hisp.dhis.color.ColorSet;
import org.hisp.dhis.common.IdentifiableObject;
import org.hisp.dhis.common.ValueType;
import org.hisp.dhis.constant.Constant;
import org.hisp.dhis.dataelement.CategoryOptionGroup;
import org.hisp.dhis.dataelement.CategoryOptionGroupSet;
import org.hisp.dhis.dataelement.DataElement;
import org.hisp.dhis.dataelement.DataElementCategory;
import org.hisp.dhis.dataelement.DataElementCategoryCombo;
import org.hisp.dhis.dataelement.DataElementCategoryOption;
import org.hisp.dhis.dataelement.DataElementCategoryOptionCombo;
import org.hisp.dhis.dataelement.DataElementGroup;
import org.hisp.dhis.dataelement.DataElementGroupSet;
import org.hisp.dhis.dataelement.DataElementOperand;
import org.hisp.dhis.eventchart.EventChart;
import org.hisp.dhis.eventreport.EventReport;
import org.hisp.dhis.indicator.Indicator;
import org.hisp.dhis.indicator.IndicatorGroup;
import org.hisp.dhis.indicator.IndicatorGroupSet;
import org.hisp.dhis.indicator.IndicatorType;
import org.hisp.dhis.legend.Legend;
import org.hisp.dhis.legend.LegendSet;
import org.hisp.dhis.mapping.ExternalMapLayer;
import org.hisp.dhis.mapping.ImageFormat;
import org.hisp.dhis.mapping.MapLayerPosition;
import org.hisp.dhis.mapping.MapService;
import org.hisp.dhis.option.Option;
import org.hisp.dhis.option.OptionGroup;
import org.hisp.dhis.option.OptionGroupSet;
import org.hisp.dhis.option.OptionSet;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.organisationunit.OrganisationUnitGroup;
import org.hisp.dhis.organisationunit.OrganisationUnitGroupSet;
import org.hisp.dhis.organisationunit.OrganisationUnitLevel;
import org.hisp.dhis.program.Program;
import org.hisp.dhis.program.ProgramDataElement;
import org.hisp.dhis.program.ProgramIndicator;
import org.hisp.dhis.program.ProgramTrackedEntityAttribute;
import org.hisp.dhis.program.ProgramTrackedEntityAttributeGroup;
import org.hisp.dhis.schema.Schema;
import org.hisp.dhis.webapi.DhisWebSpringTest;
import org.hisp.dhis.webapi.documentation.common.ResponseDocumentation;
import org.hisp.dhis.webapi.documentation.common.TestUtils;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.restdocs.payload.FieldDescriptor;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.hisp.dhis.program.ProgramIndicator.KEY_PROGRAM_VARIABLE;
import static org.springframework.restdocs.payload.PayloadDocumentation.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* @author Viet Nguyen <viet@dhis2.org>
*/
public abstract class AbstractWebApiTest<T extends IdentifiableObject>
extends DhisWebSpringTest
{
protected Class<T> testClass;
protected Schema schema;
protected int createdStatus = HttpStatus.SC_CREATED;
protected int updateStatus = HttpStatus.SC_OK;
protected int deleteStatus = HttpStatus.SC_OK;
@Override
@SuppressWarnings( "unchecked" )
public void setUpTest()
{
testClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
schema = schemaService.getSchema( testClass );
setStatues();
}
protected void setStatues()
{
}
@Test
public void testGetAll() throws Exception
{
Map<Class<? extends IdentifiableObject>, IdentifiableObject> defaultObjectMap = manager.getDefaults();
IdentifiableObject defaultTestObject = defaultObjectMap.get( testClass );
int valueToTest = defaultTestObject != null ? 5 : 4;
manager.save( createTestObject( testClass, 'A' ) );
manager.save( createTestObject( testClass, 'B' ) );
manager.save( createTestObject( testClass, 'C' ) );
manager.save( createTestObject( testClass, 'D' ) );
MockHttpSession session = getSession( "ALL" );
List<FieldDescriptor> fieldDescriptors = new ArrayList<>();
fieldDescriptors.addAll( ResponseDocumentation.pager() );
fieldDescriptors.add( fieldWithPath( schema.getPlural() ).description( schema.getPlural() ) );
mvc.perform( get( schema.getRelativeApiEndpoint() ).session( session ).accept( TestUtils.APPLICATION_JSON_UTF8 ) )
.andExpect( status().isOk() )
.andExpect( content().contentTypeCompatibleWith( TestUtils.APPLICATION_JSON_UTF8 ) )
.andExpect( jsonPath( "$." + schema.getPlural() ).isArray() )
.andExpect( jsonPath( "$." + schema.getPlural() + ".length()" ).value( valueToTest ) )
.andDo( documentPrettyPrint( schema.getPlural() + "/all",
responseFields( fieldDescriptors.toArray( new FieldDescriptor[fieldDescriptors.size()] ) )
) );
}
@Test
public void testGetByIdOk() throws Exception
{
MockHttpSession session = getSession( "ALL" );
T object = createTestObject( testClass, 'A' );
manager.save( object );
Set<FieldDescriptor> fieldDescriptors = TestUtils.getFieldDescriptors( schema );
mvc.perform( get( schema.getRelativeApiEndpoint() + "/{id}", object.getUid() ).session( session ).accept( MediaType.APPLICATION_JSON ) )
.andExpect( status().isOk() )
.andExpect( content().contentTypeCompatibleWith( MediaType.APPLICATION_JSON ) )
.andExpect( jsonPath( "$.name" ).value( object.getName() ) )
.andDo( documentPrettyPrint( schema.getPlural() + "/id",
responseFields( fieldDescriptors.toArray( new FieldDescriptor[fieldDescriptors.size()] ) ) ) );
}
@Test
public void testCreate() throws Exception
{
MockHttpSession session = getSession( "ALL" );
T object = createTestObject( testClass, 'A' );
Set<FieldDescriptor> fieldDescriptors = TestUtils.getFieldDescriptors( schema );
mvc.perform( post( schema.getRelativeApiEndpoint() )
.session( session )
.contentType( TestUtils.APPLICATION_JSON_UTF8 )
.content( TestUtils.convertObjectToJsonBytes( object ) ) )
.andExpect( status().is( createdStatus ) )
.andDo( documentPrettyPrint( schema.getPlural() + "/create",
requestFields( fieldDescriptors.toArray( new FieldDescriptor[fieldDescriptors.size()] ) ) )
);
}
@Test
public void testUpdate() throws Exception
{
MockHttpSession session = getSession( "ALL" );
T object = createTestObject( testClass, 'A' );
manager.save( object );
object.setHref( "updatedHref" );
mvc.perform( put( schema.getRelativeApiEndpoint() + "/" + object.getUid() )
.session( session )
.contentType( TestUtils.APPLICATION_JSON_UTF8 )
.content( TestUtils.convertObjectToJsonBytes( object ) ) )
.andExpect( status().is( updateStatus ) )
.andDo( documentPrettyPrint( schema.getPlural() + "/update" ) );
}
@Test
public void testDeleteByIdOk() throws Exception
{
MockHttpSession session = getSession( "ALL" );
T object = createTestObject( testClass, 'A' );
manager.save( object );
mvc.perform( delete( schema.getRelativeApiEndpoint() + "/{id}", object.getUid() ).session( session ).accept( MediaType.APPLICATION_JSON ) )
.andExpect( status().is( deleteStatus ) )
.andDo( documentPrettyPrint( schema.getPlural() + "/delete" ) );
}
@Test
public void testDeleteById404() throws Exception
{
MockHttpSession session = getSession( "ALL" );
mvc.perform( delete( schema.getRelativeApiEndpoint() + "/{id}", "deabcdefghA" ).session( session ).accept( MediaType.APPLICATION_JSON ) )
.andExpect( status().isNotFound() );
}
@SuppressWarnings( "unchecked" )
protected T createTestObject( Class<?> clazz, char uniqueName, Object... params )
{
if ( DataElementGroup.class.isAssignableFrom( clazz ) )
{
return (T) createDataElementGroup( uniqueName );
}
else if ( DataElementCategoryCombo.class.isAssignableFrom( clazz ) )
{
return (T) createCategoryCombo( uniqueName, Arrays.copyOf( params, params.length, DataElementCategory[].class ) );
}
else if ( DataElementCategoryOption.class.isAssignableFrom( clazz ) )
{
return (T) createCategoryOption( uniqueName );
}
else if ( DataElement.class.isAssignableFrom( clazz ) )
{
return (T) createDataElement( uniqueName );
}
else if ( DataElementCategory.class.isAssignableFrom( clazz ) )
{
return (T) createDataElementCategory( uniqueName, Arrays.copyOf( params, params.length, DataElementCategoryOption[].class ) );
}
else if ( Program.class.isAssignableFrom( clazz ) )
{
OrganisationUnit organisationUnitA = createOrganisationUnit( uniqueName );
manager.save( organisationUnitA );
return (T) createProgram( uniqueName, new HashSet<>(), organisationUnitA );
}
else if ( DataElementOperand.class.isAssignableFrom( clazz ) )
{
DataElement deA = createDataElement( uniqueName );
manager.save( deA );
DataElementCategoryCombo cc = createCategoryCombo( uniqueName );
DataElementCategoryOption co = createCategoryOption( uniqueName );
manager.save( cc );
manager.save( co );
DataElementCategoryOptionCombo coc = createCategoryOptionCombo( cc, co );
manager.save( coc );
return (T) new DataElementOperand( deA, coc );
}
else if ( DataElementGroupSet.class.isAssignableFrom( clazz ) )
{
return (T) createDataElementGroupSet( uniqueName );
}
else if ( DataElementCategoryOptionCombo.class.isAssignableFrom( clazz ) )
{
DataElementCategoryCombo cc = createCategoryCombo( uniqueName );
DataElementCategoryOption co = createCategoryOption( uniqueName );
manager.save( cc );
manager.save( co );
return (T) createCategoryOptionCombo( cc, co );
}
else if ( CategoryOptionGroup.class.isAssignableFrom( clazz ) )
{
DataElementCategoryOption co = createCategoryOption( uniqueName );
manager.save( co );
return (T) createCategoryOptionGroup( uniqueName, co );
}
else if ( CategoryOptionGroupSet.class.isAssignableFrom( clazz ) )
{
return (T) createCategoryOptionGroupSet( uniqueName );
}
else if ( EventChart.class.isAssignableFrom( clazz ) )
{
Program prA = createProgram( uniqueName );
manager.save( prA );
EventChart ecA = new EventChart( "evc" + uniqueName );
ecA.setProgram( prA );
ecA.setType( ChartType.COLUMN );
return (T) ecA;
}
else if ( EventReport.class.isAssignableFrom( clazz ) )
{
Program prA = createProgram( uniqueName );
manager.save( prA );
EventReport erA = new EventReport( "er" + uniqueName );
erA.setProgram( prA );
return (T) erA;
}
else if ( ProgramDataElement.class.isAssignableFrom( clazz ) )
{
Program prA = createProgram( uniqueName );
manager.save( prA );
DataElement deA = createDataElement( uniqueName );
manager.save( deA );
return (T) new ProgramDataElement( prA, deA );
}
else if ( ProgramIndicator.class.isAssignableFrom( clazz ) )
{
Program program = (Program) createTestObject( Program.class, uniqueName );
manager.save( program );
Constant constantA = createConstant( uniqueName, 7.0 );
manager.save( constantA );
String expressionA = "( " + KEY_PROGRAM_VARIABLE + "{" + ProgramIndicator.VAR_ENROLLMENT_DATE + "} - " + KEY_PROGRAM_VARIABLE + "{"
+ ProgramIndicator.VAR_INCIDENT_DATE + "} ) / " + ProgramIndicator.KEY_CONSTANT + "{" + constantA.getUid() + "}";
return (T) createProgramIndicator( uniqueName, program, expressionA, null );
}
else if ( Indicator.class.isAssignableFrom( clazz ) )
{
IndicatorType indicatorType = createIndicatorType( uniqueName );
manager.save( indicatorType );
return (T) createIndicator( uniqueName, indicatorType );
}
else if ( IndicatorGroup.class.isAssignableFrom( clazz ) )
{
return (T) createIndicatorGroup( uniqueName );
}
else if ( IndicatorGroupSet.class.isAssignableFrom( clazz ) )
{
return (T) createIndicatorGroupSet( uniqueName );
}
else if ( IndicatorType.class.isAssignableFrom( clazz ) )
{
return (T) createIndicatorType( uniqueName );
}
else if ( Legend.class.isAssignableFrom( clazz ) )
{
return (T) createLegend( uniqueName, 0d, 10d );
}
else if ( LegendSet.class.isAssignableFrom( clazz ) )
{
return (T) createLegendSet( uniqueName );
}
else if ( OrganisationUnit.class.isAssignableFrom( clazz ) )
{
return (T) createOrganisationUnit( uniqueName );
}
else if ( OrganisationUnitGroup.class.isAssignableFrom( clazz ) )
{
return (T) createOrganisationUnitGroup( uniqueName );
}
else if ( OrganisationUnitGroupSet.class.isAssignableFrom( clazz ) )
{
return (T) createOrganisationUnitGroupSet( uniqueName );
}
else if ( OrganisationUnitLevel.class.isAssignableFrom( clazz ) )
{
return (T) new OrganisationUnitLevel( uniqueName, "OrgLevel" + uniqueName );
}
else if ( Color.class.isAssignableFrom( clazz ) )
{
Color color = new Color( "#ff3200" );
color.setName( "Color" + uniqueName );
return (T) color;
}
else if ( ColorSet.class.isAssignableFrom( clazz ) )
{
ColorSet colorSet = new ColorSet();
colorSet.setName( "ColorSet" + uniqueName );
return (T) colorSet;
}
else if ( org.hisp.dhis.mapping.Map.class.isAssignableFrom( clazz ) )
{
org.hisp.dhis.mapping.Map map = new org.hisp.dhis.mapping.Map();
map.setName( "Map" + uniqueName );
map.setDisplayName( "DisplayName" + uniqueName );
map.setLatitude( 952175.62553525 );
map.setLongitude( -1378543.6774686 );
return (T) map;
}
else if ( ExternalMapLayer.class.isAssignableFrom( clazz ) )
{
ExternalMapLayer externalMapLayer = new ExternalMapLayer( "ExternalMapLayer" + uniqueName );
externalMapLayer.setMapService( MapService.WMS );
externalMapLayer.setUrl( "testUrl" );
externalMapLayer.setImageFormat( ImageFormat.JPG );
externalMapLayer.setMapLayerPosition( MapLayerPosition.BASEMAP );
return (T) externalMapLayer;
}
else if ( OptionGroup.class.isAssignableFrom( clazz ) )
{
OptionGroup optionGroup = new OptionGroup( "OptionGroup" + uniqueName );
optionGroup.setShortName( "Group" + uniqueName );
return (T) optionGroup;
}
else if ( OptionGroupSet.class.isAssignableFrom( clazz ) )
{
return (T) new OptionGroupSet( "OptionGroupSet" + uniqueName );
}
else if ( Option.class.isAssignableFrom( clazz ) )
{
return (T) new Option( "Option" + uniqueName, "code" + uniqueName );
}
else if ( OptionSet.class.isAssignableFrom( clazz ))
{
return (T) new OptionSet( "OptionSet" +uniqueName, ValueType.TEXT );
}
else if ( ProgramTrackedEntityAttributeGroup.class.isAssignableFrom( clazz ) )
{
return (T) createProgramTrackedEntityAttributeGroup( uniqueName );
}
else if ( ProgramTrackedEntityAttribute.class.isAssignableFrom( clazz ))
{
return (T) createProgramTrackedEntityAttribute( uniqueName );
}
return null;
}
}
|
// Targeted by JavaCPP version 1.5.8-SNAPSHOT: DO NOT EDIT THIS FILE
package org.bytedeco.depthai;
import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
import static org.bytedeco.javacpp.presets.javacpp.*;
import static org.bytedeco.openblas.global.openblas_nolapack.*;
import static org.bytedeco.openblas.global.openblas.*;
import org.bytedeco.opencv.opencv_core.*;
import static org.bytedeco.opencv.global.opencv_core.*;
import org.bytedeco.opencv.opencv_imgproc.*;
import static org.bytedeco.opencv.global.opencv_imgproc.*;
import static org.bytedeco.depthai.global.depthai.*;
@Name("std::unordered_map<std::int8_t,dai::BoardConfig::GPIO>") @Properties(inherit = org.bytedeco.depthai.presets.depthai.class)
public class ByteGPIOMap extends Pointer {
static { Loader.load(); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public ByteGPIOMap(Pointer p) { super(p); }
public ByteGPIOMap() { allocate(); }
private native void allocate();
public native @Name("operator =") @ByRef ByteGPIOMap put(@ByRef ByteGPIOMap x);
public boolean empty() { return size() == 0; }
public native long size();
@Index public native @ByRef BoardConfig.GPIO get(byte i);
public native ByteGPIOMap put(byte i, BoardConfig.GPIO value);
public native void erase(@ByVal Iterator pos);
public native @ByVal Iterator begin();
public native @ByVal Iterator end();
@NoOffset @Name("iterator") public static class Iterator extends Pointer {
public Iterator(Pointer p) { super(p); }
public Iterator() { }
public native @Name("operator ++") @ByRef Iterator increment();
public native @Name("operator ==") boolean equals(@ByRef Iterator it);
public native @Name("operator *().first") @MemberGetter byte first();
public native @Name("operator *().second") @MemberGetter @ByRef @Const BoardConfig.GPIO second();
}
}
|
/*
* 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.beam.sdk.transforms;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.VisibleForTesting;
import java.util.Iterator;
import org.apache.beam.sdk.coders.CannotProvideCoderException;
import org.apache.beam.sdk.coders.Coder;
import org.apache.beam.sdk.coders.CoderRegistry;
import org.apache.beam.sdk.coders.KvCoder;
import org.apache.beam.sdk.coders.NullableCoder;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.TimestampedValue;
/**
* {@link PTransform} and {@link Combine.CombineFn} for computing the latest element
* in a {@link PCollection}.
*
* <p>Example: compute the latest value for each session:
* <pre>{@code
* PCollection<Long> input = ...;
* PCollection<Long> sessioned = input
* .apply(Window.<Long>into(Sessions.withGapDuration(Duration.standardMinutes(5)));
* PCollection<Long> latestValues = sessioned.apply(Latest.<Long>globally());
* }</pre>
*
* <p>{@link #combineFn} can also be used manually, in combination with state and with the
* {@link Combine} transform.
*
* <p>For elements with the same timestamp, the element chosen for output is arbitrary.
*/
public class Latest {
// Do not instantiate
private Latest() {}
/** Returns a {@link Combine.CombineFn} that selects the latest element among its inputs. */
public static <T> Combine.CombineFn<TimestampedValue<T>, ?, T> combineFn() {
return new LatestFn<>();
}
/**
* Returns a {@link PTransform} that takes as input a {@code PCollection<T>} and returns a
* {@code PCollection<T>} whose contents is the latest element according to its event time, or
* {@literal null} if there are no elements.
*
* @param <T> The type of the elements being combined.
*/
public static <T> PTransform<PCollection<T>, PCollection<T>> globally() {
return new Globally<>();
}
/**
* Returns a {@link PTransform} that takes as input a {@code PCollection<KV<K, V>>} and returns a
* {@code PCollection<KV<K, V>>} whose contents is the latest element per-key according to its
* event time.
*
* @param <K> The key type of the elements being combined.
* @param <V> The value type of the elements being combined.
*/
public static <K, V> PTransform<PCollection<KV<K, V>>, PCollection<KV<K, V>>> perKey() {
return new PerKey<>();
}
/**
* A {@link Combine.CombineFn} that computes the latest element from a set of inputs.
*
* @param <T> Type of input element.
* @see Latest
*/
@VisibleForTesting
static class LatestFn<T>
extends Combine.CombineFn<TimestampedValue<T>, TimestampedValue<T>, T> {
/** Construct a new {@link LatestFn} instance. */
public LatestFn() {}
@Override
public TimestampedValue<T> createAccumulator() {
return TimestampedValue.atMinimumTimestamp(null);
}
@Override
public TimestampedValue<T> addInput(
TimestampedValue<T> accumulator, TimestampedValue<T> input) {
checkNotNull(accumulator, "accumulator must be non-null");
checkNotNull(input, "input must be non-null");
if (input.getTimestamp().isBefore(accumulator.getTimestamp())) {
return accumulator;
} else {
return input;
}
}
@Override
public Coder<TimestampedValue<T>> getAccumulatorCoder(
CoderRegistry registry, Coder<TimestampedValue<T>> inputCoder)
throws CannotProvideCoderException {
return NullableCoder.of(inputCoder);
}
@Override
public Coder<T> getDefaultOutputCoder(
CoderRegistry registry, Coder<TimestampedValue<T>> inputCoder)
throws CannotProvideCoderException {
checkState(
inputCoder instanceof TimestampedValue.TimestampedValueCoder,
"inputCoder must be a TimestampedValueCoder, but was %s",
inputCoder);
TimestampedValue.TimestampedValueCoder<T> inputTVCoder =
(TimestampedValue.TimestampedValueCoder<T>) inputCoder;
return NullableCoder.of(inputTVCoder.<T>getValueCoder());
}
@Override
public TimestampedValue<T> mergeAccumulators(Iterable<TimestampedValue<T>> accumulators) {
checkNotNull(accumulators, "accumulators must be non-null");
Iterator<TimestampedValue<T>> iter = accumulators.iterator();
if (!iter.hasNext()) {
return createAccumulator();
}
TimestampedValue<T> merged = iter.next();
while (iter.hasNext()) {
merged = addInput(merged, iter.next());
}
return merged;
}
@Override
public T extractOutput(TimestampedValue<T> accumulator) {
return accumulator.getValue();
}
}
/** Implementation of {@link #globally()}. */
private static class Globally<T> extends PTransform<PCollection<T>, PCollection<T>> {
@Override
public PCollection<T> expand(PCollection<T> input) {
Coder<T> inputCoder = input.getCoder();
return input
.apply("Reify Timestamps", ParDo.of(
new DoFn<T, TimestampedValue<T>>() {
@ProcessElement
public void processElement(ProcessContext c) {
c.output(TimestampedValue.of(c.element(), c.timestamp()));
}
})).setCoder(TimestampedValue.TimestampedValueCoder.of(inputCoder))
.apply("Latest Value", Combine.globally(new LatestFn<T>()))
.setCoder(NullableCoder.of(inputCoder));
}
}
/** Implementation of {@link #perKey()}. */
private static class PerKey<K, V>
extends PTransform<PCollection<KV<K, V>>, PCollection<KV<K, V>>> {
@Override
public PCollection<KV<K, V>> expand(PCollection<KV<K, V>> input) {
checkNotNull(input);
checkArgument(input.getCoder() instanceof KvCoder,
"Input specifiedCoder must be an instance of KvCoder, but was %s", input.getCoder());
@SuppressWarnings("unchecked")
KvCoder<K, V> inputCoder = (KvCoder) input.getCoder();
return input
.apply("Reify Timestamps", ParDo.of(
new DoFn<KV<K, V>, KV<K, TimestampedValue<V>>>() {
@ProcessElement
public void processElement(ProcessContext c) {
c.output(KV.of(c.element().getKey(), TimestampedValue.of(c.element().getValue(),
c.timestamp())));
}
})).setCoder(KvCoder.of(
inputCoder.getKeyCoder(),
TimestampedValue.TimestampedValueCoder.of(inputCoder.getValueCoder())))
.apply("Latest Value", Combine.<K, TimestampedValue<V>, V>perKey(new LatestFn<V>()))
.setCoder(inputCoder);
}
}
}
|
// FullScreenPackage.java
package com.ex_nihilo;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class FullScreenPackage implements ReactPackage {
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
@Override
public List<NativeModule> createNativeModules(
ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new FullScreenModule(reactContext));
return modules;
}
}
|
/*
* 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.skywalking.oap.server.storage.plugin.elasticsearch5x.cache;
import org.apache.skywalking.oap.server.core.Const;
import org.apache.skywalking.oap.server.core.register.*;
import org.apache.skywalking.oap.server.core.storage.cache.IEndpointInventoryCacheDAO;
import org.apache.skywalking.oap.server.storage.plugin.elasticsearch5x.base.EsDAO;
import org.apache.skywalking.oap.server.storage.plugin.elasticsearch5x.client.ElasticSearchClient5x;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.*;
/**
* @author peng-yongsheng
*/
public class EndpointInventoryCacheEsDAO extends EsDAO implements IEndpointInventoryCacheDAO {
private static final Logger logger = LoggerFactory.getLogger(EndpointInventoryCacheEsDAO.class);
private final EndpointInventory.Builder builder = new EndpointInventory.Builder();
public EndpointInventoryCacheEsDAO(ElasticSearchClient5x client) {
super(client);
}
@Override public int getEndpointId(int serviceId, String endpointName, int detectPoint) {
try {
String id = EndpointInventory.buildId(serviceId, endpointName, detectPoint);
GetResponse response = getClient().get(EndpointInventory.MODEL_NAME, id);
if (response.isExists()) {
return (int)response.getSource().getOrDefault(RegisterSource.SEQUENCE, 0);
} else {
return Const.NONE;
}
} catch (Throwable e) {
logger.error(e.getMessage(), e);
return Const.NONE;
}
}
@Override public EndpointInventory get(int endpointId) {
try {
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.termQuery(EndpointInventory.SEQUENCE, endpointId));
searchSourceBuilder.size(1);
SearchResponse response = getClient().search(EndpointInventory.MODEL_NAME, searchSourceBuilder);
if (response.getHits().totalHits == 1) {
SearchHit searchHit = response.getHits().getAt(0);
return builder.map2Data(searchHit.getSourceAsMap());
} else {
return null;
}
} catch (Throwable e) {
logger.error(e.getMessage(), e);
return null;
}
}
}
|
/*
* Copyright © 2022 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
*/
package io.cdap.plugin.batch.aggregator;
import io.cdap.cdap.api.data.schema.Schema;
import io.cdap.cdap.etl.api.aggregation.DeduplicateAggregationDefinition;
import io.cdap.cdap.etl.api.engine.sql.StandardSQLCapabilities;
import io.cdap.cdap.etl.api.relational.Capability;
import io.cdap.cdap.etl.api.relational.Engine;
import io.cdap.cdap.etl.api.relational.Expression;
import io.cdap.cdap.etl.api.relational.ExpressionFactory;
import io.cdap.cdap.etl.api.relational.ExtractableExpression;
import io.cdap.cdap.etl.api.relational.InvalidExtractableExpressionException;
import io.cdap.cdap.etl.api.relational.Relation;
import io.cdap.cdap.etl.api.relational.RelationalTranformContext;
import io.cdap.cdap.etl.api.relational.StringExpressionFactoryType;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Test for {@link DedupAggregatorUtils}
*/
@RunWith(MockitoJUnitRunner.class)
@SuppressWarnings("unchecked")
public class DedupAggregatorUtilsTest {
//Mocks used to configure tests
@Mock
Relation relation;
@Mock
private Engine engine;
@Mock
private ExpressionFactory<String> expressionFactory;
@Mock
private RelationalTranformContext relationalTranformContext;
@Mock
private Set<Capability> capabilities;
@Mock
private ExtractableExpression extractableExpression;
private List<String> uniqueFields;
@Before
public void setUp() {
Mockito.doReturn(engine).when(relationalTranformContext).getEngine();
uniqueFields = new ArrayList<>();
uniqueFields.add("uniqueField");
Schema inputSchema = Schema.recordOf(
"schema",
Schema.Field.of("uniqueField", Schema.nullableOf(Schema.of(Schema.Type.STRING))),
Schema.Field.of("uniqueFieldFloat", Schema.nullableOf(Schema.of(Schema.Type.FLOAT))),
Schema.Field.of("uniqueFieldDouble", Schema.nullableOf(Schema.of(Schema.Type.DOUBLE))),
Schema.Field.of("uniqueFieldDatetime", Schema.nullableOf(Schema.of(Schema.LogicalType.DATETIME))),
Schema.Field.of("selectField", Schema.nullableOf(Schema.of(Schema.Type.STRING))),
Schema.Field.of("filterField", Schema.nullableOf(Schema.of(Schema.Type.STRING)))
);
Mockito.doReturn(Collections.singleton("input_rel")).when(relationalTranformContext).getInputRelationNames();
Mockito.doReturn(inputSchema).when(relationalTranformContext).getInputSchema(Mockito.eq("input_rel"));
Schema outputSchema = Schema.recordOf(
"schema",
Schema.Field.of("uniqueField", Schema.nullableOf(Schema.of(Schema.Type.STRING))),
Schema.Field.of("selectField", Schema.nullableOf(Schema.of(Schema.Type.STRING))),
Schema.Field.of("filterField", Schema.nullableOf(Schema.of(Schema.Type.STRING)))
);
Mockito.doReturn(outputSchema).when(relationalTranformContext).getOutputSchema();
}
@Test
public void testDedupAggregatorTransformExpressionHappyPath() {
DedupConfig.DedupFunctionInfo filterFunction = new DedupConfig.DedupFunctionInfo("filterField",
DedupConfig.Function.MIN);
Mockito.doReturn(Optional.of(expressionFactory)).when(engine)
.getExpressionFactory(Mockito.eq(StringExpressionFactoryType.SQL),
Mockito.eq(StandardSQLCapabilities.BIGQUERY));
Mockito.doReturn(capabilities).when(expressionFactory).getCapabilities();
Mockito.doReturn(true).when(capabilities).contains(Mockito.any());
Mockito.doReturn(extractableExpression).when(expressionFactory).getQualifiedColumnName(Mockito.any(),
Mockito.any());
DeduplicateAggregationDefinition deduplicateAggregationDefinition = DedupAggregatorUtils
.generateAggregationDefinition(relationalTranformContext, relation, uniqueFields, filterFunction);
Assert.assertEquals(3, deduplicateAggregationDefinition.getSelectExpressions().size());
Assert.assertEquals(1, deduplicateAggregationDefinition.getGroupByExpressions().size());
Assert.assertEquals(1, deduplicateAggregationDefinition.getFilterExpressions().size());
}
@Test
public void testDedupAggregatorTransformExpressionHappyPathWithNullFilterFunction() {
DedupConfig.DedupFunctionInfo filterFunction = new DedupConfig.DedupFunctionInfo("filterField",
DedupConfig.Function.MIN);
Mockito.doReturn(Optional.of(expressionFactory)).when(engine)
.getExpressionFactory(Mockito.eq(StringExpressionFactoryType.SQL),
Mockito.eq(StandardSQLCapabilities.BIGQUERY));
Mockito.doReturn(capabilities).when(expressionFactory).getCapabilities();
Mockito.doReturn(true).when(capabilities).contains(Mockito.any());
Mockito.doReturn(extractableExpression).when(expressionFactory).getQualifiedColumnName(Mockito.any(),
Mockito.any());
DeduplicateAggregationDefinition deduplicateAggregationDefinition = DedupAggregatorUtils
.generateAggregationDefinition(relationalTranformContext, relation, uniqueFields, null);
Assert.assertEquals(3, deduplicateAggregationDefinition.getSelectExpressions().size());
Assert.assertEquals(1, deduplicateAggregationDefinition.getGroupByExpressions().size());
Assert.assertEquals(0, deduplicateAggregationDefinition.getFilterExpressions().size());
}
@Test
public void testDedupAggregatorTransformExpressionInvalidFilterFunction() {
DedupConfig.DedupFunctionInfo filterFunction = new DedupConfig.DedupFunctionInfo("filterField",
DedupConfig.Function.LAST);
Mockito.doReturn(Optional.of(expressionFactory)).when(engine)
.getExpressionFactory(Mockito.eq(StringExpressionFactoryType.SQL),
Mockito.eq(StandardSQLCapabilities.BIGQUERY));
DeduplicateAggregationDefinition deduplicateAggregationDefinition = DedupAggregatorUtils
.generateAggregationDefinition(relationalTranformContext, relation,
uniqueFields, filterFunction);
Assert.assertEquals(null, deduplicateAggregationDefinition);
}
@Test
public void testDedupAggregatorTransformExpressionFilterFunction() {
Mockito.doReturn(Optional.of(expressionFactory)).when(engine)
.getExpressionFactory(Mockito.eq(StringExpressionFactoryType.SQL),
Mockito.eq(StandardSQLCapabilities.BIGQUERY));
Mockito.doReturn(capabilities).when(expressionFactory).getCapabilities();
Mockito.doReturn(true).when(capabilities).contains(Mockito.any());
Mockito.doReturn(extractableExpression).when(expressionFactory).getQualifiedColumnName(Mockito.any(),
Mockito.any());
DedupConfig.DedupFunctionInfo min = new DedupConfig.DedupFunctionInfo("filterField",
DedupConfig.Function.MIN);
DeduplicateAggregationDefinition minDefinition = DedupAggregatorUtils
.generateAggregationDefinition(relationalTranformContext, relation, uniqueFields, min);
Assert.assertEquals(DeduplicateAggregationDefinition.FilterFunction.MIN,
minDefinition.getFilterExpressions().get(0).getFilterFunction());
DedupConfig.DedupFunctionInfo max = new DedupConfig.DedupFunctionInfo("filterField",
DedupConfig.Function.MAX);
DeduplicateAggregationDefinition maxDefinition = DedupAggregatorUtils
.generateAggregationDefinition(relationalTranformContext, relation, uniqueFields, max);
Assert.assertEquals(DeduplicateAggregationDefinition.FilterFunction.MAX,
maxDefinition.getFilterExpressions().get(0).getFilterFunction());
DedupConfig.DedupFunctionInfo any = new DedupConfig.DedupFunctionInfo("filterField",
DedupConfig.Function.ANY);
DeduplicateAggregationDefinition anyDefinition = DedupAggregatorUtils
.generateAggregationDefinition(relationalTranformContext, relation, uniqueFields, any);
Assert.assertEquals(DeduplicateAggregationDefinition.FilterFunction.ANY_NULLS_LAST,
anyDefinition.getFilterExpressions().get(0).getFilterFunction());
DedupConfig.DedupFunctionInfo first = new DedupConfig.DedupFunctionInfo("filterField",
DedupConfig.Function.FIRST);
DeduplicateAggregationDefinition firstDefinition = DedupAggregatorUtils
.generateAggregationDefinition(relationalTranformContext, relation, uniqueFields, first);
Assert.assertNull(firstDefinition);
DedupConfig.DedupFunctionInfo last = new DedupConfig.DedupFunctionInfo("filterField",
DedupConfig.Function.LAST);
DeduplicateAggregationDefinition lastDefinition = DedupAggregatorUtils
.generateAggregationDefinition(relationalTranformContext, relation, uniqueFields, last);
Assert.assertNull(lastDefinition);
}
@Test
public void testDedupAggregatorTransformExpressionWithFloatField() {
DedupConfig.DedupFunctionInfo any = new DedupConfig.DedupFunctionInfo("filterField",
DedupConfig.Function.ANY);
Mockito.doReturn(Optional.of(expressionFactory)).when(engine)
.getExpressionFactory(Mockito.eq(StringExpressionFactoryType.SQL),
Mockito.eq(StandardSQLCapabilities.BIGQUERY));
// Ensure we suppport all capabilities
Mockito.doReturn(capabilities).when(expressionFactory).getCapabilities();
Mockito.doReturn(true).when(capabilities).contains(Mockito.any());
Mockito.doReturn(extractableExpression)
.when(expressionFactory).getQualifiedColumnName(Mockito.any(), Mockito.any());
// Configure test specific return types
Mockito.doReturn(getExtractableExpressionForString("uniqueFieldFloat"))
.when(expressionFactory).getQualifiedColumnName(Mockito.any(), Mockito.eq("uniqueFieldFloat"));
Mockito.doReturn(getExtractableExpressionForString("CAST(uniqueFieldFloat AS NUMERIC)"))
.when(expressionFactory).compile("CAST(uniqueFieldFloat AS NUMERIC)");
DeduplicateAggregationDefinition anyDefinition = DedupAggregatorUtils
.generateAggregationDefinition(relationalTranformContext,
relation,
Collections.singletonList("uniqueFieldFloat"), any
);
// Ensure method to wrap expression got called
Mockito.verify(expressionFactory).compile(Mockito.eq("CAST(uniqueFieldFloat AS NUMERIC)"));
// Verify expression gets CAST statement
Expression exp = anyDefinition.getGroupByExpressions().get(0);
Assert.assertTrue(exp instanceof ExtractableExpression);
ExtractableExpression<String> extractableExp = (ExtractableExpression<String>) exp;
Assert.assertEquals("CAST(uniqueFieldFloat AS NUMERIC)", extractableExp.extract());
}
@Test
public void testDedupAggregatorTransformExpressionWithDoubleField() {
DedupConfig.DedupFunctionInfo any = new DedupConfig.DedupFunctionInfo("filterField",
DedupConfig.Function.ANY);
Mockito.doReturn(Optional.of(expressionFactory)).when(engine)
.getExpressionFactory(Mockito.eq(StringExpressionFactoryType.SQL),
Mockito.eq(StandardSQLCapabilities.BIGQUERY));
// Ensure we suppport all capabilities
Mockito.doReturn(capabilities).when(expressionFactory).getCapabilities();
Mockito.doReturn(true).when(capabilities).contains(Mockito.any());
Mockito.doReturn(extractableExpression)
.when(expressionFactory).getQualifiedColumnName(Mockito.any(), Mockito.any());
// Configure test specific return types
Mockito.doReturn(getExtractableExpressionForString("uniqueFieldDouble"))
.when(expressionFactory).getQualifiedColumnName(Mockito.any(), Mockito.eq("uniqueFieldDouble"));
Mockito.doReturn(getExtractableExpressionForString("CAST(uniqueFieldDouble AS NUMERIC)"))
.when(expressionFactory).compile("CAST(uniqueFieldDouble AS NUMERIC)");
DeduplicateAggregationDefinition anyDefinition = DedupAggregatorUtils
.generateAggregationDefinition(relationalTranformContext,
relation,
Collections.singletonList("uniqueFieldDouble"), any
);
// Ensure method to wrap expression got called
Mockito.verify(expressionFactory).compile(Mockito.eq("CAST(uniqueFieldDouble AS NUMERIC)"));
// Verify expression gets CAST statement
Expression exp = anyDefinition.getGroupByExpressions().get(0);
Assert.assertTrue(exp instanceof ExtractableExpression);
ExtractableExpression<String> extractableExp = (ExtractableExpression<String>) exp;
Assert.assertEquals("CAST(uniqueFieldDouble AS NUMERIC)", extractableExp.extract());
}
@Test
public void testDedupAggregatorTransformExpressionWithIntField() {
DedupConfig.DedupFunctionInfo any = new DedupConfig.DedupFunctionInfo("filterField",
DedupConfig.Function.ANY);
Mockito.doReturn(Optional.of(expressionFactory)).when(engine)
.getExpressionFactory(Mockito.eq(StringExpressionFactoryType.SQL),
Mockito.eq(StandardSQLCapabilities.BIGQUERY));
// Ensure we suppport all capabilities
Mockito.doReturn(capabilities).when(expressionFactory).getCapabilities();
Mockito.doReturn(true).when(capabilities).contains(Mockito.any());
Mockito.doReturn(extractableExpression)
.when(expressionFactory).getQualifiedColumnName(Mockito.any(), Mockito.any());
// Configure test specific return types
Mockito.doReturn(getExtractableExpressionForString("uniqueFieldInt"))
.when(expressionFactory).getQualifiedColumnName(Mockito.any(), Mockito.eq("uniqueFieldInt"));
DeduplicateAggregationDefinition anyDefinition = DedupAggregatorUtils
.generateAggregationDefinition(relationalTranformContext,
relation,
Collections.singletonList("uniqueFieldInt"), any
);
// Ensure method to wrap expression got called
Mockito.verify(expressionFactory, Mockito.never()).compile(Mockito.any());
// Verify expression does not get casted for an int field
Expression exp = anyDefinition.getGroupByExpressions().get(0);
Assert.assertTrue(exp instanceof ExtractableExpression);
ExtractableExpression<String> extractableExp = (ExtractableExpression<String>) exp;
Assert.assertEquals("uniqueFieldInt", extractableExp.extract());
}
@Test
public void testDedupAggregatorTransformExpressionWithDatetimeField() {
DedupConfig.DedupFunctionInfo any = new DedupConfig.DedupFunctionInfo("filterField",
DedupConfig.Function.ANY);
Mockito.doReturn(Optional.of(expressionFactory)).when(engine)
.getExpressionFactory(Mockito.eq(StringExpressionFactoryType.SQL),
Mockito.eq(StandardSQLCapabilities.BIGQUERY));
// Ensure we suppport all capabilities
Mockito.doReturn(capabilities).when(expressionFactory).getCapabilities();
Mockito.doReturn(true).when(capabilities).contains(Mockito.any());
Mockito.doReturn(extractableExpression)
.when(expressionFactory).getQualifiedColumnName(Mockito.any(), Mockito.any());
// Configure test specific return types
Mockito.doReturn(getExtractableExpressionForString("uniqueFieldDatetime"))
.when(expressionFactory).getQualifiedColumnName(Mockito.any(), Mockito.eq("uniqueFieldDatetime"));
DeduplicateAggregationDefinition anyDefinition = DedupAggregatorUtils
.generateAggregationDefinition(relationalTranformContext,
relation,
Collections.singletonList("uniqueFieldDatetime"), any
);
// Ensure method to wrap expression got called
Mockito.verify(expressionFactory, Mockito.never()).compile(Mockito.any());
// Verify expression does not get casted for an int field
Expression exp = anyDefinition.getGroupByExpressions().get(0);
Assert.assertTrue(exp instanceof ExtractableExpression);
ExtractableExpression<String> extractableExp = (ExtractableExpression<String>) exp;
Assert.assertEquals("uniqueFieldDatetime", extractableExp.extract());
}
@Test
public void testGetExpressionFactoryNullSchema() {
Optional<ExpressionFactory<String>> expressionFactory =
DedupAggregatorUtils.getExpressionFactory(relationalTranformContext, null);
Assert.assertFalse(expressionFactory.isPresent());
}
@Test
public void testGetExpressionFactoryFloatSchema() {
Mockito.doReturn(Optional.of(expressionFactory)).when(engine)
.getExpressionFactory(Mockito.eq(StringExpressionFactoryType.SQL),
Mockito.eq(StandardSQLCapabilities.BIGQUERY));
Schema floatSchema =
Schema.recordOf(
"schema",
Schema.Field.of("uniqueFieldFloat", Schema.of(Schema.Type.FLOAT)));
Optional<ExpressionFactory<String>> expressionFactory =
DedupAggregatorUtils.getExpressionFactory(relationalTranformContext, floatSchema);
Assert.assertTrue(expressionFactory.isPresent());
Mockito.verify(engine, Mockito.times(1))
.getExpressionFactory(Mockito.eq(StringExpressionFactoryType.SQL),
Mockito.eq(StandardSQLCapabilities.BIGQUERY));
Mockito.verify(engine, Mockito.never())
.getExpressionFactory(Mockito.eq(StringExpressionFactoryType.SQL));
}
@Test
public void testGetExpressionFactoryNullableFloatSchema() {
Mockito.doReturn(Optional.of(expressionFactory)).when(engine)
.getExpressionFactory(Mockito.eq(StringExpressionFactoryType.SQL),
Mockito.eq(StandardSQLCapabilities.BIGQUERY));
Schema nullableFloatSchema =
Schema.recordOf(
"schema",
Schema.Field.of("uniqueFieldFloat", Schema.nullableOf(Schema.of(Schema.Type.FLOAT))));
Optional<ExpressionFactory<String>> expressionFactory =
DedupAggregatorUtils.getExpressionFactory(relationalTranformContext, nullableFloatSchema);
Assert.assertTrue(expressionFactory.isPresent());
Mockito.verify(engine, Mockito.times(1))
.getExpressionFactory(Mockito.eq(StringExpressionFactoryType.SQL),
Mockito.eq(StandardSQLCapabilities.BIGQUERY));
Mockito.verify(engine, Mockito.never())
.getExpressionFactory(Mockito.eq(StringExpressionFactoryType.SQL));
}
@Test
public void testGetExpressionFactoryDoubleSchema() {
Mockito.doReturn(Optional.of(expressionFactory)).when(engine)
.getExpressionFactory(Mockito.eq(StringExpressionFactoryType.SQL),
Mockito.eq(StandardSQLCapabilities.BIGQUERY));
Schema doubleSchema =
Schema.recordOf(
"schema",
Schema.Field.of("uniqueFieldDouble", Schema.of(Schema.Type.DOUBLE)));
Optional<ExpressionFactory<String>> expressionFactory =
DedupAggregatorUtils.getExpressionFactory(relationalTranformContext, doubleSchema);
Assert.assertTrue(expressionFactory.isPresent());
Mockito.verify(engine, Mockito.times(1))
.getExpressionFactory(Mockito.eq(StringExpressionFactoryType.SQL),
Mockito.eq(StandardSQLCapabilities.BIGQUERY));
Mockito.verify(engine, Mockito.never())
.getExpressionFactory(Mockito.eq(StringExpressionFactoryType.SQL));
}
@Test
public void testGetExpressionFactoryNullableDoubleSchema() {
Mockito.doReturn(Optional.of(expressionFactory)).when(engine)
.getExpressionFactory(Mockito.eq(StringExpressionFactoryType.SQL),
Mockito.eq(StandardSQLCapabilities.BIGQUERY));
Schema nullableDoubleSchema =
Schema.recordOf(
"schema",
Schema.Field.of("uniqueFieldDouble", Schema.nullableOf(Schema.of(Schema.Type.DOUBLE))));
Optional<ExpressionFactory<String>> expressionFactory =
DedupAggregatorUtils.getExpressionFactory(relationalTranformContext, nullableDoubleSchema);
Assert.assertTrue(expressionFactory.isPresent());
Mockito.verify(engine, Mockito.times(1))
.getExpressionFactory(Mockito.eq(StringExpressionFactoryType.SQL),
Mockito.eq(StandardSQLCapabilities.BIGQUERY));
Mockito.verify(engine, Mockito.never())
.getExpressionFactory(Mockito.eq(StringExpressionFactoryType.SQL));
}
@Test
public void testGetExpressionFactoryNotNullableOrDoubleSchema() {
Mockito.doReturn(Optional.of(expressionFactory)).when(engine)
.getExpressionFactory(Mockito.eq(StringExpressionFactoryType.SQL));
Schema intSchema =
Schema.recordOf(
"schema",
Schema.Field.of("uniqueFieldInt", Schema.nullableOf(Schema.of(Schema.Type.INT))));
Optional<ExpressionFactory<String>> expressionFactory =
DedupAggregatorUtils.getExpressionFactory(relationalTranformContext, intSchema);
Assert.assertTrue(expressionFactory.isPresent());
Mockito.verify(engine, Mockito.never())
.getExpressionFactory(Mockito.eq(StringExpressionFactoryType.SQL),
Mockito.eq(StandardSQLCapabilities.BIGQUERY));
Mockito.verify(engine, Mockito.times(1))
.getExpressionFactory(Mockito.eq(StringExpressionFactoryType.SQL));
}
private static ExtractableExpression<String> getExtractableExpressionForString(String str) {
return new ExtractableExpression<String>() {
@Nullable
@Override
public String extract() throws InvalidExtractableExpressionException {
return String.format("%s", str);
}
@Override
public boolean isValid() {
return true;
}
@Override
public String getValidationError() {
return null;
}
};
}
}
|
/*
* *
* * Copyright (c) 2014 Antoine Jullien
* *
* * 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.cirrus.distribution.scheduler.exception;
public class CirrusAgentCannotBeFoundException extends Exception {
//==================================================================================================================
// Constants
//==================================================================================================================
private static final long serialVersionUID = -4172800061468125821L;
//==================================================================================================================
// Constructors
//==================================================================================================================
public CirrusAgentCannotBeFoundException(final String message) {
super(message);
}
}
|
package com.javarush.task.task04.task0415;
/*
Правило треугольника
*/
import java.io.*;
public class Solution {
public static void main(String[] args) throws Exception {
//напишите тут ваш код
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int a = Integer.parseInt(reader.readLine());
int b = Integer.parseInt(reader.readLine());
int c = Integer.parseInt(reader.readLine());
reader.close();
if ((a + b > c) && (a + c > b) && (b + c > a)) {
System.out.println("Треугольник существует.");
} else {
System.out.println("Треугольник не существует.");
}
}
}
|
package com.epam.jdi.light.elements.interfaces.base;
public interface JDIElement extends INamed {
}
|
package seed.domain;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.bson.types.ObjectId;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
/**
* Created by Froggy
* 2017-03-02.
*/
@Document
public class Comment {
@Id
@JsonSerialize(using = ToStringSerializer.class)
private ObjectId id;
@Indexed
@JsonSerialize(using = ToStringSerializer.class)
private ObjectId objectiveId;
@Indexed
@JsonSerialize(using = ToStringSerializer.class)
private ObjectId userId;
@NotEmpty
private String content;
public Comment(ObjectId userId, String content){
this.userId = userId;
this.content = content;
}
public ObjectId getId() {
return id;
}
public void setId(ObjectId id) {
this.id = id;
}
public ObjectId getObjectiveId() {
return objectiveId;
}
public void setObjectiveId(ObjectId objectiveId) {
this.objectiveId = objectiveId;
}
public ObjectId getUserId() {
return userId;
}
public void setUserId(ObjectId userId) {
this.userId = userId;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
protected Comment(){}
}
|
package org.springboot.samples.test_embedded.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.io.Serializable;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name="location")
public class Location implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long locationId;
private String streetAddress;
private String postalCode;
private String city;
private String stateProvince;
private Long countryId;
}
|
package rero.gui.dialogs;
import rero.gui.dck.DMain;
public class IgnoreDialog extends DMain {
public String getTitle() {
return "Ignore Setup";
}
public String getDescription() {
return "Ignore Mask Setup";
}
public void setupDialog() {
addBlankSpace();
addBlankSpace();
addLabel("The following nick/host masks will be ignored:", 30);
addBlankSpace();
addListInput("ignore.masks", "Ignore this mask (nick!user@host):", "Add Ignore Mask", 80, 125);
}
}
|
// ------------------------------------------------------------------------------
// 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.http.IRequestBuilder;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.concurrency.ICallback;
import com.microsoft.graph.models.extensions.AndroidDeviceOwnerGeneralDeviceConfiguration;
import java.util.Arrays;
import java.util.EnumSet;
import com.microsoft.graph.core.IBaseClient;
import com.microsoft.graph.http.BaseRequest;
import com.microsoft.graph.http.HttpMethod;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Android Device Owner General Device Configuration Request.
*/
public class AndroidDeviceOwnerGeneralDeviceConfigurationRequest extends BaseRequest implements IAndroidDeviceOwnerGeneralDeviceConfigurationRequest {
/**
* The request for the AndroidDeviceOwnerGeneralDeviceConfiguration
*
* @param requestUrl the request URL
* @param client the service client
* @param requestOptions the options for this request
*/
public AndroidDeviceOwnerGeneralDeviceConfigurationRequest(final String requestUrl, final IBaseClient client, final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
super(requestUrl, client, requestOptions, AndroidDeviceOwnerGeneralDeviceConfiguration.class);
}
/**
* Gets the AndroidDeviceOwnerGeneralDeviceConfiguration from the service
*
* @param callback the callback to be called after success or failure
*/
public void get(final ICallback<? super AndroidDeviceOwnerGeneralDeviceConfiguration> callback) {
send(HttpMethod.GET, callback, null);
}
/**
* Gets the AndroidDeviceOwnerGeneralDeviceConfiguration from the service
*
* @return the AndroidDeviceOwnerGeneralDeviceConfiguration from the request
* @throws ClientException this exception occurs if the request was unable to complete for any reason
*/
public AndroidDeviceOwnerGeneralDeviceConfiguration get() throws ClientException {
return send(HttpMethod.GET, null);
}
/**
* Delete this item from the service
*
* @param callback the callback when the deletion action has completed
*/
public void delete(final ICallback<? super AndroidDeviceOwnerGeneralDeviceConfiguration> callback) {
send(HttpMethod.DELETE, callback, null);
}
/**
* Delete this item from the service
*
* @throws ClientException if there was an exception during the delete operation
*/
public void delete() throws ClientException {
send(HttpMethod.DELETE, null);
}
/**
* Patches this AndroidDeviceOwnerGeneralDeviceConfiguration with a source
*
* @param sourceAndroidDeviceOwnerGeneralDeviceConfiguration the source object with updates
* @param callback the callback to be called after success or failure
*/
public void patch(final AndroidDeviceOwnerGeneralDeviceConfiguration sourceAndroidDeviceOwnerGeneralDeviceConfiguration, final ICallback<? super AndroidDeviceOwnerGeneralDeviceConfiguration> callback) {
send(HttpMethod.PATCH, callback, sourceAndroidDeviceOwnerGeneralDeviceConfiguration);
}
/**
* Patches this AndroidDeviceOwnerGeneralDeviceConfiguration with a source
*
* @param sourceAndroidDeviceOwnerGeneralDeviceConfiguration the source object with updates
* @return the updated AndroidDeviceOwnerGeneralDeviceConfiguration
* @throws ClientException this exception occurs if the request was unable to complete for any reason
*/
public AndroidDeviceOwnerGeneralDeviceConfiguration patch(final AndroidDeviceOwnerGeneralDeviceConfiguration sourceAndroidDeviceOwnerGeneralDeviceConfiguration) throws ClientException {
return send(HttpMethod.PATCH, sourceAndroidDeviceOwnerGeneralDeviceConfiguration);
}
/**
* Creates a AndroidDeviceOwnerGeneralDeviceConfiguration with a new object
*
* @param newAndroidDeviceOwnerGeneralDeviceConfiguration the new object to create
* @param callback the callback to be called after success or failure
*/
public void post(final AndroidDeviceOwnerGeneralDeviceConfiguration newAndroidDeviceOwnerGeneralDeviceConfiguration, final ICallback<? super AndroidDeviceOwnerGeneralDeviceConfiguration> callback) {
send(HttpMethod.POST, callback, newAndroidDeviceOwnerGeneralDeviceConfiguration);
}
/**
* Creates a AndroidDeviceOwnerGeneralDeviceConfiguration with a new object
*
* @param newAndroidDeviceOwnerGeneralDeviceConfiguration the new object to create
* @return the created AndroidDeviceOwnerGeneralDeviceConfiguration
* @throws ClientException this exception occurs if the request was unable to complete for any reason
*/
public AndroidDeviceOwnerGeneralDeviceConfiguration post(final AndroidDeviceOwnerGeneralDeviceConfiguration newAndroidDeviceOwnerGeneralDeviceConfiguration) throws ClientException {
return send(HttpMethod.POST, newAndroidDeviceOwnerGeneralDeviceConfiguration);
}
/**
* Creates a AndroidDeviceOwnerGeneralDeviceConfiguration with a new object
*
* @param newAndroidDeviceOwnerGeneralDeviceConfiguration the object to create/update
* @param callback the callback to be called after success or failure
*/
public void put(final AndroidDeviceOwnerGeneralDeviceConfiguration newAndroidDeviceOwnerGeneralDeviceConfiguration, final ICallback<? super AndroidDeviceOwnerGeneralDeviceConfiguration> callback) {
send(HttpMethod.PUT, callback, newAndroidDeviceOwnerGeneralDeviceConfiguration);
}
/**
* Creates a AndroidDeviceOwnerGeneralDeviceConfiguration with a new object
*
* @param newAndroidDeviceOwnerGeneralDeviceConfiguration the object to create/update
* @return the created AndroidDeviceOwnerGeneralDeviceConfiguration
* @throws ClientException this exception occurs if the request was unable to complete for any reason
*/
public AndroidDeviceOwnerGeneralDeviceConfiguration put(final AndroidDeviceOwnerGeneralDeviceConfiguration newAndroidDeviceOwnerGeneralDeviceConfiguration) throws ClientException {
return send(HttpMethod.PUT, newAndroidDeviceOwnerGeneralDeviceConfiguration);
}
/**
* Sets the select clause for the request
*
* @param value the select clause
* @return the updated request
*/
public IAndroidDeviceOwnerGeneralDeviceConfigurationRequest select(final String value) {
getQueryOptions().add(new com.microsoft.graph.options.QueryOption("$select", value));
return (AndroidDeviceOwnerGeneralDeviceConfigurationRequest)this;
}
/**
* Sets the expand clause for the request
*
* @param value the expand clause
* @return the updated request
*/
public IAndroidDeviceOwnerGeneralDeviceConfigurationRequest expand(final String value) {
getQueryOptions().add(new com.microsoft.graph.options.QueryOption("$expand", value));
return (AndroidDeviceOwnerGeneralDeviceConfigurationRequest)this;
}
}
|
package tccrouter.diamante.extension.command;
import tccrouter.diamante.core.command.Command;
import tccrouter.diamante.core.graph.Edge;
import tccrouter.diamante.core.graph.Graph;
import tccrouter.diamante.core.graph.GraphComponent;
import tccrouter.diamante.extension.graph.property.InteractiveProperty;
public class InteractivePropertyChangeCommand extends Command
{
InteractiveProperty property;
String value;
GraphComponent component;
public InteractivePropertyChangeCommand(Graph g, InteractiveProperty property, GraphComponent component, String value)
{
super(g);
this.property = property;
this.value = value;
this.component = component;
}
public void execute()
throws IllegalArgumentException
{
try
{
String oldValue = property.toString();
property.fromString(value);
value = oldValue;
if (component instanceof Edge) {
Edge e = (Edge) component;
g.updateShortestPathDistance(e.getV1(), e.getV2());
}
}
catch(IllegalArgumentException exc)
{
throw exc;
}
}
public void unexecute()
throws IllegalArgumentException
{
execute();
}
public InteractiveProperty getProperty()
{
return property;
}
public String getOldValue()
{
return property.toString();
}
public String getNewValue()
{
return value;
}
public GraphComponent getComponent()
{
return component;
}
}
|
package br.com.zupacademy.joao.mercadolivre.controller.dto.request;
import br.com.zupacademy.joao.mercadolivre.model.Categoria;
import br.com.zupacademy.joao.mercadolivre.validator.existvalues.categoria.ExistSuperCategoriaValue;
import br.com.zupacademy.joao.mercadolivre.validator.uniquevalue.generico.UniqueValue;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.persistence.EntityManager;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
public class CategoriaRequest {
@NotBlank
@UniqueValue(dommainClass = Categoria.class, fieldName = "nome")
private String nome;
@JsonProperty("super")
@ExistSuperCategoriaValue
private Long superCategoriaId;
/**
* Este construtor é para quando a superCategoriaId for nula
* */
protected CategoriaRequest(@NotBlank String nome) {
this.nome = nome;
}
protected CategoriaRequest(@NotBlank String nome,
@NotNull Long superCategoriaId) {
this.nome = nome;
this.superCategoriaId = superCategoriaId;
}
public Categoria toCategoria(EntityManager manager) {
if(superCategoriaId != null) {
Categoria categoria = manager.find(Categoria.class, superCategoriaId);
return new Categoria(this.nome, categoria);
}
return new Categoria(this.nome);
}
}
|
package org.infinispan.persistence.rocksdb.configuration;
import static org.infinispan.configuration.parsing.ParseUtils.ignoreAttribute;
import static org.infinispan.persistence.rocksdb.configuration.RocksDBStoreConfigurationParser.NAMESPACE;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import org.infinispan.commons.configuration.ConfigurationBuilderInfo;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.parsing.ConfigurationBuilderHolder;
import org.infinispan.configuration.parsing.ConfigurationParser;
import org.infinispan.configuration.parsing.Namespace;
import org.infinispan.configuration.parsing.ParseUtils;
import org.infinispan.configuration.parsing.Parser;
import org.infinispan.configuration.parsing.XMLExtendedStreamReader;
import org.kohsuke.MetaInfServices;
/**
* RocksDB XML Parser
* @author Tristan Tarrant
* @since 9.0
*/
@MetaInfServices
@Namespace(root = "rocksdb-store")
@Namespace(uri = NAMESPACE + "*", root = "rocksdb-store", since = "9.0")
public class RocksDBStoreConfigurationParser implements ConfigurationParser {
static final String NAMESPACE = Parser.NAMESPACE + "store:rocksdb:";
public RocksDBStoreConfigurationParser() {
}
@Override
public void readElement(XMLExtendedStreamReader reader, ConfigurationBuilderHolder holder) throws XMLStreamException {
ConfigurationBuilder builder = holder.getCurrentConfigurationBuilder();
Element element = Element.forName(reader.getLocalName());
switch (element) {
case ROCKSDB_STORE: {
parseRocksDBCacheStore(reader, builder.persistence().addStore(RocksDBStoreConfigurationBuilder.class));
break;
}
default: {
throw ParseUtils.unexpectedElement(reader);
}
}
}
private void parseRocksDBCacheStore(XMLExtendedStreamReader reader, RocksDBStoreConfigurationBuilder builder) throws XMLStreamException {
String path = null;
String relativeTo = null;
for (int i = 0; i < reader.getAttributeCount(); i++) {
ParseUtils.requireNoNamespaceAttribute(reader, i);
String value = reader.getAttributeValue(i);
String attrName = reader.getAttributeLocalName(i);
Attribute attribute = Attribute.forName(attrName);
switch (attribute) {
case PATH: {
path = value;
break;
}
case RELATIVE_TO: {
relativeTo = ParseUtils.requireAttributeProperty(reader, i);
break;
}
case CLEAR_THRESHOLD: {
if (!reader.getSchema().since(12, 0)) {
ignoreAttribute(reader, Attribute.CLEAR_THRESHOLD);
break;
} else {
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
case BLOCK_SIZE: {
builder.blockSize(Integer.parseInt(value));
break;
}
case CACHE_SIZE: {
builder.cacheSize(Long.parseLong(value));
break;
}
default: {
Parser.parseStoreAttribute(reader, i, builder);
}
}
}
path = ParseUtils.resolvePath(path, relativeTo);
if (path != null) {
builder.location(path);
}
while (reader.hasNext() && (reader.nextTag() != XMLStreamConstants.END_ELEMENT)) {
Element element = Element.forName(reader.getLocalName());
switch (element) {
case EXPIRATION: {
this.parseExpiry(reader, builder);
break;
}
case COMPRESSION: {
this.parseCompression(reader, builder);
break;
}
default: {
Parser.parseStoreElement(reader, builder);
}
}
}
}
private void parseExpiry(XMLExtendedStreamReader reader, RocksDBStoreConfigurationBuilder builder) throws XMLStreamException {
for (int i = 0; i < reader.getAttributeCount(); i++) {
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case PATH: {
builder.expiredLocation(value);
break;
}
case QUEUE_SIZE: {
if (!reader.getSchema().since(12, 0)) {
ignoreAttribute(reader, Attribute.CLEAR_THRESHOLD);
break;
} else {
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
default:
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
ParseUtils.requireNoContent(reader);
}
private void parseCompression(XMLExtendedStreamReader reader, RocksDBStoreConfigurationBuilder builder) throws XMLStreamException {
for (int i = 0; i < reader.getAttributeCount(); i++) {
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
switch (attribute) {
case TYPE: {
builder.compressionType(CompressionType.valueOf(value));
break;
}
default:
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
ParseUtils.requireNoContent(reader);
}
@Override
public Namespace[] getNamespaces() {
return ParseUtils.getNamespaceAnnotations(getClass());
}
@Override
public Class<? extends ConfigurationBuilderInfo> getConfigurationBuilderInfo() {
return RocksDBStoreConfigurationBuilder.class;
}
}
|
/*********************************************************************************
* *
* The MIT License (MIT) *
* *
* Copyright (c) 2015-2022 aoju.org OSHI and other contributors. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy *
* of this software and associated documentation files (the "Software"), to deal *
* in the Software without restriction, including without limitation the rights *
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell *
* copies of the Software, and to permit persons to whom the Software is *
* furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, *
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN *
* THE SOFTWARE. *
* *
********************************************************************************/
package org.aoju.bus.health.windows.drivers.wmi;
import com.sun.jna.platform.win32.COM.WbemcliUtil.WmiQuery;
import com.sun.jna.platform.win32.COM.WbemcliUtil.WmiResult;
import org.aoju.bus.core.annotation.ThreadSafe;
import org.aoju.bus.health.windows.WmiQueryHandler;
import java.util.Objects;
/**
* Utility to query WMI class {@code Win32_Processor}
*
* @author Kimi Liu
* @version 6.5.0
* @since Java 17+
*/
@ThreadSafe
public final class Win32Processor {
private static final String WIN32_PROCESSOR = "Win32_Processor";
/**
* Returns processor voltage.
*
* @return Current voltage of the processor. If the eighth bit is set, bits 0-6
* contain the voltage multiplied by 10. If the eighth bit is not set,
* then the bit setting in VoltageCaps represents the voltage value.
*/
public static WmiResult<VoltProperty> queryVoltage() {
WmiQuery<VoltProperty> voltQuery = new WmiQuery<>(WIN32_PROCESSOR, VoltProperty.class);
return Objects.requireNonNull(WmiQueryHandler.createInstance()).queryWMI(voltQuery);
}
/**
* Returns processor ID.
*
* @return Processor information that describes the processor features. For an
* x86 class CPU, the field format depends on the processor support of
* the CPUID instruction. If the instruction is supported, the property
* contains 2 (two) DWORD formatted values. The first is an offset of
* 08h-0Bh, which is the EAX value that a CPUID instruction returns with
* input EAX set to 1. The second is an offset of 0Ch-0Fh, which is the
* EDX value that the instruction returns. Only the first two bytes of
* the property are significant and contain the contents of the DX
* register at CPU reset—all others are set to 0 (zero), and the
* contents are in DWORD format.
*/
public static WmiResult<ProcessorIdProperty> queryProcessorId() {
WmiQuery<ProcessorIdProperty> idQuery = new WmiQuery<>(WIN32_PROCESSOR, ProcessorIdProperty.class);
return Objects.requireNonNull(WmiQueryHandler.createInstance()).queryWMI(idQuery);
}
/**
* Returns address width.
*
* @return On a 32-bit operating system, the value is 32 and on a 64-bit
* operating system it is 64.
*/
public static WmiResult<BitnessProperty> queryBitness() {
WmiQuery<BitnessProperty> bitnessQuery = new WmiQuery<>(WIN32_PROCESSOR, BitnessProperty.class);
return Objects.requireNonNull(WmiQueryHandler.createInstance()).queryWMI(bitnessQuery);
}
/**
* Processor voltage properties.
*/
public enum VoltProperty {
CURRENTVOLTAGE, VOLTAGECAPS
}
/**
* Processor ID property
*/
public enum ProcessorIdProperty {
PROCESSORID
}
/**
* Processor bitness property
*/
public enum BitnessProperty {
ADDRESSWIDTH
}
}
|
package com.prowidesoftware.swift.model.mx;
import com.prowidesoftware.swift.model.mx.dic.*;
import com.prowidesoftware.swift.model.mx.AbstractMX;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import com.prowidesoftware.swift.model.MxSwiftMessage;
import com.prowidesoftware.swift.model.mx.AbstractMX;
import com.prowidesoftware.swift.model.mx.MxRead;
import com.prowidesoftware.swift.model.mx.MxReadImpl;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
/**
* Class for caaa.009.001.03 ISO 20022 message.
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Document", propOrder = {
"accptrRcncltnReq"
})
@XmlRootElement(name = "Document", namespace = "urn:iso:std:iso:20022:tech:xsd:caaa.009.001.03")
public class MxCaaa00900103
extends AbstractMX
{
@XmlElement(name = "AccptrRcncltnReq", required = true)
protected AcceptorReconciliationRequestV03 accptrRcncltnReq;
public final static transient String BUSINESS_PROCESS = "caaa";
public final static transient int FUNCTIONALITY = 9;
public final static transient int VARIANT = 1;
public final static transient int VERSION = 3;
@SuppressWarnings("rawtypes")
public final static transient Class[] _classes = new Class[] {AcceptorReconciliationRequest3 .class, AcceptorReconciliationRequestV03 .class, Acquirer2 .class, Algorithm10Code.class, Algorithm5Code.class, Algorithm7Code.class, Algorithm8Code.class, Algorithm9Code.class, AlgorithmIdentification10 .class, AlgorithmIdentification7 .class, AlgorithmIdentification8 .class, AlgorithmIdentification9 .class, AttributeType1Code.class, AuthenticatedData3 .class, CardPaymentEnvironment25 .class, CertificateIdentifier1 .class, CertificateIssuer1 .class, CommunicationCharacteristics2 .class, ContentInformationType8 .class, ContentType1Code.class, EncapsulatedContent2 .class, GenericIdentification31 .class, GenericIdentification32 .class, GenericIdentification48 .class, Header7 .class, IssuerAndSerialNumber1 .class, KEK3 .class, KEKIdentifier1 .class, KeyTransport3 .class, MemoryCharacteristics1 .class, MemoryUnit1Code.class, MessageFunction4Code.class, MxCaaa00900103 .class, POICommunicationType1Code.class, POIComponentAssessment1Code.class, POIComponentStatus1Code.class, POIComponentType3Code.class, Parameter1 .class, Parameter2 .class, Parameter3 .class, PartyType3Code.class, PartyType4Code.class, PartyType7Code.class, PointOfInteractionComponent4 .class, PointOfInteractionComponentAssessment1 .class, PointOfInteractionComponentCharacteristics2 .class, PointOfInteractionComponentIdentification1 .class, PointOfInteractionComponentStatus1 .class, Recipient3Choice.class, RelativeDistinguishedName1 .class, Traceability1 .class, TransactionIdentifier1 .class, TransactionReconciliation2 .class, TransactionTotals2 .class, TypeTransactionTotals2Code.class };
public final static transient String NAMESPACE = "urn:iso:std:iso:20022:tech:xsd:caaa.009.001.03";
public MxCaaa00900103() {
super();
}
/**
* Creates the MX object parsing the parameter String with the XML content
*
*/
public MxCaaa00900103(final String xml) {
this();
MxCaaa00900103 tmp = parse(xml);
accptrRcncltnReq = tmp.getAccptrRcncltnReq();
}
/**
* Creates the MX object parsing the raw content from the parameter MxSwiftMessage
*
*/
public MxCaaa00900103(final MxSwiftMessage mxSwiftMessage) {
this(mxSwiftMessage.message());
}
/**
* Gets the value of the accptrRcncltnReq property.
*
* @return
* possible object is
* {@link AcceptorReconciliationRequestV03 }
*
*/
public AcceptorReconciliationRequestV03 getAccptrRcncltnReq() {
return accptrRcncltnReq;
}
/**
* Sets the value of the accptrRcncltnReq property.
*
* @param value
* allowed object is
* {@link AcceptorReconciliationRequestV03 }
*
*/
public MxCaaa00900103 setAccptrRcncltnReq(AcceptorReconciliationRequestV03 value) {
this.accptrRcncltnReq = value;
return this;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
@Override
public boolean equals(Object that) {
return EqualsBuilder.reflectionEquals(this, that);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
@Override
public String getBusinessProcess() {
return BUSINESS_PROCESS;
}
@Override
public int getFunctionality() {
return FUNCTIONALITY;
}
@Override
public int getVariant() {
return VARIANT;
}
@Override
public int getVersion() {
return VERSION;
}
/**
* Creates the MX object parsing the raw content from the parameter XML
*
*/
public static MxCaaa00900103 parse(String xml) {
return ((MxCaaa00900103) MxReadImpl.parse(MxCaaa00900103 .class, xml, _classes));
}
/**
* Creates the MX object parsing the raw content from the parameter XML with injected read implementation
* @since 9.0.1
*
* @param parserImpl an MX unmarshall implementation
*/
public static MxCaaa00900103 parse(String xml, MxRead parserImpl) {
return ((MxCaaa00900103) parserImpl.read(MxCaaa00900103 .class, xml, _classes));
}
@Override
public String getNamespace() {
return NAMESPACE;
}
@Override
@SuppressWarnings("rawtypes")
public Class[] getClasses() {
return _classes;
}
/**
* Creates an MxCaaa00900103 messages from its JSON representation.
* <p>
* For generic conversion of JSON into the corresponding MX instance
* see {@link AbstractMX#fromJson(String)}
*
* @since 7.10.2
*
* @param json a JSON representation of an MxCaaa00900103 message
* @return
* a new instance of MxCaaa00900103
*/
public final static MxCaaa00900103 fromJson(String json) {
return AbstractMX.fromJson(json, MxCaaa00900103 .class);
}
}
|
package com.example.medical;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.example.medical.adapter.subadapter;
import com.smarteist.autoimageslider.IndicatorView.animation.type.IndicatorAnimationType;
import com.smarteist.autoimageslider.SliderAnimations;
import com.smarteist.autoimageslider.SliderView;
public class MainActivity54 extends AppCompatActivity {
SliderView sliderView;
int[] images = {R.drawable.xdf,
R.drawable.zdf,
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate ( savedInstanceState );
setContentView ( R.layout.activity_main54 );
getSupportActionBar ().hide ();
sliderView=findViewById ( R.id.image_slider );
subadapter subadapter=new subadapter ( images );
sliderView.setSliderAdapter ( subadapter);
sliderView.setIndicatorAnimation ( IndicatorAnimationType.WORM );
sliderView.setSliderTransformAnimation ( SliderAnimations.DEPTHTRANSFORMATION );
sliderView.startAutoCycle ();
}
}
|
package ru.ajana.admin.jpa.entities;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQuery;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
/**
* The persistent class for the rights database table.
*/
@Entity
@Table(name = "rights")
@NamedQuery(name = "Right.findAll", query = "SELECT r FROM RightEntity r")
public class RightEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@SequenceGenerator(name = "RIGHTS_ID_GENERATOR", sequenceName = "SEQ_IDENT")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "RIGHTS_ID_GENERATOR")
private Long id;
private String ident;
private String name;
//bi-directional many-to-many association to GroupEntity
// @ManyToMany
// @JoinTable(
// name = "group_rights"
// , joinColumns = {
// @JoinColumn(name = "right_id")
// }
// , inverseJoinColumns = {
// @JoinColumn(name = "group_id")
// }
// )
// private List<GroupEntity> groupEntities;
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getIdent() {
return this.ident;
}
public void setIdent(String ident) {
this.ident = ident;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
// public List<GroupEntity> getGroupEntities() {
// return this.groupEntities;
// }
// public void setGroupEntities(List<GroupEntity> groupEntities) {
// this.groupEntities = groupEntities;
// }
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RightEntity that = (RightEntity) o;
if (id != null ? !id.equals(that.id) : that.id != null) {
return false;
}
if (ident != null ? !ident.equals(that.ident) : that.ident != null) {
return false;
}
return name != null ? name.equals(that.name) : that.name == null;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (ident != null ? ident.hashCode() : 0);
result = 31 * result + (name != null ? name.hashCode() : 0);
return result;
}
}
|
package tech.aistar.day18.homework;
import java.util.Date;
/**
* @author: Merlin
* @time: 2020/8/19 17:13
*/
public class Student {
Integer id;
String name;
Integer no;
Date birthday;
Address address;
public Student(Integer id, String name, Integer no, Date birthday, Address address) {
this.id = id;
this.name = name;
this.no = no;
this.birthday = birthday;
this.address = address;
}
public Student() {
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Student{");
sb.append("id=").append(id);
sb.append(", name='").append(name).append('\'');
sb.append(", no=").append(no);
sb.append(", birthday=").append(birthday);
sb.append(", address=").append(address);
sb.append('}');
return sb.toString();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getNo() {
return no;
}
public void setNo(Integer no) {
this.no = no;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
|
package com.composum.sling.platform.staging.versions;
import com.composum.sling.core.filter.ResourceFilter;
import com.composum.sling.core.util.CoreConstants;
import com.composum.sling.platform.staging.*;
import com.composum.sling.platform.staging.impl.SiblingOrderUpdateStrategy;
import org.apache.sling.api.resource.PersistenceException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.jcr.RepositoryException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Service to view / manage which documents are put into a release - mostly for {@link PlatformVersionsServlet}.
*
* @see PlatformVersionsServlet
*/
public interface PlatformVersionsService {
/**
* A {@link ResourceFilter} that filters things that can be activated (that is, is versionable itself or contains a
* content node that can be activated).
*/
ResourceFilter ACTIVATABLE_FILTER = ResourceFilter.FilterSet.Rule.or.of(
new ResourceFilter.TypeFilter(CoreConstants.MIX_VERSIONABLE),
new ResourceFilter.ContentNodeFilter(false, ResourceFilter.ALL,
new ResourceFilter.TypeFilter(CoreConstants.MIX_VERSIONABLE)
)
);
/** Specifies the state of a versionable wrt. a specific release. */
enum ActivationState {
/** New, not activated (not in release and has never been there). */
initial,
/** Activated and not modified (in release). */
activated,
/**
* Activated but modified since last activation, or deleted in the release content.
* As modification count both a changed {@link com.composum.sling.core.util.CoreConstants#PROP_LAST_MODIFIED}
* wrt. to the last activation, as well as a different version.
*/
modified,
/** Deactivated (originally present but later removed ({@link #deactivate(String, List)}) from release. */
deactivated,
/** When comparing the workspace to a release: deleted from the workspace. */
deleted
}
/** Information about the status of a versionable in the workspace wrt. a release, or of a versionable within a release wrt. a previous release. */
interface Status {
String getPath();
/** Calculated modification status. */
@Nonnull
ActivationState getActivationState();
/**
* The time the versionable was last modified in the workspace.
*
* @return 'last modified' or 'created'
*/
@Nullable
Calendar getLastModified();
@Nullable
String getLastModifiedBy();
/**
* The latest version reference - when comparing workspace to release, this is in the release; when
* comparing release to release, this is in {@link #getNextRelease()}. Might be null in case of {@link ActivationState#initial}.
*/
@Nullable
VersionReference getVersionReference();
/**
* The release we compare from. If we compare the workspace, this is null.
*/
@Nullable
Release getNextRelease();
/**
* The detail information about the versionable as it is in the workspace / the release if we're comparing a release with a previous release.
* This is null if the status refers to a deleted versionable.
*/
@Nullable
ReleasedVersionable getNextVersionable();
/**
* The release {@link #getPreviousVersionable()} is about (see there). When comparing workspace to
* release this is not null,
* when comparing release to release this might be null (if there was no previous release).
*/
@Nullable
Release getPreviousRelease();
/**
* The detail information about the versionable within the release if the status is about the workspace / within the previous release if it's comparing two releases. This is null if the versionable is {@link ActivationState#initial} /
* if the previous release did not contain the versionable at all.
*/
@Nullable
ReleasedVersionable getPreviousVersionable();
/** The workspace resource (versionable) that corresponds to the released stuff. */
@Nullable
Resource getWorkspaceResource();
}
/**
* Returns the release number of the default release - currently the
* {@value com.composum.sling.platform.staging.StagingConstants#CURRENT_RELEASE} release.
* This is used in many of the other methods if the release isn't given explicitly.
*/
@Nonnull
Release getDefaultRelease(@Nonnull Resource versionable);
/**
* Returns the status for the versionable comparing the workspace to the given or {@link #getDefaultRelease(Resource)} release.
* Some non-obvious edge cases:
*
* @param versionable the versionable in the workspace
* @param releaseKey the key for the release; if null we take the {@link #getDefaultRelease(Resource)}
* @return the status or null if this isn't applicable because there is no release root or the resource is not a versionable.
*/
@Nullable
Status getStatus(@Nonnull Resource versionable, @Nullable String releaseKey)
throws RepositoryException;
/**
* Puts the latest content (or a specified version) of the document into the release.
* If no version is given, we automatically {@link javax.jcr.version.VersionManager#checkpoint(String)} the versionable
* if it was modified, and use the latest version of it.
* <p>
* Caution: since this may do a checkpoint, it needs a clean resolver before calling.
*
* @param releaseKey a release number or null for the {@link #getDefaultRelease(Resource)}.
* @param versionable the path to a versionable. In case of the "activation" of a deletion, this can be {@link org.apache.sling.api.resource.NonExistingResource}. In this case we use the path to find it in the release.
* @param versionUuid optionally, a previous version of the document that is
* @return information about the activation
*/
@Nonnull
ActivationResult activate(@Nullable String releaseKey, @Nonnull Resource versionable, @Nullable String versionUuid)
throws PersistenceException, RepositoryException, StagingReleaseManager.ReleaseClosedException, ReleaseChangeFailedException;
/**
* Puts the latest content of a couple of documents into the release.
* We automatically {@link javax.jcr.version.VersionManager#checkpoint(String)} each versionables
* if it was modified, and use the latest version of it.
* <p>
* Caution: since this may do a checkpoint, it needs a clean resolver before calling.
*
* @param releaseKey a release number or null for the {@link #getDefaultRelease(Resource)}.
* @param versionables a number of versionables which are possibly checkpointed and then activated simultaneously
* @return information about the activation
*/
@Nonnull
ActivationResult activate(@Nullable String releaseKey, @Nonnull List<Resource> versionables)
throws PersistenceException, RepositoryException, StagingReleaseManager.ReleaseClosedException, ReleaseChangeFailedException;
/**
* Sets the versionables to "deactivated" - it is marked as not present in the release anymore.
*
* @param releaseKey a release number or null for the {@link #getDefaultRelease(Resource)}.
* @param versionables ist of versionables to revert
*/
void deactivate(@Nullable String releaseKey, @Nonnull List<Resource> versionables)
throws PersistenceException, RepositoryException, StagingReleaseManager.ReleaseClosedException, ReleaseChangeFailedException;
/**
* Reverts a number of versionables to the state they were in the previous release
* (in the sense of {@link com.composum.sling.platform.staging.ReleaseNumberCreator#COMPARATOR_RELEASES}).
* If there is no previous release, this deletes the versionable from the content (the "previous release" counting as empty in this case).
*
* @param resolver a resolver we can use
* @param releaseKey a release number or null for the {@link #getDefaultRelease(Resource)}.
* @param versionablePaths list of paths to versionables to revert. We use paths instead of resources since they might not exist in the workspace (if moved or deleted)
* nor in the StagingResolver (if deactivated)
* @return information about the activation
*/
@Nonnull
ActivationResult revert(@Nonnull ResourceResolver resolver, @Nullable String releaseKey, @Nonnull List<String> versionablePaths)
throws PersistenceException, RepositoryException, StagingReleaseManager.ReleaseClosedException, ReleaseChangeFailedException;
/** Deletes old versions of the versionable - only versions in releases and after the last version which is in a release are kept. */
void purgeVersions(@Nonnull Resource versionable)
throws RepositoryException;
/**
* Returns a {@link ResourceFilter} that accepts resources contained in a release. Outside of the release root it just takes the current contet.
*
* @param resourceInRelease some resource below a release root, used to find the release root
* @param releaseKey a release number or null for the {@link #getDefaultRelease(Resource)}.
* @param releaseMapper a {@link ReleaseMapper} that determines what is taken from the release, and what from the current content
* @param additionalFilter a resource filter that has additionally be matched for the resource within the release (and is executed with the Staging Resolver).
* If null, we just use {@link ResourceFilter#ALL}.
* @return a {@link ResourceFilter} that returns true for resources contained in the release
*/
@Nonnull
ResourceFilter releaseAsResourceFilter(@Nonnull Resource resourceInRelease, @Nullable String releaseKey,
@Nullable ReleaseMapper releaseMapper, @Nullable ResourceFilter additionalFilter);
/**
* Returns description of versionables which are changed in a release in comparision to the release before.
*/
@Nonnull
List<Status> findReleaseChanges(@Nonnull final Release release) throws RepositoryException;
/**
* Returns description of versionables which are changed in the workspace in comparision to the release.
*/
@Nonnull
List<Status> findWorkspaceChanges(@Nonnull final Release release) throws RepositoryException;
/** Can be used to inform the user about the results of an activation. */
class ActivationResult {
@Nullable
private transient final Release release;
@Nonnull
private final Map<String, SiblingOrderUpdateStrategy.Result> changedPathsInfo;
@Nonnull
private final Set<String> newPaths;
@Nonnull
private final Map<String, String> movedPaths;
@Nonnull
private final Set<String> removedPaths;
/**
* Constructor for which the sets / maps are modified later.
*/
public ActivationResult(@Nullable Release release) {
this(release, null, null, null, null);
}
/**
* Constructor that immediately sets everything.
*/
public ActivationResult(@Nullable Release release, @Nullable Map<String, SiblingOrderUpdateStrategy.Result> changedPathsInfo,
@Nullable Set<String> newPaths, @Nullable Map<String, String> movedPaths, @Nullable Set<String> removedPaths) {
this.release = release;
this.changedPathsInfo = changedPathsInfo != null ? changedPathsInfo : new HashMap<>();
this.newPaths = newPaths != null ? newPaths : new HashSet<>();
this.movedPaths = movedPaths != null ? movedPaths : new HashMap<>();
this.removedPaths = removedPaths != null ? removedPaths : new HashSet<>();
}
@Nonnull
public ActivationResult merge(@Nonnull ActivationResult other) {
if (release != null && !release.equals(other.getRelease())) {
throw new IllegalArgumentException("Merging results for different releases.");
}
Release newRelease = release != null ? release : other.getRelease();
Map<String, String> moved = new HashMap<>();
moved.putAll(getMovedPaths());
moved.putAll(other.getMovedPaths());
LinkedHashSet<String> combinedNewPaths = new LinkedHashSet<>(getNewPaths());
combinedNewPaths.addAll(other.newPaths);
LinkedHashSet<String> combinedRemovedPaths = new LinkedHashSet<>(getRemovedPaths());
combinedRemovedPaths.addAll(other.getRemovedPaths());
return new ActivationResult(newRelease,
SiblingOrderUpdateStrategy.Result.combine(changedPathsInfo, other.getChangedPathsInfo()),
combinedNewPaths,
moved,
combinedRemovedPaths
);
}
/** A map with paths where we changed the order of children in the release. */
@Nonnull
public Map<String, SiblingOrderUpdateStrategy.Result> getChangedPathsInfo() {
return changedPathsInfo;
}
@Nullable
public Release getRelease() {
return release;
}
/** If as result of an operation there is a new item in a release, this contains its path. */
@Nonnull
public Set<String> getNewPaths() {
return newPaths;
}
/** If an item was moved in a release according to the operation, this maps the absolute old path to the absolute new path. */
@Nonnull
public Map<String, String> getMovedPaths() {
return movedPaths;
}
/** If as result of an operation an item vanished in a release, this contains its path. */
@Nonnull
public Set<String> getRemovedPaths() {
return removedPaths;
}
@Nonnull
@Override
public String toString() {
return "ActivationResult(" + changedPathsInfo + ")";
}
}
}
|
/*
* (C) Copyright IBM Corp. 2021.
*
* 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.ibm.cloud.is.vpc.v1.model;
import com.ibm.cloud.is.vpc.v1.model.SecurityGroupRuleRemoteIP;
import com.ibm.cloud.is.vpc.v1.utils.TestUtilities;
import com.ibm.cloud.sdk.core.service.model.FileWithMetadata;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
/**
* Unit test class for the SecurityGroupRuleRemoteIP model.
*/
public class SecurityGroupRuleRemoteIPTest {
final HashMap<String, InputStream> mockStreamMap = TestUtilities.createMockStreamMap();
final List<FileWithMetadata> mockListFileWithMetadata = TestUtilities.creatMockListFileWithMetadata();
@Test
public void testSecurityGroupRuleRemoteIP() throws Throwable {
SecurityGroupRuleRemoteIP securityGroupRuleRemoteIpModel = new SecurityGroupRuleRemoteIP();
assertNull(securityGroupRuleRemoteIpModel.getAddress());
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.